-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
490 lines (440 loc) · 21.4 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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
from fastapi import FastAPI, Request, Form, HTTPException, Cookie, Depends, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi.responses import Response
import httpx
import asyncio
from pydantic import BaseModel, EmailStr
import os
import logging
from typing import List, Dict, Any
from fastapi.staticfiles import StaticFiles
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI()
templates = Jinja2Templates(directory="templates")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
class LoginRequest(BaseModel):
email: EmailStr
class TokenRequest(BaseModel):
code: str
request: str
class ResetPasswordRequest(BaseModel):
access_token: str
jwt_token: str
new_password: str
class CreateBridgeRequest(BaseModel):
beeper_token: str
bridge: str
region: str
bridgeType: str = None
isSelfHosted: bool = None
reason: str = None
source: str = None
stateEvent: str = None
username: str = None
class DeleteBridgeRequest(BaseModel):
beeper_token: str
name: str
class UserProfile(BaseModel):
full_name: str
email: EmailStr
analyticsId: str = None
bridgeClusterId: str = None
channel: str = None
createdAt: str = None
customerLead: Dict[str, Any] = None
dataLocation: str = None
deactivatedAt: str = None
deletedAt: str = None
hungryUrl: str = None
hungryUrlDirect: str = None
isAdmin: bool = None
isFree: bool = None
isUserBridgeChangesLocked: bool = None
referralCode: str = None
supportRoomId: str = None
token: str = None
username: str = None
GITHUB_REPOS = {
"discordgo": "mautrix/discord",
"facebookgo": "mautrix/meta",
"gmessages": "mautrix/gmessages",
"googlechat": "mautrix/googlechat",
"instagramgo": "mautrix/meta",
"linkedin": "beeper/linkedin",
"signal": "mautrix/signal",
"slackgo": "mautrix/slack",
"telegram": "mautrix/telegram",
"twitter": "mautrix/twitter",
"whatsapp": "mautrix/whatsapp",
"hungryserv": "beeper/hungryserv",
"asmux": "beeper/asmux",
"gvoice": "mautrix/gvoice",
"imessage": "mautrix/imessage",
"imessagego": "beeper/imessagego",
"heisenbridge": "hifi/heisenbridge",
}
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
@app.on_event("startup")
async def startup_event():
app.state.httpx_client = httpx.AsyncClient()
app.state.notification_clients = []
def save_tokens_to_cookies(response: Response, access_token: str, jwt_token: str):
response.set_cookie(key="access_token", value=access_token, httponly=True)
response.set_cookie(key="jwt_token", value=jwt_token, httponly=True)
def retrieve_tokens_from_cookies(request: Request) -> (str, str):
access_token = request.cookies.get("access_token")
jwt_token = request.cookies.get("jwt_token")
return access_token, jwt_token
@app.on_event("shutdown")
async def shutdown_event():
await app.state.httpx_client.aclose()
# Mount the static directory
app.mount("/static", StaticFiles(directory="static"), name="static")
async def make_authenticated_request(url: str) -> Dict[str, Any]:
headers = {}
if GITHUB_TOKEN:
headers["Authorization"] = f"Bearer {GITHUB_TOKEN}"
async with httpx.AsyncClient() as client:
response = await client.get(url, headers=headers, timeout=10.0)
response.raise_for_status()
return response.json()
async def get_github_commit_data(repo: str, branch: str) -> Dict[str, str]:
github_url = f"https://api.github.com/repos/{repo}/commits/{branch}"
try:
commit_data = await make_authenticated_request(github_url)
return {
"sha": commit_data.get("sha", "Unknown"),
"date": commit_data.get("commit", {}).get("committer", {}).get("date", "Unknown"),
"message": commit_data.get("commit", {}).get("message", "No commit message")
}
except httpx.HTTPStatusError as exc:
logger.error(f"Error fetching commit data from {github_url}: {exc}")
return {"sha": "Unknown", "date": "Unknown", "message": "Error fetching commit data"}
async def get_latest_github_commit_hash(bridge_name: str) -> Dict[str, str]:
repo = GITHUB_REPOS.get(bridge_name, "")
if not repo:
return {"sha": "Unknown", "date": "Unknown", "message": "Unknown"}
branches = ["main", "master"]
for branch in branches:
commit_data = await get_github_commit_data(repo, branch)
if commit_data["sha"] != "Unknown":
return commit_data
return {"sha": "Unknown", "date": "Unknown", "message": "Unknown"}
async def get_commit_data_by_hash(repo: str, commit_hash: str) -> Dict[str, str]:
github_url = f"https://api.github.com/repos/{repo}/commits/{commit_hash}"
try:
commit_data = await make_authenticated_request(github_url)
return {
"sha": commit_data.get("sha", "Unknown"),
"date": commit_data.get("commit", {}).get("committer", {}).get("date", "Unknown"),
"message": commit_data.get("commit", {}).get("message", "No commit message")
}
except httpx.HTTPStatusError as exc:
logger.error(f"Error fetching commit data from {github_url}: {exc}")
return {"sha": "Unknown", "date": "Unknown", "message": "Error fetching commit data"}
async def update_bridge_info(bridge_name: str, bridge_info: Dict[str, Any]):
if bridge_name not in GITHUB_REPOS:
logger.error(f"Bridge name {bridge_name} not found in GITHUB_REPOS")
bridge_info.update({
'is_up_to_date': None,
'latest_commit_date': "Unknown",
'latest_version': "Unknown",
'latest_commit_message': "Unknown",
'current_commit_date': "Unknown",
'current_commit_message': "Unknown"
})
return
if 'version' in bridge_info and bridge_info['version']:
current_version = bridge_info['version'].split(':')[-1].split('-')[0]
latest_commit = await get_latest_github_commit_hash(bridge_name)
latest_version = latest_commit["sha"]
latest_date = latest_commit["date"]
latest_message = latest_commit["message"]
current_commit = await get_commit_data_by_hash(GITHUB_REPOS[bridge_name], current_version)
current_date = current_commit["date"]
current_message = current_commit["message"]
bridge_info.update({
'is_up_to_date': (current_version == latest_version),
'latest_commit_date': latest_date,
'latest_version': latest_version,
'latest_commit_message': latest_message,
'current_commit_date': current_date,
'current_commit_message': current_message
})
logger.info(f"Bridge: {bridge_name}, Current version: {current_version}, Latest version: {latest_version}, Up-to-date: {bridge_info['is_up_to_date']}, Latest commit date: {latest_date}, Current commit date: {current_date}")
else:
bridge_info.update({
'is_up_to_date': None,
'latest_commit_date': "Unknown",
'latest_version': "Unknown",
'latest_commit_message': "Unknown",
'current_commit_date': "Unknown",
'current_commit_message': "Unknown"
})
# Process additional fields from the JSON payload
if 'remoteState' in bridge_info:
for remote_id, remote_info in bridge_info['remoteState'].items():
if 'info' in remote_info:
remote_info.update({
'battery_low': remote_info['info'].get('battery_low', None),
'browser_active': remote_info['info'].get('browser_active', None),
'google_account_pairing': remote_info['info'].get('google_account_pairing', None),
'mobile_data': remote_info['info'].get('mobile_data', None),
'settings': remote_info['info'].get('settings', None),
'sims': remote_info['info'].get('sims', None)
})
def is_authenticated(access_token: str, jwt_token: str) -> bool:
return bool(access_token and jwt_token)
@app.get("/", response_class=HTMLResponse)
async def login_page(request: Request):
access_token, jwt_token = retrieve_tokens_from_cookies(request)
if is_authenticated(access_token, jwt_token):
return RedirectResponse(url="/dashboard", status_code=302)
return templates.TemplateResponse("login.html", {"request": request})
@app.post("/login")
async def login(request: Request, email: EmailStr = Form(...)):
client = app.state.httpx_client
try:
login_response = await client.post(
"https://api.beeper.com/user/login",
headers={"Authorization": "Bearer BEEPER-PRIVATE-API-PLEASE-DONT-USE"},
timeout=10.0
)
login_response.raise_for_status()
request_data = login_response.json().get("request")
await client.post(
"https://api.beeper.com/user/login/email",
headers={
"Authorization": "Bearer BEEPER-PRIVATE-API-PLEASE-DONT-USE",
"Content-Type": "application/json"},
json={"request": request_data, "email": email},
timeout=10.0
)
except httpx.HTTPStatusError as exc:
logger.error(f"Error during login: {exc.response.status_code}")
return templates.TemplateResponse("error.html", {"request": request, "error": "Login failed"})
except httpx.RequestError as exc:
logger.error(f"An error occurred while requesting {exc.request.url!r}.")
return templates.TemplateResponse("error.html", {"request": request, "error": "Login failed"})
response = templates.TemplateResponse("code.html", {"request": request, "login_request": request_data})
save_tokens_to_cookies(response, "", "")
return response
@app.post("/token")
async def get_token(request: Request, code: str = Form(...), login_request: str = Form(...)):
client = app.state.httpx_client
try:
login_challenge_response = await client.post(
"https://api.beeper.com/user/login/response",
headers={
"Authorization": "Bearer BEEPER-PRIVATE-API-PLEASE-DONT-USE",
"Content-Type": "application/json"},
json={"request": login_request, "response": code},
timeout=10.0
)
login_challenge_response.raise_for_status()
except httpx.HTTPStatusError as exc:
logger.error(f"Error response {exc.response.status_code} while requesting {exc.request.url!r}.")
return templates.TemplateResponse("error.html", {"request": request, "error": "Invalid token"})
except httpx.RequestError as exc:
logger.error(f"An error occurred while requesting {exc.request.url!r}.")
return templates.TemplateResponse("error.html", {"request": request, "error": "Invalid token"})
token = login_challenge_response.json().get("token")
access_token_response = await client.post(
"https://matrix.beeper.com/_matrix/client/v3/login",
headers={"Content-Type": "application/json"},
json={"type": "org.matrix.login.jwt", "token": token},
timeout=10.0
)
access_token = access_token_response.json().get("access_token")
response = RedirectResponse(url="/dashboard", status_code=303)
save_tokens_to_cookies(response, access_token, token)
return response
@app.get("/dashboard", response_class=HTMLResponse)
async def dashboard(request: Request):
access_token, jwt_token = retrieve_tokens_from_cookies(request)
if not access_token or not jwt_token:
return RedirectResponse(url="/", status_code=302)
client = app.state.httpx_client
try:
beeper_response = await client.get(
"https://api.beeper.com/whoami",
headers={"Authorization": f"Bearer {access_token}"},
timeout=10.0
)
beeper_response.raise_for_status()
except httpx.HTTPStatusError as exc:
logger.error(f"Error fetching Beeper data: {exc.response.status_code}")
return templates.TemplateResponse("error.html", {"request": request, "error": "Failed to fetch Beeper data"})
except httpx.RequestError as exc:
logger.error(f"An error occurred while requesting {exc.request.url!r}.")
return templates.TemplateResponse("error.html", {"request": request, "error": "Failed to fetch Beeper data"})
beeper_data = beeper_response.json()
bridges = beeper_data.get("user", {}).get("bridges", {})
asmux_data = beeper_data.get("user", {}).get("asmuxData", {})
user_info = beeper_data.get("userInfo", {})
await asyncio.gather(*[
update_bridge_info(bridge_name, bridge_info)
for bridge_name, bridge_info in bridges.items()
])
return templates.TemplateResponse("dashboard.html", {
"request": request,
"bridges": bridges,
"beeper_data": beeper_data,
"token": access_token,
"asmux_data": asmux_data,
"user_info": user_info,
"jwt_token": jwt_token,
"GITHUB_REPOS": GITHUB_REPOS, # Pass GITHUB_REPOS to the template
})
@app.post("/reset_password", response_class=HTMLResponse)
async def reset_password(request: Request, access_token: str = Form(...), jwt_token: str = Form(...), new_password: str = Form(...)):
client = app.state.httpx_client
try:
user_interactive_auth_response = await client.post(
"https://matrix.beeper.com/_matrix/client/v3/account/password",
headers={"Authorization": f"Bearer {access_token}", "Content-Type": "application/json"},
json={},
timeout=10.0
)
user_interactive_auth_response.raise_for_status()
session_data = user_interactive_auth_response.json()
session = session_data["session"]
await client.post(
"https://matrix.beeper.com/_matrix/client/v3/account/password",
headers={"Authorization": f"Bearer {access_token}", "Content-Type": "application/json"},
json={
"auth": {
"type": "org.matrix.login.jwt",
"token": jwt_token,
"session": session,
},
"new_password": new_password,
"logout_devices": False,
},
timeout=10.0
)
except httpx.HTTPStatusError as exc:
logger.error(f"Error resetting password: {exc.response.status_code}")
return HTMLResponse(content="Failed to reset password", status_code=500)
except httpx.RequestError as exc:
logger.error(f"An error occurred while requesting {exc.request.url!r}.")
return HTMLResponse(content="Failed to reset password", status_code=500)
return HTMLResponse(content="Password reset successfully")
@app.post("/delete_bridge", response_class=HTMLResponse)
async def delete_bridge(request: Request, beeper_token: str = Form(...), name: str = Form(...)):
client = app.state.httpx_client
try:
res_delete_beeper = await client.delete(
f"https://api.beeper.com/bridge/{name}",
headers={"Authorization": f"Bearer {beeper_token}", "Content-Type": "application/json"},
timeout=10.0 # Set a timeout of 10 seconds
)
res_delete_beeper.raise_for_status()
except httpx.ReadTimeout:
logger.error("Request to delete bridge timed out.")
# Check if the bridge still exists
try:
res_check_bridge = await client.get(
f"https://api.beeper.com/bridge/{name}",
headers={"Authorization": f"Bearer {beeper_token}", "Content-Type": "application/json"},
timeout=10.0 # Set a timeout of 10 seconds
)
if res_check_bridge.status_code == 404:
return HTMLResponse(content=f"Bridge {name} deleted successfully (timeout occurred but bridge no longer exists).")
else:
return HTMLResponse(content="Request to delete bridge timed out. Please try again later.", status_code=500)
except httpx.HTTPStatusError as exc:
logger.error(f"Error checking bridge existence: {exc.response.status_code}")
return HTMLResponse(content="Failed to verify bridge deletion status.", status_code=500)
except httpx.RequestError as exc:
logger.error(f"An error occurred while requesting {exc.request.url!r}.")
return HTMLResponse(content="Failed to verify bridge deletion status.", status_code=500)
except httpx.HTTPStatusError as exc:
logger.error(f"Error deleting bridge: {exc.response.status_code}")
return HTMLResponse(content="Failed to delete bridge on Beeper", status_code=500)
except httpx.RequestError as exc:
logger.error(f"An error occurred while requesting {exc.request.url!r}.")
return HTMLResponse(content="Failed to delete bridge on Beeper", status_code=500)
return HTMLResponse(content=f"Bridge {name} deleted successfully")
@app.post("/start_or_update_bridge", response_class=HTMLResponse)
async def start_or_update_bridge(request: Request, beeper_token: str = Form(...), name: str = Form(...)):
client = app.state.httpx_client
try:
res_start_update_beeper = await client.post(
f"https://api.beeper.com/bridge/{name}/start",
headers={"Authorization": f"Bearer {beeper_token}", "Content-Type": "application/json"},
timeout=10.0 # # Set a timeout of 10 seconds
)
res_start_update_beeper.raise_for_status()
except httpx.ReadTimeout:
logger.error("Request to start or update bridge timed out.")
return HTMLResponse(content="Request to start or update bridge timed out. Please try again later.", status_code=500)
except httpx.HTTPStatusError as exc:
logger.error(f"Error starting or updating bridge: {exc.response.status_code}")
return HTMLResponse(content="Failed to start or update bridge on Beeper", status_code=500)
return HTMLResponse(content=f"Bridge {name} started or updated successfully")
@app.get("/profile", response_class=HTMLResponse)
async def get_profile(request: Request, access_token: str = Cookie(None)):
if not access_token:
access_token, _ = retrieve_tokens_from_cookies(access_token, None)
if not access_token:
return RedirectResponse(url="/", status_code=302)
client = app.state.httpx_client
profile_response = await client.get(
"https://api.beeper.com/user/profile",
headers={"Authorization": f"Bearer {access_token}"},
)
if profile_response.status_code != 200:
return templates.TemplateResponse("error.html", {"request": request, "error": "Failed to fetch profile data"})
profile_data = profile_response.json()
return templates.TemplateResponse("profile.html", {"request": request, "profile": profile_data})
@app.post("/profile", response_class=HTMLResponse)
async def update_profile(request: Request, access_token: str = Cookie(None), full_name: str = Form(...), email: EmailStr = Form(...)):
if not access_token:
access_token, _ = retrieve_tokens_from_cookies(access_token, None)
if not access_token:
return RedirectResponse(url="/", status_code=302)
client = app.state.httpx_client
try:
update_response = await client.put(
"https://api.beeper.com/user/profile",
headers={"Authorization": f"Bearer {access_token}", "Content-Type": "application/json"},
json={"full_name": full_name, "email": email},
)
if update_response.status_code != 200:
return templates.TemplateResponse("error.html", {"request": request, "error": "Failed to update profile data"})
return RedirectResponse(url="/profile", status_code=303)
except Exception as e:
logger.error(f"An error occurred while updating profile data: {e}")
return templates.TemplateResponse("error.html", {"request": request, "error": "An unexpected error occurred"})
@app.post("/post_bridge_state", response_class=HTMLResponse)
async def post_bridge_state(request: Request, beeper_token: str = Form(...), username: str = Form(...), bridge_name: str = Form(...), state_event: str = Form(...), reason: str = Form(...), is_self_hosted: bool = Form(...), bridge_type: str = Form(...)):
client = app.state.httpx_client
url = f"https://api.beeper.com/bridgebox/{username}/bridge/{bridge_name}/bridge_state"
headers = {"Authorization": f"Bearer {beeper_token}", "Content-Type": "application/json"}
payload = {
"stateEvent": state_event,
"reason": reason,
"isSelfHosted": is_self_hosted,
"bridgeType": bridge_type
}
try:
response = await client.post(
url,
headers=headers,
json=payload,
timeout=10.0 # Set a timeout of 10 seconds
)
response.raise_for_status()
except httpx.ReadTimeout:
logger.error("Request to post bridge state timed out.")
return HTMLResponse(content="Request to post bridge state timed out. Please try again later.", status_code=500)
except httpx.HTTPStatusError as exc:
logger.error(f"Error posting bridge state: {exc.response.status_code}")
logger.error(f"Response content: {exc.response.text}")
return HTMLResponse(content=f"Failed to post bridge state on Beeper: {exc.response.text}", status_code=500)
return HTMLResponse(content=f"Bridge state for {bridge_name} posted successfully")