-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
127 lines (104 loc) · 3.21 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
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
var disable = false;
var reverse = false;
var shuffle = false;
var folder = "playlist";
// todo use 'browser' everywhere
var browser = browser || chrome;
function loadSettings()
{
chrome.storage.sync.get([
"disable",
"shuffle",
"reverse",
"folder",
], function(cfg) {
disable = cfg.disable;
reverse = cfg.reverse;
shuffle = cfg.shuffle;
folder = cfg.folder || "playlist";
});
}
loadSettings();
function updateTabUrl(tabId, newUrl)
{
chrome.tabs.update(tabId, {url: newUrl});
}
function pickNext(tab)
{
// disable can be true when the user clicks our action icon
if (disable) {
disable = false;
chrome.storage.sync.set({disable: false});
}
function pickNonShuffle(items, begin, end) {
var found = false;
var n = items.length;
var a = !reverse ? begin : end-1;
var b = !reverse ? end-1 : begin;
var d = !reverse ? 1 : -1;
for (var i = a; i != b; i += d) {
if (found && items[i].url && items[i].url.indexOf(".youtube.com/watch") != -1) {
updateTabUrl(tab.id, items[i].url);
return true;
}
found |= items[i].url == tab.url;
}
return false;
}
function pickShuffle(items, begin, end) {
if (! (begin < end)) return;
var cur;
for (cur=begin; cur<end; cur++)
if (items[cur].url == tab.url)
break;
if (cur == end)
cur = begin;
for (;;) {
var n = end - begin;
var r = Math.floor(Math.random() * (n - 1));
var next = begin + (cur + 1 + r) % n;
if (items[next].url && items[next].url.indexOf(".youtube.com/watch") != -1) {
updateTabUrl(tab.id, items[next].url);
return;
}
}
}
chrome.bookmarks.search({}, function(items) {
var begin = 0;
var end = items.length;
for (var i=0; i<items.length; i++) {
if (items[i].title == folder && !items[i].url) {
begin = i;
} else if (begin && items[i].parentId == items[begin].parentId) {
end = i;
break;
}
}
if (shuffle || !pickNonShuffle(items, begin, end))
pickShuffle(items, begin, end);
});
}
chrome.browserAction.onClicked.addListener(function(tab__unused) {
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
if (!tabs[0]) return;
if (tabs[0].url.indexOf(".youtube.com") != -1) {
pickNext(tabs[0]);
return;
}
chrome.tabs.query({'url': "https://*.youtube.com/*"}, function (tabs) {
if (tabs[0]) {
pickNext(tabs[0]);
return;
}
alert("Open a youtube tab first.");
});
});
});
browser.runtime.onMessage.addListener(function(msg, sender) {
if (msg.name == "settings-changed") {
loadSettings();
} else if (msg.name == "video-ended") {
if (!disable)
pickNext(sender.tab);
}
});