Pārlūkot izejas kodu

linebot rewrite

conradlan 3 gadi atpakaļ
vecāks
revīzija
be72a30895

+ 1 - 1
.vscode/launch.json

@@ -14,7 +14,7 @@
                 "--host",
                 "0.0.0.0",
                 "--port",
-                "8751",
+                "8750",
                 "--ssl-keyfile=/home/conrad/privkey.pem",
                 "--ssl-certfile=/home/conrad/fullchain.pem",
                 "--reload"

+ 1 - 1
app/api/api_v1/api.py

@@ -7,5 +7,5 @@ api_router.include_router(login.router, tags=["login"])
 api_router.include_router(users.router, prefix="/user", tags=["user"])
 api_router.include_router(nft.router, prefix="/nft", tags=["nft"])
 api_router.include_router(line.router, prefix="/line", tags=["line"])
-api_router.include_router(joyso.router, prefix="/joyso", tags=["joyso"])
+# api_router.include_router(joyso.router, prefix="/joyso", tags=["joyso"])
 api_router.include_router(linepay.router, prefix="/linepay", tags=["linepay"])

+ 26 - 5
app/api/api_v1/endpoints/line.py

@@ -5,10 +5,12 @@ from linebot.models import (
     MessageEvent, TextMessage, TextSendMessage, FollowEvent,
     TemplateSendMessage, ButtonsTemplate, URITemplateAction,
 )
+from linebot.exceptions import LineBotApiError
 import dataset
 import requests
 import json
 import qrcode
+from fastapi.encoders import jsonable_encoder
 from random import randrange
 from app.schemas import line
 from app.core.config import settings
@@ -44,8 +46,11 @@ class LineRouter(APIRoute):
 
 
 router = APIRouter(route_class=LineRouter)
-
-
+baseUrl = "https://nft-api-staging.joyso.io/api/v1/"
+headers = {
+    'Authorization':
+        'Basic %s' % 'bmZ0OmMxOTEzOWMzYjM3YjdjZWU3ZmY3OTFiZGU3NzdjZWNl'
+}
 
 # callback event
 @router.post("/callback")
@@ -84,10 +89,15 @@ def handle_follow(event):
             'Authorization':
             'Basic bmZ0OmMxOTEzOWMzYjM3YjdjZWU3ZmY3OTFiZGU3NzdjZWNl'
         }
-
+        try:
+            profile = settings.line_bot_api.get_profile(real_user_id)
+            print(profile['displayName'])
+        except LineBotApiError as e:
+            pass
         # setup for temp use (unique id)
         rand_num = str(randrange(99999))
-        user_id = event.source.user_id + rand_num
+        # user_id = event.source.user_id + rand_num
+        user_id = event.source.user_id
         data = 'uid=' + user_id
         r = requests.post(url=url, headers=headers, data=data)
 
@@ -205,8 +215,19 @@ def push_text(user, message):
 
 # nft collection api
 @router.get("/collection/{userid}")
-def collection(userid):
+def collection(userid, db: Session = Depends(deps.get_db)):
     # db connect
+    url = 'accounts/' + str(userid)  + '/nft_balances'
+    r = requests.get(url=baseUrl + url, headers=headers)
+    nft_all = {}
+    outcome = r.json()['nft_balances']
+    for i in range(len(outcome)):
+        nft_ = crud.nft.get_by_uid(db, uid=outcome[i]['uid'])
+        if nft_:
+            nft_all[i] = jsonable_encoder(nft_)
+            nft_all[i]['amount'] = outcome[i]['amount']
+
+    return nft_all
     db = dataset.connect(
         'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
     )

+ 60 - 10
app/api/api_v1/endpoints/nft.py

@@ -1,4 +1,7 @@
 from typing import Any, Optional
+import requests
+import uuid
+import json
 
 from fastapi import APIRouter, Depends, HTTPException, File, UploadFile, Form
 from fastapi.encoders import jsonable_encoder
@@ -10,7 +13,11 @@ from app.api import deps
 from uuid import uuid4
 
 router = APIRouter()
-
+baseUrl = "https://nft-api-staging.joyso.io/api/v1/"
+headers = {
+  'Authorization': 'Basic bmZ0OmMxOTEzOWMzYjM3YjdjZWU3ZmY3OTFiZGU3NzdjZWNl',
+  'Content-Type': 'application/json'
+}
 
 @router.get("/", response_model=list[schemas.NftPrint])
 # @router.get("/")
