fileReceiver.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import Nanobus from 'nanobus';
  2. import Keychain from './keychain';
  3. import { delay, bytes, streamToArrayBuffer } from './utils';
  4. import {
  5. downloadFile,
  6. downloadDone,
  7. metadata,
  8. getApiUrl,
  9. reportLink,
  10. getDownloadToken
  11. } from './api';
  12. import { blobStream } from './streams';
  13. import Zip from './zip';
  14. export default class FileReceiver extends Nanobus {
  15. constructor(fileInfo) {
  16. super('FileReceiver');
  17. this.keychain = new Keychain(fileInfo.secretKey, fileInfo.nonce);
  18. if (fileInfo.requiresPassword) {
  19. this.keychain.setPassword(fileInfo.password, fileInfo.url);
  20. }
  21. this.fileInfo = fileInfo;
  22. this.dlToken = null;
  23. this.reset();
  24. }
  25. get id() {
  26. return this.fileInfo.id;
  27. }
  28. get progressRatio() {
  29. return this.progress[0] / this.progress[1];
  30. }
  31. get progressIndefinite() {
  32. return this.state !== 'downloading';
  33. }
  34. get sizes() {
  35. return {
  36. partialSize: bytes(this.progress[0]),
  37. totalSize: bytes(this.progress[1])
  38. };
  39. }
  40. cancel() {
  41. if (this.downloadRequest) {
  42. this.downloadRequest.cancel();
  43. }
  44. }
  45. reset() {
  46. this.msg = 'fileSizeProgress';
  47. this.state = 'initialized';
  48. this.progress = [0, 1];
  49. }
  50. async getMetadata() {
  51. const meta = await metadata(this.fileInfo.id, this.keychain);
  52. this.fileInfo.name = meta.name;
  53. this.fileInfo.type = meta.type;
  54. this.fileInfo.size = +meta.size;
  55. this.fileInfo.manifest = meta.manifest;
  56. this.fileInfo.flagged = meta.flagged;
  57. this.state = 'ready';
  58. }
  59. async reportLink(reason) {
  60. await reportLink(this.fileInfo.id, this.keychain, reason);
  61. }
  62. sendMessageToSw(msg) {
  63. return new Promise((resolve, reject) => {
  64. const channel = new MessageChannel();
  65. channel.port1.onmessage = function(event) {
  66. if (event.data === undefined) {
  67. reject('bad response from serviceWorker');
  68. } else if (event.data.error !== undefined) {
  69. reject(event.data.error);
  70. } else {
  71. resolve(event.data);
  72. }
  73. };
  74. navigator.serviceWorker.controller.postMessage(msg, [channel.port2]);
  75. });
  76. }
  77. async downloadBlob(noSave = false) {
  78. this.state = 'downloading';
  79. this.downloadRequest = await downloadFile(
  80. this.fileInfo.id,
  81. this.dlToken,
  82. p => {
  83. this.progress = [p, this.fileInfo.size];
  84. this.emit('progress');
  85. }
  86. );
  87. try {
  88. const ciphertext = await this.downloadRequest.result;
  89. this.downloadRequest = null;
  90. this.msg = 'decryptingFile';
  91. this.state = 'decrypting';
  92. this.emit('decrypting');
  93. let size = this.fileInfo.size;
  94. let plainStream = this.keychain.decryptStream(blobStream(ciphertext));
  95. if (this.fileInfo.type === 'send-archive') {
  96. const zip = new Zip(this.fileInfo.manifest, plainStream);
  97. plainStream = zip.stream;
  98. size = zip.size;
  99. }
  100. const plaintext = await streamToArrayBuffer(plainStream, size);
  101. if (!noSave) {
  102. await saveFile({
  103. plaintext,
  104. name: decodeURIComponent(this.fileInfo.name),
  105. type: this.fileInfo.type
  106. });
  107. }
  108. this.msg = 'downloadFinish';
  109. this.emit('complete');
  110. this.state = 'complete';
  111. } catch (e) {
  112. this.downloadRequest = null;
  113. throw e;
  114. }
  115. }
  116. async downloadStream(noSave = false) {
  117. const start = Date.now();
  118. const onprogress = p => {
  119. this.progress = [p, this.fileInfo.size];
  120. this.emit('progress');
  121. };
  122. this.downloadRequest = {
  123. cancel: () => {
  124. this.sendMessageToSw({ request: 'cancel', id: this.fileInfo.id });
  125. }
  126. };
  127. try {
  128. this.state = 'downloading';
  129. const info = {
  130. request: 'init',
  131. id: this.fileInfo.id,
  132. filename: this.fileInfo.name,
  133. type: this.fileInfo.type,
  134. manifest: this.fileInfo.manifest,
  135. key: this.fileInfo.secretKey,
  136. requiresPassword: this.fileInfo.requiresPassword,
  137. password: this.fileInfo.password,
  138. url: this.fileInfo.url,
  139. size: this.fileInfo.size,
  140. nonce: this.keychain.nonce,
  141. dlToken: this.dlToken,
  142. noSave
  143. };
  144. await this.sendMessageToSw(info);
  145. onprogress(0);
  146. if (noSave) {
  147. const res = await fetch(getApiUrl(`/api/download/${this.fileInfo.id}`));
  148. if (res.status !== 200) {
  149. throw new Error(res.status);
  150. }
  151. } else {
  152. const downloadPath = `/api/download/${this.fileInfo.id}`;
  153. let downloadUrl = getApiUrl(downloadPath);
  154. if (downloadUrl === downloadPath) {
  155. downloadUrl = `${location.protocol}//${location.host}${downloadPath}`;
  156. }
  157. const a = document.createElement('a');
  158. a.href = downloadUrl;
  159. document.body.appendChild(a);
  160. a.click();
  161. }
  162. let prog = 0;
  163. let hangs = 0;
  164. while (prog < this.fileInfo.size) {
  165. const msg = await this.sendMessageToSw({
  166. request: 'progress',
  167. id: this.fileInfo.id
  168. });
  169. if (msg.progress === prog) {
  170. hangs++;
  171. } else {
  172. hangs = 0;
  173. }
  174. if (hangs > 30) {
  175. // TODO: On Chrome we don't get a cancel
  176. // signal so one is indistinguishable from
  177. // a hang. We may be able to detect
  178. // which end is hung in the service worker
  179. // to improve on this.
  180. const e = new Error('hung download');
  181. e.duration = Date.now() - start;
  182. e.size = this.fileInfo.size;
  183. e.progress = prog;
  184. throw e;
  185. }
  186. prog = msg.progress;
  187. onprogress(prog);
  188. await delay(1000);
  189. }
  190. this.downloadRequest = null;
  191. this.msg = 'downloadFinish';
  192. this.emit('complete');
  193. this.state = 'complete';
  194. } catch (e) {
  195. this.downloadRequest = null;
  196. if (e === 'cancelled' || e.message === '400') {
  197. throw new Error(0);
  198. }
  199. throw e;
  200. }
  201. }
  202. async download({ stream, storage, noSave }) {
  203. this.dlToken = storage.getDownloadToken(this.id);
  204. if (!this.dlToken) {
  205. this.dlToken = await getDownloadToken(this.id, this.keychain);
  206. storage.setDownloadToken(this.id, this.dlToken);
  207. }
  208. if (stream) {
  209. await this.downloadStream(noSave);
  210. } else {
  211. await this.downloadBlob(noSave);
  212. }
  213. await downloadDone(this.id, this.dlToken);
  214. storage.setDownloadToken(this.id);
  215. }
  216. }
  217. async function saveFile(file) {
  218. return new Promise(function(resolve, reject) {
  219. const dataView = new DataView(file.plaintext);
  220. const blob = new Blob([dataView], { type: file.type });
  221. if (navigator.msSaveBlob) {
  222. navigator.msSaveBlob(blob, file.name);
  223. return resolve();
  224. } else if (/iPhone|fxios/i.test(navigator.userAgent)) {
  225. // This method is much slower but createObjectURL
  226. // is buggy on iOS
  227. const reader = new FileReader();
  228. reader.addEventListener('loadend', function() {
  229. if (reader.error) {
  230. return reject(reader.error);
  231. }
  232. if (reader.result) {
  233. const a = document.createElement('a');
  234. a.href = reader.result;
  235. a.download = file.name;
  236. document.body.appendChild(a);
  237. a.click();
  238. }
  239. resolve();
  240. });
  241. reader.readAsDataURL(blob);
  242. } else {
  243. const downloadUrl = URL.createObjectURL(blob);
  244. const a = document.createElement('a');
  245. a.href = downloadUrl;
  246. a.download = file.name;
  247. document.body.appendChild(a);
  248. a.click();
  249. URL.revokeObjectURL(downloadUrl);
  250. setTimeout(resolve, 100);
  251. }
  252. });
  253. }