-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
78 lines (66 loc) · 2.04 KB
/
background.js
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
const menuId = "detektor";
const storage = browser.storage.local;
browser.contextMenus.create({
id: menuId,
title: "Add to Playlist"
});
browser.contextMenus.onClicked.addListener(function(info, tab) {
if (info.menuItemId == menuId) {
browser.tabs.executeScript({
file: "detektor.js"
});
}
});
var socket = new Phoenix.Socket('ws://localhost:4000/socket');
socket.connect();
channel = socket.channel("detektor:main", {});
channel
.join()
.receive("ok", resp => {
console.log("Joined successfully", resp)
})
.receive("error", resp => { console.log("Unable to join", resp) })
var port;
// popup
function onConnection(data) {
storage.get("playlist").then(function (res) {
var currentPlaylist = res["playlist"];
if (!currentPlaylist) {
currentPlaylist = [];
}
if (data.action == 'addToPlaylist') {
if (_.findWhere(currentPlaylist, {url: data.url})) {
return;
}
var track = {
url: data.url,
title: data.title,
key: "N/A"
};
channel.push("getKeyForUrl", data.url);
currentPlaylist.push(track);
storage.set({"playlist": currentPlaylist});
} else if (data.action == 'analyze') {
channel.push("getKeyForUrl", data.url);
}
});
}
browser.runtime.onConnect.addListener(function(_port) {
port = _port;
port.onMessage.addListener(onConnection);
});
// content script
channel.on("keyFound", track => {
storage.get("playlist").then(function (res) {
var playlist = res["playlist"];
var oldTrack = _.findWhere(playlist, {url: track.url});
if (!oldTrack) {
console.log("Playlist should've been cleared before receving key response.");
return
}
var newPlaylist = _.without(playlist, oldTrack);
oldTrack.key = track.key;
newPlaylist.push(oldTrack);
storage.set({"playlist": newPlaylist});
})
})