should be working

This commit is contained in:
benarc 2021-10-10 23:57:15 +01:00
parent 7dd29b3eca
commit 9ff1313b0b
6 changed files with 269 additions and 186 deletions

View File

@ -1,17 +1,39 @@
from quart import Blueprint
import asyncio
from fastapi import APIRouter, FastAPI
from fastapi.staticfiles import StaticFiles
from starlette.routing import Mount
from lnbits.db import Database
from lnbits.helpers import template_renderer
from lnbits.tasks import catch_everything_and_restart
db = Database("ext_jukebox")
jukebox_ext: Blueprint = Blueprint(
"jukebox", __name__, static_folder="static", template_folder="templates"
)
jukebox_static_files = [
{
"path": "/jukebox/static",
"app": StaticFiles(directory="lnbits/extensions/jukebox/static"),
"name": "jukebox_static",
}
]
jukebox_ext: APIRouter = APIRouter(prefix="/jukebox", tags=["jukebox"])
def jukebox_renderer():
return template_renderer(
[
"lnbits/extensions/jukebox/templates",
]
)
from .views_api import * # noqa
from .views import * # noqa
from .tasks import register_listeners
from .tasks import wait_for_paid_invoices
from lnbits.tasks import record_async
jukebox_ext.record(record_async(register_listeners))
def jukebox_start():
loop = asyncio.get_event_loop()
loop.create_task(catch_everything_and_restart(wait_for_paid_invoices))

View File

@ -1,5 +1,19 @@
from typing import NamedTuple
from sqlite3 import Row
from fastapi.param_functions import Query
class CreateJukeLinkData(BaseModel):
user: str = Query(None)
title: str = Query(None)
wallet: str = Query(None)
sp_user: str = Query(None)
sp_secret: str = Query(None)
sp_access_token: str = Query(None)
sp_refresh_token: str = Query(None)
sp_device: str = Query(None)
sp_playlists: str = Query(None)
price: str = Query(None)
class Jukebox(NamedTuple):

View File

@ -1,23 +1,20 @@
import asyncio
import json
import trio # type: ignore
import httpx
from lnbits.core.models import Payment
from lnbits.core.crud import create_payment
from lnbits.core import db as core_db
from lnbits.tasks import register_invoice_listener, internal_invoice_paid
from lnbits.helpers import urlsafe_short_hash
from lnbits.core.models import Payment
from lnbits.tasks import register_invoice_listener
from .crud import get_jukebox, update_jukebox_payment
async def register_listeners():
invoice_paid_chan_send, invoice_paid_chan_recv = trio.open_memory_channel(2)
register_invoice_listener(invoice_paid_chan_send)
await wait_for_paid_invoices(invoice_paid_chan_recv)
async def wait_for_paid_invoices():
invoice_queue = asyncio.Queue()
register_invoice_listener(invoice_queue)
async def wait_for_paid_invoices(invoice_paid_chan: trio.MemoryReceiveChannel):
async for payment in invoice_paid_chan:
while True:
payment = await invoice_queue.get()
await on_invoice_paid(payment)

View File

@ -2,7 +2,7 @@ import json
import time
from datetime import datetime
from http import HTTPStatus
from lnbits.decorators import check_user_exists
from lnbits.decorators import check_user_exists, WalletTypeInfo, get_key_type
from . import jukebox_ext, jukebox_renderer
from .crud import get_jukebox
from fastapi import FastAPI, Request
@ -11,6 +11,9 @@ from fastapi.templating import Jinja2Templates
from starlette.exceptions import HTTPException
from starlette.responses import HTMLResponse
from lnbits.core.models import User, Payment
from .views_api import api_get_jukebox_device_check
templates = Jinja2Templates(directory="templates")
@jukebox_ext.get("/", response_class=HTMLResponse)

View File

