nft.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. from typing import Any, Optional
  2. import requests
  3. import uuid
  4. import json
  5. from fastapi import APIRouter, Depends, HTTPException, File, UploadFile, Form
  6. from fastapi.encoders import jsonable_encoder
  7. from sqlalchemy.orm import Session
  8. from app import crud, models, schemas
  9. from app.core.config import settings
  10. from app.api import deps
  11. from uuid import uuid4
  12. from linebot.models import (
  13. MessageEvent, TextMessage, TextSendMessage, FollowEvent,
  14. TemplateSendMessage, ButtonsTemplate, URITemplateAction,
  15. )
  16. from app.api.api_v1.endpoints.line import LineRouter
  17. router = APIRouter(route_class=LineRouter)
  18. baseUrl = "https://nft-api-staging.joyso.io/api/v1/"
  19. headers = {
  20. 'Authorization': 'Basic bmZ0OmMxOTEzOWMzYjM3YjdjZWU3ZmY3OTFiZGU3NzdjZWNl',
  21. 'Content-Type': 'application/json'
  22. }
  23. @router.get("/", response_model=list[schemas.NftPrint])
  24. # @router.get("/")
  25. def read_items(
  26. db: Session = Depends(deps.get_db),
  27. skip: int = 0,
  28. limit: int = 100,
  29. current_user: models.users = Depends(deps.get_current_active_superuser),
  30. ) -> Any:
  31. """
  32. Retrieve items.
  33. """
  34. if crud.user.is_superuser(current_user):
  35. nfts = crud.nft.get_group_by_title(db)
  36. else:
  37. nfts = crud.nft.get_multi_by_owner(
  38. db=db, owner_id=current_user.userid
  39. )
  40. return nfts
  41. @router.post("/", response_model=schemas.NftBase)
  42. async def create_item(
  43. *,
  44. db: Session = Depends(deps.get_db),
  45. # item_in: schemas.NftCreate,
  46. hash: Optional[str] = Form(None),
  47. title: str = Form(...),
  48. context: Optional[str] = Form(None),
  49. is_active: Optional[bool] = Form(True),
  50. catagory: Optional[str] = Form(None),
  51. image: UploadFile = File(...),
  52. uid: int = Form(...),
  53. address: str = Form(...),
  54. amount: int = Form(...),
  55. current_user: models.users = Depends(deps.get_current_active_user),
  56. ) -> Any:
  57. """
  58. Create new item.
  59. """
  60. path = "erc1155"
  61. txid = str(uuid.uuid4())
  62. payload = json.dumps({
  63. "txid": txid,
  64. "to": address,
  65. "uid": uid,
  66. "amount": amount
  67. })
  68. r = requests.post(
  69. baseUrl + path,
  70. headers=headers,
  71. data=payload
  72. )
  73. if r.status_code != 200:
  74. raise HTTPException(status_code=400, detail="not correct mint informaiton")
  75. if image.content_type.split('/')[0] != 'image':
  76. raise HTTPException(status_code=415,
  77. detail='content type error! Please upload valid image type')
  78. filename = str(uuid4()) + '.' + image.content_type.split('/')[1]
  79. with open(settings.IMG_PATH + filename, 'wb+') as f:
  80. f.write(image.file.read())
  81. f.close()
  82. userid = crud.user.get_by_address(db, address = address)
  83. item_in = schemas.NftCreate
  84. item_in.hash = hash
  85. item_in.userid = userid
  86. item_in.title = title
  87. item_in.context = context
  88. item_in.is_active = is_active
  89. item_in.category = catagory
  90. item_in.imgurl = settings.IMG_HOST + filename
  91. item_in.uid = uid
  92. nft = crud.nft.create_with_owner(
  93. db=db, obj_in=item_in, owner_id=item_in.userid)
  94. message = "您mint的 nft(" + title + ") 已經為您存到錢包"
  95. settings.line_bot_api.push_message(
  96. userid, TextSendMessage(text=message))
  97. return nft
  98. @router.put("/", response_model=schemas.NftCreate)
  99. def update_item(
  100. *,
  101. db: Session = Depends(deps.get_db),
  102. title: str,
  103. id: int,
  104. context: Optional[str] = Form(None),
  105. is_active: Optional[bool] = Form(True),
  106. catagory: Optional[str] = Form(None),
  107. image: Optional[UploadFile] = File(None),
  108. current_user: models.users = Depends(deps.get_current_active_user),
  109. ) -> Any:
  110. """
  111. Update items.
  112. """
  113. nft = crud.nft.get(db=db, id = id)
  114. if not nft:
  115. raise HTTPException(status_code=404, detail="Item not found")
  116. # if not crud.user.is_superuser(current_user) and (nft.userid != current_user.userid):
  117. if not crud.user.is_superuser(current_user):
  118. raise HTTPException(status_code=400, detail="Not enough permissions")
  119. item_in = schemas.NftBulkUpdate(**jsonable_encoder(nft))
  120. if image:
  121. if image.content_type.split('/')[0] != 'image':
  122. raise HTTPException(status_code=415,
  123. detail='content type error! Please upload valid image type')
  124. filename = str(uuid4()) + '.' + image.content_type.split('/')[1]
  125. with open(settings.IMG_PATH + filename, 'wb+') as f:
  126. f.write(image.file.read())
  127. f.close()
  128. item_in.imgurl = settings.IMG_HOST + filename
  129. if title:
  130. item_in.title = title
  131. if context:
  132. item_in.context = context
  133. if is_active:
  134. item_in.is_active = is_active
  135. if catagory:
  136. item_in.category = catagory
  137. nft = crud.nft.update_bulk_title(db=db, db_obj_list=nft, obj_in=item_in)
  138. return nft
  139. @router.put("/{id}", response_model=schemas.NftCreate)
  140. def update_item(
  141. *,
  142. db: Session = Depends(deps.get_db),
  143. title: Optional[str] = Form(None),
  144. id: int,
  145. context: Optional[str] = Form(None),
  146. is_active: Optional[bool] = Form(True),
  147. catagory: Optional[str] = Form(None),
  148. image: Optional[UploadFile] = File(None),
  149. current_user: models.users = Depends(deps.get_current_active_user),
  150. ) -> Any:
  151. """
  152. Update an item.
  153. """
  154. nft = crud.nft.get(db=db, id=id)
  155. if not nft:
  156. raise HTTPException(status_code=404, detail="Item not found")
  157. if not crud.user.is_superuser(current_user) and (nft.userid != current_user.userid):
  158. raise HTTPException(status_code=400, detail="Not enough permissions")
  159. item_in = schemas.NftUpdate(**jsonable_encoder(nft))
  160. if image:
  161. if image.content_type.split('/')[0] != 'image':
  162. raise HTTPException(status_code=415,
  163. detail='content type error! Please upload valid image type')
  164. filename = str(uuid4()) + '.' + image.content_type.split('/')[1]
  165. with open(settings.IMG_PATH + filename, 'wb+') as f:
  166. f.write(image.file.read())
  167. f.close()
  168. item_in.imgurl = settings.IMG_HOST + filename
  169. if title:
  170. item_in.title = title
  171. if context:
  172. item_in.context = context
  173. item_in.is_active = is_active
  174. if catagory:
  175. item_in.category = catagory
  176. nft = crud.nft.update(db=db, db_obj=nft, obj_in=item_in)
  177. return nft
  178. @router.get("/{id}", response_model=schemas.NftCreate)
  179. def read_item(
  180. *,
  181. db: Session = Depends(deps.get_db),
  182. id: int,
  183. current_user: models.users = Depends(deps.get_current_active_user),
  184. ) -> Any:
  185. """
  186. Get item by ID.
  187. """
  188. nft = crud.nft.get(db=db, id=id)
  189. if not nft:
  190. raise HTTPException(status_code=404, detail="Item not found")
  191. if not crud.user.is_superuser(current_user) and (nft.userid != current_user.userid):
  192. raise HTTPException(status_code=400, detail="Not enough permissions")
  193. return nft
  194. # @router.post("/title", response_model=schemas.NftCreate)
  195. @router.post("/title")
  196. def read_user_by_title(
  197. *,
  198. db: Session = Depends(deps.get_db),
  199. title: str,
  200. skip: int = 0,
  201. limit: int = 100,
  202. current_user: models.users = Depends(deps.get_current_active_user),
  203. ) -> Any:
  204. """
  205. Get item by title.
  206. """
  207. nft = crud.nft.get_user_by_title(db=db, title=title, skip=skip, limit=limit)
  208. if not nft:
  209. raise HTTPException(status_code=404, detail="Item not found")
  210. if not crud.user.is_superuser(current_user) and (nft.userid != current_user.userid):
  211. raise HTTPException(status_code=400, detail="Not enough permissions")
  212. return nft
  213. @router.delete("/{id}", response_model=schemas.NftCreate)
  214. def delete_item(
  215. *,
  216. db: Session = Depends(deps.get_db),
  217. id: int,
  218. current_user: models.users = Depends(deps.get_current_active_user),
  219. ) -> Any:
  220. """
  221. Delete an item.
  222. """
  223. nft = crud.nft.get(db=db, id=id)
  224. if not nft:
  225. raise HTTPException(status_code=404, detail="Item not found")
  226. if not crud.user.is_superuser(current_user) and (nft.userid != current_user.userid):
  227. raise HTTPException(status_code=400, detail="Not enough permissions")
  228. nft = crud.nft.remove(db=db, id=id)
  229. return nft