files.js 15 KB

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