file-upload.js 39 KB

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