-
Notifications
You must be signed in to change notification settings - Fork 3
/
views_api.py
482 lines (431 loc) · 17.9 KB
/
views_api.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
import base64
import json
from http import HTTPStatus
from typing import Optional
import httpx
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi.responses import HTMLResponse
from lnbits.core.crud import get_standalone_payment
from lnbits.core.models import WalletTypeInfo
from lnbits.core.services import create_invoice
from lnbits.decorators import require_admin_key
from loguru import logger
from .crud import (
create_jukebox,
create_jukebox_payment,
delete_jukebox,
get_jukebox,
get_jukebox_payment,
get_jukeboxs,
update_jukebox,
update_jukebox_payment_paid,
)
from .models import CreateJukeboxPayment, CreateJukeLinkData, Jukebox
jukebox_api_router = APIRouter()
@jukebox_api_router.get("/api/v1/jukebox")
async def api_get_jukeboxs(
wallet: WalletTypeInfo = Depends(require_admin_key),
) -> list[Jukebox]:
wallet_user = wallet.wallet.user
return await get_jukeboxs(wallet_user)
##################SPOTIFY AUTH#####################
@jukebox_api_router.get(
"/api/v1/jukebox/spotify/cb/{juke_id}", response_class=HTMLResponse
)
async def api_check_credentials_callbac(
juke_id: str,
code: str = Query(None),
access_token: str = Query(None),
refresh_token: str = Query(None),
):
jukebox = await get_jukebox(juke_id)
if not jukebox:
raise HTTPException(detail="No Jukebox", status_code=HTTPStatus.FORBIDDEN)
if code:
jukebox.sp_access_token = code
await update_jukebox(jukebox)
if access_token:
jukebox.sp_access_token = access_token
jukebox.sp_refresh_token = refresh_token
await update_jukebox(jukebox)
return "<h1>Success!</h1><h2>You can close this window</h2>"
@jukebox_api_router.get(
"/api/v1/jukebox/{juke_id}", dependencies=[Depends(require_admin_key)]
)
async def api_check_credentials_check(juke_id: str):
jukebox = await get_jukebox(juke_id)
return jukebox
@jukebox_api_router.post(
"/api/v1/jukebox",
status_code=HTTPStatus.CREATED,
)
async def api_create_jukebox(
data: CreateJukeLinkData,
key_info: WalletTypeInfo = Depends(require_admin_key),
) -> Jukebox:
return await create_jukebox(key_info.wallet.inkey, data)
@jukebox_api_router.put(
"/api/v1/jukebox/{juke_id}", dependencies=[Depends(require_admin_key)]
)
async def api_update_jukebox(data: CreateJukeLinkData, juke_id: str) -> Jukebox:
jukebox = await get_jukebox(juke_id)
if not jukebox:
raise HTTPException(status_code=HTTPStatus.NOT_FOUND, detail="No Jukeboxes")
for k, v in data.dict().items():
if v is not None:
setattr(jukebox, k, v)
return await update_jukebox(jukebox)
@jukebox_api_router.delete(
"/api/v1/jukebox/{juke_id}", dependencies=[Depends(require_admin_key)]
)
async def api_delete_item(juke_id: str):
await delete_jukebox(juke_id)
################JUKEBOX ENDPOINTS##################
@jukebox_api_router.get("/api/v1/jukebox/jb/playlist/{juke_id}/{sp_playlist}")
async def api_get_jukebox_song(
juke_id: str,
sp_playlist: str,
retry: bool = Query(False),
):
jukebox = await get_jukebox(juke_id)
if not jukebox:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No Jukeboxes")
tracks = []
async with httpx.AsyncClient() as client:
try:
assert jukebox.sp_access_token
url: Optional[str] = (
f"https://api.spotify.com/v1/playlists/{sp_playlist}/tracks"
)
while url is not None:
r = await client.get(
url,
timeout=40,
headers={"Authorization": "Bearer " + jukebox.sp_access_token},
)
response = r.json()
if not response["items"]:
if r.status_code == 401:
token = await api_get_token(juke_id)
if token is False:
return False
elif retry:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Failed to get auth",
)
else:
return await api_get_jukebox_song(
juke_id, sp_playlist, retry=True
)
return r
try:
for item in response["items"]:
if not item["track"] or not item["track"]["id"]:
continue
tracks.append(
{
"id": item["track"]["id"],
"name": item["track"]["name"],
"album": item["track"]["album"]["name"],
"artist": item["track"]["artists"][0]["name"],
"image": (
item["track"]["album"]["images"][0]["url"]
if item["track"]["album"]["images"]
else None
),
}
)
except Exception as e:
logger.error(f"Error loop: {e}")
pass
# Check if there are more pages
url = response.get("next")
except Exception as e:
# Handle exceptions appropriately
logger.error(f"Error: {e}")
return list(tracks)
######GET ACCESS TOKEN######
async def api_get_token(juke_id):
jukebox = await get_jukebox(juke_id)
if not jukebox:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No Jukeboxes")
async with httpx.AsyncClient() as client:
try:
r = await client.post(
"https://accounts.spotify.com/api/token",
timeout=40,
params={
"grant_type": "refresh_token",
"refresh_token": jukebox.sp_refresh_token,
"client_id": jukebox.sp_user,
},
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic "
+ base64.b64encode(
str(jukebox.sp_user + ":" + jukebox.sp_secret).encode("ascii")
).decode("ascii"),
},
)
if "access_token" not in r.json():
return False
else:
jukebox.sp_access_token = r.json()["access_token"]
await update_jukebox(jukebox)
except Exception:
pass
return True
######CHECK DEVICE
@jukebox_api_router.get("/api/v1/jukebox/jb/{juke_id}")
async def api_get_jukebox_device_check(juke_id: str, retry: bool = Query(False)):
jukebox = await get_jukebox(juke_id)
if not jukebox:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No Jukeboxes")
async with httpx.AsyncClient() as client:
assert jukebox.sp_access_token
r_device = await client.get(
"https://api.spotify.com/v1/me/player/devices",
timeout=40,
headers={"Authorization": "Bearer " + jukebox.sp_access_token},
)
if r_device.status_code in (204, 200):
return json.loads(r_device.text)
elif r_device.status_code in (401, 403):
token = await api_get_token(juke_id)
if token is False:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="No devices connected"
)
elif retry:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="Failed to get auth"
)
else:
return await api_get_jukebox_device_check(juke_id, retry=True)
else:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="No device connected"
)
######GET INVOICE STUFF
@jukebox_api_router.get("/api/v1/jukebox/jb/invoice/{juke_id}/{song_id}")
async def api_get_jukebox_invoice(juke_id, song_id):
jukebox = await get_jukebox(juke_id)
if not jukebox:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No jukebox")
try:
assert jukebox.sp_device
devices = await api_get_jukebox_device_check(juke_id)
device_connected = False
for device in devices["devices"]:
if device["id"] == jukebox.sp_device.split("-")[1]:
device_connected = True
if not device_connected:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="No device connected"
)
except Exception as exc:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="No device connected"
) from exc
payment = await create_invoice(
wallet_id=jukebox.wallet,
amount=jukebox.price,
memo=jukebox.title,
extra={"tag": "jukebox"},
)
data = CreateJukeboxPayment(
invoice=payment.bolt11,
payment_hash=payment.payment_hash,
juke_id=juke_id,
song_id=song_id,
)
jukebox_payment = await create_jukebox_payment(data)
return {**jukebox_payment.dict(), "invoice": payment.bolt11}
@jukebox_api_router.get("/api/v1/jukebox/jb/checkinvoice/{pay_hash}/{juke_id}")
async def api_get_jukebox_invoice_check(pay_hash: str, juke_id: str):
try:
await get_jukebox(juke_id)
except Exception as exc:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="No jukebox"
) from exc
payment = await get_standalone_payment(pay_hash, incoming=True)
if not payment:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No payment found")
status = await payment.check_status()
if status.paid:
await update_jukebox_payment_paid(pay_hash)
return {"paid": status.paid}
@jukebox_api_router.get("/api/v1/jukebox/jb/invoicep/{song_id}/{juke_id}/{pay_hash}")
async def api_get_jukebox_invoice_paid(
song_id: str,
juke_id: str,
pay_hash: str,
retry: bool = Query(False),
):
jukebox = await get_jukebox(juke_id)
if not jukebox:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No jukebox")
await api_get_jukebox_invoice_check(pay_hash, juke_id)
jukebox_payment = await get_jukebox_payment(pay_hash)
if jukebox_payment and jukebox_payment.paid:
async with httpx.AsyncClient() as client:
assert jukebox.sp_access_token
r = await client.get(
"https://api.spotify.com/v1/me/player/currently-playing?market=ES",
timeout=40,
headers={"Authorization": "Bearer " + jukebox.sp_access_token},
)
r_device = await client.get(
"https://api.spotify.com/v1/me/player",
timeout=40,
headers={"Authorization": "Bearer " + jukebox.sp_access_token},
)
is_playing = False
if r_device.status_code == 200:
is_playing = r_device.json()["is_playing"]
if r.status_code == 204 or is_playing is False:
async with httpx.AsyncClient() as client:
uri = ["spotify:track:" + song_id]
assert jukebox.sp_device
r = await client.put(
"https://api.spotify.com/v1/me/player/play?device_id="
+ jukebox.sp_device.split("-")[1],
json={"uris": uri},
timeout=40,
headers={"Authorization": "Bearer " + jukebox.sp_access_token},
)
if r.status_code == 204:
return jukebox_payment
elif r.status_code in (401, 403):
token = await api_get_token(juke_id)
if token is False:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Invoice not paid",
)
elif retry:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Failed to get auth",
)
else:
return api_get_jukebox_invoice_paid(
song_id, juke_id, pay_hash, retry=True
)
else:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="Invoice not paid"
)
elif r.status_code == 200:
async with httpx.AsyncClient() as client:
assert jukebox.sp_access_token
assert jukebox.sp_device
r = await client.post(
"https://api.spotify.com/v1/me/player/queue?uri=spotify%3Atrack%3A"
+ song_id
+ "&device_id="
+ jukebox.sp_device.split("-")[1],
timeout=40,
headers={"Authorization": "Bearer " + jukebox.sp_access_token},
)
if r.status_code == 204:
return jukebox_payment
elif r.status_code in (401, 403):
token = await api_get_token(juke_id)
if token is False:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Invoice not paid",
)
elif retry:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Failed to get auth",
)
else:
return await api_get_jukebox_invoice_paid(
song_id, juke_id, pay_hash
)
else:
raise HTTPException(
status_code=HTTPStatus.OK, detail="Invoice not paid"
)
elif r.status_code in (401, 403):
token = await api_get_token(juke_id)
if token is False:
raise HTTPException(
status_code=HTTPStatus.OK, detail="Invoice not paid"
)
elif retry:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="Failed to get auth"
)
else:
return await api_get_jukebox_invoice_paid(
song_id, juke_id, pay_hash
)
raise HTTPException(status_code=HTTPStatus.OK, detail="Invoice not paid")
############################GET QUEUE
@jukebox_api_router.get("/api/v1/jukebox/jb/queue/{juke_id}")
async def api_get_jukebox_queue(
juke_id: str,
):
jukebox = await get_jukebox(juke_id)
if not jukebox:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No jukebox")
async with httpx.AsyncClient() as client:
try:
assert jukebox.sp_access_token
r = await client.get(
"https://api.spotify.com/v1/me/player/queue",
timeout=40,
headers={"Authorization": "Bearer " + jukebox.sp_access_token},
)
if r.status_code == 204:
raise HTTPException(status_code=HTTPStatus.OK, detail="Nothing")
elif r.status_code == 200:
try:
response = r.json()
track = None
if response["currently_playing"] not in (None, ""):
item = response["currently_playing"]
track = {
"id": item["id"],
"name": item["name"],
"album": item["album"]["name"],
"artist": item["artists"][0]["name"],
"image": item["album"]["images"][0]["url"],
}
tracks = []
for _item in response["queue"]:
tracks.append(
{
"id": _item["id"],
"name": _item["name"],
"album": _item["album"]["name"],
"artist": _item["artists"][0]["name"],
"image": _item["album"]["images"][0]["url"],
}
)
return {"playing": track, "queue": tracks}
except Exception as exc:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Something went wrong"
) from exc
elif r.status_code == 401:
token = await api_get_token(juke_id)
if token is False:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="Invoice not paid"
)
else:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Something went wrong"
)
except Exception as exc:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="Something went wrong, or no song is playing yet",
) from exc