1
0

file-upload.js 36 KB

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