line.py 12 KB

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