line.py 12 KB

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