conradlan %!s(int64=2) %!d(string=hai) anos
pai
achega
dfecee1077

+ 59 - 58
app/api/api_v1/endpoints/line.py

@@ -1,3 +1,4 @@
+import uuid
 import fastapi
 import pymysql
 pymysql.install_as_MySQLdb()
@@ -23,10 +24,16 @@ from typing import Callable, List
 from uuid import uuid4
 from sqlalchemy.orm import Session
 from datetime import datetime
+import httpx
 
 import pymysql
 pymysql.install_as_MySQLdb()
 
+
+async def request_get(url, headers):
+    async with httpx.AsyncClient() as client:
+       return await client.get(url, headers = headers)
+
 class LineRouter(APIRoute):
     def get_route_handler(self) -> Callable:
         original_route_handler = super().get_route_handler()
@@ -215,17 +222,20 @@ def push_text(user, message):
 
 # nft collection api
 @router.get("/collection/{userid}")
-def collection(userid, db: Session = Depends(deps.get_db)):
+async 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)
+    r = await request_get(baseUrl + url, headers)
     nft_all = {}
     outcome = r.json()['nft_balances']
+    ii = 0
     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']
+            nft_all[ii] = jsonable_encoder(nft_)
+            nft_all[ii]['amount'] = outcome[i]['amount']
+            ii+=1
 
     return nft_all
     db = dataset.connect(
@@ -283,66 +293,50 @@ def receive(userid):
 
 # send handler
 @router.post("/send")
-async def send(userModel: line.TransactionNft):
-    # db connect
+async def send(
+    userid: str,
+    to: str,
+    nftuid: int,
+    amount: int,
+    db_: Session = Depends(deps.get_db),
+    ):
+    to_userid = crud.user.get_by_address(db_, address=to)
     db = dataset.connect(
         'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
     )
-    table = db['users']
-    table2 = db['nft']
-    table3 = db['nftdrops']
     transaction_table = db['transaction']
-
-    # input and find userid
-    nftid = userModel.nftid
-    address = userModel.address
-    result = table.find_one(useraddress=address)
-
-    # first confirm if the user exist
-    if not result:
-        db.close()
-        return {'msg': 'user address not found'}
-    else:
-        userid = result['userid']
-
-    # update nft owner
-    if table3.find_one(nftid=nftid):
-        data = dict(nftid=nftid, userid=userid)
-        table3.update(data, ['nftid'])
-
-        # push訊息
-        result3 = table2.find_one(id=nftid)
-        title = result3['title']
-        pre_own = result3['userid']
-        message = "您的NFT : " + title + ", 已劃轉成功!"
+    txid = str(uuid.uuid4())
+    payload = {
+        "txid": txid,
+        # "contract": "0xe0d9102c88b09369df99b1c126fb2eebc13804f8",
+        "contract": "0x8d5a7d8ca33fd9edca4b871cf5fb2a9cb5091505",
+        "to": to,
+        "uid": nftuid,
+        "value": amount
+    }
+    url = "https://nft-api-staging.joyso.io/api/v1/accounts/Uba38e8903d243cd1bd15d5c27cc6653e/erc1155/safe_transfer_to"
+    # r = requests.post(baseUrl + "accounts/" + userid+ "/erc1155/safe_transfer_to" , headers=headers, data=payload)
+    r = requests.post(baseUrl + "accounts/" + userid+ "/erc1155/transfer_by_admin" , headers=headers, data=payload)
+    # r = requests.post(url , headers=headers, data=payload)
+    if r.status_code == 200:
+        title = crud.nft.get_by_uid(db_, uid=nftuid).__dict__['title']
+        message = "您的NFT : " + title + ", 已劃轉!"
         push_text(userid, message)
-        transaction_table.insert({'tfrom':pre_own,'to':userid,'nft':nftid,'transaction_at':datetime.now()})
-        db.close()
-    elif table2.find_one(id=nftid):
-        result3 = table2.find_one(id=nftid)
-
-        pre_own = result3['userid']
-        data = dict(id=nftid, userid=userid)
-        table2.update(data, ['id'])
-
-        # push訊息
+        transaction_table.insert({'txid':txid,'tfrom':userid,'to':to_userid,'nft':nftuid,'transaction_at':datetime.now()})
+        from_name = settings.line_bot_api.get_profile(userid).as_json_dict()['displayName']
         try:
-            transaction_table.insert({'tfrom':pre_own,'to':userid,'nft':nftid,'transaction_at':datetime.now()})
-            title = result3['title']
-            fr = "您的NFT : " + title + ", 已發送成功!"
-            to = "您的NFT : "+title+", 已收到!"
-            push_text(userid, to)
-            push_text(pre_own, fr)
+            to_name = settings.line_bot_api.get_profile(to_userid).as_json_dict()['displayName']
         except:
-            return "找不到原使用者"
-
-        db.close()
+            to_name = "外部"
+        fr = "您給"+ to_name +"的NFT(" + title + "), 已發送成功!"
+        to_message = from_name +"給您的NFT("+title+"), 已收到!"
+        push_text(userid, fr)
+        push_text(to_userid, to_message)
     else:
         # push訊息
         message = "交易失敗!如果有疑問,請洽網站的服務信箱!"
         push_text(userid, message)
-        db.close()
-        return {'msg': 'nft not found'}
+        return {'msg': r.content}
     return {'msg': 'OK'}
 
 
@@ -354,8 +348,8 @@ def shop(userid):
         'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
     )
 
