line.py 16 KB

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