-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviews_api.py
More file actions
473 lines (420 loc) · 15.7 KB
/
views_api.py
File metadata and controls
473 lines (420 loc) · 15.7 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
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
from http import HTTPStatus
from fastapi import APIRouter, Depends, Request
from fastapi.exceptions import HTTPException
from lnbits.core.models import SimpleStatus
from lnbits.core.models.users import AccountId
from lnbits.db import Filters, Page
from lnbits.decorators import check_account_id_exists, optional_user_id, parse_filters
from lnbits.helpers import generate_filter_params_openapi
from lnbits.settings import settings
from .crud import (
create_categories,
delete_categories,
get_categories,
get_categories_by_id,
get_categories_ids_by_user,
get_categories_paginated,
get_chat,
get_chat_for_category,
get_chats_paginated,
update_categories,
)
from .helpers import chat_lnurl_url, lnurl_encode_chat
from .models import (
DEFAULT_PUBLIC_NOTE,
Categories,
CategoriesFilters,
ChatMessage,
ChatNotifications,
ChatPaymentRequest,
ChatSession,
ChatsFilters,
CreateCategories,
CreateChat,
CreateChatMessage,
PublicCategories,
TipRequest,
)
from .services import (
create_public_chat,
get_public_chat,
mark_chat_resolved,
mark_chat_seen,
request_tip,
send_admin_message,
send_public_message,
toggle_chat_claim,
update_chat_notifications,
)
categories_filters = parse_filters(CategoriesFilters)
chats_filters = parse_filters(ChatsFilters)
chat_api_router = APIRouter()
############################# Categories #############################
@chat_api_router.post("/api/v1/categories", status_code=HTTPStatus.CREATED)
async def api_create_categories(
data: CreateCategories,
account_id: AccountId = Depends(check_account_id_exists),
) -> Categories:
payload = data.dict()
if not payload.get("paid"):
payload["lnurlp"] = False
payload["claim_split"] = 0
if payload.get("claim_split") is not None:
payload["claim_split"] = max(0, min(float(payload["claim_split"]), 90))
if payload.get("public_note") is None:
payload["public_note"] = DEFAULT_PUBLIC_NOTE
categories = await create_categories(account_id.id, CreateCategories(**payload))
return categories
@chat_api_router.put("/api/v1/categories/{categories_id}", status_code=HTTPStatus.CREATED)
async def api_update_categories(
categories_id: str,
data: CreateCategories,
account_id: AccountId = Depends(check_account_id_exists),
) -> Categories:
categories = await get_categories(account_id.id, categories_id)
if not categories:
raise HTTPException(HTTPStatus.NOT_FOUND, "Categories not found.")
if categories.user_id != account_id.id:
raise HTTPException(HTTPStatus.FORBIDDEN, "You do not own this categories.")
payload = data.dict()
if not payload.get("paid"):
payload["lnurlp"] = False
payload["claim_split"] = 0
if payload.get("claim_split") is not None:
payload["claim_split"] = max(0, min(float(payload["claim_split"]), 90))
if payload.get("public_note") is None:
payload["public_note"] = DEFAULT_PUBLIC_NOTE
categories = await update_categories(Categories(**{**categories.dict(), **payload}))
return categories
@chat_api_router.get(
"/api/v1/categories/paginated",
name="Categories List",
summary="get paginated list of categories",
response_description="list of categories",
openapi_extra=generate_filter_params_openapi(CategoriesFilters),
response_model=Page[Categories],
)
async def api_get_categories_paginated(
account_id: AccountId = Depends(check_account_id_exists),
filters: Filters = Depends(categories_filters),
) -> Page[Categories]:
return await get_categories_paginated(
user_id=account_id.id,
filters=filters,
)
@chat_api_router.get(
"/api/v1/categories/{categories_id}",
name="Get Categories",
summary="Get the categories with this id.",
response_description="An categories or 404 if not found",
response_model=Categories,
)
async def api_get_categories(
categories_id: str,
account_id: AccountId = Depends(check_account_id_exists),
) -> Categories:
categories = await get_categories(account_id.id, categories_id)
if not categories:
raise HTTPException(HTTPStatus.NOT_FOUND, "Categories not found.")
return categories
@chat_api_router.get(
"/api/v1/categories/{categories_id}/public",
name="Get Public Categories",
summary="Get the public categories with this id." "This is a public endpoint.",
response_description="An categories or 404 if not found",
response_model=PublicCategories,
)
async def api_get_public_categories(categories_id: str) -> PublicCategories:
categories = await get_categories_by_id(categories_id)
if not categories:
raise HTTPException(HTTPStatus.NOT_FOUND, "Categories not found.")
payload = categories.dict()
payload["claim_split"] = categories.claim_split or 0
if payload.get("public_note") is None:
payload["public_note"] = DEFAULT_PUBLIC_NOTE
payload["notify_email_available"] = settings.lnbits_email_notifications_enabled
payload["notify_nostr_available"] = settings.is_nostr_notifications_configured()
return PublicCategories(**payload)
@chat_api_router.delete(
"/api/v1/categories/{categories_id}",
name="Delete Categories",
summary="Delete the categories " "and optionally all its associated chats.",
response_description="The status of the deletion.",
response_model=SimpleStatus,
)
async def api_delete_categories(
categories_id: str,
clear_chats: bool | None = False,
account_id: AccountId = Depends(check_account_id_exists),
) -> SimpleStatus:
await delete_categories(account_id.id, categories_id)
return SimpleStatus(success=True, message="Categories Deleted")
############################# Chats #############################
@chat_api_router.post(
"/api/v1/chats/{categories_id}/public",
name="Create Chat",
summary="Create a new chat for this category (public endpoint).",
response_description="The created chat.",
response_model=ChatSession,
status_code=HTTPStatus.CREATED,
)
async def api_create_public_chat(
categories_id: str,
data: CreateChat,
request: Request,
) -> ChatSession:
base_url = str(request.base_url)
try:
return await create_public_chat(categories_id, data, base_url)
except ValueError as exc:
raise HTTPException(HTTPStatus.BAD_REQUEST, str(exc)) from exc
@chat_api_router.get(
"/api/v1/chats/{categories_id}/{chat_id}/public",
name="Get Chat (Public)",
summary="Get chat history for the public page.",
response_model=ChatSession,
)
async def api_get_public_chat(categories_id: str, chat_id: str) -> ChatSession:
try:
return await get_public_chat(categories_id, chat_id)
except ValueError as exc:
raise HTTPException(HTTPStatus.NOT_FOUND, str(exc)) from exc
@chat_api_router.get(
"/api/v1/chats/{categories_id}/{chat_id}/lnurl",
name="Get Chat LNURL",
summary="Get LNURL for chat balance funding.",
)
async def api_get_chat_lnurl(categories_id: str, chat_id: str, request: Request) -> dict:
chat = await get_chat_for_category(categories_id, chat_id)
if not chat:
raise HTTPException(HTTPStatus.NOT_FOUND, "Chat not found.")
categories = await get_categories_by_id(categories_id)
if not categories or not categories.paid or not categories.lnurlp:
raise HTTPException(HTTPStatus.NOT_FOUND, "Chat does not accept balance.")
return {
"lnurl": lnurl_encode_chat(request, chat.id),
"url": chat_lnurl_url(request, chat.id),
}
@chat_api_router.post(
"/api/v1/chats/{categories_id}/{chat_id}/public/messages",
name="Send Message (Public)",
summary="Send a message to a chat (public endpoint).",
response_model=ChatPaymentRequest,
)
async def api_send_public_message(
categories_id: str,
chat_id: str,
data: CreateChatMessage,
request: Request,
user_id: str | None = Depends(optional_user_id),
) -> ChatPaymentRequest:
try:
base_url = str(request.base_url)
return await send_public_message(categories_id, chat_id, data, user_id=user_id, base_url=base_url)
except ValueError as exc:
raise HTTPException(HTTPStatus.BAD_REQUEST, str(exc)) from exc
@chat_api_router.post(
"/api/v1/chats/{categories_id}/{chat_id}/public/notifications",
name="Update Chat Notifications (Public)",
summary="Attach notification identifiers for this chat (public endpoint).",
response_model=SimpleStatus,
)
async def api_update_chat_notifications(
categories_id: str,
chat_id: str,
data: ChatNotifications,
user_id: str | None = Depends(optional_user_id),
) -> SimpleStatus:
if user_id:
raise HTTPException(HTTPStatus.FORBIDDEN, "Notifications are only available for guests.")
try:
await update_chat_notifications(categories_id, chat_id, data.email, data.nostr)
return SimpleStatus(success=True, message="Notifications updated.")
except ValueError as exc:
raise HTTPException(HTTPStatus.BAD_REQUEST, str(exc)) from exc
@chat_api_router.post(
"/api/v1/chats/{categories_id}/{chat_id}/public/claim",
name="Toggle Chat Claim",
summary="Claim or release a chat (public endpoint, logged-in users only).",
response_model=ChatSession,
)
async def api_toggle_chat_claim(
categories_id: str,
chat_id: str,
user_id: str | None = Depends(optional_user_id),
) -> ChatSession:
if not user_id:
raise HTTPException(HTTPStatus.UNAUTHORIZED, "Login required.")
chat = await get_chat_for_category(categories_id, chat_id)
if not chat:
raise HTTPException(HTTPStatus.NOT_FOUND, "Chat not found.")
try:
return await toggle_chat_claim(chat_id, user_id)
except ValueError as exc:
raise HTTPException(HTTPStatus.BAD_REQUEST, str(exc)) from exc
@chat_api_router.post(
"/api/v1/chats/{categories_id}/{chat_id}/public/resolve",
name="Resolve Chat (Public)",
summary="Resolve or reopen a chat (public endpoint, logged-in users only).",
response_model=ChatSession,
)
async def api_resolve_public_chat(
categories_id: str,
chat_id: str,
data: dict,
user_id: str | None = Depends(optional_user_id),
) -> ChatSession:
if not user_id:
raise HTTPException(HTTPStatus.UNAUTHORIZED, "Login required.")
chat = await get_chat_for_category(categories_id, chat_id)
if not chat:
raise HTTPException(HTTPStatus.NOT_FOUND, "Chat not found.")
resolved = bool(data.get("resolved", True))
try:
return await mark_chat_resolved(chat.id, resolved)
except ValueError as exc:
raise HTTPException(HTTPStatus.BAD_REQUEST, str(exc)) from exc
@chat_api_router.post(
"/api/v1/chats/{categories_id}/{chat_id}/public/tip",
name="Send Tip (Public)",
summary="Create a tip invoice for this chat.",
response_model=ChatPaymentRequest,
)
async def api_send_tip(
categories_id: str,
chat_id: str,
data: TipRequest,
) -> ChatPaymentRequest:
try:
return await request_tip(
categories_id,
chat_id,
data.amount,
data.sender_id,
data.sender_name,
)
except ValueError as exc:
raise HTTPException(HTTPStatus.BAD_REQUEST, str(exc)) from exc
@chat_api_router.get(
"/api/v1/chats/paginated",
name="Chats List",
summary="get paginated list of chats",
response_description="list of chats",
openapi_extra=generate_filter_params_openapi(ChatsFilters),
response_model=Page[ChatSession],
)
async def api_get_chats_paginated(
account_id: AccountId = Depends(check_account_id_exists),
categories_id: str | None = None,
filters: Filters = Depends(chats_filters),
) -> Page[ChatSession]:
categories_ids = await get_categories_ids_by_user(account_id.id)
if categories_id:
if categories_id not in categories_ids:
raise HTTPException(HTTPStatus.FORBIDDEN, "Not your categories.")
categories_ids = [categories_id]
return await get_chats_paginated(
categories_ids=categories_ids,
filters=filters,
)
@chat_api_router.get(
"/api/v1/chats/{categories_id}/paginated",
name="Chats List (Category)",
summary="get paginated list of chats for a category",
response_description="list of chats",
openapi_extra=generate_filter_params_openapi(ChatsFilters),
response_model=Page[ChatSession],
)
async def api_get_chats_paginated_for_category(
categories_id: str,
account_id: AccountId = Depends(check_account_id_exists),
filters: Filters = Depends(chats_filters),
) -> Page[ChatSession]:
categories = await get_categories(account_id.id, categories_id)
if not categories:
raise HTTPException(HTTPStatus.NOT_FOUND, "Categories not found.")
return await get_chats_paginated(
categories_ids=[categories_id],
filters=filters,
)
@chat_api_router.get(
"/api/v1/chats/{chat_id}",
name="Get Chat (Admin)",
summary="Get the chat with this id.",
response_description="A chat or 404 if not found",
response_model=ChatSession,
)
async def api_get_chat(
chat_id: str,
account_id: AccountId = Depends(check_account_id_exists),
) -> ChatSession:
chat = await get_chat(chat_id)
if not chat:
raise HTTPException(HTTPStatus.NOT_FOUND, "Chat not found.")
categories = await get_categories(account_id.id, chat.categories_id)
if not categories:
raise HTTPException(HTTPStatus.NOT_FOUND, "Categories deleted for this chat.")
return chat
@chat_api_router.post(
"/api/v1/chats/{chat_id}/messages",
name="Send Chat Message (Admin)",
summary="Send a message as admin to this chat.",
response_model=ChatMessage,
)
async def api_send_admin_message(
chat_id: str,
data: CreateChatMessage,
account_id: AccountId = Depends(check_account_id_exists),
) -> ChatMessage:
chat = await get_chat(chat_id)
if not chat:
raise HTTPException(HTTPStatus.NOT_FOUND, "Chat not found.")
categories = await get_categories(account_id.id, chat.categories_id)
if not categories:
raise HTTPException(HTTPStatus.NOT_FOUND, "Categories deleted for this chat.")
try:
return await send_admin_message(chat_id, data)
except ValueError as exc:
raise HTTPException(HTTPStatus.BAD_REQUEST, str(exc)) from exc
@chat_api_router.post(
"/api/v1/chats/{chat_id}/resolve",
name="Resolve Chat",
summary="Mark chat as resolved or unresolved.",
response_model=ChatSession,
)
async def api_resolve_chat(
chat_id: str,
data: dict,
account_id: AccountId = Depends(check_account_id_exists),
) -> ChatSession:
chat = await get_chat(chat_id)
if not chat:
raise HTTPException(HTTPStatus.NOT_FOUND, "Chat not found.")
categories = await get_categories(account_id.id, chat.categories_id)
if not categories:
raise HTTPException(HTTPStatus.NOT_FOUND, "Categories deleted for this chat.")
resolved = bool(data.get("resolved", True))
try:
return await mark_chat_resolved(chat_id, resolved)
except ValueError as exc:
raise HTTPException(HTTPStatus.BAD_REQUEST, str(exc)) from exc
@chat_api_router.post(
"/api/v1/chats/{chat_id}/seen",
name="Mark Chat Seen",
summary="Mark chat as seen (no longer unread).",
response_model=ChatSession,
)
async def api_mark_chat_seen(
chat_id: str,
account_id: AccountId = Depends(check_account_id_exists),
) -> ChatSession:
chat = await get_chat(chat_id)
if not chat:
raise HTTPException(HTTPStatus.NOT_FOUND, "Chat not found.")
categories = await get_categories(account_id.id, chat.categories_id)
if not categories:
raise HTTPException(HTTPStatus.NOT_FOUND, "Categories deleted for this chat.")
try:
return await mark_chat_seen(chat_id)
except ValueError as exc:
raise HTTPException(HTTPStatus.BAD_REQUEST, str(exc)) from exc