-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent-script.js
107 lines (82 loc) · 2.64 KB
/
content-script.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
function getCurrentVideoId(window) {
const videoIdMatch = window.location.href.match(/\/watch\?v=([0-9a-zA-Z]+)/);
if(videoIdMatch == null) {
return null;
}
return videoIdMatch[1];
}
function getCurrentVideoInfo(window) {
return {
videoId: getCurrentVideoId(window),
videoDescription: getDescription(window.document, isTracklistCandidate),
videoComments: getTopTracklistComments(window.document, isTracklistCandidate)
};
}
function hasInfoChanged(oldVideoInfo, newVideoInfo) {
return !_.isEqual(oldVideoInfo, newVideoInfo);
}
function updateVideoInfo(state, newVideoInfo, updateTime) {
state.currentVideoInfo = newVideoInfo;
state.isInfoChanging = true;
state.lastInfoChange = updateTime;
}
function isInfoChangeComplete(state, currentTime, debounceMilliseconds) {
return state.isInfoChanging &&
currentTime.getTime() - state.lastInfoChange.getTime() >= debounceMilliseconds;
}
function getNowPlaying(time, tracklist) {
if (!tracklist) return null;
let i = 0;
while (i < tracklist.length && time >= tracklist[i].time) i++;
return i - 1;
}
const updateCompleteDebounceMillis = 1000;
const player = document.getElementById("movie_player");
const state = {
currentVideoInfo: null,
isInfoChanging: false,
lastInfoChange: null,
candidates: null,
tracklist: null,
currentlyPlaying: -1,
video: player.getElementsByTagName("video")[0]
};
function clearNowPlayingInfo(state) {
state.currentlyPlaying = -1;
state.tracklist = null
}
function updateTracklist(state, document) {
state.candidates = getTracklistCandidates(document, isTracklistCandidate);
console.log(state.candidates);
state.tracklist = getTrackList(state.candidates);
console.log(state.tracklist);
}
function updateNowPlayingInfo(state) {
const newNowPlaying = getNowPlaying(state.video.currentTime, state.tracklist);
if (newNowPlaying !== null && newNowPlaying !== state.currentlyPlaying) {
state.currentlyPlaying = newNowPlaying;
const track = state.tracklist[state.currentlyPlaying];
console.log(track.title);
chrome.runtime.sendMessage({
name: track.title,
time: track.time,
index: state.currentlyPlaying
});
}
}
function loopFn() {
const now = new Date();
const newVideoInfo = getCurrentVideoInfo(window);
if(hasInfoChanged(state.currentVideoInfo, newVideoInfo)) {
updateVideoInfo(state, newVideoInfo, now);
clearNowPlayingInfo(state);
}
if (isInfoChangeComplete(state, now, updateCompleteDebounceMillis)) {
state.isInfoChanging = false;
updateTracklist(state, document);
}
if(state.tracklist) {
updateNowPlayingInfo(state)
}
}
setInterval(loopFn, 1000);