file-upload.js 41 KB

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