@@ -38,17 +45,35 @@ async def create_item(
     db: Session = Depends(deps.get_db),
     # item_in: schemas.NftCreate,
     hash: Optional[str] = Form(None),
-    userid: Optional[str] = Form(None),
-    title: Optional[str] = Form(None),
+    title: str = Form(...),
     context: Optional[str] = Form(None),
     is_active: Optional[bool] = Form(True),
     catagory: Optional[str] = Form(None),
     image: UploadFile = File(...),
+    uid: int = Form(...),
+    address: str = Form(...),
+    amount: int = Form(...),
     current_user: models.users = Depends(deps.get_current_active_user),
 ) -> Any:
     """
     Create new item.
     """
+    path = "erc1155"
+    txid = str(uuid.uuid4())
+
+    payload = json.dumps({
+                "txid": txid,
+                "to": address,
+                "uid": uid,
+                "amount": amount
+            })
+    r = requests.post(
+        baseUrl + path,
+        headers=headers,
+        data=payload
+    )
+    if r.status_code != 200:
+        raise HTTPException(status_code=400, detail="not correct mint informaiton")
     if image.content_type.split('/')[0] != 'image':
         raise HTTPException(status_code=415,
                             detail='content type error! Please upload valid image type')
@@ -56,6 +81,7 @@ async def create_item(
     with open(settings.IMG_PATH + filename, 'wb+') as f:
         f.write(image.file.read())
         f.close()
+    userid = crud.user.get_by_address(db, address = address)
     item_in = schemas.NftCreate
     item_in.hash = hash
     item_in.userid = userid
@@ -64,6 +90,7 @@ async def create_item(
     item_in.is_active = is_active
     item_in.category = catagory
     item_in.imgurl = settings.IMG_HOST + filename
+    item_in.uid = uid
     nft = crud.nft.create_with_owner(
         db=db, obj_in=item_in, owner_id=item_in.userid)
     return nft
@@ -74,7 +101,7 @@ def update_item(
     *,
     db: Session = Depends(deps.get_db),
     title: str,
-    title_new: Optional[str] = Form(None),
+    id: int,
     context: Optional[str] = Form(None),
     is_active: Optional[bool] = Form(True),
     catagory: Optional[str] = Form(None),
@@ -82,15 +109,15 @@ def update_item(
     current_user: models.users = Depends(deps.get_current_active_user),
 ) -> Any:
     """
-    Update bulk items.
+    Update items.
     """
-    nft = crud.nft.get_by_title(db=db, title=title)
+    nft = crud.nft.get(db=db, id = id)
     if not nft:
         raise HTTPException(status_code=404, detail="Item not found")
     # if not crud.user.is_superuser(current_user) and (nft.userid != current_user.userid):
     if not crud.user.is_superuser(current_user):
         raise HTTPException(status_code=400, detail="Not enough permissions")
-    item_in = schemas.NftBulkUpdate(**jsonable_encoder(nft[0]))
+    item_in = schemas.NftBulkUpdate(**jsonable_encoder(nft))
     if image:
         if image.content_type.split('/')[0] != 'image':
             raise HTTPException(status_code=415,
@@ -100,14 +127,15 @@ def update_item(
             f.write(image.file.read())
             f.close()
         item_in.imgurl = settings.IMG_HOST + filename
-    if title_new:
-        item_in.title = title_new
+    if title:
+        item_in.title = title
     if context:
         item_in.context = context
     if is_active:
         item_in.is_active = is_active
     if catagory:
         item_in.category = catagory
+
     
     nft = crud.nft.update_bulk_title(db=db, db_obj_list=nft, obj_in=item_in)
     return nft
@@ -117,8 +145,12 @@ def update_item(
 def update_item(
     *,
     db: Session = Depends(deps.get_db),
+    title: Optional[str] = Form(None),
     id: int,
-    item_in: schemas.NftUpdate,
+    context: Optional[str] = Form(None),
+    is_active: Optional[bool] = Form(True),
+    catagory: Optional[str] = Form(None),
+    image: Optional[UploadFile] = File(None),
     current_user: models.users = Depends(deps.get_current_active_user),
 ) -> Any:
     """
@@ -129,6 +161,24 @@ def update_item(
         raise HTTPException(status_code=404, detail="Item not found")
     if not crud.user.is_superuser(current_user) and (nft.userid != current_user.userid):
         raise HTTPException(status_code=400, detail="Not enough permissions")
+    item_in = schemas.NftUpdate(**jsonable_encoder(nft))
+    if image:
+        if image.content_type.split('/')[0] != 'image':
+            raise HTTPException(status_code=415,
+                                detail='content type error! Please upload valid image type')
+        filename = str(uuid4()) + '.' + image.content_type.split('/')[1]
+        with open(settings.IMG_PATH + filename, 'wb+') as f:
+            f.write(image.file.read())
+            f.close()
+        item_in.imgurl = settings.IMG_HOST + filename
+    if title:
+        item_in.title = title
+    if context:
+        item_in.context = context
+    if is_active:
+        item_in.is_active = is_active
+    if catagory:
+        item_in.category = catagory
     nft = crud.nft.update(db=db, db_obj=nft, obj_in=item_in)
     return nft
 

+ 8 - 1
app/crud/crud_nft.py

@@ -20,6 +20,11 @@ UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
 
 
 class CRUDNft(CRUDBase[Nft, NftBase, NftCreate]):
+    def get_by_uid(
+        self, db: Session, *, uid: int
+    ) -> list[Nft]:
+        return db.query(Nft).filter(Nft.uid == uid).first()
+
     def get_by_title(
         self, db: Session, *, title: str
     ) -> list[Nft]:
@@ -57,7 +62,9 @@ class CRUDNft(CRUDBase[Nft, NftBase, NftCreate]):
             title=obj_in.title,
             context=obj_in.context,
             is_active=obj_in.is_active,
-            category=obj_in.category
+            category=obj_in.category,
+            uid = obj_in.uid
+            
         )
         db.add(db_obj)
         db.commit()

+ 4 - 0
app/crud/crud_user.py

@@ -1,3 +1,4 @@
+from audioop import add
 from typing import Any, Dict, Optional, Union
 
 from sqlalchemy.orm import Session
@@ -11,6 +12,9 @@ from app.schemas.user import UserBase, UserCreate, UserUpdate
 class CRUDUser(CRUDBase[users, UserBase, UserCreate]):
     def get_by_email(self, db: Session, *, email: str) -> Optional[users]:
         return db.query(users).filter(users.email == email).first()
+    
+    def get_by_address(selft, db: Session, *, address: str) -> Optional[str]:
+        return db.query(users).filter(users.useraddress == address).first().__dict__['userid']
 
     def get_by_account(self, db: Session, *, account: str) -> Optional[users]:
         return db.query(users).filter(users.account == account).first()

+ 1 - 0
app/models/nft.py

@@ -12,3 +12,4 @@ class Nft(Base):
     context = Column(String(200))
     is_active = Column(Boolean(), default=True)
     category = Column(String(100))
+    uid = Column(String(200))

+ 6 - 2
app/schemas/nft.py

@@ -1,3 +1,4 @@
+from optparse import Option
 from typing import Optional
 from pydantic import BaseModel
 
@@ -11,7 +12,8 @@ class NftBase(BaseModel):
     context: Optional[str] = None
     is_active: Optional[bool] = True
     category: Optional[str] = None
-    # id: int
+    uid: Optional[str] = None
+    id: int
 
     class Config:
         orm_mode = True
@@ -34,8 +36,10 @@ class NftUpdate(NftBase):
 
 
 class NftBulkUpdate(BaseModel):
+    hash: Optional[str] = None
     imgurl: Optional[str] = None
+    userid: Optional[str] = None
     title: str
     context: Optional[str] = None
     is_active: Optional[bool] = True
-    category: Optional[str] = None
+    category: Optional[str] = None

+ 44 - 0
script/refresh_address.py

@@ -0,0 +1,44 @@
+import requests
+import pymysql
+
+# from app import crud
+# from app.api import deps
+pymysql.install_as_MySQLdb()
+import dataset
+import requests
+import json
+import qrcode
+
+baseUrl = "https://nft-api-staging.joyso.io/api/v1/"
+headers = {
+    'Authorization':
+        'Basic %s' % 'bmZ0OmMxOTEzOWMzYjM3YjdjZWU3ZmY3OTFiZGU3NzdjZWNl'
+}
+db = dataset.connect(
+        'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
+    )
+table = db.query('select * from users')
+# result1 = table.find_one(userid=real_user_id)
+for i in table:
+    if i.get('userid'):
+        user_id = i.get('userid')
+        data = 'uid=' + user_id 
+        r = requests.post(url=baseUrl + 'accounts', headers=headers, data=data)
+
+        # extract the account address
+        dict_str = json.loads(r.text)
+        user_account = dict_str['account']
+        user_address = user_account['address']
+
+        # generate qr code from user id
+        qr = qrcode.QRCode(
+            version=1,
+            box_size=10,
+            border=5)
+        qr.add_data(user_address)
+        qr.make(fit=True)
+        img_qr = qr.make_image(fill='black', back_color='white')
+        filename = "/var/www/ArkCard-Linebot/ArkCard-web/qrcode/" + \
+                    user_id + '.png'
+        img_qr.save(filename)
+        db.query('update users set useraddress=\"' + str(user_address) + '\" where id=' + str(i.get('id')))