-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspq_functions.js
More file actions
255 lines (215 loc) · 8.08 KB
/
spq_functions.js
File metadata and controls
255 lines (215 loc) · 8.08 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
var spQ_deviceId = "";
var spQ_connectionId = "";
var spQ_subdomain = "";
var spQ_isUnlocked = false;
var spQ_accessToken = "";
var spQ_accessTokenExpiry = 0;
const HIGHLIGHTED_CLASS = 'nCwi6jOC9FEKO5tKAQKW';
const FADED_CLASS = 'Svg-sc-ytk21e-0 ewCuAY';
const Action = {
SendToTop: 0,
SendToBottom: 1,
ShuffleQueue: 2,
ReverseQueue: 3
};
const QueueType = {
Queue: 0,
NextUp: 1
};
// Detect when a context menu is opened, add the options
new MutationObserver(function() {
// Do nothing if the queue page is not open
if (!getQueueSongs() && !getNextSongs()) return;
const contextMenus = document.querySelectorAll("#context-menu > ul");
for (const menu of contextMenus) {
updateMenu(menu);
}
}).observe(document.body, { childList: true });
// Add new options to the context menu
function updateMenu(menu) {
// Get the index of the 'Remove from queue' button, used to determine valid menu
const rqIndx = [...menu.children].findIndex((c) => c.firstChild.children[1].innerText === 'Remove from queue');
const nextButton = menu.children[rqIndx+1].firstChild.children[1];
// Check if new buttons have been added yet
if (rqIndx !== -1 && nextButton.innerText !== 'Send to top') {
// Create 4 new cloned buttons
for (let i = 0; i < 4; i++) {
menu.insertBefore(menu.children[rqIndx].cloneNode(true), menu.children[rqIndx+1]);
}
const leftArrow = document.querySelector("[data-testid='top-bar-back-button']").firstChild;
const shuffleIcon = document.querySelector("[data-testid='control-button-shuffle']").firstChild;
const reverseIcon = document.querySelector("[data-testid='control-button-repeat']").firstChild;
// Update cloned buttons icons
menu.children[rqIndx+1].firstChild.firstChild.replaceWith(leftArrow.cloneNode(true));
menu.children[rqIndx+1].firstChild.firstChild.setAttribute('transform', 'rotate(90)');
menu.children[rqIndx+2].firstChild.firstChild.replaceWith(leftArrow.cloneNode(true));
menu.children[rqIndx+2].firstChild.firstChild.setAttribute('transform', 'rotate(-90)');
menu.children[rqIndx+3].firstChild.firstChild.replaceWith(shuffleIcon.cloneNode(true));
menu.children[rqIndx+4].firstChild.firstChild.replaceWith(reverseIcon.cloneNode(true));
// Update classes to match appearance with other buttons
for (let i = 1; i < 5; i++) {
menu.children[rqIndx+i].firstChild.firstChild.setAttribute('class', FADED_CLASS);
}
// Update cloned buttons text
menu.children[rqIndx+1].firstChild.children[1].innerText = 'Send to top';
menu.children[rqIndx+2].firstChild.children[1].innerText = 'Send to bottom';
menu.children[rqIndx+3].firstChild.children[1].innerText = 'Shuffle queue';
menu.children[rqIndx+4].firstChild.children[1].innerText = 'Reverse queue';
// Check if user selected song in "Next in queue"
let res = initButtons(QueueType.Queue, menu, rqIndx);
// Check if user selected song in "Next up/Next from"
if (res === -1) initButtons(QueueType.NextUp, menu, rqIndx);
}
}
// Modify song list, then send API call to update queue
async function updateQueue(queueType, index, action) {
const authToken = await getOAuthToken();
const subdomain = await getSubdomain();
const songLists = await getSongLists();
if (queueType === QueueType.Queue) {
updateSongList(songLists.queueSongs, index, action);
} else if (queueType === QueueType.NextUp) {
updateSongList(songLists.nextSongs, index, action);
} else {
console.log("Unknown queue type");
}
let body = {command: {
next_tracks: [...songLists.queueSongs, ...songLists.nextSongs],
endpoint: 'set_queue',
}};
fetch(`https://${subdomain}.spotify.com/connect-state/v1/player/command/from/${spQ_deviceId}/to/${spQ_deviceId}`, {
headers: {
authorization: `Bearer ${authToken}`
},
body: JSON.stringify(body),
method: "POST"
});
}
// Initialise buttons to become usable
function initButtons(queueType, menu, rqIndx) {
let queue;
let selectedIndex = -1;
if (queueType === QueueType.Queue) {
queue = getQueueSongs();
} else if (queueType === QueueType.NextUp) {
queue = getNextSongs();
} else {
console.log("Unknown queue type");
}
if (!queue) return selectedIndex;
for (var i = 0; i < queue.children.length; i++) {
const row = queue.children[i].firstChild;
if (row.firstChild.classList.contains(HIGHLIGHTED_CLASS)
|| row.firstChild.getAttribute("data-context-menu-open") === "true") {
selectedIndex = row.ariaPosInSet;
menu.children[rqIndx+1].onclick = () => { updateQueue(queueType, selectedIndex, Action.SendToTop); menu.remove(); };
menu.children[rqIndx+2].onclick = () => { updateQueue(queueType, selectedIndex, Action.SendToBottom); menu.remove(); };
menu.children[rqIndx+3].onclick = () => { updateQueue(queueType, selectedIndex, Action.ShuffleQueue); menu.remove(); };
menu.children[rqIndx+4].onclick = () => { updateQueue(queueType, selectedIndex, Action.ReverseQueue); menu.remove(); };
break;
}
}
return selectedIndex;
}
// Modify song list locally before sending to API
function updateSongList(list, index, action) {
if (action === Action.SendToTop) {
const temp = list[index];
list.splice(index, 1);
list.unshift(temp);
} else if (action === Action.SendToBottom) {
const temp = list[index];
list.splice(index, 1);
list.push(temp);
} else if (action === Action.ShuffleQueue) {
// Fisher-Yates shuffle
var j, temp;
for (var i = list.length-1; i > 0; i--) {
j = Math.floor(Math.random() * (i+1));
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
} else if (action === Action.ReverseQueue) {
var temp;
for (var i = 0; i < list.length/2; i++) {
temp = list[i];
list[i] = list[list.length-i-1];
list[list.length-i-1] = temp;
}
} else {
console.log("Unknown action");
}
return list;
}
// Get current songs in queue and next up/next from
async function getSongLists() {
let queueSongs = [];
let nextSongs = [];
const authToken = await getOAuthToken();
const subdomain = await getSubdomain();
const response = await fetch(`https://${subdomain}.spotify.com/connect-state/v1/devices/hobs_${spQ_deviceId.slice(0, 35)}`, {
headers: {
authorization: `Bearer ${authToken}`,
"x-spotify-connection-id": spQ_connectionId
},
body: '{"member_type":"CONNECT_STATE","device":{"device_info":{"capabilities":{"can_be_player":false,"hidden":true,"needs_full_player_state":true}}}}',
method: "PUT"
});
const data = await response.json();
for (const track of data["player_state"]["next_tracks"]) {
if (track["provider"] === "queue") {
queueSongs.push(track);
} else if (track["provider"] === "context") {
nextSongs.push(track);
}
}
return {queueSongs: queueSongs, nextSongs: nextSongs};
}
// Spotify sometimes locks use of the menu, this will allow the user to regain control of the added buttons
async function unlockMenu() {
spQ_isUnlocked = true;
const authToken = await getOAuthToken();
const subdomain = await getSubdomain();
fetch(`https://${subdomain}.spotify.com/connect-state/v1/connect/transfer/from/${spQ_deviceId}/to/${spQ_deviceId}`, {
headers: {
authorization: `Bearer ${authToken}`
},
body: '{"transfer_options":{"restore_paused":"pause"}}',
method: "POST"
}).then(function(response) {
if (!response.ok) {
setTimeout(() => { unlockMenu() }, 500);
}
});
}
async function getOAuthToken() {
if (Date.now() > spQ_accessTokenExpiry) {
const response = await fetch("https://open.spotify.com/get_access_token?reason=transport&productType=web_player");
const data = await response.json();
spQ_accessToken = data["accessToken"];
spQ_accessTokenExpiry = data["accessTokenExpirationTimestampMs"];
}
return spQ_accessToken;
}
async function getSubdomain() {
if (spQ_subdomain === "") {
const response = await fetch("https://apresolve.spotify.com/?type=spclient");
const data = await response.json();
var subd = "";
for (var i = 0; data["spclient"][0][i] !== "."; i++) {
subd += data["spclient"][0][i];
}
spQ_subdomain = subd;
}
return spQ_subdomain;
}
chrome.runtime.onMessage.addListener(
function(message) {
if (message.deviceId && message.connectionId) {
spQ_deviceId = message.deviceId;
spQ_connectionId = message.connectionId;
if (!spQ_isUnlocked) unlockMenu();
}
}
);