content-fetch.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. /*
  2. * Copyright 2010-2020 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global browser, window, addEventListener, fetch, CustomEvent, dispatchEvent, removeEventListener */
  24. this.singlefile.extension.lib.fetch.content.resources = this.singlefile.extension.lib.fetch.content.resources || (() => {
  25. const MAX_CONTENT_SIZE = 8 * (1024 * 1024);
  26. const FETCH_REQUEST_EVENT = "single-file-request-fetch";
  27. const FETCH_RESPONSE_EVENT = "single-file-response-fetch";
  28. const pendingRequests = [];
  29. browser.runtime.onMessage.addListener(message => {
  30. if ((message.method == "singlefile.fetchFrameRequest" && window.frameId && window.frameId == message.frameId)
  31. || message.method == "singlefile.fetchResponse"
  32. || message.method == "singlefile.fetchFrameResponse") {
  33. return onMessage(message);
  34. }
  35. });
  36. return {
  37. fetch: async url => {
  38. try {
  39. let response = await fetch(url, { cache: "force-cache" });
  40. if (response.status == 403 || response.status == 404) {
  41. response = hostFetch(url);
  42. }
  43. return response;
  44. }
  45. catch (error) {
  46. return sendRequest("singlefile.fetchRequest", url);
  47. }
  48. },
  49. frameFetch: (url, frameId) => sendRequest("singlefile.fetchFrameRequest", url, frameId)
  50. };
  51. async function onMessage(message) {
  52. if (message.method == "singlefile.fetchFrameRequest") {
  53. sendFetchFrameResponse(message);
  54. return {};
  55. } else if (message.method == "singlefile.fetchResponse" || message.method == "singlefile.fetchFrameResponse") {
  56. resolveRequest(message);
  57. return {};
  58. }
  59. }
  60. async function sendFetchFrameResponse(message) {
  61. const { id, tabId } = message;
  62. try {
  63. let response = await fetch(message.url, { cache: "force-cache" });
  64. if (response.status == 403 || response.status == 404) {
  65. response = hostFetch(message.url);
  66. }
  67. const array = new Uint8Array(await response.arrayBuffer());
  68. for (let blockIndex = 0; blockIndex * MAX_CONTENT_SIZE < array.length; blockIndex++) {
  69. const message = {
  70. method: "singlefile.bgFetchFrameResponse",
  71. id,
  72. tabId
  73. };
  74. message.truncated = array.length > MAX_CONTENT_SIZE;
  75. if (message.truncated) {
  76. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > array.length;
  77. message.array = array.slice(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  78. } else {
  79. message.array = array;
  80. }
  81. message.array = Array.from(message.array);
  82. const headers = {};
  83. response.headers.forEach((value, key) => headers[key] = value);
  84. if (!message.truncated || message.finished) {
  85. message.headers = headers;
  86. message.status = response.status;
  87. }
  88. browser.runtime.sendMessage(message);
  89. }
  90. } catch (error) {
  91. await browser.runtime.sendMessage({
  92. method: "singlefile.bgFetchFrameResponse",
  93. id: message.id,
  94. tabId,
  95. error: error.toString()
  96. });
  97. }
  98. }
  99. function resolveRequest(message) {
  100. const pendingRequest = pendingRequests[message.id];
  101. if (pendingRequest) {
  102. if (message.error) {
  103. pendingRequest.reject(new Error(message.error.toString()));
  104. pendingRequests[message.id] = null;
  105. } else {
  106. if (message.truncated) {
  107. if (!pendingRequest.responseArray) {
  108. pendingRequest.responseArray = [];
  109. }
  110. pendingRequest.responseArray = pendingRequest.responseArray.concat(message.array);
  111. } else {
  112. pendingRequest.responseArray = message.array;
  113. }
  114. if (!message.truncated || message.finished) {
  115. pendingRequest.resolve({
  116. status: message.status,
  117. headers: {
  118. get: headerName => message.headers[headerName]
  119. },
  120. arrayBuffer: async () => new Uint8Array(pendingRequest.responseArray).buffer
  121. });
  122. pendingRequests[message.id] = null;
  123. }
  124. }
  125. }
  126. }
  127. function sendRequest(method, url, frameId) {
  128. return new Promise((resolve, reject) => {
  129. const responsePromise = browser.runtime.sendMessage({ method, url, frameId, id: pendingRequests.length });
  130. responsePromise
  131. .then(response => {
  132. if (!response) {
  133. reject();
  134. }
  135. })
  136. .catch(reject);
  137. pendingRequests.push({ resolve, reject });
  138. });
  139. }
  140. function hostFetch(url) {
  141. return new Promise((resolve, reject) => {
  142. dispatchEvent(new CustomEvent(FETCH_REQUEST_EVENT, { detail: url }));
  143. addEventListener(FETCH_RESPONSE_EVENT, onResponseFetch, false);
  144. function onResponseFetch(event) {
  145. if (event.detail) {
  146. if (event.detail.url == url) {
  147. removeEventListener(FETCH_RESPONSE_EVENT, onResponseFetch, false);
  148. if (event.detail.response) {
  149. resolve({
  150. status: event.detail.status,
  151. headers: {
  152. get: name => {
  153. const header = event.detail.headers.find(header => header[0] == name);
  154. return header && header[1];
  155. }
  156. },
  157. arrayBuffer: async () => event.detail.response
  158. });
  159. } else {
  160. reject(event.detail.error);
  161. }
  162. }
  163. } else {
  164. reject();
  165. }
  166. }
  167. });
  168. }
  169. })();