Browse Source

log table

ming 2 years ago
parent
commit
f5f54933c6
4 changed files with 80 additions and 47 deletions
  1. 45 6
      app/api/api_v1/endpoints/line.py
  2. 2 1
      app/api/api_v1/endpoints/nft.py
  3. 3 1
      app/api/api_v1/endpoints/users.py
  4. 30 39
      app/main.py

+ 45 - 6
app/api/api_v1/endpoints/line.py

@@ -1,6 +1,7 @@
 import uuid
 import fastapi
 import pymysql
+import base64
 pymysql.install_as_MySQLdb()
 from linebot.models import (
     MessageEvent, TextMessage, TextSendMessage, FollowEvent,
@@ -18,6 +19,7 @@ from app.core.config import settings
 import datetime as dt
 from fastapi import APIRouter, FastAPI, Request, Response, Body,Depends
 from fastapi.routing import APIRoute
+from starlette.types import Message
 from app.api import deps
 from app import crud, models, schemas
 from typing import Callable, List
@@ -29,6 +31,15 @@ import httpx
 import pymysql
 pymysql.install_as_MySQLdb()
 
+async def set_body(request: Request, body: bytes):
+    async def receive() -> Message:
+        return {"type": "http.request", "body": body}
+    request._receive = receive
+ 
+async def get_body(request: Request) -> bytes:
+    body = await request.body()
+    await set_body(request, body)
+    return body
 
 async def request_get(url, headers):
     async with httpx.AsyncClient() as client:
@@ -39,14 +50,42 @@ class LineRouter(APIRoute):
         original_route_handler = super().get_route_handler()
 
         async def custom_route_handler(request: Request) -> Response:
+            db = dataset.connect(
+                'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
+                )
+            log_table = db['log']
             try:
-                the_body = await request.json()
+                userid = int(json.loads(base64.b64decode(request.headers['authorization'][7:].split('.')[1]).decode('utf-8'))['sub'])
             except:
-                the_body = ""
+                if( "/api/v1/line/collection/" or "/api/v1/line/receive/" or "/api/v1/line/shop/" or "/api/v1/line/send" in request.url.path):
+                    lineid = request.url.path.split("/")[-1]
+                    
+                    sql = 'SELECT id, userid FROM users where userid =\'' + lineid + '\''
+                    try:
+                        userid = int(db.query(sql).next()['id'])
+                    except:
+                        userid = -1
+            
+            await set_body(request, await request.body())
+            body = await get_body(request)
+            body = str(body).replace("\"","\'")
+            body = str(body).split('Content-Type: image/')[0]
+            ip = request.client.host 
+            port = str(request.client.port)
+            query = request.url.query
+            headers = str(request.headers).replace("\"","\'")
+            method = request.method
+            
             response: Response = await original_route_handler(request)
-            print(f"request payload: {the_body}")
-            # print(f"route response: {response.body}")
-            print(f"route response headers: {response.headers}")
+            response_body = str(response.body).replace("\"","\'")
+            log_table.insert(
+                dict(
+                    create_time=str(datetime.now()), url_path=request.url.path,
+                    headers=headers, request=body, userid=userid,
+                    ip=ip+":"+port, method=method, response=response_body,
+                    request_query=query
+                    )
+                )
             return response
 
         return custom_route_handler
@@ -294,7 +333,7 @@ def receive(userid):
 
 
 # send handler
-@router.post("/send")
+@router.get("/send/{userid}")
 async def send(
     userid: str,
     to: str,

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

@@ -15,8 +15,9 @@ from linebot.models import (
     MessageEvent, TextMessage, TextSendMessage, FollowEvent,
     TemplateSendMessage, ButtonsTemplate, URITemplateAction,
 )
+from app.api.api_v1.endpoints.line import LineRouter
 
-router = APIRouter()
+router = APIRouter(route_class=LineRouter)
 baseUrl = "https://nft-api-staging.joyso.io/api/v1/"
 headers = {
   'Authorization': 'Basic bmZ0OmMxOTEzOWMzYjM3YjdjZWU3ZmY3OTFiZGU3NzdjZWNl',

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

@@ -1,3 +1,4 @@
+import imp
 from typing import Any, List
 
 from fastapi import APIRouter, Body, Depends, HTTPException
@@ -8,8 +9,9 @@ from sqlalchemy.orm import Session
 from app import crud, models, schemas
 from app.api import deps
 from app.core.config import settings
+from app.api.api_v1.endpoints.line import LineRouter
 
-router = APIRouter()
+router = APIRouter(route_class=LineRouter)
 
 
 @router.get("/")

+ 30 - 39
app/main.py

@@ -30,48 +30,39 @@ if settings.BACKEND_CORS_ORIGINS:
         allow_headers=["*"],
     )
 
-async def set_body(request: Request, body: bytes):
-    async def receive() -> Message:
-        return {"type": "http.request", "body": body}
-    request._receive = receive
+# async def set_body(request: Request, body: bytes):
+#     async def receive() -> Message:
+#         return {"type": "http.request", "body": body}
+#     request._receive = receive
  
-async def get_body(request: Request) -> bytes:
-    body = await request.body()
-    await set_body(request, body)
-    return body
+# async def get_body(request: Request) -> bytes:
+#     body = await request.body()
+#     await set_body(request, body)
+#     return body
  
-@app.middleware("http")
-async def app_entry(request: Request, call_next,
-):
-    db = dataset.connect(
-                'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
-                )
-    await set_body(request, await request.body())
-    # body = await get_body(request)
-    # body = str(body).replace("\"","\'")
-    headers = str(request.headers).replace("\"","\'")
-    try:
-        userid = int(json.loads(base64.b64decode(request.headers['authorization'][7:].split('.')[1]).decode('utf-8'))['sub'])
-    except:
-        if( "/api/v1/line/collection/" or "/api/v1/line/receive/" or "/api/v1/line/shop/" in request.url.path):
-            lineid = request.url.path.split("/")[-1]
-            
-            sql = 'SELECT id, userid FROM users where userid =\'' + lineid + '\''
-            try:
-                userid = int(db.query(sql).next()['id'])
-            except:
-                userid = -1
-    db.query('Insert into log (create_time, url_path, headers, userid) VALUE (\'' + str(datetime.now()) + '\' ,\'' + request.url.path + '\' , \"' + headers + '\" , '+ str(userid) + ')')
-    response = await call_next(request)
-    return response
-    # response = await call_next(request)
-
-    
-    # print(request.url.path)
-    # print(request.headers)
+# @app.middleware("http")
+# async def app_entry(request: Request, call_next,
+# ):
+#     db = dataset.connect(
+#                 'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
+#                 )
+#     await set_body(request, await request.body())
 
-
-    # return response
+#     headers = str(request.headers).replace("\"","\'")
+#     try:
+#         userid = int(json.loads(base64.b64decode(request.headers['authorization'][7:].split('.')[1]).decode('utf-8'))['sub'])
+#     except:
+#         if( "/api/v1/line/collection/" or "/api/v1/line/receive/" or "/api/v1/line/shop/" in request.url.path):
+#             lineid = request.url.path.split("/")[-1]
+            
+#             sql = 'SELECT id, userid FROM users where userid =\'' + lineid + '\''
+#             try:
+#                 userid = int(db.query(sql).next()['id'])
+#             except:
+#                 userid = -1
+#     db.query('Insert into log (create_time, url_path, headers, userid) VALUE (\'' + str(datetime.now()) + '\' ,\'' + request.url.path + '\' , \"' + headers + '\" , '+ str(userid) + ')')
+#     response = await call_next(request)
+#     return response
 
 
 app.include_router(api_router, prefix=settings.API_V1_STR)