summaryrefslogtreecommitdiff
path: root/src/bg/RequestUtil.js
blob: 2999cc1be792008dd0cdd8ea74abc111e7216fae (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
'use strict';
{
  let xmlFeedOrImage = /^(?:(?:application|text)\/(?:(?:r(?:ss|df)|atom)\+)xml(;|$))|image\//i;
  let rawXml = /^(?:application|text)\/xml;/i;
  let brokenXMLOnLoad;
  (async () => brokenXMLOnLoad = parseInt((await browser.runtime.getBrowserInfo()).version) < 61)()
  
  let pendingScripts = new Map();
  let NOP = () => {};
  
  let reloadingTabs = new Map();
  let tabKey = (tabId, url) => `${tabId}:${url}`;

  let cleanup = r => {
    pendingScripts.delete(r.requestId);
    let key = tabKey(r.tabId, r.url);
    if (reloadingTabs.get(key) === false) {
      reloadingTabs.delete(key);
    }
  };
  
  let executeAll = async request => {
    let {url, tabId, frameId, requestId} = request;
    let scripts = pendingScripts.get(requestId);
    if (!scripts) return -1;
    pendingScripts.delete(requestId);
    let count = 0;
    await Promise.all([...scripts.values()].map(async details => {
      details = Object.assign({
        runAt: "document_start",
        matchAboutBlank: true,
        frameId,
      }, details);
      try {
        for (let attempts = 10; attempts-- > 0;) {
          try {
            await browser.tabs.executeScript(tabId, details);
          } catch(e) {
            if (!/No matching message handler/.test(e.message)) throw e;
            debug("Couldn't inject script into %s: too early? Retrying up to %s times...", url, attempts);
          }
        }
        count++;
        debug("Execute on start OK", url, details);
      } catch (e) {
        error(e, "Execute on start failed", url, details);
      }
    }));
    return count;
  };
  
  {
    let filter = {
      urls: ["<all_urls>"],
      types:  ["main_frame", "sub_frame", "object"]
    };
    let wr = browser.webRequest;
    for (let event of ["onCompleted", "onErrorOccurred"]) {
      wr[event].addListener(cleanup, filter);
    }
    
    filter.types = ["main_frame"];
    wr.onResponseStarted.addListener(r => {
      let scripts = pendingScripts.get(r.requestId);
      if (scripts) scripts.runAndFlush();
    }, filter);
  }
  
  var RequestUtil = {

    getResponseMetaData(request) {
      return request.response || (request.response = new ResponseMetaData(request));
    },

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

      if (statusCode >= 300 && statusCode < 400) return;
      if (frameId === 0) {
        let key = tabKey(tabId, url);
        debug("Checking whether %s is a reloading tab...", key);
        if (reloadingTabs.get(key)) {
          reloadingTabs.set(key, false); // doom it for removal in cleanup
          return;
        }
      }
      
      let response = this.getResponseMetaData(request);
      let {contentType, contentDisposition} = response;
      if (contentDisposition ||
          xmlFeedOrImage.test(contentType) && !/\/svg\b/i.test(contentType)) {
        debug("Skipping execute on start of %s %o.", url, response);
        return;
      }
      
      debug("Injecting script on start in %s (%o).", url, response);

      let scripts = pendingScripts.get(requestId);
      let scriptKey = JSON.stringify(details);
      if (!scripts) {
        pendingScripts.set(requestId, scripts = new Map());
        scripts.set(scriptKey, details);
      } else {
        scripts.set(scriptKey, details);
        return;
      }
      
      if (/^(?:application|text)\//.test(contentType) 
          && !/[^;]+\b(html|xml)\b/i.test(contentType)) {
        debug("Not HTML: defer script to onResponseStarted for %s (%o)", url, response);
        return;
      }
      
      let mustCheckFeed = brokenXMLOnLoad && frameId === 0 && rawXml.test(contentType);
      debug("mustCheckFeed = %s, brokenXMLOnLoad = %s", mustCheckFeed, brokenXMLOnLoad);
      let filter = browser.webRequest.filterResponseData(requestId);
      let buffer = [];
      let responseCompleted = false;
      let mustReload = false;
      scripts.runAndFlush = async () => {
        scripts.runAndFlush = NOP;
        if (responseCompleted && buffer && !buffer.length) {
          filter.disconnect();
        }
        let scriptsRan = await executeAll(request);
        if (mustCheckFeed && !scriptsRan) {
          mustReload = true;
          debug(`Marking as "must reload"`, tabId, url);
          reloadingTabs.set(tabKey(tabId, url), true);
        }
        if (buffer && buffer.length) {
          debug("Flushing %s buffer chunks on %s", buffer.length, url);
          for (let chunk of buffer) {
            filter.write(chunk);
          }
          buffer = null;
        }
        filter.disconnect();
        if (responseCompleted) {
          filter.onstop(null);
        }
      };
      
      filter.ondata = event => {
        scripts.runAndFlush();
        if (buffer) {
          debug("buffering", url);
          buffer.push(event.data);
          return;
        }

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

      filter.onstop = async event => {
        responseCompleted = true;
        await scripts.runAndFlush();
        if (mustReload && !buffer) {
          mustReload = false;
          browser.tabs.update(tabId, {url});
        }
      }
    }
  }
}