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

@@ -165,10 +165,10 @@ new Vue({
LNbits.utils.notifyApiError(err)
})
},
authAccess() {
authAccess() {
self = this
self.requestAuthorization()
self.getSpotifyTokens()
self.requestAuthorization()
self.getSpotifyTokens()
self.$q.notify({
spinner: true,
message: 'Processing',
@@ -195,7 +195,10 @@ new Vue({
if (self.jukeboxDialog.data.sp_access_token) {
self.refreshPlaylists()
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) {
self.$q.notify({
spinner: true,
@@ -205,7 +208,7 @@ new Vue({
timeout: 10000
})
LNbits.api
.request(
.request(
'DELETE',
'/jukebox/api/v1/jukebox/' + response.data.id,
self.g.user.wallets[0].adminkey
@@ -222,6 +225,7 @@ new Vue({
self.step = 4
clearInterval(timerId)
}
}, 2000)
}
}
})
@@ -305,6 +309,7 @@ new Vue({
responseObj.items[i].name + '-' + responseObj.items[i].id
)
}
console.log(self.playlists)
}
},
refreshPlaylists() {
@@ -342,15 +347,15 @@ new Vue({
}
}
},
refreshDevices() {
refreshDevices() {
self = this
self.deviceApi(
self.deviceApi(
'GET',
'https://api.spotify.com/v1/me/player/devices',
null
)
},
fetchAccessToken(code) {
fetchAccessToken(code) {
self = this
let body = 'grant_type=authorization_code'
body += '&code=' + code
@@ -358,22 +363,22 @@ new Vue({
'&redirect_uri=' +
encodeURI(self.locationcbPath + self.jukeboxDialog.data.sp_id)
this.callAuthorizationApi(body)
self.callAuthorizationApi(body)
},
refreshAccessToken() {
refreshAccessToken() {
self = this
let body = 'grant_type=refresh_token'
body += '&refresh_token=' + self.jukeboxDialog.data.sp_refresh_token
body += '&client_id=' + self.jukeboxDialog.data.sp_user
this.callAuthorizationApi(body)
self.callAuthorizationApi(body)
},
callAuthorizationApi(body) {
callAuthorizationApi(body) {
self = this
console.log(
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()
@@ -383,9 +388,9 @@ new Vue({
'Authorization',
'Basic ' +
btoa(
this.jukeboxDialog.data.sp_user +
self.jukeboxDialog.data.sp_user +
':' +
this.jukeboxDialog.data.sp_secret
self.jukeboxDialog.data.sp_secret
)
)
xhr.send(body)

View File

@@ -111,6 +111,7 @@
playlist: '',
heavyList: [],
selectedWallet: {},
paid: false,
receive: {
dialogues: {
first: false,
@@ -166,17 +167,67 @@
song_id
)
.then(function (response) {
console.log('response.data')
console.log(response.data)
console.log('response.data')
self.receive.paymentReq = response.data[0][1]
self.receive.paymentHash = response.data[0][0]
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 => {
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() {
axios
.get('/jukebox/api/v1/jukebox/jb/currently/{{juke_id}}')

View File

@@ -22,6 +22,7 @@ from .crud import (
from .models import Jukebox
from lnbits.core.services import create_invoice, check_invoice_status
@jukebox_ext.route("/api/v1/jukebox", methods=["GET"])
@api_check_wallet_key("invoice")
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"])
async def api_check_credentials_callbac(juke_id):
print(request.args)
sp_code = ""
sp_access_token = ""
sp_refresh_token = ""
@@ -89,9 +89,10 @@ async def api_check_credentials_check(sp_id):
)
async def api_create_update_jukebox(juke_id=None):
if juke_id:
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:
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
@@ -130,7 +131,7 @@ async def api_get_jukebox_son(sp_id, sp_playlist):
if r.json()["error"]["status"] == 401:
token = await api_get_token(sp_id)
if token == False:
print("invalid")
return False
else:
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"]:
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"]
"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"],
}
)
except AssertionError:
something = None
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):
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:
try:
r = await client.post(
@@ -192,50 +189,64 @@ async def api_get_token(sp_id):
######GET INVOICE STUFF
@jukebox_ext.route("/api/v1/jukebox/jb/invoice/<sp_id>/<song_id>", methods=["GET"])
async def api_get_jukebox_invoice(sp_id, song_id):
jukebox = await get_jukebox(sp_id)
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])
print(jukebox_payment)
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])
return jsonify(invoice, jukebox_payment)
@jukebox_ext.route("/api/v1/jukebox/jb/invoicepaid/<payment_hash>/<sp_id>", methods=["GET"])
async def api_get_jukebox_invoice_paid(sp_id, payment_hash):
@jukebox_ext.route(
"/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_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)
print(jukebox)
paid = await check_invoice_status(jukebox.wallet, payment_hash)
if paid:
jukebox_payment = await update_jukebox_payment(payment_hash, paid=True)
else:
return jsonify({"error": "Invoice not paid"})
async with httpx.AsyncClient() as client:
try:
r = await client.get(
"https://api.spotify.com/v1/me/player/queue?uri=spotify%3Atrack%3A" + jukebox_payment.song_id + "&device_id=" + jukebox.sp_device,
timeout=40,
headers={"Authorization": "Bearer " + jukebox.sp_access_token},
)
if r.json()["error"]["status"] == 401:
token = await api_get_token(sp_id)
if token == False:
print("invalid")
return jsonify({"error": "Something went wrong"})
else:
return await api_get_jukebox_invoice_paid(sp_id, payment_hash)
if r.json()["error"]["status"] == 400:
return jsonify({"error": "Something went wrong"})
return jsonify(r), HTTPStatus.OK
except AssertionError:
something = None
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.split("-")[1],
timeout=40,
headers={"Authorization": "Bearer " + jukebox.sp_access_token},
)
print(r)
if r.json()["error"]["status"] == 401:
token = await api_get_token(sp_id)
if token == False:
return jsonify({"error": "Something went wrong"})
else:
return await api_get_jukebox_invoice_paid(sp_id, payment_hash)
if r.json()["error"]["status"] == 400:
return jsonify({"error": "Something went wrong"})
if not is_paid:
return jsonify({"status": False})
return jsonify({"error": "Something went wrong"})
return jsonify(r), HTTPStatus.OK
# if not is_paid:
# return jsonify({"status": False})
# return jsonify({"error": "Something went wrong"})
############################GET TRACKS
@jukebox_ext.route("/api/v1/jukebox/jb/currently/<sp_id>", methods=["GET"])
async def api_get_jukebox_currently(sp_id):
jukebox = await get_jukebox(sp_id)
@@ -249,11 +260,11 @@ async def api_get_jukebox_currently(sp_id):
try:
if r.json()["item"]:
track = {
'id': r.json()["item"]["id"],
'name': r.json()["item"]["name"],
'album': r.json()["item"]["album"]["name"],
'artist': r.json()["item"]["artists"][0]["name"],
'image': r.json()["item"]["album"]["images"][0]["url"]
"id": r.json()["item"]["id"],
"name": r.json()["item"]["name"],
"album": r.json()["item"]["album"]["name"],
"artist": r.json()["item"]["artists"][0]["name"],
"image": r.json()["item"]["album"]["images"][0]["url"],
}
return track, HTTPStatus.OK
except AssertionError:
@@ -262,7 +273,7 @@ async def api_get_jukebox_currently(sp_id):
if r.json()["error"]["status"] == 401:
token = await api_get_token(sp_id)
if token == False:
print("invalid")
return jsonify({"error": "Something went wrong"})
else:
return await api_get_jukebox_currently(sp_id)
@@ -270,8 +281,8 @@ async def api_get_jukebox_currently(sp_id):
return jsonify({"error": "Something went wrong"})
except ValueError:
return jsonify({"error": "Something went wrong"})
except AssertionError:
something = None
return jsonify({"error": "Something went wrong"})
return jsonify({"error": "Something went wrong"})
return jsonify({"error": "Something went wrong"})