-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
139 lines (112 loc) · 3.34 KB
/
main.py
File metadata and controls
139 lines (112 loc) · 3.34 KB
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
from typing import Union
from fastapi import FastAPI, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from pywebpush import webpush, WebPushException
from uuid import uuid4
import ujson
from fastapi.staticfiles import StaticFiles
from fastapi.responses import RedirectResponse
from os import getenv
import multiprocessing
from custom_types import Push, Keys, Subscription, Register
from contextlib import asynccontextmanager
tags_metadata = [
{
"name": "client",
"description": "Operations for clients.",
},
{
"name": "server",
"description": "Operations for the server.",
},
]
# pool = None
# @asynccontextmanager
# async def lifespan(app: FastAPI):
# global pool
# pool = multiprocessing.Pool(
# multiprocessing.cpu_count()
# ) # create a pool of processesm
# yield
# pool.close()
# pool.join()
# pool.terminate()
app = FastAPI(
title="WebPush",
openapi_tags=tags_metadata,
# lifespan=lifespan
)
app.mount("/server", StaticFiles(directory="static/server", html=True), name="server")
app.mount("/client", StaticFiles(directory="static/client", html=True), name="client")
origins = [
"http://localhost",
"http://127.0.0.1:5501",
"http://localhost:8000",
"http://127.0.0.1:5500",
"http://127.0.0.1:5501",
"http://127.0.0.1:8000",
"https://web-push-client.mehdiabdi.com",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# read keys
with open("./public_key.pem") as file:
public_key = file.read()
with open("./private_key.pem") as file:
private_key = file.read()
subscriptions_in_db = {}
def send_webpush(subscription_info, message, private_key, vapid_claims):
webpush(
subscription_info=subscription_info,
data=message,
vapid_private_key=private_key,
vapid_claims=vapid_claims,
)
@app.post("/push", tags=["server"])
async def push(data: Push, background_tasks: BackgroundTasks):
if data.user_id:
webpush(
subscription_info=subscriptions_in_db.get(data.user_id),
data=data.message,
vapid_private_key=private_key,
vapid_claims={
"sub": f"mailto: {getenv('SUBJECT', 'mailto: <example@gmail.com>')}",
},
)
return "done"
else:
for subs in subscriptions_in_db.values():
try:
background_tasks.add_task(
send_webpush,
subs,
data.message,
private_key,
{
"sub": f"mailto: {getenv('SUBJECT', 'mailto: <example@gmail.com>')}",
},
)
except Exception as exc:
print(exc.args)
continue
return "done"
@app.post("/register", status_code=201, tags=["client"])
def read_item(data: Register):
subscriptions_in_db[
data.user_id if data.user_id else uuid4().hex
] = data.subscription.model_dump()
return "ok"
@app.get("/vapidPublicKey", tags=["client"])
async def read_item():
return public_key
@app.get("/")
def home_page():
return RedirectResponse("/server")
@app.get("/client")
def home_page():
return RedirectResponse("/client")