generated from render-examples/fastapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
159 lines (118 loc) · 4.49 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import os
from fastapi import (
FastAPI,
Request,
WebSocketDisconnect,
UploadFile,
File,
Depends,
HTTPException,
Security,
)
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
import json
from starlette.websockets import WebSocket
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from comments_websocket_service.comments_socket import WebSocketHandler
from devotionals_service.devotional_service import process_devotional_document
from livestream_service.livestream import get_user_token, setup_church_livestream_channel
from livestream_service.webhook_handler import handle_webhook_event
from models.channel_response_model import ChurchChannelResponse
from models.user_token_model import GetTokenResponse
import sys
import subprocess
# Ensure python-multipart is installed
try:
import multipart
except ImportError:
subprocess.check_call([sys.executable, "-m", "pip", "install", "python-multipart"])
app = FastAPI()
# Initialize HTTPBearer for receiving tokens
security = HTTPBearer()
# To allow CORS for frontend applications
app.add_middleware(
CORSMiddleware,
allow_origins=["https://gospeltube-livestream-test-server.onrender.com"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def root():
return {"message": "Hello, from GTube Livestream server, with comments WebSocket"}
@app.post("/receive_webhook")
async def receive_webhook_event(request: Request):
"""
This is the endpoint that receives the Webhook event from Stream.io.
"""
try:
print("Receiving Event Notification from Stream's Webhook")
body = await request.json()
print(body)
handle_webhook_event(body)
except Exception as error:
print("Error occured: ", error)
return {"message": "Webhook received successfully"}
@app.get("/user/get_token/{user_id}")
async def generate_token(user_id: str):
"""
Generate a livestream token for a user.
"""
return get_user_token(user_id)
@app.get(
"/church/create_livestream_channel/{church_id}",
# response_model=ChurchChannelResponse,
)
async def create_church_livestream_channel(church_id: str):
"""
Create a livestream channel for a new church.
'church_id' is the church's streamID generated during church account creation in the onboarding.
"""
return setup_church_livestream_channel(church_id)
# Chat Websocket endpoint
manager = WebSocketHandler()
@app.websocket("/ws/{topic}")
async def comments_websocket_endpoint(websocket: WebSocket, topic: str):
"""FastAPI WebSocket route that interacts with WebSocketHandler."""
print("Topic received from client: ", topic)
await manager.connect(websocket, topic)
try:
while True:
data = await websocket.receive_text() # Receive message from client
print(f"Message received on topic {topic}: {data}")
# Acknowledge receipt
# ack_message = json.dumps({"ack": f"Received '{data}' on topic '{topic}'"})
# await websocket.send_text(ack_message)
# Broadcast message to all clients in the topic
await manager.send_message(topic, data)
except WebSocketDisconnect:
manager.disconnect(websocket, topic)
# Bulk devotional upload endpoint
@app.post("church/devotional/upload_doc/{church_id}")
async def upload_bulk_devotional(
church_id: str,
file: UploadFile = File(...),
credentials: HTTPAuthorizationCredentials = Security(security),
):
"""
Upload bulk devotionals for a church, allows only PDF, Word doc/docx, and TXT file formats.
Handle file upload, extract text, and return structured devotionals, each containing the date, title, bible verse amd content of each devotional.
"""
token = credentials.credentials
print(f"Received file for church {church_id}")
print(f"Token received: {token}")
response = process_devotional_document(file.filename)
try:
admonitions_data = json.loads(response)
return admonitions_data
except json.JSONDecodeError as e:
return {"error": f"Error parsing response: {str(e)}: {response}"}
if __name__ == "__main__":
port = int(os.environ.get("PORT", 10000)) # Use the PORT environment variable
uvicorn.run(app, host="0.0.0.0", port=port)
# python -m venv venv
# venv\Scripts\activate
# pip freeze > requirements.txt
# deepseek_ai_api_key = 'sk-630b91e4926e42b7b1eb097ffe5a4c02'
# gemini_ai_api_key = 'AIzaSyDgFx4bfhJG4RkzxEs10J6yZkK-3jVfYmU'