-    sql = 'SELECT DISTINCT(title), id, imgurl, userid FROM arkcard.nft  ' \
-          'WHERE id<1001 and userid IS NULL GROUP BY title LIMIT 5'
+    sql = 'SELECT title, id, imgurl, userid FROM arkcard.nft  ' \
+          'GROUP BY uid'
     result = db.query(sql)
     rows = {}
     i = 0
@@ -443,7 +437,11 @@ async def nftdrops(userModel: line.NftDrops):
 
 
 @router.get("/transactions")
-def transactions(skip: int = 0, limit: int = 100):
+def transactions(
+    skip: int = 0,
+    limit: int = 100,
+    current_user: models.users = Depends(deps.get_current_active_superuser),
+    ):
     # db connect
     db = dataset.connect(
         'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
@@ -454,8 +452,11 @@ def transactions(skip: int = 0, limit: int = 100):
     result = db.query(sql)
     rows = []
     for row in result:
-        nft_item = nft_table.find_one(id=row['nft'])
-        row['nft'] = nft_item['title']
+        nft_item = nft_table.find_one(uid=row['nft'])
+        try:
+            row['nft'] = nft_item['title']
+        except:
+            pass
         rows.append(row)
     db.close()
 

+ 3 - 1
app/api/api_v1/endpoints/linepay.py

@@ -60,7 +60,8 @@ async def pay_request(
 
         ],
         "redirectUrls": {
-            "confirmUrl": LINE_PAY_REQEST_BASE_URL + "/confirm/"
+            # "confirmUrl": LINE_PAY_REQEST_BASE_URL + "/confirm/"
+            "confirmUrl": "https://ark.cards/collect.html"
             # "cancelUrl": LINE_PAY_REQEST_BASE_URL + "/cancel/"
         }
     }
@@ -81,6 +82,7 @@ async def pay_request(
     )
     payment = crud.payment.create(db=db, obj_in=payment_obj)
     # return response
+    return {"web":response["info"]["paymentUrl"]['web'], "app":response["info"]["paymentUrl"]['web']}
     return response["info"]["paymentUrl"]
 
 

+ 8 - 2
app/api/api_v1/endpoints/nft.py

@@ -11,6 +11,10 @@ from app import crud, models, schemas
 from app.core.config import settings
 from app.api import deps
 from uuid import uuid4
+from linebot.models import (
+    MessageEvent, TextMessage, TextSendMessage, FollowEvent,
+    TemplateSendMessage, ButtonsTemplate, URITemplateAction,
+)
 
 router = APIRouter()
 baseUrl = "https://nft-api-staging.joyso.io/api/v1/"
