aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/background.ts
blob: b204b64c63a8a2595319cf0fecf4752af2c8635e (plain)
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
import * as Types from "./types";

import Config from "./config";
// Make the config public for debugging purposes
(<any> window).SB = Config;

import Utils from "./utils";
var utils = new Utils({
    registerFirefoxContentScript,
    unregisterFirefoxContentScript
});

// Used only on Firefox, which does not support non persistent background pages.
var contentScriptRegistrations = {};

// Register content script if needed
if (utils.isFirefox()) {
    utils.wait(() => Config.config !== null).then(function() {
        if (Config.config.supportInvidious) utils.setupExtraSiteContentScripts();
    });
} 

chrome.tabs.onUpdated.addListener(function(tabId) {
	chrome.tabs.sendMessage(tabId, {
        message: 'update',
	}, () => void chrome.runtime.lastError ); // Suppress error on Firefox
});

chrome.runtime.onMessage.addListener(function (request, sender, callback) {
	switch(request.message) {
        case "openConfig":
            chrome.runtime.openOptionsPage();
            return
        case "addSponsorTime":
            addSponsorTime(request.time, request.videoID, callback);
        
            //this allows the callback to be called later
            return true;
        
        case "getSponsorTimes":
            getSponsorTimes(request.videoID, function(sponsorTimes) {
                callback({
                    sponsorTimes
                });
            });
        
            //this allows the callback to be called later
            return true;
        case "submitVote":
            submitVote(request.type, request.UUID, callback);
        
            //this allows the callback to be called later
            return true;
        case "alertPrevious":
            chrome.notifications.create("stillThere" + Math.random(), {
                type: "basic",
                title: chrome.i18n.getMessage("wantToSubmit") + " " + request.previousVideoID + "?",
                message: chrome.i18n.getMessage("leftTimes"),
                iconUrl: "./icons/LogoSponsorBlocker256px.png"
            });
        case "registerContentScript": 
            registerFirefoxContentScript(request);
            return false;
        case "unregisterContentScript": 
            unregisterFirefoxContentScript(request.id)
            return false;
	}
});

//add help page on install
chrome.runtime.onInstalled.addListener(function (object) {
    // This let's the config sync to run fully before checking.
    // This is required on Firefox
    setTimeout(function() {
        const userID = Config.config.userID;

        // If there is no userID, then it is the first install.
        if (!userID){
            //open up the install page
            chrome.tabs.create({url: chrome.extension.getURL("/help/index_en.html")});

            //generate a userID
            const newUserID = utils.generateUserID();
            //save this UUID
            Config.config.userID = newUserID;
        }
    }, 1500);
});

/**
 * Only works on Firefox.
 * Firefox requires that it be applied after every extension restart.
 * 
 * @param {JSON} options 
 */
function registerFirefoxContentScript(options) {
    let oldRegistration = contentScriptRegistrations[options.id];
    if (oldRegistration) oldRegistration.unregister();

    browser.contentScripts.register({
        allFrames: options.allFrames,
        js: options.js,
        css: options.css,
        matches: options.matches
    }).then((registration) => void (contentScriptRegistrations[options.id] = registration));
}

/**
 * Only works on Firefox.
 * Firefox requires that this is handled by the background script
 * 
 */
function unregisterFirefoxContentScript(id: string) {
    contentScriptRegistrations[id].unregister();
    delete contentScriptRegistrations[id];
}

//gets the sponsor times from memory
function getSponsorTimes(videoID, callback) {
    let sponsorTimes = [];
    let sponsorTimesStorage = Config.config.sponsorTimes.get(videoID);

    if (sponsorTimesStorage != undefined && sponsorTimesStorage.length > 0) {
        sponsorTimes = sponsorTimesStorage;
    }
	
    callback(sponsorTimes);
}

function addSponsorTime(time, videoID, callback) {
    getSponsorTimes(videoID, function(sponsorTimes) {
        //add to sponsorTimes
        if (sponsorTimes.length > 0 && sponsorTimes[sponsorTimes.length - 1].length < 2) {
            //it is an end time
            sponsorTimes[sponsorTimes.length - 1][1] = time;
        } else {
            //it is a start time
            let sponsorTimesIndex = sponsorTimes.length;
            sponsorTimes[sponsorTimesIndex] = [];

            sponsorTimes[sponsorTimesIndex][0] = time;
        }

        //save this info
		Config.config.sponsorTimes.set(videoID, sponsorTimes);
		callback();
    });
}

function submitVote(type, UUID, callback) {
    let userID = Config.config.userID;

    if (userID == undefined || userID === "undefined") {
        //generate one
        userID = utils.generateUserID();
        Config.config.userID = userID;
    }

    //publish this vote
    utils.sendRequestToServer("POST", "/api/voteOnSponsorTime?UUID=" + UUID + "&userID=" + userID + "&type=" + type, function(xmlhttp, error) {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            callback({
                successType: 1
            });
        } else if (xmlhttp.readyState == 4 && xmlhttp.status == 405) {
            //duplicate vote
            callback({
                successType: 0,
                statusCode: xmlhttp.status
            });
        } else if (error) {
            //error while connect
            callback({
                successType: -1,
                statusCode: xmlhttp.status
            });
        }

    });
}