Spaces:
Running
on
Zero
Running
on
Zero
test
Browse files- mysite/webhook/webhook.py +0 -114
mysite/webhook/webhook.py
DELETED
@@ -1,114 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import subprocess
|
3 |
-
import logging
|
4 |
-
from fastapi import FastAPI, Request, HTTPException
|
5 |
-
import requests
|
6 |
-
import json
|
7 |
-
from datetime import datetime
|
8 |
-
import importlib
|
9 |
-
import os
|
10 |
-
import pkgutil
|
11 |
-
from mysite.libs.utilities import validate_signature, no_process_file
|
12 |
-
from mysite.database.database import ride,create_ride
|
13 |
-
|
14 |
-
logger = logging.getLogger(__name__)
|
15 |
-
|
16 |
-
def include_routers(app):
|
17 |
-
package_dir = "/home/user/app/routers"
|
18 |
-
if not os.path.exists(package_dir):
|
19 |
-
logger.error(f"Package directory {package_dir} does not exist.")
|
20 |
-
return
|
21 |
-
|
22 |
-
for module_info in pkgutil.iter_modules([package_dir]):
|
23 |
-
try:
|
24 |
-
if module_info.ispkg:
|
25 |
-
sub_package_dir = os.path.join(package_dir, module_info.name)
|
26 |
-
for sub_module_info in pkgutil.iter_modules([sub_package_dir]):
|
27 |
-
module_name = (
|
28 |
-
f"routers.{module_info.name}.{sub_module_info.name}"
|
29 |
-
if sub_module_info.ispkg
|
30 |
-
else f"routers.{module_info.name}.{sub_module_info.name}"
|
31 |
-
)
|
32 |
-
module = importlib.import_module(module_name)
|
33 |
-
if hasattr(module, "router"):
|
34 |
-
app.include_router(module.router)
|
35 |
-
else:
|
36 |
-
module_name = f"routers.{module_info.name}"
|
37 |
-
module = importlib.import_module(module_name)
|
38 |
-
if hasattr(module, "router"):
|
39 |
-
app.include_router(module.router)
|
40 |
-
except ModuleNotFoundError as e:
|
41 |
-
logger.error(f"Module not found: {e}")
|
42 |
-
except Exception as e:
|
43 |
-
logger.error(f"An error occurred: {e}")
|
44 |
-
|
45 |
-
|
46 |
-
def setup_webhook_routes(app: FastAPI):
|
47 |
-
from polls.routers import register_routers
|
48 |
-
|
49 |
-
register_routers(app)
|
50 |
-
@app.post("/webhook")
|
51 |
-
async def webhook(request: Request):
|
52 |
-
logger.info("[Start] ====== LINE webhook ======")
|
53 |
-
try:
|
54 |
-
body = await request.body()
|
55 |
-
received_headers = dict(request.headers)
|
56 |
-
body_str = body.decode("utf-8")
|
57 |
-
logger.info("Received Body: %s", body_str)
|
58 |
-
body_json = json.loads(body_str)
|
59 |
-
events = body_json.get("events", [])
|
60 |
-
|
61 |
-
for event in events:
|
62 |
-
if event["type"] == "message" and event["message"]["type"] == "text":
|
63 |
-
user_id = event["source"]["userId"]
|
64 |
-
text = event["message"]["text"]
|
65 |
-
logger.info("------------------------------------------")
|
66 |
-
logger.info(f"User ID: {user_id}, Text: {text}")
|
67 |
-
no_process_file(text, "ai")
|
68 |
-
|
69 |
-
|
70 |
-
for event in events:
|
71 |
-
if event["type"] == "message" and event["message"]["type"] == "text":
|
72 |
-
user_id = event["source"]["userId"]
|
73 |
-
text = event["message"]["text"]
|
74 |
-
logger.info(event)
|
75 |
-
logger.info(f"User ID: {user_id}, Text: {text}")
|
76 |
-
now = datetime.now().strftime("%Y%m%d%H%M%S")
|
77 |
-
title = text[:10]
|
78 |
-
user_id_with_timestamp = f"{now}_{title}_{user_id}"
|
79 |
-
no_process_file(text, user_id_with_timestamp)
|
80 |
-
|
81 |
-
logger.info("Received Headers: %s", received_headers)
|
82 |
-
logger.info("Received Body: %s", body.decode("utf-8"))
|
83 |
-
|
84 |
-
line_signature = received_headers.get("x-line-signature")
|
85 |
-
if not line_signature:
|
86 |
-
raise HTTPException(status_code=400, detail="X-Line-Signature header is missing.")
|
87 |
-
|
88 |
-
if not validate_signature(body.decode("utf-8"), line_signature, os.getenv("ChannelSecret")):
|
89 |
-
raise HTTPException(status_code=400, detail="Invalid signature.")
|
90 |
-
|
91 |
-
if not os.getenv("WEBHOOK_URL") or not os.getenv("WEBHOOK_URL").startswith("https://"):
|
92 |
-
raise HTTPException(status_code=400, detail="Invalid webhook URL")
|
93 |
-
|
94 |
-
headers = {
|
95 |
-
"Content-Type": "application/json",
|
96 |
-
"X-Line-Signature": line_signature,
|
97 |
-
"Authorization": f"Bearer {os.getenv('ChannelAccessToken')}",
|
98 |
-
}
|
99 |
-
|
100 |
-
logger.info("Forwarding to URL: %s", os.getenv("WEBHOOK_URL"))
|
101 |
-
logger.info("Forwarding Headers: %s", headers)
|
102 |
-
logger.info("Forwarding Body: %s", body.decode("utf-8"))
|
103 |
-
|
104 |
-
response = requests.post(os.getenv("WEBHOOK_URL"), headers=headers, data=body)
|
105 |
-
|
106 |
-
logger.info("Response Code: %s", response.status_code)
|
107 |
-
logger.info("Response Content: %s", response.text)
|
108 |
-
logger.info("Response Headers: %s", response.headers)
|
109 |
-
|
110 |
-
return {"status": "success", "response_content": response.text}, response.status_code
|
111 |
-
|
112 |
-
except Exception as e:
|
113 |
-
logger.error("Error: %s", str(e))
|
114 |
-
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|