@@ -93,6 +97,9 @@ async def create_item(
     item_in.uid = uid
     nft = crud.nft.create_with_owner(
         db=db, obj_in=item_in, owner_id=item_in.userid)
+    message = "您mint的 nft(" + title + ") 已經為您存到錢包"
+    settings.line_bot_api.push_message(
+        userid, TextSendMessage(text=message))
     return nft
 
 
@@ -175,8 +182,7 @@ def update_item(
         item_in.title = title
     if context:
         item_in.context = context
-    if is_active:
-        item_in.is_active = 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)

+ 5 - 5
app/api/api_v1/endpoints/users.py

@@ -68,7 +68,7 @@ def update_user_me(
     return user
 
 
-@router.get("/me")
+@router.get("/me", response_model=schemas.UserBase)
 def read_user_me(
     db: Session = Depends(deps.get_db),
     current_user: models.users = Depends(deps.get_current_active_user),
@@ -76,7 +76,7 @@ def read_user_me(
     """
     Get current user.
     """
-    return current_user
+    return current_user.__dict__
 
 
 @router.post("/open")
@@ -112,7 +112,7 @@ def create_user_open(
     return user
 
 
-@router.get("/{user_id}")
+@router.get("/{user_id}", response_model=schemas.UserBase)
 def read_user_by_id(
     user_id: int,
     current_user: models.users = Depends(deps.get_current_active_user),
@@ -123,12 +123,12 @@ def read_user_by_id(
     """
     user = crud.user.get(db, id=user_id)
     if user == current_user:
-        return user
+        return user.__dict__
     if not crud.user.is_superuser(current_user):
         raise HTTPException(
             status_code=400, detail="The user doesn't have enough privileges"
         )
-    return user
+    return user.__dict__
 
 
 @router.put("/{user_id}")

+ 1 - 1
app/crud/crud_nft.py

@@ -23,7 +23,7 @@ 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()
+        return db.query(Nft).filter(Nft.uid == uid).filter(Nft.is_active == True).first()
 
     def get_by_title(
         self, db: Session, *, title: str

+ 8 - 4
app/crud/crud_user.py

@@ -16,6 +16,9 @@ class CRUDUser(CRUDBase[users, UserBase, UserCreate]):
     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_lineid(selft, db: Session, *, lineid: str) -> Optional[str]:
+        return db.query(users).filter(users.userid == lineid).first()
+
     def get_by_account(self, db: Session, *, account: str) -> Optional[users]:
         return db.query(users).filter(users.account == account).first()
 
@@ -42,10 +45,11 @@ class CRUDUser(CRUDBase[users, UserBase, UserCreate]):
             update_data = obj_in
         else:
             update_data = obj_in.dict(exclude_unset=True)
-        if update_data["password"]:
-            hashed_password = get_password_hash(update_data["password"])
-            del update_data["password"]
-            update_data["password"] = hashed_password
+            # update_data = obj_in.dict()
+        if "hashed_password" in update_data:
+            hashed_password = get_password_hash(update_data["hashed_password"])
+            del update_data["hashed_password"]
+            update_data["hashed_password"] = hashed_password
         return super().update(db, db_obj=db_obj, obj_in=update_data)
 
     def authenticate(

+ 1 - 1
app/models/user.py

@@ -14,4 +14,4 @@ class users(Base):
     is_active = Column(Boolean(), default=True)
     is_superuser = Column(Boolean(), default=False)
     created_at = Column(DateTime, default=datetime.datetime.now, nullable=False)
-    updated_at = Column(DateTime, default=datetime.datetime.now, nullable=False)
+    updated_at = Column(DateTime, default=datetime.datetime.now, nullable=False, onupdate=datetime.datetime.now)

+ 3 - 2
app/schemas/user.py

@@ -1,3 +1,4 @@
+from lib2to3.pgen2.token import OP
 from typing import Optional
 from pydantic import BaseModel, EmailStr
 
@@ -17,8 +18,8 @@ class UserCreate(UserBase):
     hashed_password: str
 
 
-class UserUpdate(UserCreate):
-    pass
+class UserUpdate(UserBase):
+    hashed_password: Optional[str] = None
 
 
 class User(UserCreate):

+ 30 - 0
test.py

@@ -0,0 +1,30 @@
+import os
+
+
+
+def balancedSum(arr):
+    # Write your code here
+    length = arr[0]
+    target = arr[1:]
+    target.sort()
+    for i in range(length):
+        if(target[:i] == target[i:]):
+            return i
+        
+
+if __name__ == '__main__':
+    # fptr = open(os.environ['OUTPUT_PATH'], 'w')
+
+    arr_count = int(input().strip())
+
+    arr = []
+
+    for _ in range(arr_count):
+        arr_item = int(input().strip())
+        arr.append(arr_item)
+
+    result = balancedSum(arr)
+
+    fptr.write(str(result) + '\n')
+
+    fptr.close()