files.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. /* global getURLParameter */
  11. /**
  12. * Utility class for file related operations
  13. */
  14. (function() {
  15. var Files = {
  16. // file space size sync
  17. _updateStorageStatistics: function(currentDir) {
  18. var state = Files.updateStorageStatistics;
  19. if (state.dir){
  20. if (state.dir === currentDir) {
  21. return;
  22. }
  23. // cancel previous call, as it was for another dir
  24. state.call.abort();
  25. }
  26. state.dir = currentDir;
  27. state.call = $.getJSON(OC.filePath('files','ajax','getstoragestats.php') + '?dir=' + encodeURIComponent(currentDir),function(response) {
  28. state.dir = null;
  29. state.call = null;
  30. Files.updateMaxUploadFilesize(response);
  31. });
  32. },
  33. // update quota
  34. updateStorageQuotas: function() {
  35. Files._updateStorageQuotasThrottled();
  36. },
  37. _updateStorageQuotas: function() {
  38. var state = Files.updateStorageQuotas;
  39. state.call = $.getJSON(OC.filePath('files','ajax','getstoragestats.php'),function(response) {
  40. Files.updateQuota(response);
  41. });
  42. },
  43. /**
  44. * Update storage statistics such as free space, max upload,
  45. * etc based on the given directory.
  46. *
  47. * Note this function is debounced to avoid making too
  48. * many ajax calls in a row.
  49. *
  50. * @param dir directory
  51. * @param force whether to force retrieving
  52. */
  53. updateStorageStatistics: function(dir, force) {
  54. if (!OC.currentUser) {
  55. return;
  56. }
  57. if (force) {
  58. Files._updateStorageStatistics(dir);
  59. }
  60. else {
  61. Files._updateStorageStatisticsDebounced(dir);
  62. }
  63. },
  64. updateMaxUploadFilesize:function(response) {
  65. if (response === undefined) {
  66. return;
  67. }
  68. if (response.data !== undefined && response.data.uploadMaxFilesize !== undefined) {
  69. $('#free_space').val(response.data.freeSpace);
  70. $('#upload.button').attr('data-original-title', response.data.maxHumanFilesize);
  71. $('#usedSpacePercent').val(response.data.usedSpacePercent);
  72. $('#usedSpacePercent').data('mount-type', response.data.mountType);
  73. $('#usedSpacePercent').data('mount-point', response.data.mountPoint);
  74. $('#owner').val(response.data.owner);
  75. $('#ownerDisplayName').val(response.data.ownerDisplayName);
  76. Files.displayStorageWarnings();
  77. OCA.Files.App.fileList._updateDirectoryPermissions();
  78. }
  79. if (response[0] === undefined) {
  80. return;
  81. }
  82. if (response[0].uploadMaxFilesize !== undefined) {
  83. $('#upload.button').attr('data-original-title', response[0].maxHumanFilesize);
  84. $('#usedSpacePercent').val(response[0].usedSpacePercent);
  85. Files.displayStorageWarnings();
  86. }
  87. },
  88. updateQuota:function(response) {
  89. if (response === undefined) {
  90. return;
  91. }
  92. if (response.data !== undefined
  93. && response.data.quota !== undefined
  94. && response.data.used !== undefined
  95. && response.data.usedSpacePercent !== undefined) {
  96. var humanUsed = OC.Util.humanFileSize(response.data.used, true);
  97. var humanQuota = OC.Util.humanFileSize(response.data.quota, true);
  98. if (response.data.quota > 0) {
  99. $('#quota').attr('data-original-title', Math.floor(response.data.used/response.data.quota*1000)/10 + '%');
  100. $('#quota progress').val(response.data.usedSpacePercent);
  101. $('#quotatext').text(t('files', '{used} of {quota} used', {used: humanUsed, quota: humanQuota}));
  102. } else {
  103. $('#quotatext').text(t('files', '{used} used', {used: humanUsed}));
  104. }
  105. if (response.data.usedSpacePercent > 80) {
  106. $('#quota progress').addClass('warn');
  107. } else {
  108. $('#quota progress').removeClass('warn');
  109. }
  110. }
  111. },
  112. /**
  113. * Fix path name by removing double slash at the beginning, if any
  114. */
  115. fixPath: function(fileName) {
  116. if (fileName.substr(0, 2) == '//') {
  117. return fileName.substr(1);
  118. }
  119. return fileName;
  120. },
  121. /**
  122. * Checks whether the given file name is valid.
  123. * @param name file name to check
  124. * @return true if the file name is valid.
  125. * Throws a string exception with an error message if
  126. * the file name is not valid
  127. *
  128. * NOTE: This function is duplicated in the filepicker inside core/src/OC/dialogs.js
  129. */
  130. isFileNameValid: function (name) {
  131. var trimmedName = name.trim();
  132. if (trimmedName === '.' || trimmedName === '..')
  133. {
  134. throw t('files', '"{name}" is an invalid file name.', {name: name});
  135. } else if (trimmedName.length === 0) {
  136. throw t('files', 'File name cannot be empty.');
  137. } else if (trimmedName.indexOf('/') !== -1) {
  138. throw t('files', '"/" is not allowed inside a file name.');
  139. } else if (!!(trimmedName.match(OC.config.blacklist_files_regex))) {
  140. throw t('files', '"{name}" is not an allowed filetype', {name: name});
  141. }
  142. return true;
  143. },
  144. displayStorageWarnings: function() {
  145. if (!OC.Notification.isHidden()) {
  146. return;
  147. }
  148. var usedSpacePercent = $('#usedSpacePercent').val(),
  149. owner = $('#owner').val(),
  150. ownerDisplayName = $('#ownerDisplayName').val(),
  151. mountType = $('#usedSpacePercent').data('mount-type'),
  152. mountPoint = $('#usedSpacePercent').data('mount-point');
  153. if (usedSpacePercent > 98) {
  154. if (owner !== OC.getCurrentUser().uid) {
  155. OC.Notification.show(t('files', 'Storage of {owner} is full, files can not be updated or synced anymore!',
  156. {owner: ownerDisplayName}), {type: 'error'}
  157. );
  158. } else if (mountType === 'group') {
  159. OC.Notification.show(t('files',
  160. 'Group folder "{mountPoint}" is full, files can not be updated or synced anymore!',
  161. {mountPoint: mountPoint}),
  162. {type: 'error'}
  163. );
  164. } else if (mountType === 'external') {
  165. OC.Notification.show(t('files',
  166. 'External storage "{mountPoint}" is full, files can not be updated or synced anymore!',
  167. {mountPoint: mountPoint}),
  168. {type : 'error'}
  169. );
  170. } else {
  171. OC.Notification.show(t('files',
  172. 'Your storage is full, files can not be updated or synced anymore!'),
  173. {type: 'error'}
  174. );
  175. }
  176. } else if (usedSpacePercent > 90) {
  177. if (owner !== OC.getCurrentUser().uid) {
  178. OC.Notification.show(t('files', 'Storage of {owner} is almost full ({usedSpacePercent}%).',
  179. {
  180. usedSpacePercent: usedSpacePercent,
  181. owner: ownerDisplayName
  182. }),
  183. {
  184. type: 'error'
  185. }
  186. );
  187. } else if (mountType === 'group') {
  188. OC.Notification.show(t('files',
  189. 'Group folder "{mountPoint}" is almost full ({usedSpacePercent}%).',
  190. {mountPoint: mountPoint, usedSpacePercent: usedSpacePercent}),
  191. {type : 'error'}
  192. );
  193. } else if (mountType === 'external') {
  194. OC.Notification.show(t('files',
  195. 'External storage "{mountPoint}" is almost full ({usedSpacePercent}%).',
  196. {mountPoint: mountPoint, usedSpacePercent: usedSpacePercent}),
  197. {type : 'error'}
  198. );
  199. } else {
  200. OC.Notification.show(t('files', 'Your storage is almost full ({usedSpacePercent}%).',
  201. {usedSpacePercent: usedSpacePercent}),
  202. {type : 'error'}
  203. );
  204. }
  205. }
  206. },
  207. /**
  208. * Returns the download URL of the given file(s)
  209. * @param {string} filename string or array of file names to download
  210. * @param {string} [dir] optional directory in which the file name is, defaults to the current directory
  211. * @param {bool} [isDir=false] whether the given filename is a directory and might need a special URL
  212. */
  213. getDownloadUrl: function(filename, dir, isDir) {
  214. if (!_.isArray(filename) && !isDir) {
  215. var pathSections = dir.split('/');
  216. pathSections.push(filename);
  217. var encodedPath = '';
  218. _.each(pathSections, function(section) {
  219. if (section !== '') {
  220. encodedPath += '/' + encodeURIComponent(section);
  221. }
  222. });
  223. return OC.linkToRemoteBase('webdav') + encodedPath;
  224. }
  225. if (_.isArray(filename)) {
  226. filename = JSON.stringify(filename);
  227. }
  228. var params = {
  229. dir: dir,
  230. files: filename
  231. };
  232. return this.getAjaxUrl('download', params);
  233. },
  234. /**
  235. * Returns the ajax URL for a given action
  236. * @param action action string
  237. * @param params optional params map
  238. */
  239. getAjaxUrl: function(action, params) {
  240. var q = '';
  241. if (params) {
  242. q = '?' + OC.buildQueryString(params);
  243. }
  244. return OC.filePath('files', 'ajax', action + '.php') + q;
  245. },
  246. /**
  247. * Fetch the icon url for the mimetype
  248. * @param {string} mime The mimetype
  249. * @param {Files~mimeicon} ready Function to call when mimetype is retrieved
  250. * @deprecated use OC.MimeType.getIconUrl(mime)
  251. */
  252. getMimeIcon: function(mime, ready) {
  253. ready(OC.MimeType.getIconUrl(mime));
  254. },
  255. /**
  256. * Generates a preview URL based on the URL space.
  257. * @param urlSpec attributes for the URL
  258. * @param {int} urlSpec.x width
  259. * @param {int} urlSpec.y height
  260. * @param {String} urlSpec.file path to the file
  261. * @return preview URL
  262. * @deprecated used OCA.Files.FileList.generatePreviewUrl instead
  263. */
  264. generatePreviewUrl: function(urlSpec) {
  265. console.warn('DEPRECATED: please use generatePreviewUrl() from an OCA.Files.FileList instance');
  266. return OCA.Files.App.fileList.generatePreviewUrl(urlSpec);
  267. },
  268. /**
  269. * Lazy load preview
  270. * @deprecated used OCA.Files.FileList.lazyLoadPreview instead
  271. */
  272. lazyLoadPreview : function(path, mime, ready, width, height, etag) {
  273. console.warn('DEPRECATED: please use lazyLoadPreview() from an OCA.Files.FileList instance');
  274. return FileList.lazyLoadPreview({
  275. path: path,
  276. mime: mime,
  277. callback: ready,
  278. width: width,
  279. height: height,
  280. etag: etag
  281. });
  282. },
  283. /**
  284. * Initialize the files view
  285. */
  286. initialize: function() {
  287. Files.bindKeyboardShortcuts(document, $);
  288. // TODO: move file list related code (upload) to OCA.Files.FileList
  289. $('#file_action_panel').attr('activeAction', false);
  290. // drag&drop support using jquery.fileupload
  291. // TODO use OC.dialogs
  292. $(document).bind('drop dragover', function (e) {
  293. e.preventDefault(); // prevent browser from doing anything, if file isn't dropped in dropZone
  294. });
  295. // display storage warnings
  296. setTimeout(Files.displayStorageWarnings, 100);
  297. // only possible at the moment if user is logged in or the files app is loaded
  298. if (OC.currentUser && OCA.Files.App && OC.config.session_keepalive) {
  299. // start on load - we ask the server every 5 minutes
  300. var func = _.bind(OCA.Files.App.fileList.updateStorageStatistics, OCA.Files.App.fileList);
  301. var updateStorageStatisticsInterval = 5*60*1000;
  302. var updateStorageStatisticsIntervalId = setInterval(func, updateStorageStatisticsInterval);
  303. // TODO: this should also stop when switching to another view
  304. // Use jquery-visibility to de-/re-activate file stats sync
  305. if ($.support.pageVisibility) {
  306. $(document).on({
  307. 'show': function() {
  308. if (!updateStorageStatisticsIntervalId) {
  309. updateStorageStatisticsIntervalId = setInterval(func, updateStorageStatisticsInterval);
  310. }
  311. },
  312. 'hide': function() {
  313. clearInterval(updateStorageStatisticsIntervalId);
  314. updateStorageStatisticsIntervalId = 0;
  315. }
  316. });
  317. }
  318. }
  319. $('#webdavurl').on('click touchstart', function () {
  320. this.focus();
  321. this.setSelectionRange(0, this.value.length);
  322. });
  323. $('#upload').tooltip({placement:'right'});
  324. //FIXME scroll to and highlight preselected file
  325. /*
  326. if (getURLParameter('scrollto')) {
  327. FileList.scrollTo(getURLParameter('scrollto'));
  328. }
  329. */
  330. },
  331. /**
  332. * Handles the download and calls the callback function once the download has started
  333. * - browser sends download request and adds parameter with a token
  334. * - server notices this token and adds a set cookie to the download response
  335. * - browser now adds this cookie for the domain
  336. * - JS periodically checks for this cookie and then knows when the download has started to call the callback
  337. *
  338. * @param {string} url download URL
  339. * @param {Function} callback function to call once the download has started
  340. */
  341. handleDownload: function(url, callback) {
  342. var randomToken = Math.random().toString(36).substring(2),
  343. checkForDownloadCookie = function() {
  344. if (!OC.Util.isCookieSetToValue('ocDownloadStarted', randomToken)){
  345. return false;
  346. } else {
  347. callback();
  348. return true;
  349. }
  350. };
  351. if (url.indexOf('?') >= 0) {
  352. url += '&';
  353. } else {
  354. url += '?';
  355. }
  356. OC.redirect(url + 'downloadStartSecret=' + randomToken);
  357. OC.Util.waitFor(checkForDownloadCookie, 500);
  358. }
  359. };
  360. Files._updateStorageStatisticsDebounced = _.debounce(Files._updateStorageStatistics, 250);
  361. Files._updateStorageQuotasThrottled = _.throttle(Files._updateStorageQuotas, 30000);
  362. OCA.Files.Files = Files;
  363. })();
  364. // TODO: move to FileList
  365. var createDragShadow = function(event) {
  366. // FIXME: inject file list instance somehow
  367. /* global FileList, Files */
  368. //select dragged file
  369. var isDragSelected = $(event.target).parents('tr').find('td input:first').prop('checked');
  370. if (!isDragSelected) {
  371. //select dragged file
  372. FileList._selectFileEl($(event.target).parents('tr:first'), true, false);
  373. }
  374. // do not show drag shadow for too many files
  375. var selectedFiles = _.first(FileList.getSelectedFiles(), FileList.pageSize());
  376. selectedFiles = _.sortBy(selectedFiles, FileList._fileInfoCompare);
  377. if (!isDragSelected && selectedFiles.length === 1) {
  378. //revert the selection
  379. FileList._selectFileEl($(event.target).parents('tr:first'), false, false);
  380. }
  381. // build dragshadow
  382. var dragshadow = $('<table class="dragshadow"></table>');
  383. var tbody = $('<tbody></tbody>');
  384. dragshadow.append(tbody);
  385. var dir = FileList.getCurrentDirectory();
  386. $(selectedFiles).each(function(i,elem) {
  387. // TODO: refactor this with the table row creation code
  388. var newtr = $('<tr/>')
  389. .attr('data-dir', dir)
  390. .attr('data-file', elem.name)
  391. .attr('data-origin', elem.origin);
  392. newtr.append($('<td class="filename" />').text(elem.name).css('background-size', 32));
  393. newtr.append($('<td class="size" />').text(OC.Util.humanFileSize(elem.size)));
  394. tbody.append(newtr);
  395. if (elem.type === 'dir') {
  396. newtr.find('td.filename')
  397. .css('background-image', 'url(' + OC.MimeType.getIconUrl('folder') + ')');
  398. } else {
  399. var path = dir + '/' + elem.name;
  400. Files.lazyLoadPreview(path, elem.mimetype, function(previewpath) {
  401. newtr.find('td.filename')
  402. .css('background-image', 'url(' + previewpath + ')');
  403. }, null, null, elem.etag);
  404. }
  405. });
  406. return dragshadow;
  407. };
  408. //options for file drag/drop
  409. //start&stop handlers needs some cleaning up
  410. // TODO: move to FileList class
  411. var dragOptions={
  412. revert: 'invalid',
  413. revertDuration: 300,
  414. opacity: 0.7,
  415. appendTo: 'body',
  416. cursorAt: { left: 24, top: 18 },
  417. helper: createDragShadow,
  418. cursor: 'move',
  419. start: function(event, ui){
  420. var $selectedFiles = $('td.filename input:checkbox:checked');
  421. if (!$selectedFiles.length) {
  422. $selectedFiles = $(this);
  423. }
  424. $selectedFiles.closest('tr').addClass('animate-opacity dragging');
  425. $selectedFiles.closest('tr').filter('.ui-droppable').droppable( 'disable' );
  426. // Show breadcrumbs menu
  427. $('.crumbmenu').addClass('canDropChildren');
  428. },
  429. stop: function(event, ui) {
  430. var $selectedFiles = $('td.filename input:checkbox:checked');
  431. if (!$selectedFiles.length) {
  432. $selectedFiles = $(this);
  433. }
  434. var $tr = $selectedFiles.closest('tr');
  435. $tr.removeClass('dragging');
  436. $tr.filter('.ui-droppable').droppable( 'enable' );
  437. setTimeout(function() {
  438. $tr.removeClass('animate-opacity');
  439. }, 300);
  440. // Hide breadcrumbs menu
  441. $('.crumbmenu').removeClass('canDropChildren');
  442. },
  443. drag: function(event, ui) {
  444. var scrollingArea = window;
  445. var currentScrollTop = $(scrollingArea).scrollTop();
  446. var scrollArea = Math.min(Math.floor($(window).innerHeight() / 2), 100);
  447. var bottom = $(window).innerHeight() - scrollArea;
  448. var top = $(window).scrollTop() + scrollArea;
  449. if (event.pageY < top) {
  450. $(scrollingArea).animate({
  451. scrollTop: currentScrollTop - 10
  452. }, 400);
  453. } else if (event.pageY > bottom) {
  454. $(scrollingArea).animate({
  455. scrollTop: currentScrollTop + 10
  456. }, 400);
  457. }
  458. }
  459. };
  460. // sane browsers support using the distance option
  461. if ( $('html.ie').length === 0) {
  462. dragOptions['distance'] = 20;
  463. }
  464. // TODO: move to FileList class
  465. var folderDropOptions = {
  466. hoverClass: "canDrop",
  467. drop: function( event, ui ) {
  468. // don't allow moving a file into a selected folder
  469. /* global FileList */
  470. if ($(event.target).parents('tr').find('td input:first').prop('checked') === true) {
  471. return false;
  472. }
  473. var $tr = $(this).closest('tr');
  474. if (($tr.data('permissions') & OC.PERMISSION_CREATE) === 0) {
  475. FileList._showPermissionDeniedNotification();
  476. return false;
  477. }
  478. var targetPath = FileList.getCurrentDirectory() + '/' + $tr.data('file');
  479. var files = FileList.getSelectedFiles();
  480. if (files.length === 0) {
  481. // single one selected without checkbox?
  482. files = _.map(ui.helper.find('tr'), function(el) {
  483. return FileList.elementToFile($(el));
  484. });
  485. }
  486. FileList.move(_.pluck(files, 'name'), targetPath);
  487. },
  488. tolerance: 'pointer'
  489. };
  490. // for backward compatibility
  491. window.Files = OCA.Files.Files;