@ -1,11 +1,23 @@
from quart import g, jsonify, request
from fastapi import Request
from http import HTTPStatus
from starlette.exceptions import HTTPException
from starlette.responses import HTMLResponse, JSONResponse # type: ignore
import base64
from lnbits.core.crud import get_wallet
from lnbits.core.services import create_invoice, check_invoice_status
import json
from lnbits.decorators import api_check_wallet_key, api_validate_post_request
from typing import Optional
from fastapi.params import Depends
from fastapi.param_functions import Query
from pydantic.main import BaseModel
from .models import CreateJukeLinkData
from lnbits.decorators import (
check_user_exists,
WalletTypeInfo,
get_key_type,
api_check_wallet_key,
api_validate_post_request,
)
import httpx
from . import jukebox_ext
from .crud import (
@ -20,43 +32,52 @@ from .crud import (
)
@jukebox_ext.route("/api/v1/jukebox", methods=["GET"])
@api_check_wallet_key("admin")
async def api_get_jukeboxs():
@jukebox_ext.get("/api/v1/jukebox", status_code=HTTPStatus.OK)
async def api_get_jukeboxs(
req: Request,
wallet: WalletTypeInfo = Depends(get_key_type),
all_wallets: bool = Query(False),
):
wallet_user = wallet.wallet[0].user
try:
return (
jsonify(
[{**jukebox._asdict()} for jukebox in await get_jukeboxs(g.wallet.user)]
),
HTTPStatus.OK,
)
return [
{**jukebox.dict(), "jukebox": jukebox.jukebox(req)}
for jukebox in await get_jukeboxs(wallet_user)
]
except:
return "", HTTPStatus.NO_CONTENT
raise HTTPException(
status_code=HTTPStatus.NO_CONTENT,
detail="No Jukeboxes",
)
##################SPOTIFY AUTH#####################
@jukebox_ext.route("/api/v1/jukebox/spotify/cb/<juke_id>", methods=["GET"])
async def api_check_credentials_callbac(juke_id):
@jukebox_ext.get("/api/v1/jukebox/spotify/cb/<juke_id>", status_code=HTTPStatus.OK)
async def api_check_credentials_callbac(
juke_id: str = Query(None),
code: str = Query(None),
access_token: str = Query(None),
refresh_token: str = Query(None),
):
sp_code = ""
sp_access_token = ""
sp_refresh_token = ""
try:
jukebox = await get_jukebox(juke_id)
except:
return (
jsonify({"error": "No Jukebox"}),
HTTPStatus.FORBIDDEN,
)
if request.args.get("code"):
sp_code = request.args.get("code")
raise HTTPException(detail="No Jukebox", status_code=HTTPStatus.FORBIDDEN)
if code:
sp_code = code
jukebox = await update_jukebox(
juke_id=juke_id, sp_secret=jukebox.sp_secret, sp_access_token=sp_code
)
if request.args.get("access_token"):
sp_access_token = request.args.get("access_token")
sp_refresh_token = request.args.get("refresh_token")
if access_token:
sp_access_token = access_token
sp_refresh_token = refresh_token
jukebox = await update_jukebox(
juke_id=juke_id,
sp_secret=jukebox.sp_secret,
@ -66,52 +87,42 @@ async def api_check_credentials_callbac(juke_id):
return "<h1>Success!</h1><h2>You can close this window</h2>"
@jukebox_ext.route("/api/v1/jukebox/<juke_id>", methods=["GET"])
@api_check_wallet_key("admin")
async def api_check_credentials_check(juke_id):
@jukebox_ext.get("/api/v1/jukebox/{juke_id}", status_code=HTTPStatus.OK)
async def api_check_credentials_check(
juke_id=None, wallet: WalletTypeInfo = Depends(get_key_type)
):
jukebox = await get_jukebox(juke_id)
return jsonify(jukebox._asdict()), HTTPStatus.CREATED
return jukebox._asdict()
@jukebox_ext.route("/api/v1/jukebox/", methods=["POST"])
@jukebox_ext.route("/api/v1/jukebox/<juke_id>", methods=["PUT"])
@api_check_wallet_key("admin")
@api_validate_post_request(
schema={
"user": {"type": "string", "empty": False, "required": True},
"title": {"type": "string", "empty": False, "required": True},
"wallet": {"type": "string", "empty": False, "required": True},
"sp_user": {"type": "string", "empty": False, "required": True},
"sp_secret": {"type": "string", "required": True},
"sp_access_token": {"type": "string", "required": False},
"sp_refresh_token": {"type": "string", "required": False},
"sp_device": {"type": "string", "required": False},
"sp_playlists": {"type": "string", "required": False},
"price": {"type": "string", "required": False},
}
)
async def api_create_update_jukebox(juke_id=None):
@jukebox_ext.post("/api/v1/jukebox", status_code=HTTPStatus.CREATED)
@jukebox_ext.put("/api/v1/jukebox/{juke_id}", status_code=HTTPStatus.OK)
async def api_create_update_jukebox(
data: CreateJukeLinkData,
juke_id=None,
wallet: WalletTypeInfo = Depends(get_key_type),
):
if juke_id:
jukebox = await update_jukebox(juke_id=juke_id, inkey=g.wallet.inkey, **g.data)
else:
jukebox = await create_jukebox(inkey=g.wallet.inkey, **g.data)
return jsonify(jukebox._asdict()), HTTPStatus.CREATED
return jukebox._asdict()
@jukebox_ext.route("/api/v1/jukebox/<juke_id>", methods=["DELETE"])
@api_check_wallet_key("admin")
async def api_delete_item(juke_id):
@jukebox_ext.delete("/api/v1/jukebox/{juke_id}", status_code=HTTPStatus.OK)
async def api_delete_item(
juke_id=None,
wallet: WalletTypeInfo = Depends(get_key_type),
):
await delete_jukebox(juke_id)
try:
return (
jsonify(
[{**jukebox._asdict()} for jukebox in await get_jukeboxs(g.wallet.user)]
),
HTTPStatus.OK,
)
return [{**jukebox._asdict()} for jukebox in await get_jukeboxs(g.wallet.user)]
except:
return "", HTTPStatus.NO_CONTENT
raise HTTPException(
status_code=HTTPStatus.NO_CONTENT,
detail="No Jukebox",
)
################JUKEBOX ENDPOINTS##################
@ -119,16 +130,20 @@ async def api_delete_item(juke_id):
######GET ACCESS TOKEN######
@jukebox_ext.route(
"/api/v1/jukebox/jb/playlist/<juke_id>/<sp_playlist>", methods=["GET"]
@jukebox_ext.get(
"/api/v1/jukebox/jb/playlist/{juke_id}/{sp_playlist}", status_code=HTTPStatus.OK
)
async def api_get_jukebox_song(juke_id, sp_playlist, retry=False):
async def api_get_jukebox_song(
juke_id: str = Query(None),
sp_playlist: str = Query(None),
retry: bool = Query(False),
):
try:
jukebox = await get_jukebox(juke_id)
except:
return (
jsonify({"error": "No Jukebox"}),
HTTPStatus.FORBIDDEN,
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="No Jukeboxes",
)
tracks = []
async with httpx.AsyncClient() as client:
@ -144,15 +159,15 @@ async def api_get_jukebox_song(juke_id, sp_playlist, retry=False):
if token == False:
return False
elif retry:
return (
jsonify({"error": "Failed to get auth"}),
HTTPStatus.FORBIDDEN,
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, HTTPStatus.OK
return r
for item in r.json()["items"]:
tracks.append(
{
@ -163,18 +178,18 @@ async def api_get_jukebox_song(juke_id, sp_playlist, retry=False):
"image": item["track"]["album"]["images"][0]["url"],
}
)
except AssertionError:
except:
something = None
return jsonify([track for track in tracks])
return [track for track in tracks]
async def api_get_token(juke_id):
async def api_get_token(juke_id=None):
try:
jukebox = await get_jukebox(juke_id)
except:
return (
jsonify({"error": "No Jukebox"}),
HTTPStatus.FORBIDDEN,
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="No Jukeboxes",
)
async with httpx.AsyncClient() as client:
@ -202,7 +217,7 @@ async def api_get_token(juke_id):
await update_jukebox(
juke_id=juke_id, sp_access_token=r.json()["access_token"]
)
except AssertionError:
except:
something = None
return True
@ -210,14 +225,17 @@ async def api_get_token(juke_id):
######CHECK DEVICE
@jukebox_ext.route("/api/v1/jukebox/jb/<juke_id>", methods=["GET"])
async def api_get_jukebox_device_check(juke_id, retry=False):
@jukebox_ext.get("/api/v1/jukebox/jb/{juke_id}", status_code=HTTPStatus.OK)
async def api_get_jukebox_device_check(
juke_id: str = Query(None),
retry: bool = Query(False),
):
try:
jukebox = await get_jukebox(juke_id)
except:
return (
jsonify({"error": "No Jukebox"}),
HTTPStatus.FORBIDDEN,
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="No Jukeboxes",
)
async with httpx.AsyncClient() as client:
rDevice = await client.get(
@ -227,42 +245,44 @@ async def api_get_jukebox_device_check(juke_id, retry=False):
)
if rDevice.status_code == 204 or rDevice.status_code == 200:
return (
rDevice,
HTTPStatus.OK,
)
return rDevice
elif rDevice.status_code == 401 or rDevice.status_code == 403:
token = await api_get_token(juke_id)
if token == False:
return (
jsonify({"error": "No device connected"}),
HTTPStatus.FORBIDDEN,
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="No devices connected",
)
elif retry:
return (
jsonify({"error": "Failed to get auth"}),
HTTPStatus.FORBIDDEN,
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Failed to get auth",
)
else:
return api_get_jukebox_device_check(juke_id, retry=True)
else:
return (
jsonify({"error": "No device connected"}),
HTTPStatus.FORBIDDEN,
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="No device connected",
)
######GET INVOICE STUFF
@jukebox_ext.route("/api/v1/jukebox/jb/invoice/<juke_id>/<song_id>", methods=["GET"])
async def api_get_jukebox_invoice(juke_id, song_id):
@jukebox_ext.get(
"/api/v1/jukebox/jb/invoice/{juke_id}/{song_id}", status_code=HTTPStatus.OK
)
async def api_get_jukebox_invoice(
juke_id: str = Query(None),
song_id: str = Query(None),
):
try:
jukebox = await get_jukebox(juke_id)
except:
return (
jsonify({"error": "No Jukebox"}),
HTTPStatus.FORBIDDEN,
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="No jukebox",
)
try:
deviceCheck = await api_get_jukebox_device_check(juke_id)
@ -272,14 +292,14 @@ async def api_get_jukebox_invoice(juke_id, song_id):
if device["id"] == jukebox.sp_device.split("-")[1]:
deviceConnected = True
if not deviceConnected:
return (
jsonify({"error": "No device connected"}),
HTTPStatus.NOT_FOUND,
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="No device connected",
)
except:
return (
jsonify({"error": "No device connected"}),
HTTPStatus.NOT_FOUND,
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="No device connected",
)
invoice = await create_invoice(
@ -291,44 +311,53 @@ async def api_get_jukebox_invoice(juke_id, song_id):
jukebox_payment = await create_jukebox_payment(song_id, invoice[0], juke_id)
return jsonify(invoice, jukebox_payment)
return {invoice, jukebox_payment}
@jukebox_ext.route(
"/api/v1/jukebox/jb/checkinvoice/<pay_hash>/<juke_id>", methods=["GET"]
@jukebox_ext.get(
"/api/v1/jukebox/jb/checkinvoice/{pay_hash}/{juke_id}", status_code=HTTPStatus.OK
)
async def api_get_jukebox_invoice_check(pay_hash, juke_id):
async def api_get_jukebox_invoice_check(
pay_hash: str = Query(None),
juke_id: str = Query(None),
):
try:
jukebox = await get_jukebox(juke_id)
except:
return (
jsonify({"error": "No Jukebox"}),
HTTPStatus.FORBIDDEN,
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="No jukebox",
)
try:
status = await check_invoice_status(jukebox.wallet, pay_hash)
is_paid = not status.pending
except Exception as exc:
return jsonify({"paid": False}), HTTPStatus.OK
except:
return {"paid": False}
if is_paid:
wallet = await get_wallet(jukebox.wallet)
payment = await wallet.get_payment(pay_hash)
await payment.set_pending(False)
await update_jukebox_payment(pay_hash, paid=True)
return jsonify({"paid": True}), HTTPStatus.OK
return jsonify({"paid": False}), HTTPStatus.OK
return {"paid": True}
return {"paid": False}
@jukebox_ext.route(
"/api/v1/jukebox/jb/invoicep/<song_id>/<juke_id>/<pay_hash>", methods=["GET"]
@jukebox_ext.get(
"/api/v1/jukebox/jb/invoicep/{song_id}/{juke_id}/{pay_hash}",
status_code=HTTPStatus.OK,
)
async def api_get_jukebox_invoice_paid(song_id, juke_id, pay_hash, retry=False):
async def api_get_jukebox_invoice_paid(
song_id: str = Query(None),
juke_id: str = Query(None),
pay_hash: str = Query(None),
retry: bool = Query(False),
):
try:
jukebox = await get_jukebox(juke_id)
except:
return (
jsonify({"error": "No Jukebox"}),
HTTPStatus.FORBIDDEN,
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)
@ -363,23 +392,23 @@ async def api_get_jukebox_invoice_paid(song_id, juke_id, pay_hash, retry=False):
elif r.status_code == 401 or r.status_code == 403:
token = await api_get_token(juke_id)
if token == False:
return (
jsonify({"error": "Invoice not paid"}),
HTTPStatus.FORBIDDEN,
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Invoice not paid",
)
elif retry:
return (
jsonify({"error": "Failed to get auth"}),
HTTPStatus.FORBIDDEN,
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:
return (
jsonify({"error": "Invoice not paid"}),
HTTPStatus.FORBIDDEN,
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Invoice not paid",
)
elif r.status_code == 200:
async with httpx.AsyncClient() as client:
@ -392,59 +421,65 @@ async def api_get_jukebox_invoice_paid(song_id, juke_id, pay_hash, retry=False):
headers={"Authorization": "Bearer " + jukebox.sp_access_token},
)
if r.status_code == 204:
return jsonify(jukebox_payment), HTTPStatus.OK
return jukebox_payment
elif r.status_code == 401 or r.status_code == 403:
token = await api_get_token(juke_id)
if token == False:
return (
jsonify({"error": "Invoice not paid"}),
HTTPStatus.OK,
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Invoice not paid",
)
elif retry:
return (
jsonify({"error": "Failed to get auth"}),
HTTPStatus.FORBIDDEN,
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:
return (
jsonify({"error": "Invoice not paid"}),
HTTPStatus.OK,
raise HTTPException(
status_code=HTTPStatus.OK,
detail="Invoice not paid",
)
elif r.status_code == 401 or r.status_code == 403:
token = await api_get_token(juke_id)
if token == False:
return (
jsonify({"error": "Invoice not paid"}),
HTTPStatus.OK,
raise HTTPException(
status_code=HTTPStatus.OK,
detail="Invoice not paid",
)
elif retry:
return (
jsonify({"error": "Failed to get auth"}),
HTTPStatus.FORBIDDEN,
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
)
return jsonify({"error": "Invoice not paid"}), HTTPStatus.OK
raise HTTPException(
status_code=HTTPStatus.OK,
detail="Invoice not paid",
)
############################GET TRACKS
@jukebox_ext.route("/api/v1/jukebox/jb/currently/<juke_id>", methods=["GET"])
async def api_get_jukebox_currently(juke_id, retry=False):
@jukebox_ext.get("/api/v1/jukebox/jb/currently/{juke_id}", status_code=HTTPStatus.OK)
async def api_get_jukebox_currently(
retry: bool = Query(False),
juke_id: str = Query(None),
):
try:
jukebox = await get_jukebox(juke_id)
except:
return (
jsonify({"error": "No Jukebox"}),
HTTPStatus.FORBIDDEN,
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="No jukebox",
)
async with httpx.AsyncClient() as client:
try:
@ -454,7 +489,10 @@ async def api_get_jukebox_currently(juke_id, retry=False):
headers={"Authorization": "Bearer " + jukebox.sp_access_token},
)
if r.status_code == 204:
return jsonify({"error": "Nothing"}), HTTPStatus.OK
raise HTTPException(
status_code=HTTPStatus.OK,
detail="Nothing",
)
elif r.status_code == 200:
try:
response = r.json()
@ -466,25 +504,34 @@ async def api_get_jukebox_currently(juke_id, retry=False):
"artist": response["item"]["artists"][0]["name"],
"image": response["item"]["album"]["images"][0]["url"],
}
return jsonify(track), HTTPStatus.OK
return track
except:
return jsonify("Something went wrong"), HTTPStatus.NOT_FOUND
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="Something went wrong",
)
elif r.status_code == 401:
token = await api_get_token(juke_id)
if token == False:
return (
jsonify({"error": "Invoice not paid"}),
HTTPStatus.FORBIDDEN,
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="INvoice not paid",
)
elif retry:
return (
jsonify({"error": "Failed to get auth"}),
HTTPStatus.FORBIDDEN,
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Failed to get auth",
)
else:
return await api_get_jukebox_currently(juke_id, retry=True)
return await api_get_jukebox_currently(retry=True, juke_id=juke_id)
else:
return jsonify("Something went wrong"), HTTPStatus.NOT_FOUND
except AssertionError:
return jsonify("Something went wrong"), HTTPStatus.NOT_FOUND
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="Something went wrong",
)
except:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="Something went wrong",
)

View File

@ -24,6 +24,7 @@ lnurlp_ext: APIRouter = APIRouter(
# "lnurlp", __name__, static_folder="static", template_folder="templates"
)
def lnurlp_renderer():
return template_renderer(
[
@ -37,13 +38,12 @@ from .views import * # noqa
from .tasks import wait_for_paid_invoices
from .lnurl import * # noqa
def lnurlp_start():
loop = asyncio.get_event_loop()
loop.create_task(catch_everything_and_restart(wait_for_paid_invoices))
# from lnbits.tasks import record_async
# lnurlp_ext.record(record_async(register_listeners))