line.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import fastapi
  2. from linebot.models import (
  3. MessageEvent, TextMessage, TextSendMessage, FollowEvent,
  4. TemplateSendMessage, ButtonsTemplate, URITemplateAction,
  5. )
  6. import dataset
  7. import requests
  8. import json
  9. import qrcode
  10. from random import randrange
  11. from app.schemas import line
  12. from app.core.config import settings
  13. import datetime as dt
  14. from fastapi import APIRouter, FastAPI, Request, Response, Body,Depends
  15. from fastapi.routing import APIRoute
  16. from app.api import deps
  17. from app import crud, models, schemas
  18. from typing import Callable, List
  19. from uuid import uuid4
  20. from sqlalchemy.orm import Session
  21. from datetime import datetime
  22. router = APIRouter()
  23. # callback event
  24. @router.post("/callback")
  25. async def callback(request: fastapi.Request):
  26. signature = request.headers['X-Line-Signature']
  27. body = await request.body()
  28. settings.handler.handle(body.decode('utf-8'), signature)
  29. return 'OK'
  30. # follow event
  31. @settings.handler.add(FollowEvent)
  32. def handle_follow(event):
  33. # get user id when follow
  34. real_user_id = event.source.user_id
  35. # db connect and search
  36. db = dataset.connect(
  37. 'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
  38. )
  39. table = db['users']
  40. result1 = table.find_one(userid=real_user_id)
  41. # 都存在db的話
  42. if result1:
  43. db.close()
  44. settings.line_bot_api.reply_message(
  45. event.reply_token,
  46. TextSendMessage(text='很高興再見到您!'))
  47. # 建立全新使用者
  48. else:
  49. # create user account api
  50. url = 'https://nft-api-staging.joyso.io/api/v1/accounts'
  51. headers = {
  52. 'Authorization':
  53. 'Basic bmZ0OmMxOTEzOWMzYjM3YjdjZWU3ZmY3OTFiZGU3NzdjZWNl'
  54. }
  55. # setup for temp use (unique id)
  56. rand_num = str(randrange(99999))
  57. user_id = event.source.user_id + rand_num
  58. data = 'uid=' + user_id
  59. r = requests.post(url=url, headers=headers, data=data)
  60. # extract the account address
  61. dict_str = json.loads(r.text)
  62. user_account = dict_str['account']
  63. user_address = user_account['address']
  64. # generate qr code from user id
  65. qr = qrcode.QRCode(
  66. version=1,
  67. box_size=10,
  68. border=5)
  69. qr.add_data(user_address)
  70. qr.make(fit=True)
  71. img_qr = qr.make_image(fill='black', back_color='white')
  72. filename = "/var/www/ArkCard-Linebot/ArkCard-web/qrcode/" + \
  73. real_user_id + '.png'
  74. img_qr.save(filename)
  75. # add to db
  76. data = dict(userid=real_user_id, useraddress=user_address)
  77. table.insert(data)
  78. db.close()
  79. settings.line_bot_api.reply_message(
  80. event.reply_token,
  81. TextSendMessage(text='歡迎加入好友'))
  82. # message handler
  83. @settings.handler.add(MessageEvent, message=TextMessage)
  84. def message(event):
  85. if '我要發送' in event.message.text:
  86. button_template_message = ButtonsTemplate(
  87. title=' ',
  88. text='點擊並打開收藏的NFT,可以選擇想要發送的NFT給對方!',
  89. actions=[
  90. URITemplateAction(
  91. label='打開發送頁',
  92. uri='https://ark.cards/collect.html?'
  93. + event.source.user_id)])
  94. settings.line_bot_api.reply_message(
  95. event.reply_token,
  96. TemplateSendMessage(
  97. alt_text="Receive",
  98. template=button_template_message))
  99. elif '我要接收' in event.message.text:
  100. button_template_message = ButtonsTemplate(
  101. title=' ',
  102. text='點擊並打開接收頁面,即可分享接收地址給對方!',
  103. actions=[
  104. URITemplateAction(
  105. label='打開接收頁',
  106. uri='https://ark.cards/qr-code.html?' +
  107. event.source.user_id)])
  108. settings.line_bot_api.reply_message(
  109. event.reply_token,
  110. TemplateSendMessage(
  111. alt_text="Receive",
  112. template=button_template_message))
  113. elif 'NFT商店' in event.message.text:
  114. button_template_message = ButtonsTemplate(
  115. title=' ',
  116. text='點擊並打開NFT商品頁,就可以購買您所想要的NFT商品哦!',
  117. actions=[
  118. URITemplateAction(
  119. label='打開NFT商品頁',
  120. uri='https://ark.cards/shop.html?' +
  121. event.source.user_id)])
  122. settings.line_bot_api.reply_message(
  123. event.reply_token,
  124. TemplateSendMessage(
  125. alt_text="Receive",
  126. template=button_template_message))
  127. elif 'NFT收藏' in event.message.text:
  128. button_template_message = ButtonsTemplate(
  129. title=' ',
  130. text='點擊並打開收藏的NFT,可以查看收到的NFT!',
  131. actions=[
  132. URITemplateAction(
  133. label='打開收藏頁',
  134. uri='https://ark.cards/collect.html?' +
  135. event.source.user_id), ])
  136. settings.line_bot_api.reply_message(
  137. event.reply_token,
  138. TemplateSendMessage(
  139. alt_text="Receive",
  140. template=button_template_message))
  141. else:
  142. button_template_message = ButtonsTemplate(
  143. title=' ',
  144. text='更多的服務內容,歡迎請上我們的官網!',
  145. actions=[
  146. URITemplateAction(
  147. label='ArkCard的官網',
  148. uri='https://ark.cards')])
  149. settings.line_bot_api.reply_message(
  150. event.reply_token,
  151. TemplateSendMessage(
  152. alt_text="Receive",
  153. template=button_template_message))
  154. @router.post("/push/")
  155. def push_text(user, message):
  156. settings.line_bot_api.push_message(
  157. user, TextSendMessage(text=message)
  158. )
  159. # nft collection api
  160. @router.get("/collection/{userid}")
  161. def collection(userid):
  162. # db connect
  163. db = dataset.connect(
  164. 'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
  165. )
  166. table3 = db['nftdrops']
  167. table2 = db['nft']
  168. nftdrops = {}
  169. nft = {}
  170. nfts_all = {}
  171. i = 0
  172. j = 0
  173. if not table3.find_one(userid=userid) and not table2.find_one(userid=userid):
  174. db.close()
  175. return "error: user don't have any nft"
  176. else:
  177. results1 = table3.find(userid=userid)
  178. for item in results1:
  179. nft_id = item['nftid']
  180. nftdrops[i] = table2.find_one(id=nft_id)
  181. i += 1
  182. results2 = table2.find(userid=userid)
  183. for item in results2:
  184. nft[j] = item
  185. j += 1
  186. nfts_all[0] = nftdrops
  187. nfts_all[1] = nft
  188. return nfts_all
  189. db.close()
  190. # receive handler
  191. @router.get("/receive/{userid}")
  192. def receive(userid):
  193. # db connect
  194. db = dataset.connect(
  195. 'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
  196. )
  197. table = db['users']
  198. table.find_one(userid=userid)
  199. if not table.find_one(userid=userid):
  200. db.close()
  201. return "ERROR: User Not Found"
  202. else:
  203. result = table.find_one(userid=userid)
  204. return {
  205. "userid": result['userid'], "useraddress": result['useraddress']
  206. }
  207. db.close()
  208. # send handler
  209. @router.post("/send")
  210. async def send(userModel: line.TransactionNft):
  211. # db connect
  212. db = dataset.connect(
  213. 'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
  214. )
  215. table = db['users']
  216. table2 = db['nft']
  217. table3 = db['nftdrops']
  218. transaction_table = db['transaction']
  219. # input and find userid
  220. nftid = userModel.nftid
  221. address = userModel.address
  222. result = table.find_one(useraddress=address)
  223. # first confirm if the user exist
  224. if not result:
  225. db.close()
  226. return {'msg': 'user address not found'}
  227. else:
  228. userid = result['userid']
  229. # update nft owner
  230. if table3.find_one(nftid=nftid):
  231. data = dict(nftid=nftid, userid=userid)
  232. table3.update(data, ['nftid'])
  233. # push訊息
  234. result3 = table2.find_one(id=nftid)
  235. title = result3['title']
  236. pre_own = result3['userid']
  237. message = "您的NFT : " + title + ", 已劃轉成功!"
  238. push_text(userid, message)
  239. transaction_table.insert({'tfrom':pre_own,'to':userid,'nft':nftid,'transaction_at':datetime.now()})
  240. db.close()
  241. elif table2.find_one(id=nftid):
  242. result3 = table2.find_one(id=nftid)
  243. pre_own = result3['userid']
  244. data = dict(id=nftid, userid=userid)
  245. table2.update(data, ['id'])
  246. # push訊息
  247. try:
  248. transaction_table.insert({'tfrom':pre_own,'to':userid,'nft':nftid,'transaction_at':datetime.now()})
  249. title = result3['title']
  250. fr = "您的NFT : " + title + ", 已發送成功!"
  251. to = "您的NFT : "+title+", 已收到!"
  252. push_text(userid, to)
  253. push_text(pre_own, fr)
  254. except:
  255. return "找不到原使用者"
  256. db.close()
  257. else:
  258. # push訊息
  259. message = "交易失敗!如果有疑問,請洽網站的服務信箱!"
  260. push_text(userid, message)
  261. db.close()
  262. return {'msg': 'nft not found'}
  263. return {'msg': 'OK'}
  264. # shop handler
  265. @router.get("/shop/{userid}")
  266. def shop(userid):
  267. # db connect
  268. db = dataset.connect(
  269. 'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
  270. )
  271. sql = 'SELECT DISTINCT(title), id, imgurl, userid FROM arkcard.nft ' \
  272. 'WHERE id<1001 and userid IS NULL GROUP BY title LIMIT 5'
  273. result = db.query(sql)
  274. rows = {}
  275. i = 0
  276. for row in result:
  277. rows[i] = row
  278. i += 1
  279. return rows
  280. db.close()
  281. @router.post("/buy")
  282. async def buy(userModel: line.BuyNft):
  283. # db connect
  284. db = dataset.connect(
  285. 'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
  286. )
  287. table2 = db['nft']
  288. # input
  289. nftid = userModel.nftid
  290. userid = userModel.userid
  291. if not table2.find_one(id=nftid):
  292. db.close()
  293. # push訊息
  294. message = "購買失敗!如果有疑問,請洽網站的服務信箱!"
  295. push_text(userid, message)
  296. return "該NFT商品不存在!如果有疑問,請洽網站的服務信箱!"
  297. else:
  298. user_obj = table2.find_one(id=nftid)
  299. user_obj['userid'] = userid
  300. table2.update(dict(user_obj), ['id'])
  301. # push訊息
  302. result3 = table2.find_one(id=nftid)
  303. title = result3['title']
  304. message = "您的NFT : " + title + ", 已購買成功!"
  305. push_text(userid, message)
  306. db.close()
  307. return "您已購買成功!"
  308. @router.post("/event")
  309. async def nftdrops(userModel: line.NftDrops):
  310. # db connect
  311. db = dataset.connect(
  312. 'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
  313. )
  314. table3 = db['nftdrops']
  315. # input對應
  316. eventid = '1'
  317. nftid = '1001'
  318. nftid2 = '1002'
  319. userid = userModel.userid
  320. email = userModel.email
  321. now = dt.datetime.now()
  322. # 如果userid不在db, 寫入到一個空值nft
  323. if not table3.find_one(userid=userid):
  324. # 新增資料
  325. table3.insert(
  326. dict(
  327. eventid=eventid, nftid=nftid,
  328. userid=userid, email=email, time=now
  329. ))
  330. table3.insert(
  331. dict(
  332. eventid=eventid, nftid=nftid2,
  333. userid=userid, email=email, time=now
  334. ))
  335. db.close()
  336. # push訊息
  337. message = "已為您登記活動!"
  338. push_text(userid, message)
  339. return "新增成功"
  340. # 如果userid存在,回傳通知
  341. else:
  342. db.close()
  343. # push訊息
  344. message = "您已登記過活動了!"
  345. push_text(userid, message)
  346. return "已有資料"
  347. @router.get("/transactions/{userid}")
  348. def transactions(userid,skip: int = 0, limit: int = 100):
  349. # db connect
  350. db = dataset.connect(
  351. 'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
  352. )
  353. sql = 'SELECT * FROM transaction ' \
  354. 'WHERE tfrom="'+userid+'" limit '+str(skip)+', '+str(limit)
  355. result = db.query(sql)
  356. rows = {}
  357. i = 0
  358. for row in result:
  359. rows[i] = row
  360. i += 1
  361. db.close()
  362. return rows