time to add a websocket

This commit is contained in:
Ben Arc 2021-06-07 12:03:13 +01:00
parent 3faf426945
commit 9963412fe6
3 changed files with 141 additions and 74 deletions

View file

@ -195,7 +195,10 @@ new Vue({
if (self.jukeboxDialog.data.sp_access_token) { if (self.jukeboxDialog.data.sp_access_token) {
self.refreshPlaylists() self.refreshPlaylists()
self.refreshDevices() self.refreshDevices()
setTimeout(function () {}, 2000) console.log("this.devices")
console.log(self.devices)
console.log("this.devices")
setTimeout(function () {
if (self.devices.length < 1 && self.playlists.length < 1) { if (self.devices.length < 1 && self.playlists.length < 1) {
self.$q.notify({ self.$q.notify({
spinner: true, spinner: true,
@ -222,6 +225,7 @@ new Vue({
self.step = 4 self.step = 4
clearInterval(timerId) clearInterval(timerId)
} }
}, 2000)
} }
} }
}) })
@ -305,6 +309,7 @@ new Vue({
responseObj.items[i].name + '-' + responseObj.items[i].id responseObj.items[i].name + '-' + responseObj.items[i].id
) )
} }
console.log(self.playlists)
} }
}, },
refreshPlaylists() { refreshPlaylists() {
@ -358,22 +363,22 @@ new Vue({
'&redirect_uri=' + '&redirect_uri=' +
encodeURI(self.locationcbPath + self.jukeboxDialog.data.sp_id) encodeURI(self.locationcbPath + self.jukeboxDialog.data.sp_id)
this.callAuthorizationApi(body) self.callAuthorizationApi(body)
}, },
refreshAccessToken() { refreshAccessToken() {
self = this self = this
let body = 'grant_type=refresh_token' let body = 'grant_type=refresh_token'
body += '&refresh_token=' + self.jukeboxDialog.data.sp_refresh_token body += '&refresh_token=' + self.jukeboxDialog.data.sp_refresh_token
body += '&client_id=' + self.jukeboxDialog.data.sp_user body += '&client_id=' + self.jukeboxDialog.data.sp_user
this.callAuthorizationApi(body) self.callAuthorizationApi(body)
}, },
callAuthorizationApi(body) { callAuthorizationApi(body) {
self = this self = this
console.log( console.log(
btoa( btoa(
this.jukeboxDialog.data.sp_user + self.jukeboxDialog.data.sp_user +
':' + ':' +
this.jukeboxDialog.data.sp_secret self.jukeboxDialog.data.sp_secret
) )
) )
let xhr = new XMLHttpRequest() let xhr = new XMLHttpRequest()
@ -383,9 +388,9 @@ new Vue({
'Authorization', 'Authorization',
'Basic ' + 'Basic ' +
btoa( btoa(
this.jukeboxDialog.data.sp_user + self.jukeboxDialog.data.sp_user +
':' + ':' +
this.jukeboxDialog.data.sp_secret self.jukeboxDialog.data.sp_secret
) )
) )
xhr.send(body) xhr.send(body)

View file

@ -111,6 +111,7 @@
playlist: '', playlist: '',
heavyList: [], heavyList: [],
selectedWallet: {}, selectedWallet: {},
paid: false,
receive: { receive: {
dialogues: { dialogues: {
first: false, first: false,
@ -166,16 +167,66 @@
song_id song_id
) )
.then(function (response) { .then(function (response) {
console.log('response.data')
console.log(response.data)
console.log('response.data')
self.receive.paymentReq = response.data[0][1] self.receive.paymentReq = response.data[0][1]
self.receive.paymentHash = response.data[0][0] self.receive.paymentHash = response.data[0][0]
self.receive.dialogues.second = true self.receive.dialogues.second = true
var refreshIntervalId = setInterval(function () {
self.checkInvoice(self.receive.paymentHash)
if(self.paid){
self.receive.dialogues.first = false
self.receive.dialogues.second = false
self.$q.notify({
message:
'Processing',
})
console.log('/api/v1/jukebox/jb/invoicepaid/' + self.receive.paymentHash + '/{{ juke_id }}')
LNbits.api
.request(
'GET',
'/api/v1/jukebox/jb/invoicepaid/' + self.receive.paymentHash + '/{{ juke_id }}')
.then(function (response) {
self.$q.notify({
color: 'green',
message:
'Success! "' + self.receive.name + '" will be played soon',
timeout: 2000
})
clearInterval(refreshIntervalId)
}) })
.catch(err => { .catch(err => {
LNbits.utils.notifyApiError(err) LNbits.utils.notifyApiError(err)
}) })
}
}, 2000)
})
.catch(err => {
LNbits.utils.notifyApiError(err)
})
},
checkInvoice: function (paymentHash) {
var self = this
LNbits.api
.request(
'GET',
'/public/v1/payment/' + paymentHash,
'filla'
)
.then(function (response) {
console.log(response)
if (response) {
self.paid = true
return
}
else{
self.paid = false
return
}
})
.catch(function (error) {
LNbits.utils.notifyApiError(error)
})
}, },
getCurrent() { getCurrent() {
axios axios

View file

@ -22,6 +22,7 @@ from .crud import (
from .models import Jukebox from .models import Jukebox
from lnbits.core.services import create_invoice, check_invoice_status from lnbits.core.services import create_invoice, check_invoice_status
@jukebox_ext.route("/api/v1/jukebox", methods=["GET"]) @jukebox_ext.route("/api/v1/jukebox", methods=["GET"])
@api_check_wallet_key("invoice") @api_check_wallet_key("invoice")
async def api_get_jukeboxs(): async def api_get_jukeboxs():
@ -41,7 +42,6 @@ async def api_get_jukeboxs():
@jukebox_ext.route("/api/v1/jukebox/spotify/cb/<juke_id>", methods=["GET"]) @jukebox_ext.route("/api/v1/jukebox/spotify/cb/<juke_id>", methods=["GET"])
async def api_check_credentials_callbac(juke_id): async def api_check_credentials_callbac(juke_id):
print(request.args)
sp_code = "" sp_code = ""
sp_access_token = "" sp_access_token = ""
sp_refresh_token = "" sp_refresh_token = ""
@ -92,6 +92,7 @@ async def api_create_update_jukebox(juke_id=None):
jukebox = await update_jukebox(juke_id=juke_id, inkey=g.wallet.inkey, **g.data) jukebox = await update_jukebox(juke_id=juke_id, inkey=g.wallet.inkey, **g.data)
else: else:
jukebox = await create_jukebox(inkey=g.wallet.inkey, **g.data) jukebox = await create_jukebox(inkey=g.wallet.inkey, **g.data)
return jsonify(jukebox._asdict()), HTTPStatus.CREATED return jsonify(jukebox._asdict()), HTTPStatus.CREATED
@ -130,7 +131,7 @@ async def api_get_jukebox_son(sp_id, sp_playlist):
if r.json()["error"]["status"] == 401: if r.json()["error"]["status"] == 401:
token = await api_get_token(sp_id) token = await api_get_token(sp_id)
if token == False: if token == False:
print("invalid")
return False return False
else: else:
return await api_get_jukebox_son(sp_id, sp_playlist) return await api_get_jukebox_son(sp_id, sp_playlist)
@ -138,28 +139,24 @@ async def api_get_jukebox_son(sp_id, sp_playlist):
for item in r.json()["items"]: for item in r.json()["items"]:
tracks.append( tracks.append(
{ {
'id': item["track"]["id"], "id": item["track"]["id"],
'name': item["track"]["name"], "name": item["track"]["name"],
'album': item["track"]["album"]["name"], "album": item["track"]["album"]["name"],
'artist': item["track"]["artists"][0]["name"], "artist": item["track"]["artists"][0]["name"],
'image': item["track"]["album"]["images"][0]["url"] "image": item["track"]["album"]["images"][0]["url"],
} }
) )
except AssertionError: except AssertionError:
something = None something = None
return jsonify([track for track in tracks]) return jsonify([track for track in tracks])
# return jsonify([track for track in tracks]) # return jsonify([track for track in tracks])
async def api_get_token(sp_id): async def api_get_token(sp_id):
jukebox = await get_jukebox(sp_id) jukebox = await get_jukebox(sp_id)
print(
"Authorization: Bearer "
+ base64.b64encode(
str(jukebox.sp_user + ":" + jukebox.sp_secret).encode("ascii")
).decode("ascii")
)
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
try: try:
r = await client.post( r = await client.post(
@ -192,50 +189,64 @@ async def api_get_token(sp_id):
######GET INVOICE STUFF ######GET INVOICE STUFF
@jukebox_ext.route("/api/v1/jukebox/jb/invoice/<sp_id>/<song_id>", methods=["GET"]) @jukebox_ext.route("/api/v1/jukebox/jb/invoice/<sp_id>/<song_id>", methods=["GET"])
async def api_get_jukebox_invoice(sp_id, song_id): async def api_get_jukebox_invoice(sp_id, song_id):
jukebox = await get_jukebox(sp_id) jukebox = await get_jukebox(sp_id)
invoice = await create_invoice(wallet_id=jukebox.wallet,amount=jukebox.price,memo=jukebox.title, extra={"tag": "jukebox"},) invoice = await create_invoice(
wallet_id=jukebox.wallet,
amount=jukebox.price,
memo=jukebox.title,
extra={"tag": "jukebox"},
)
jukebox_payment = await create_jukebox_payment(song_id, invoice[0]) jukebox_payment = await create_jukebox_payment(song_id, invoice[0])
print(jukebox_payment)
return jsonify(invoice, jukebox_payment) return jsonify(invoice, jukebox_payment)
@jukebox_ext.route("/api/v1/jukebox/jb/invoicepaid/<payment_hash>/<sp_id>", methods=["GET"]) @jukebox_ext.route(
async def api_get_jukebox_invoice_paid(sp_id, payment_hash): "/api/v1/jukebox/jb/invoicep/<sp_id>/<payment_hash>", methods=["GET"]
)
async def api_get_jukebox_invoice_paid(payment_hash, sp_id):
jukebox = await get_jukebox(sp_id) jukebox = await get_jukebox(sp_id)
print(jukebox)
paid = await check_invoice_status(jukebox.wallet, payment_hash)
if paid:
jukebox_payment = await update_jukebox_payment(payment_hash, paid=True) jukebox_payment = await update_jukebox_payment(payment_hash, paid=True)
print("https://api.spotify.com/v1/me/player/queue?uri=spotify%3Atrack%3A" + jukebox_payment.song_id + "&device_id=" + jukebox.sp_device) else:
return jsonify({"error": "Invoice not paid"})
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
try:
r = await client.get( r = await client.post(
"https://api.spotify.com/v1/me/player/queue?uri=spotify%3Atrack%3A" + jukebox_payment.song_id + "&device_id=" + jukebox.sp_device, "https://api.spotify.com/v1/me/player/queue?uri=spotify%3Atrack%3A"
+ jukebox_payment.song_id
+ "&device_id="
+ jukebox.sp_device.split("-")[1],
timeout=40, timeout=40,
headers={"Authorization": "Bearer " + jukebox.sp_access_token}, headers={"Authorization": "Bearer " + jukebox.sp_access_token},
) )
print(r)
if r.json()["error"]["status"] == 401: if r.json()["error"]["status"] == 401:
token = await api_get_token(sp_id) token = await api_get_token(sp_id)
if token == False: if token == False:
print("invalid")
return jsonify({"error": "Something went wrong"}) return jsonify({"error": "Something went wrong"})
else: else:
return await api_get_jukebox_invoice_paid(sp_id, payment_hash) return await api_get_jukebox_invoice_paid(sp_id, payment_hash)
if r.json()["error"]["status"] == 400: if r.json()["error"]["status"] == 400:
return jsonify({"error": "Something went wrong"}) return jsonify({"error": "Something went wrong"})
return jsonify(r), HTTPStatus.OK return jsonify(r), HTTPStatus.OK
except AssertionError:
something = None
return jsonify({"error": "Something went wrong"}) # if not is_paid:
if not is_paid: # return jsonify({"status": False})
return jsonify({"status": False}) # return jsonify({"error": "Something went wrong"})
return jsonify({"error": "Something went wrong"})
############################GET TRACKS ############################GET TRACKS
@jukebox_ext.route("/api/v1/jukebox/jb/currently/<sp_id>", methods=["GET"]) @jukebox_ext.route("/api/v1/jukebox/jb/currently/<sp_id>", methods=["GET"])
async def api_get_jukebox_currently(sp_id): async def api_get_jukebox_currently(sp_id):
jukebox = await get_jukebox(sp_id) jukebox = await get_jukebox(sp_id)
@ -249,11 +260,11 @@ async def api_get_jukebox_currently(sp_id):
try: try:
if r.json()["item"]: if r.json()["item"]:
track = { track = {
'id': r.json()["item"]["id"], "id": r.json()["item"]["id"],
'name': r.json()["item"]["name"], "name": r.json()["item"]["name"],
'album': r.json()["item"]["album"]["name"], "album": r.json()["item"]["album"]["name"],
'artist': r.json()["item"]["artists"][0]["name"], "artist": r.json()["item"]["artists"][0]["name"],
'image': r.json()["item"]["album"]["images"][0]["url"] "image": r.json()["item"]["album"]["images"][0]["url"],
} }
return track, HTTPStatus.OK return track, HTTPStatus.OK
except AssertionError: except AssertionError:
@ -262,7 +273,7 @@ async def api_get_jukebox_currently(sp_id):
if r.json()["error"]["status"] == 401: if r.json()["error"]["status"] == 401:
token = await api_get_token(sp_id) token = await api_get_token(sp_id)
if token == False: if token == False:
print("invalid")
return jsonify({"error": "Something went wrong"}) return jsonify({"error": "Something went wrong"})
else: else:
return await api_get_jukebox_currently(sp_id) return await api_get_jukebox_currently(sp_id)