file-upload.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452
  1. /*
  2. * Copyright (c) 2014
  3. *
  4. * This file is licensed under the Affero General Public License version 3
  5. * or later.
  6. *
  7. * See the COPYING-README file.
  8. *
  9. */
  10. /**
  11. * The file upload code uses several hooks to interact with blueimps jQuery file upload library:
  12. * 1. the core upload handling hooks are added when initializing the plugin,
  13. * 2. if the browser supports progress events they are added in a separate set after the initialization
  14. * 3. every app can add its own triggers for fileupload
  15. * - files adds d'n'd handlers and also reacts to done events to add new rows to the filelist
  16. * - TODO pictures upload button
  17. * - TODO music upload button
  18. */
  19. /* global jQuery, md5 */
  20. /**
  21. * File upload object
  22. *
  23. * @class OC.FileUpload
  24. * @classdesc
  25. *
  26. * Represents a file upload
  27. *
  28. * @param {OC.Uploader} uploader uploader
  29. * @param {Object} data blueimp data
  30. */
  31. OC.FileUpload = function(uploader, data) {
  32. this.uploader = uploader;
  33. this.data = data;
  34. var basePath = '';
  35. if (this.uploader.fileList) {
  36. basePath = this.uploader.fileList.getCurrentDirectory();
  37. }
  38. var path = OC.joinPaths(basePath, this.getFile().relativePath || '', this.getFile().name);
  39. this.id = 'web-file-upload-' + md5(path) + '-' + (new Date()).getTime();
  40. };
  41. OC.FileUpload.CONFLICT_MODE_DETECT = 0;
  42. OC.FileUpload.CONFLICT_MODE_OVERWRITE = 1;
  43. OC.FileUpload.CONFLICT_MODE_AUTORENAME = 2;
  44. // IE11 polyfill
  45. // TODO: nuke out of orbit as well as this legacy code
  46. if (!FileReader.prototype.readAsBinaryString) {
  47. FileReader.prototype.readAsBinaryString = function(fileData) {
  48. var binary = ''
  49. var pt = this
  50. var reader = new FileReader()
  51. reader.onload = function (e) {
  52. var bytes = new Uint8Array(reader.result)
  53. var length = bytes.byteLength
  54. for (var i = 0; i < length; i++) {
  55. binary += String.fromCharCode(bytes[i])
  56. }
  57. // pt.result - readonly so assign binary
  58. pt.content = binary
  59. $(pt).trigger('onload')
  60. }
  61. reader.readAsArrayBuffer(fileData)
  62. }
  63. }
  64. OC.FileUpload.prototype = {
  65. /**
  66. * Unique upload id
  67. *
  68. * @type string
  69. */
  70. id: null,
  71. /**
  72. * Upload data structure
  73. */
  74. data: null,
  75. /**
  76. * Upload element
  77. *
  78. * @type Object
  79. */
  80. $uploadEl: null,
  81. /**
  82. * Target folder
  83. *
  84. * @type string
  85. */
  86. _targetFolder: '',
  87. /**
  88. * @type int
  89. */
  90. _conflictMode: OC.FileUpload.CONFLICT_MODE_DETECT,
  91. /**
  92. * New name from server after autorename
  93. *
  94. * @type String
  95. */
  96. _newName: null,
  97. /**
  98. * Returns the unique upload id
  99. *
  100. * @return string
  101. */
  102. getId: function() {
  103. return this.id;
  104. },
  105. /**
  106. * Returns the file to be uploaded
  107. *
  108. * @return {File} file
  109. */
  110. getFile: function() {
  111. return this.data.files[0];
  112. },
  113. /**
  114. * Return the final filename.
  115. *
  116. * @return {String} file name
  117. */
  118. getFileName: function() {
  119. // autorenamed name
  120. if (this._newName) {
  121. return this._newName;
  122. }
  123. return this.getFile().name;
  124. },
  125. setTargetFolder: function(targetFolder) {
  126. this._targetFolder = targetFolder;
  127. },
  128. getTargetFolder: function() {
  129. return this._targetFolder;
  130. },
  131. /**
  132. * Get full path for the target file, including relative path,
  133. * without the file name.
  134. *
  135. * @return {String} full path
  136. */
  137. getFullPath: function() {
  138. return OC.joinPaths(this._targetFolder, this.getFile().relativePath || '');
  139. },
  140. /**
  141. * Get full path for the target file,
  142. * including relative path and file name.
  143. *
  144. * @return {String} full path
  145. */
  146. getFullFilePath: function() {
  147. return OC.joinPaths(this.getFullPath(), this.getFile().name);
  148. },
  149. /**
  150. * Returns conflict resolution mode.
  151. *
  152. * @return {number} conflict mode
  153. */
  154. getConflictMode: function() {
  155. return this._conflictMode || OC.FileUpload.CONFLICT_MODE_DETECT;
  156. },
  157. /**
  158. * Set conflict resolution mode.
  159. * See CONFLICT_MODE_* constants.
  160. *
  161. * @param {number} mode conflict mode
  162. */
  163. setConflictMode: function(mode) {
  164. this._conflictMode = mode;
  165. },
  166. deleteUpload: function() {
  167. delete this.data.jqXHR;
  168. },
  169. /**
  170. * Trigger autorename and append "(2)".
  171. * Multiple calls will increment the appended number.
  172. */
  173. autoRename: function() {
  174. var name = this.getFile().name;
  175. if (!this._renameAttempt) {
  176. this._renameAttempt = 1;
  177. }
  178. var dotPos = name.lastIndexOf('.');
  179. var extPart = '';
  180. if (dotPos > 0) {
  181. this._newName = name.substr(0, dotPos);
  182. extPart = name.substr(dotPos);
  183. } else {
  184. this._newName = name;
  185. }
  186. // generate new name
  187. this._renameAttempt++;
  188. this._newName = this._newName + ' (' + this._renameAttempt + ')' + extPart;
  189. },
  190. /**
  191. * Submit the upload
  192. */
  193. submit: function() {
  194. var self = this;
  195. var data = this.data;
  196. var file = this.getFile();
  197. // if file is a directory, just create it
  198. // files are handled separately
  199. if (file.isDirectory) {
  200. return this.uploader.ensureFolderExists(OC.joinPaths(this._targetFolder, file.fullPath));
  201. }
  202. if (self.aborted === true) {
  203. return $.Deferred().resolve().promise();
  204. }
  205. // it was a folder upload, so make sure the parent directory exists already
  206. var folderPromise;
  207. if (file.relativePath) {
  208. folderPromise = this.uploader.ensureFolderExists(this.getFullPath());
  209. } else {
  210. folderPromise = $.Deferred().resolve().promise();
  211. }
  212. if (this.uploader.fileList) {
  213. this.data.url = this.uploader.fileList.getUploadUrl(this.getFileName(), this.getFullPath());
  214. }
  215. if (!this.data.headers) {
  216. this.data.headers = {};
  217. }
  218. // webdav without multipart
  219. this.data.multipart = false;
  220. this.data.type = 'PUT';
  221. delete this.data.headers['If-None-Match'];
  222. if (this._conflictMode === OC.FileUpload.CONFLICT_MODE_DETECT
  223. || this._conflictMode === OC.FileUpload.CONFLICT_MODE_AUTORENAME) {
  224. this.data.headers['If-None-Match'] = '*';
  225. }
  226. var userName = this.uploader.davClient.getUserName();
  227. var password = this.uploader.davClient.getPassword();
  228. if (userName) {
  229. // copy username/password from DAV client
  230. this.data.headers['Authorization'] =
  231. 'Basic ' + btoa(userName + ':' + (password || ''));
  232. }
  233. var chunkFolderPromise;
  234. if ($.support.blobSlice
  235. && this.uploader.fileUploadParam.maxChunkSize
  236. && this.getFile().size > this.uploader.fileUploadParam.maxChunkSize
  237. ) {
  238. data.isChunked = true;
  239. var headers = {
  240. Destination: this.uploader.davClient._buildUrl(this.getTargetDestination())
  241. };
  242. chunkFolderPromise = this.uploader.davClient.createDirectory(
  243. 'uploads/' + OC.getCurrentUser().uid + '/' + this.getId(), headers
  244. );
  245. // TODO: if fails, it means same id already existed, need to retry
  246. } else {
  247. chunkFolderPromise = $.Deferred().resolve().promise();
  248. var mtime = this.getFile().lastModified;
  249. if (mtime) {
  250. data.headers['X-OC-Mtime'] = mtime / 1000;
  251. }
  252. }
  253. // wait for creation of the required directory before uploading
  254. return Promise.all([folderPromise, chunkFolderPromise]).then(function() {
  255. if (self.aborted !== true) {
  256. data.submit();
  257. }
  258. }, function() {
  259. self.abort();
  260. });
  261. },
  262. /**
  263. * Process end of transfer
  264. */
  265. done: function() {
  266. if (!this.data.isChunked) {
  267. return $.Deferred().resolve().promise();
  268. }
  269. var uid = OC.getCurrentUser().uid;
  270. var mtime = this.getFile().lastModified;
  271. var size = this.getFile().size;
  272. var headers = {};
  273. if (mtime) {
  274. headers['X-OC-Mtime'] = mtime / 1000;
  275. }
  276. if (size) {
  277. headers['OC-Total-Length'] = size;
  278. }
  279. headers['Destination'] = this.uploader.davClient._buildUrl(this.getTargetDestination());
  280. return this.uploader.davClient.move(
  281. 'uploads/' + uid + '/' + this.getId() + '/.file',
  282. this.getTargetDestination(),
  283. true,
  284. headers
  285. );
  286. },
  287. getTargetDestination: function() {
  288. var uid = OC.getCurrentUser().uid;
  289. return 'files/' + uid + '/' + OC.joinPaths(this.getFullPath(), this.getFileName());
  290. },
  291. _deleteChunkFolder: function() {
  292. // delete transfer directory for this upload
  293. this.uploader.davClient.remove(
  294. 'uploads/' + OC.getCurrentUser().uid + '/' + this.getId()
  295. );
  296. },
  297. _delete: function() {
  298. if (this.data.isChunked) {
  299. this._deleteChunkFolder()
  300. }
  301. this.deleteUpload();
  302. },
  303. /**
  304. * Abort the upload
  305. */
  306. abort: function() {
  307. if (this.aborted) {
  308. return
  309. }
  310. this.aborted = true;
  311. if (this.data) {
  312. // abort running XHR
  313. this.data.abort();
  314. }
  315. this._delete();
  316. },
  317. /**
  318. * Fail the upload
  319. */
  320. fail: function() {
  321. if (this.aborted) {
  322. return
  323. }
  324. this._delete();
  325. },
  326. /**
  327. * Returns the server response
  328. *
  329. * @return {Object} response
  330. */
  331. getResponse: function() {
  332. var response = this.data.response();
  333. if (response.errorThrown || response.textStatus === 'error') {
  334. // attempt parsing Sabre exception is available
  335. var xml = response.jqXHR.responseXML;
  336. if (xml && xml.documentElement.localName === 'error' && xml.documentElement.namespaceURI === 'DAV:') {
  337. var messages = xml.getElementsByTagNameNS('http://sabredav.org/ns', 'message');
  338. var exceptions = xml.getElementsByTagNameNS('http://sabredav.org/ns', 'exception');
  339. if (messages.length) {
  340. response.message = messages[0].textContent;
  341. }
  342. if (exceptions.length) {
  343. response.exception = exceptions[0].textContent;
  344. }
  345. return response;
  346. }
  347. }
  348. if (typeof response.result !== 'string' && response.result) {
  349. //fetch response from iframe
  350. response = $.parseJSON(response.result[0].body.innerText);
  351. if (!response) {
  352. // likely due to internal server error
  353. response = {status: 500};
  354. }
  355. } else {
  356. response = response.result;
  357. }
  358. return response;
  359. },
  360. /**
  361. * Returns the status code from the response
  362. *
  363. * @return {number} status code
  364. */
  365. getResponseStatus: function() {
  366. if (this.uploader.isXHRUpload()) {
  367. var xhr = this.data.response().jqXHR;
  368. if (xhr) {
  369. return xhr.status;
  370. }
  371. return null;
  372. }
  373. return this.getResponse().status;
  374. },
  375. /**
  376. * Returns the response header by name
  377. *
  378. * @param {String} headerName header name
  379. * @return {Array|String} response header value(s)
  380. */
  381. getResponseHeader: function(headerName) {
  382. headerName = headerName.toLowerCase();
  383. if (this.uploader.isXHRUpload()) {
  384. return this.data.response().jqXHR.getResponseHeader(headerName);
  385. }
  386. var headers = this.getResponse().headers;
  387. if (!headers) {
  388. return null;
  389. }
  390. var value = _.find(headers, function(value, key) {
  391. return key.toLowerCase() === headerName;
  392. });
  393. if (_.isArray(value) && value.length === 1) {
  394. return value[0];
  395. }
  396. return value;
  397. }
  398. };
  399. /**
  400. * keeps track of uploads in progress and implements callbacks for the conflicts dialog
  401. * @namespace
  402. */
  403. OC.Uploader = function() {
  404. this.init.apply(this, arguments);
  405. };
  406. OC.Uploader.prototype = _.extend({
  407. /**
  408. * @type Array<OC.FileUpload>
  409. */
  410. _uploads: {},
  411. /**
  412. * Count of upload done promises that have not finished yet.
  413. *
  414. * @type int
  415. */
  416. _pendingUploadDoneCount: 0,
  417. /**
  418. * Is it currently uploading?
  419. *
  420. * @type boolean
  421. */
  422. _uploading: false,
  423. /**
  424. * List of directories known to exist.
  425. *
  426. * Key is the fullpath and value is boolean, true meaning that the directory
  427. * was already created so no need to create it again.
  428. */
  429. _knownDirs: {},
  430. /**
  431. * @type OCA.Files.FileList
  432. */
  433. fileList: null,
  434. /**
  435. * @type OCA.Files.OperationProgressBar
  436. */
  437. progressBar: null,
  438. /**
  439. * @type OC.Files.Client
  440. */
  441. filesClient: null,
  442. /**
  443. * Webdav client pointing at the root "dav" endpoint
  444. *
  445. * @type OC.Files.Client
  446. */
  447. davClient: null,
  448. /**
  449. * Function that will allow us to know if Ajax uploads are supported
  450. * @link https://github.com/New-Bamboo/example-ajax-upload/blob/master/public/index.html
  451. * also see article @link http://blog.new-bamboo.co.uk/2012/01/10/ridiculously-simple-ajax-uploads-with-formdata
  452. */
  453. _supportAjaxUploadWithProgress: function() {
  454. if (window.TESTING) {
  455. return true;
  456. }
  457. return supportFileAPI() && supportAjaxUploadProgressEvents() && supportFormData();
  458. // Is the File API supported?
  459. function supportFileAPI() {
  460. var fi = document.createElement('INPUT');
  461. fi.type = 'file';
  462. return 'files' in fi;
  463. }
  464. // Are progress events supported?
  465. function supportAjaxUploadProgressEvents() {
  466. var xhr = new XMLHttpRequest();
  467. return !! (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload));
  468. }
  469. // Is FormData supported?
  470. function supportFormData() {
  471. return !! window.FormData;
  472. }
  473. },
  474. /**
  475. * Returns whether an XHR upload will be used
  476. *
  477. * @return {boolean} true if XHR upload will be used,
  478. * false for iframe upload
  479. */
  480. isXHRUpload: function () {
  481. return !this.fileUploadParam.forceIframeTransport &&
  482. ((!this.fileUploadParam.multipart && $.support.xhrFileUpload) ||
  483. $.support.xhrFormDataFileUpload);
  484. },
  485. /**
  486. * Makes sure that the upload folder and its parents exists
  487. *
  488. * @param {String} fullPath full path
  489. * @return {Promise} promise that resolves when all parent folders
  490. * were created
  491. */
  492. ensureFolderExists: function(fullPath) {
  493. if (!fullPath || fullPath === '/') {
  494. return $.Deferred().resolve().promise();
  495. }
  496. // remove trailing slash
  497. if (fullPath.charAt(fullPath.length - 1) === '/') {
  498. fullPath = fullPath.substr(0, fullPath.length - 1);
  499. }
  500. var self = this;
  501. var promise = this._knownDirs[fullPath];
  502. if (this.fileList) {
  503. // assume the current folder exists
  504. this._knownDirs[this.fileList.getCurrentDirectory()] = $.Deferred().resolve().promise();
  505. }
  506. if (!promise) {
  507. var deferred = new $.Deferred();
  508. promise = deferred.promise();
  509. this._knownDirs[fullPath] = promise;
  510. // make sure all parents already exist
  511. var parentPath = OC.dirname(fullPath);
  512. var parentPromise = this._knownDirs[parentPath];
  513. if (!parentPromise) {
  514. parentPromise = this.ensureFolderExists(parentPath);
  515. }
  516. parentPromise.then(function() {
  517. self.filesClient.createDirectory(fullPath).always(function(status) {
  518. // 405 is expected if the folder already exists
  519. if ((status >= 200 && status < 300) || status === 405) {
  520. if (status !== 405) {
  521. self.trigger('createdfolder', fullPath);
  522. }
  523. deferred.resolve();
  524. return;
  525. }
  526. OC.Notification.show(t('files', 'Could not create folder "{dir}"', {dir: fullPath}), {type: 'error'});
  527. deferred.reject();
  528. });
  529. }, function() {
  530. deferred.reject();
  531. });
  532. }
  533. return promise;
  534. },
  535. /**
  536. * Submit the given uploads
  537. *
  538. * @param {Array} array of uploads to start
  539. */
  540. submitUploads: function(uploads) {
  541. var self = this;
  542. _.each(uploads, function(upload) {
  543. self._uploads[upload.data.uploadId] = upload;
  544. });
  545. if (!self._uploading) {
  546. self.totalToUpload = 0;
  547. self.totalUploadCount = 0;
  548. }
  549. self.totalToUpload += _.reduce(uploads, function(memo, upload) { return memo+upload.getFile().size; }, 0);
  550. self.totalUploadCount += uploads.length;
  551. var semaphore = new OCA.Files.Semaphore(5);
  552. var promises = _.map(uploads, function(upload) {
  553. return semaphore.acquire().then(function(){
  554. return upload.submit().then(function(){
  555. semaphore.release();
  556. });
  557. });
  558. });
  559. },
  560. confirmBeforeUnload: function() {
  561. if (this._uploading) {
  562. return t('files', 'This will stop your current uploads.')
  563. }
  564. },
  565. /**
  566. * Show conflict for the given file object
  567. *
  568. * @param {OC.FileUpload} file upload object
  569. */
  570. showConflict: function(fileUpload) {
  571. //show "file already exists" dialog
  572. var self = this;
  573. var file = fileUpload.getFile();
  574. // already attempted autorename but the server said the file exists ? (concurrently added)
  575. if (fileUpload.getConflictMode() === OC.FileUpload.CONFLICT_MODE_AUTORENAME) {
  576. // attempt another autorename, defer to let the current callback finish
  577. _.defer(function() {
  578. self.onAutorename(fileUpload);
  579. });
  580. return;
  581. }
  582. // retrieve more info about this file
  583. this.filesClient.getFileInfo(fileUpload.getFullFilePath()).then(function(status, fileInfo) {
  584. var original = fileInfo;
  585. var replacement = file;
  586. original.directory = original.path;
  587. OC.dialogs.fileexists(fileUpload, original, replacement, self);
  588. });
  589. },
  590. /**
  591. * cancels all uploads
  592. */
  593. cancelUploads:function() {
  594. this.log('canceling uploads');
  595. jQuery.each(this._uploads, function(i, upload) {
  596. upload.abort();
  597. });
  598. this.clear();
  599. },
  600. /**
  601. * Clear uploads
  602. */
  603. clear: function() {
  604. this._knownDirs = {};
  605. },
  606. /**
  607. * Returns an upload by id
  608. *
  609. * @param {number} data uploadId
  610. * @return {OC.FileUpload} file upload
  611. */
  612. getUpload: function(data) {
  613. if (_.isString(data)) {
  614. return this._uploads[data];
  615. } else if (data.uploadId && this._uploads[data.uploadId]) {
  616. this._uploads[data.uploadId].data = data;
  617. return this._uploads[data.uploadId];
  618. }
  619. return null;
  620. },
  621. /**
  622. * Removes an upload from the list of known uploads.
  623. *
  624. * @param {OC.FileUpload} upload the upload to remove.
  625. */
  626. removeUpload: function(upload) {
  627. if (!upload || !upload.data || !upload.data.uploadId) {
  628. return;
  629. }
  630. // defer as some calls/chunks might still be busy failing, so we need
  631. // the upload info there still
  632. var self = this;
  633. var uploadId = upload.data.uploadId;
  634. // mark as deleted for the progress bar
  635. this._uploads[uploadId].deleted = true;
  636. window.setTimeout(function() {
  637. delete self._uploads[uploadId];
  638. }, 5000)
  639. },
  640. _activeUploadCount: function() {
  641. var count = 0;
  642. for (var key in this._uploads) {
  643. if (!this._uploads[key].deleted) {
  644. count++;
  645. }
  646. }
  647. return count;
  648. },
  649. showUploadCancelMessage: _.debounce(function() {
  650. OC.Notification.show(t('files', 'Upload cancelled.'), { timeout : 7000, type: 'error' });
  651. }, 500),
  652. /**
  653. * callback for the conflicts dialog
  654. */
  655. onCancel:function() {
  656. this.cancelUploads();
  657. },
  658. /**
  659. * callback for the conflicts dialog
  660. * calls onSkip, onReplace or onAutorename for each conflict
  661. * @param {object} conflicts - list of conflict elements
  662. */
  663. onContinue:function(conflicts) {
  664. var self = this;
  665. //iterate over all conflicts
  666. jQuery.each(conflicts, function (i, conflict) {
  667. conflict = $(conflict);
  668. var keepOriginal = conflict.find('.original input[type="checkbox"]:checked').length === 1;
  669. var keepReplacement = conflict.find('.replacement input[type="checkbox"]:checked').length === 1;
  670. if (keepOriginal && keepReplacement) {
  671. // when both selected -> autorename
  672. self.onAutorename(conflict.data('data'));
  673. } else if (keepReplacement) {
  674. // when only replacement selected -> overwrite
  675. self.onReplace(conflict.data('data'));
  676. } else {
  677. // when only original selected -> skip
  678. // when none selected -> skip
  679. self.onSkip(conflict.data('data'));
  680. }
  681. });
  682. },
  683. /**
  684. * handle skipping an upload
  685. * @param {OC.FileUpload} upload
  686. */
  687. onSkip:function(upload) {
  688. this.log('skip', null, upload);
  689. upload.deleteUpload();
  690. },
  691. /**
  692. * handle replacing a file on the server with an uploaded file
  693. * @param {FileUpload} data
  694. */
  695. onReplace:function(upload) {
  696. this.log('replace', null, upload);
  697. upload.setConflictMode(OC.FileUpload.CONFLICT_MODE_OVERWRITE);
  698. this.submitUploads([upload]);
  699. },
  700. /**
  701. * handle uploading a file and letting the server decide a new name
  702. * @param {object} upload
  703. */
  704. onAutorename:function(upload) {
  705. this.log('autorename', null, upload);
  706. upload.setConflictMode(OC.FileUpload.CONFLICT_MODE_AUTORENAME);
  707. do {
  708. upload.autoRename();
  709. // if file known to exist on the client side, retry
  710. } while (this.fileList && this.fileList.inList(upload.getFileName()));
  711. // resubmit upload
  712. this.submitUploads([upload]);
  713. },
  714. _trace: false, //TODO implement log handler for JS per class?
  715. log: function(caption, e, data) {
  716. if (this._trace) {
  717. console.log(caption);
  718. console.log(data);
  719. }
  720. },
  721. /**
  722. * checks the list of existing files prior to uploading and shows a simple dialog to choose
  723. * skip all, replace all or choose which files to keep
  724. *
  725. * @param {array} selection of files to upload
  726. * @param {object} callbacks - object with several callback methods
  727. * @param {Function} callbacks.onNoConflicts
  728. * @param {Function} callbacks.onSkipConflicts
  729. * @param {Function} callbacks.onReplaceConflicts
  730. * @param {Function} callbacks.onChooseConflicts
  731. * @param {Function} callbacks.onCancel
  732. */
  733. checkExistingFiles: function (selection, callbacks) {
  734. var fileList = this.fileList;
  735. var conflicts = [];
  736. // only keep non-conflicting uploads
  737. selection.uploads = _.filter(selection.uploads, function(upload) {
  738. var file = upload.getFile();
  739. if (file.relativePath) {
  740. // can't check in subfolder contents
  741. return true;
  742. }
  743. if (!fileList) {
  744. // no list to check against
  745. return true;
  746. }
  747. if (upload.getTargetFolder() !== fileList.getCurrentDirectory()) {
  748. // not uploading to the current folder
  749. return true;
  750. }
  751. var fileInfo = fileList.findFile(file.name);
  752. if (fileInfo) {
  753. conflicts.push([
  754. // original
  755. _.extend(fileInfo, {
  756. directory: fileInfo.directory || fileInfo.path || fileList.getCurrentDirectory()
  757. }),
  758. // replacement (File object)
  759. upload
  760. ]);
  761. return false;
  762. }
  763. return true;
  764. });
  765. if (conflicts.length) {
  766. // wait for template loading
  767. OC.dialogs.fileexists(null, null, null, this).done(function() {
  768. _.each(conflicts, function(conflictData) {
  769. OC.dialogs.fileexists(conflictData[1], conflictData[0], conflictData[1].getFile(), this);
  770. });
  771. });
  772. }
  773. // upload non-conflicting files
  774. // note: when reaching the server they might still meet conflicts
  775. // if the folder was concurrently modified, these will get added
  776. // to the already visible dialog, if applicable
  777. callbacks.onNoConflicts(selection);
  778. },
  779. _updateProgressBarOnUploadStop: function() {
  780. if (this._pendingUploadDoneCount === 0) {
  781. // All the uploads ended and there is no pending operation, so hide
  782. // the progress bar.
  783. // Note that this happens here only with non-chunked uploads; if the
  784. // upload was chunked then this will have been executed after all
  785. // the uploads ended but before the upload done handler that reduces
  786. // the pending operation count was executed.
  787. this._hideProgressBar();
  788. return;
  789. }
  790. this._setProgressBarText(t('files', 'Processing files …'), t('files', '…'));
  791. // Nothing is being uploaded at this point, and the pending operations
  792. // can not be cancelled, so the cancel button should be hidden.
  793. this._hideCancelButton();
  794. },
  795. _hideProgressBar: function() {
  796. this.progressBar.hideProgressBar();
  797. },
  798. _hideCancelButton: function() {
  799. this.progressBar.hideCancelButton();
  800. },
  801. _showProgressBar: function() {
  802. this.progressBar.showProgressBar();
  803. },
  804. _setProgressBarValue: function(value) {
  805. this.progressBar.setProgressBarValue(value);
  806. },
  807. _setProgressBarText: function(textDesktop, textMobile, title) {
  808. this.progressBar.setProgressBarText(textDesktop, textMobile, title);
  809. },
  810. /**
  811. * Returns whether the given file is known to be a received shared file
  812. *
  813. * @param {Object} file file
  814. * @return {boolean} true if the file is a shared file
  815. */
  816. _isReceivedSharedFile: function(file) {
  817. if (!window.FileList) {
  818. return false;
  819. }
  820. var $tr = window.FileList.findFileEl(file.name);
  821. if (!$tr.length) {
  822. return false;
  823. }
  824. return ($tr.attr('data-mounttype') === 'shared-root' && $tr.attr('data-mime') !== 'httpd/unix-directory');
  825. },
  826. /**
  827. * Initialize the upload object
  828. *
  829. * @param {Object} $uploadEl upload element
  830. * @param {Object} options
  831. * @param {OCA.Files.FileList} [options.fileList] file list object
  832. * @param {OC.Files.Client} [options.filesClient] files client object
  833. * @param {Object} [options.dropZone] drop zone for drag and drop upload
  834. */
  835. init: function($uploadEl, options) {
  836. var self = this;
  837. options = options || {};
  838. this.fileList = options.fileList;
  839. this.progressBar = options.progressBar;
  840. this.filesClient = options.filesClient || OC.Files.getClient();
  841. this.davClient = new OC.Files.Client({
  842. host: this.filesClient.getHost(),
  843. root: OC.linkToRemoteBase('dav'),
  844. useHTTPS: OC.getProtocol() === 'https',
  845. userName: this.filesClient.getUserName(),
  846. password: this.filesClient.getPassword()
  847. });
  848. $uploadEl = $($uploadEl);
  849. this.$uploadEl = $uploadEl;
  850. if ($uploadEl.exists()) {
  851. this.progressBar.on('cancel', function() {
  852. self.cancelUploads();
  853. self.showUploadCancelMessage();
  854. });
  855. this.fileUploadParam = {
  856. type: 'PUT',
  857. dropZone: options.dropZone, // restrict dropZone to content div
  858. autoUpload: false,
  859. progressInterval: 300, // increased from the default of 100ms for more stable behvaviour when predicting remaining time
  860. sequentialUploads: false,
  861. limitConcurrentUploads: 4,
  862. /**
  863. * on first add of every selection
  864. * - check all files of originalFiles array with files in dir
  865. * - on conflict show dialog
  866. * - skip all -> remember as single skip action for all conflicting files
  867. * - replace all -> remember as single replace action for all conflicting files
  868. * - choose -> show choose dialog
  869. * - mark files to keep
  870. * - when only existing -> remember as single skip action
  871. * - when only new -> remember as single replace action
  872. * - when both -> remember as single autorename action
  873. * - start uploading selection
  874. * @param {object} e
  875. * @param {object} data
  876. * @returns {boolean}
  877. */
  878. add: function(e, data) {
  879. self.log('add', e, data);
  880. var that = $(this), freeSpace = 0;
  881. var upload = new OC.FileUpload(self, data);
  882. // can't link directly due to jQuery not liking cyclic deps on its ajax object
  883. data.uploadId = upload.getId();
  884. // create a container where we can store the data objects
  885. if ( ! data.originalFiles.selection ) {
  886. // initialize selection and remember number of files to upload
  887. data.originalFiles.selection = {
  888. uploads: [],
  889. filesToUpload: data.originalFiles.length,
  890. totalBytes: 0
  891. };
  892. }
  893. // TODO: move originalFiles to a separate container, maybe inside OC.Upload
  894. var selection = data.originalFiles.selection;
  895. // add uploads
  896. if ( selection.uploads.length < selection.filesToUpload ) {
  897. // remember upload
  898. selection.uploads.push(upload);
  899. }
  900. //examine file
  901. var file = upload.getFile();
  902. try {
  903. // FIXME: not so elegant... need to refactor that method to return a value
  904. Files.isFileNameValid(file.name);
  905. }
  906. catch (errorMessage) {
  907. data.textStatus = 'invalidcharacters';
  908. data.errorThrown = errorMessage;
  909. }
  910. if (data.targetDir) {
  911. upload.setTargetFolder(data.targetDir);
  912. delete data.targetDir;
  913. }
  914. // in case folder drag and drop is not supported file will point to a directory
  915. // http://stackoverflow.com/a/20448357
  916. if ( !file.type && file.size % 4096 === 0 && file.size <= 102400) {
  917. var dirUploadFailure = false;
  918. try {
  919. var reader = new FileReader();
  920. reader.readAsBinaryString(file);
  921. } catch (error) {
  922. console.log(reader, error)
  923. //file is a directory
  924. dirUploadFailure = true;
  925. }
  926. if (dirUploadFailure) {
  927. data.textStatus = 'dirorzero';
  928. data.errorThrown = t('files',
  929. 'Unable to upload {filename} as it is a directory or has 0 bytes',
  930. {filename: file.name}
  931. );
  932. }
  933. }
  934. // only count if we're not overwriting an existing shared file
  935. if (self._isReceivedSharedFile(file)) {
  936. file.isReceivedShare = true;
  937. } else {
  938. // add size
  939. selection.totalBytes += file.size;
  940. }
  941. // check free space
  942. if (!self.fileList || upload.getTargetFolder() === self.fileList.getCurrentDirectory()) {
  943. // Use global free space if there is no file list to check or the current directory is the target
  944. freeSpace = $('input[name=free_space]').val()
  945. } else if (upload.getTargetFolder().indexOf(self.fileList.getCurrentDirectory()) === 0) {
  946. // Check subdirectory free space if file is uploaded there
  947. // Retrieve the folder destination name
  948. var targetSubdir = upload._targetFolder.split('/').pop()
  949. freeSpace = parseInt(upload.uploader.fileList.getModelForFile(targetSubdir).get('quotaAvailableBytes'))
  950. }
  951. if (freeSpace >= 0 && selection.totalBytes > freeSpace) {
  952. data.textStatus = 'notenoughspace';
  953. data.errorThrown = t('files',
  954. 'Not enough free space, you are uploading {size1} but only {size2} is left', {
  955. 'size1': OC.Util.humanFileSize(selection.totalBytes, false, false),
  956. 'size2': OC.Util.humanFileSize(freeSpace, false, false)
  957. });
  958. }
  959. // end upload for whole selection on error
  960. if (data.errorThrown) {
  961. // trigger fileupload fail handler
  962. var fu = that.data('blueimp-fileupload') || that.data('fileupload');
  963. fu._trigger('fail', e, data);
  964. return false; //don't upload anything
  965. }
  966. // check existing files when all is collected
  967. if ( selection.uploads.length >= selection.filesToUpload ) {
  968. //remove our selection hack:
  969. delete data.originalFiles.selection;
  970. var callbacks = {
  971. onNoConflicts: function (selection) {
  972. self.submitUploads(selection.uploads);
  973. },
  974. onSkipConflicts: function (selection) {
  975. //TODO mark conflicting files as toskip
  976. },
  977. onReplaceConflicts: function (selection) {
  978. //TODO mark conflicting files as toreplace
  979. },
  980. onChooseConflicts: function (selection) {
  981. //TODO mark conflicting files as chosen
  982. },
  983. onCancel: function (selection) {
  984. $.each(selection.uploads, function(i, upload) {
  985. upload.abort();
  986. });
  987. }
  988. };
  989. self.checkExistingFiles(selection, callbacks);
  990. }
  991. return true; // continue adding files
  992. },
  993. /**
  994. * called after the first add, does NOT have the data param
  995. * @param {object} e
  996. */
  997. start: function(e) {
  998. self.log('start', e, null);
  999. self._uploading = true;
  1000. },
  1001. fail: function(e, data) {
  1002. var upload = self.getUpload(data);
  1003. var status = null;
  1004. if (upload) {
  1005. if (upload.aborted) {
  1006. // uploads might fail with errors from the server when aborted
  1007. return
  1008. }
  1009. status = upload.getResponseStatus();
  1010. }
  1011. self.log('fail', e, upload);
  1012. self.removeUpload(upload);
  1013. if (data.textStatus === 'abort' || data.errorThrown === 'abort') {
  1014. return
  1015. } else if (status === 412) {
  1016. // file already exists
  1017. self.showConflict(upload);
  1018. } else if (status === 404) {
  1019. // target folder does not exist any more
  1020. OC.Notification.show(t('files', 'Target folder "{dir}" does not exist any more', {dir: upload.getFullPath()} ), {type: 'error'});
  1021. self.cancelUploads();
  1022. } else if (data.textStatus === 'notenoughspace') {
  1023. // not enough space
  1024. OC.Notification.show(t('files', 'Not enough free space'), {type: 'error'});
  1025. self.cancelUploads();
  1026. } else {
  1027. // HTTP connection problem or other error
  1028. var message = t('files', 'An unknown error has occurred');
  1029. if (upload) {
  1030. var response = upload.getResponse();
  1031. if (response) {
  1032. message = response.message;
  1033. }
  1034. }
  1035. console.error(e, data, response)
  1036. OC.Notification.show(message || data.errorThrown || t('files', 'File could not be uploaded'), {type: 'error'});
  1037. }
  1038. if (upload) {
  1039. upload.fail();
  1040. }
  1041. },
  1042. /**
  1043. * called for every successful upload
  1044. * @param {object} e
  1045. * @param {object} data
  1046. */
  1047. done:function(e, data) {
  1048. var upload = self.getUpload(data);
  1049. var that = $(this);
  1050. self.log('done', e, upload);
  1051. self.removeUpload(upload);
  1052. var status = upload.getResponseStatus();
  1053. if (status < 200 || status >= 300) {
  1054. // trigger fail handler
  1055. var fu = that.data('blueimp-fileupload') || that.data('fileupload');
  1056. fu._trigger('fail', e, data);
  1057. return;
  1058. }
  1059. },
  1060. /**
  1061. * called after last upload
  1062. * @param {object} e
  1063. * @param {object} data
  1064. */
  1065. stop: function(e, data) {
  1066. self.log('stop', e, data);
  1067. self._uploading = false;
  1068. }
  1069. };
  1070. if (options.maxChunkSize) {
  1071. this.fileUploadParam.maxChunkSize = options.maxChunkSize;
  1072. }
  1073. // initialize jquery fileupload (blueimp)
  1074. var fileupload = this.$uploadEl.fileupload(this.fileUploadParam);
  1075. if (this._supportAjaxUploadWithProgress()) {
  1076. //remaining time
  1077. var lastUpdate, lastSize, bufferSize, buffer, bufferIndex, bufferTotal, smoothRemainingSeconds, smoothBitrate;
  1078. var dragging = false;
  1079. // add progress handlers
  1080. fileupload.on('fileuploadadd', function(e, data) {
  1081. self.log('progress handle fileuploadadd', e, data);
  1082. self.trigger('add', e, data);
  1083. });
  1084. // add progress handlers
  1085. fileupload.on('fileuploadstart', function(e, data) {
  1086. self.log('progress handle fileuploadstart', e, data);
  1087. self._setProgressBarText(t('files', 'Uploading …'), t('files', '…'));
  1088. self._setProgressBarValue(0);
  1089. self._showProgressBar();
  1090. // initial remaining time variables
  1091. lastUpdate = new Date().getTime();
  1092. lastSize = 0;
  1093. bufferSize = 20; // length of the ring buffer
  1094. buffer = [];
  1095. bufferIndex = 0; // index of the ring buffer, runs from 0 to bufferSize continuously
  1096. bufferTotal = 0;
  1097. newTotal = 0;
  1098. smoothing = 0.02; // smoothing factor for EMA
  1099. h = '';
  1100. bufferFilled = false;
  1101. for(var i = 0; i < bufferSize; i++){
  1102. buffer[i] = 0;
  1103. }
  1104. self.trigger('start', e, data);
  1105. });
  1106. fileupload.on('fileuploadprogress', function(e, data) {
  1107. self.log('progress handle fileuploadprogress', e, data);
  1108. //TODO progressbar in row
  1109. self.trigger('progress', e, data);
  1110. });
  1111. fileupload.on('fileuploadprogressall', function(e, data) {
  1112. self.log('progress handle fileuploadprogressall', e, data);
  1113. var total = self.totalToUpload;
  1114. var progress = (data.loaded / total) * 100;
  1115. var thisUpdate = new Date().getTime();
  1116. var diffUpdate = (thisUpdate - lastUpdate)/1000; // eg. 2s
  1117. lastUpdate = thisUpdate;
  1118. var diffSize = data.loaded - lastSize;
  1119. if (diffSize <= 0) {
  1120. diffSize = lastSize;
  1121. }
  1122. lastSize = data.loaded;
  1123. diffSize = diffSize / diffUpdate; // apply timing factor, eg. 1MiB/2s = 0.5MiB/s, unit is byte per second
  1124. var remainingSeconds = ((total - data.loaded) / diffSize);
  1125. if(remainingSeconds >= 0) {
  1126. // bufferTotal holds the sum of all entries in the buffer, initially 0 like the entries itself
  1127. // substract current entry from total and add the current value to total
  1128. bufferTotal = bufferTotal - (buffer[bufferIndex]) + remainingSeconds;
  1129. // put current value to the entry
  1130. buffer[bufferIndex] = remainingSeconds; //buffer to make it smoother
  1131. bufferIndex = (bufferIndex + 1) % bufferSize;
  1132. }
  1133. if (bufferIndex === bufferSize - 1) {
  1134. bufferFilled = true;
  1135. }
  1136. //console.log('#', ' idx: ',bufferIndex, ' Total: ', bufferTotal, ' remainSeconds: ', remainingSeconds, ' during: ', diffUpdate);
  1137. if (smoothRemainingSeconds) {
  1138. smoothRemainingSeconds = smoothing * (bufferTotal / bufferSize) + ((1-smoothing) * smoothRemainingSeconds);
  1139. } else {
  1140. smoothRemainingSeconds = bufferTotal / bufferSize;
  1141. }
  1142. // the number of currently running uploads
  1143. const runningUploads = Object.keys(self._uploads).length;
  1144. // Only show remaining time if enough buffer information is available and debounce to 1/4
  1145. if (bufferFilled && bufferIndex % 4 === 0) {
  1146. h = moment.duration(smoothRemainingSeconds, "seconds").humanize({m: 50, h: 50});
  1147. if (self.totalUploadCount > 1) {
  1148. h = t('files', '{remainingTime} ({currentNumber}/{total})', { remainingTime: h, currentNumber: self.totalUploadCount - runningUploads + 1, total: self.totalUploadCount });
  1149. }
  1150. }
  1151. // wait for the buffer to be filled and also show "Uploading ..." for durations longer than 4 hours
  1152. if (!bufferFilled || !(smoothRemainingSeconds >= 0 && smoothRemainingSeconds < 14400)) {
  1153. // Do not show file index when there is just one
  1154. if (self.totalUploadCount > 1) {
  1155. h = t('files', 'Uploading … ({currentNumber}/{total})', { currentNumber: self.totalUploadCount - runningUploads + 1, total: self.totalUploadCount });
  1156. } else {
  1157. h = t('files', 'Uploading …');
  1158. }
  1159. }
  1160. // smooth bitrate
  1161. if (smoothBitrate) {
  1162. smoothBitrate = smoothing * data.bitrate + ((1-smoothing) * smoothBitrate);
  1163. } else {
  1164. smoothBitrate = data.bitrate;
  1165. }
  1166. self._setProgressBarText(h, h, t('files', '{loadedSize} of {totalSize} ({bitrate})' , {
  1167. loadedSize: OC.Util.humanFileSize(data.loaded, false, false),
  1168. totalSize: OC.Util.humanFileSize(total, false, false),
  1169. bitrate: OC.Util.humanFileSize(smoothBitrate / 8, false, false) + '/s'
  1170. }));
  1171. self._setProgressBarValue(progress);
  1172. self.trigger('progressall', e, data);
  1173. });
  1174. fileupload.on('fileuploadstop', function(e, data) {
  1175. self.log('progress handle fileuploadstop', e, data);
  1176. self.clear();
  1177. self._updateProgressBarOnUploadStop();
  1178. self.trigger('stop', e, data);
  1179. });
  1180. fileupload.on('fileuploadfail', function(e, data) {
  1181. self.log('progress handle fileuploadfail', e, data);
  1182. self.trigger('fail', e, data);
  1183. });
  1184. fileupload.on('fileuploaddragover', function(e){
  1185. $('#app-content').addClass('file-drag');
  1186. $('.emptyfilelist.emptycontent .icon-folder').addClass('icon-filetype-folder-drag-accept');
  1187. var filerow = $(e.delegatedEvent.target).closest('tr');
  1188. if(!filerow.hasClass('dropping-to-dir')){
  1189. $('.dropping-to-dir .icon-filetype-folder-drag-accept').removeClass('icon-filetype-folder-drag-accept');
  1190. $('.dropping-to-dir').removeClass('dropping-to-dir');
  1191. $('.dir-drop').removeClass('dir-drop');
  1192. }
  1193. if(filerow.attr('data-type') === 'dir'){
  1194. $('#app-content').addClass('dir-drop');
  1195. filerow.addClass('dropping-to-dir');
  1196. filerow.find('.thumbnail').addClass('icon-filetype-folder-drag-accept');
  1197. }
  1198. dragging = true;
  1199. });
  1200. var disableDropState = function() {
  1201. $('#app-content').removeClass('file-drag');
  1202. $('.dropping-to-dir').removeClass('dropping-to-dir');
  1203. $('.dir-drop').removeClass('dir-drop');
  1204. $('.icon-filetype-folder-drag-accept').removeClass('icon-filetype-folder-drag-accept');
  1205. dragging = false;
  1206. };
  1207. fileupload.on('fileuploaddragleave fileuploaddrop', disableDropState);
  1208. // In some browsers the "drop" event can be triggered with no
  1209. // files even if the "dragover" event seemed to suggest that a
  1210. // file was being dragged (and thus caused "fileuploaddragover"
  1211. // to be triggered).
  1212. fileupload.on('fileuploaddropnofiles', function() {
  1213. if (!dragging) {
  1214. return;
  1215. }
  1216. disableDropState();
  1217. OC.Notification.show(t('files', 'Uploading that item is not supported'), {type: 'error'});
  1218. });
  1219. fileupload.on('fileuploadchunksend', function(e, data) {
  1220. // modify the request to adjust it to our own chunking
  1221. var upload = self.getUpload(data);
  1222. if (!upload) {
  1223. // likely cancelled
  1224. return
  1225. }
  1226. var range = data.contentRange.split(' ')[1];
  1227. var chunkId = range.split('/')[0].split('-')[0];
  1228. // Use a numeric chunk id and set the Destination header on all request for ChunkingV2
  1229. chunkId = Math.ceil((data.chunkSize+Number(chunkId)) / upload.uploader.fileUploadParam.maxChunkSize);
  1230. data.headers['Destination'] = self.davClient._buildUrl(upload.getTargetDestination());
  1231. data.url = OC.getRootPath() +
  1232. '/remote.php/dav/uploads' +
  1233. '/' + OC.getCurrentUser().uid +
  1234. '/' + upload.getId() +
  1235. '/' + chunkId;
  1236. delete data.contentRange;
  1237. delete data.headers['Content-Range'];
  1238. });
  1239. fileupload.on('fileuploaddone', function(e, data) {
  1240. var upload = self.getUpload(data);
  1241. self._pendingUploadDoneCount++;
  1242. upload.done().always(function() {
  1243. self._pendingUploadDoneCount--;
  1244. if (self._activeUploadCount() === 0 && self._pendingUploadDoneCount === 0) {
  1245. // All the uploads ended and there is no pending
  1246. // operation, so hide the progress bar.
  1247. // Note that this happens here only with chunked
  1248. // uploads; if the upload was non-chunked then this
  1249. // handler is immediately executed, before the
  1250. // jQuery upload done handler that removes the
  1251. // upload from the list, and thus at this point
  1252. // there is still at least one upload that has not
  1253. // ended (although the upload stop handler is always
  1254. // executed after all the uploads have ended, which
  1255. // hides the progress bar in that case).
  1256. self._hideProgressBar();
  1257. }
  1258. }).done(function() {
  1259. self.trigger('done', e, upload);
  1260. }).fail(function(status, response) {
  1261. if (upload.aborted) {
  1262. return
  1263. }
  1264. var message = response.message;
  1265. if (status === 507) {
  1266. // not enough space
  1267. OC.Notification.show(message || t('files', 'Not enough free space'), {type: 'error'});
  1268. self.cancelUploads();
  1269. } else if (status === 409) {
  1270. OC.Notification.show(message || t('files', 'Target folder does not exist any more'), {type: 'error'});
  1271. } else if (status === 403) {
  1272. OC.Notification.show(message || t('files', 'Operation is blocked by access control'), {type: 'error'});
  1273. } else {
  1274. OC.Notification.show(message || t('files', 'Error when assembling chunks, status code {status}', {status: status}), {type: 'error'});
  1275. }
  1276. self.trigger('fail', e, data);
  1277. });
  1278. });
  1279. fileupload.on('fileuploaddrop', function(e, data) {
  1280. self.trigger('drop', e, data);
  1281. if (e.isPropagationStopped()) {
  1282. return false;
  1283. }
  1284. });
  1285. }
  1286. window.onbeforeunload = function() {
  1287. return self.confirmBeforeUnload();
  1288. }
  1289. }
  1290. //add multiply file upload attribute to all browsers except konqueror (which crashes when it's used)
  1291. if (navigator.userAgent.search(/konqueror/i) === -1) {
  1292. this.$uploadEl.attr('multiple', 'multiple');
  1293. }
  1294. return this.fileUploadParam;
  1295. }
  1296. }, OC.Backbone.Events);