summaryrefslogtreecommitdiff
path: root/src/bg/RequestUtil.js
blob: fa099d69bfb1d8f7a63f25a0a8d08ca24cb5e0c2 (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
'use strict';
{
  let NULL = new Uint8Array();
  let DEFAULT_CHARSET = "utf-8";
  let xmlFeedOrImage = /^(?:(?:application|text)\/(?:(?:r(?:ss|df)|atom)\+)xml(;|$))|image\//i;
  let rawXml = /^(?:application|text)\/xml;/i;
  let brokenOnLoad;

  let pendingRequests = new Map();

  let reloadingTabs = new Set();
  let tabKey = (tabId, url) => `${tabId}:${url}`;

  let cleanup = r => {
    pendingRequests.delete(r.requestId);
  };
  let filter = {
    urls: ["<all_urls>"],
    types:  ["main_frame", "sub_frame", "object"]
  };


  browser.webRequest.onCompleted.addListener(r => {
    cleanup(r);
    let {tabId, url} = r;
    let key = tabKey(tabId, url);
    if (reloadingTabs.has(key)) {
      debug("Reloading tab", key);
      browser.tabs.update(tabId, {url});
    }
  }, filter);
  browser.webRequest.onErrorOccurred.addListener(cleanup, filter);

  let executeAll = async (scripts, where) => {
    let {url, tabId, frameId} = where;

    let count = 0;
    for (let details of scripts.values()) {
      details = Object.assign({
        runAt: "document_start",
        matchAboutBlank: true,
        frameId,
      }, details);
      try {
        await browser.tabs.executeScript(tabId, details);
        count++;
        debug("Execute on start OK", url, details);
      } catch (e) {
        error(e, "Execute on start failed", url, details);
      }
    }
    return count;
  };

  var RequestUtil = {

    getContentMetaData(request) {
      return request.content || (request.content = new ContentMetaData(request));
    },

    async executeOnStart(request, details) {
      let {requestId, url, tabId, frameId, statusCode} = request;

      if (statusCode >= 300 && statusCode < 400) return;
      let scripts = pendingRequests.get(requestId);
      let scriptKey = JSON.stringify(details);
      if (!scripts) {
        pendingRequests.set(requestId, scripts = new Map());
        scripts.set(scriptKey, details);
      } else {
        scripts.set(scriptKey, details);
        return;
      }

      if (frameId === 0) {
        let key = tabKey(tabId, url);
        debug("Checking whether %s is a reloading tab...", key);
        if (reloadingTabs.has(key)) {
          debug("Skipping dynamic script injection for reloading feed tab", key);
          let filter = browser.webRequest.filterResponseData(requestId);
          filter.onstart = e => {
            reloadingTabs.delete(key);
            filter.write(NULL);
            filter.disconnect();
          }
          return;
        }
      }

      let content = this.getContentMetaData(request);
      debug(url, content.type, content.charset);
      if (xmlFeedOrImage.test(content.type) && !/\/svg\b/i.test(content.type)) return;
      if (typeof brokenOnLoad === "undefined") {
        brokenOnLoad = await (async () => parseInt((await browser.runtime.getBrowserInfo()).version) < 61)();
      }

      let mustCheckFeed = brokenOnLoad && frameId === 0 && rawXml.test(content.type);
      debug("mustCheckFeed = %s, brokenOnLoad = %s", mustCheckFeed, brokenOnLoad);
      let filter = browser.webRequest.filterResponseData(requestId);
      let buffer = [];
      let first = true;
      let runAndFlush = async () => {
        let scriptsRan = await executeAll(scripts, request);
        if (mustCheckFeed && !scriptsRan) {
          debug(`Marking as "must reload"`, tabId, url);
          reloadingTabs.add(tabKey(tabId, url));
        }
        if (buffer && buffer.length) {
          debug("Flushing %s buffer chunks", buffer.length);
          for (let chunk of buffer) {
            filter.write(chunk);
          }
          filter.disconnect();
          buffer = null;
        }
      };

      if (brokenOnLoad) {
        filter.onstart = event => {
          filter.write(NULL);
          debug("onstart", url);
        }
      }

      filter.ondata = event => {
        if (first) {
          runAndFlush();
          first = false;
        }
        if (buffer) {
          buffer.push(event.data);
          return;
        }

        debug("ondata", url);
        filter.write(event.data);
        filter.disconnect();
      };


    }
  }
}