files.js 15 KB

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