filelist.js 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217
  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. (function() {
  11. /**
  12. * @class OCA.Files.FileList
  13. * @classdesc
  14. *
  15. * The FileList class manages a file list view.
  16. * A file list view consists of a controls bar and
  17. * a file list table.
  18. *
  19. * @param $el container element with existing markup for the #controls
  20. * and a table
  21. * @param [options] map of options, see other parameters
  22. * @param [options.scrollContainer] scrollable container, defaults to $(window)
  23. * @param [options.dragOptions] drag options, disabled by default
  24. * @param [options.folderDropOptions] folder drop options, disabled by default
  25. */
  26. var FileList = function($el, options) {
  27. this.initialize($el, options);
  28. };
  29. /**
  30. * @memberof OCA.Files
  31. */
  32. FileList.prototype = {
  33. SORT_INDICATOR_ASC_CLASS: 'icon-triangle-n',
  34. SORT_INDICATOR_DESC_CLASS: 'icon-triangle-s',
  35. id: 'files',
  36. appName: t('files', 'Files'),
  37. isEmpty: true,
  38. useUndo:true,
  39. /**
  40. * Top-level container with controls and file list
  41. */
  42. $el: null,
  43. /**
  44. * Files table
  45. */
  46. $table: null,
  47. /**
  48. * List of rows (table tbody)
  49. */
  50. $fileList: null,
  51. /**
  52. * @type OCA.Files.BreadCrumb
  53. */
  54. breadcrumb: null,
  55. /**
  56. * @type OCA.Files.FileSummary
  57. */
  58. fileSummary: null,
  59. /**
  60. * Whether the file list was initialized already.
  61. * @type boolean
  62. */
  63. initialized: false,
  64. /**
  65. * Number of files per page
  66. *
  67. * @return {int} page size
  68. */
  69. pageSize: function() {
  70. return Math.ceil(this.$container.height() / 50);
  71. },
  72. /**
  73. * Array of files in the current folder.
  74. * The entries are of file data.
  75. *
  76. * @type Array.<Object>
  77. */
  78. files: [],
  79. /**
  80. * File actions handler, defaults to OCA.Files.FileActions
  81. * @type OCA.Files.FileActions
  82. */
  83. fileActions: null,
  84. /**
  85. * Whether selection is allowed, checkboxes and selection overlay will
  86. * be rendered
  87. */
  88. _allowSelection: true,
  89. /**
  90. * Map of file id to file data
  91. * @type Object.<int, Object>
  92. */
  93. _selectedFiles: {},
  94. /**
  95. * Summary of selected files.
  96. * @type OCA.Files.FileSummary
  97. */
  98. _selectionSummary: null,
  99. /**
  100. * If not empty, only files containing this string will be shown
  101. * @type String
  102. */
  103. _filter: '',
  104. /**
  105. * Sort attribute
  106. * @type String
  107. */
  108. _sort: 'name',
  109. /**
  110. * Sort direction: 'asc' or 'desc'
  111. * @type String
  112. */
  113. _sortDirection: 'asc',
  114. /**
  115. * Sort comparator function for the current sort
  116. * @type Function
  117. */
  118. _sortComparator: null,
  119. /**
  120. * Whether to do a client side sort.
  121. * When false, clicking on a table header will call reload().
  122. * When true, clicking on a table header will simply resort the list.
  123. */
  124. _clientSideSort: false,
  125. /**
  126. * Current directory
  127. * @type String
  128. */
  129. _currentDirectory: null,
  130. _dragOptions: null,
  131. _folderDropOptions: null,
  132. /**
  133. * Initialize the file list and its components
  134. *
  135. * @param $el container element with existing markup for the #controls
  136. * and a table
  137. * @param options map of options, see other parameters
  138. * @param options.scrollContainer scrollable container, defaults to $(window)
  139. * @param options.dragOptions drag options, disabled by default
  140. * @param options.folderDropOptions folder drop options, disabled by default
  141. * @param options.scrollTo name of file to scroll to after the first load
  142. * @private
  143. */
  144. initialize: function($el, options) {
  145. var self = this;
  146. options = options || {};
  147. if (this.initialized) {
  148. return;
  149. }
  150. if (options.dragOptions) {
  151. this._dragOptions = options.dragOptions;
  152. }
  153. if (options.folderDropOptions) {
  154. this._folderDropOptions = options.folderDropOptions;
  155. }
  156. this.$el = $el;
  157. if (options.id) {
  158. this.id = options.id;
  159. }
  160. this.$container = options.scrollContainer || $(window);
  161. this.$table = $el.find('table:first');
  162. this.$fileList = $el.find('#fileList');
  163. this._initFileActions(options.fileActions);
  164. this.files = [];
  165. this._selectedFiles = {};
  166. this._selectionSummary = new OCA.Files.FileSummary();
  167. this.fileSummary = this._createSummary();
  168. this.setSort('name', 'asc');
  169. var breadcrumbOptions = {
  170. onClick: _.bind(this._onClickBreadCrumb, this),
  171. getCrumbUrl: function(part) {
  172. return self.linkTo(part.dir);
  173. }
  174. };
  175. // if dropping on folders is allowed, then also allow on breadcrumbs
  176. if (this._folderDropOptions) {
  177. breadcrumbOptions.onDrop = _.bind(this._onDropOnBreadCrumb, this);
  178. }
  179. this.breadcrumb = new OCA.Files.BreadCrumb(breadcrumbOptions);
  180. this.$el.find('#controls').prepend(this.breadcrumb.$el);
  181. this.$el.find('thead th .columntitle').click(_.bind(this._onClickHeader, this));
  182. this._onResize = _.debounce(_.bind(this._onResize, this), 100);
  183. $(window).resize(this._onResize);
  184. this.$el.on('show', this._onResize);
  185. this.updateSearch();
  186. this.$fileList.on('click','td.filename>a.name', _.bind(this._onClickFile, this));
  187. this.$fileList.on('change', 'td.filename>.selectCheckBox', _.bind(this._onClickFileCheckbox, this));
  188. this.$el.on('urlChanged', _.bind(this._onUrlChanged, this));
  189. this.$el.find('.select-all').click(_.bind(this._onClickSelectAll, this));
  190. this.$el.find('.download').click(_.bind(this._onClickDownloadSelected, this));
  191. this.$el.find('.delete-selected').click(_.bind(this._onClickDeleteSelected, this));
  192. this.setupUploadEvents();
  193. this.$container.on('scroll', _.bind(this._onScroll, this));
  194. if (options.scrollTo) {
  195. this.$fileList.one('updated', function() {
  196. self.scrollTo(options.scrollTo);
  197. });
  198. }
  199. OC.Plugins.attach('OCA.Files.FileList', this);
  200. },
  201. /**
  202. * Destroy / uninitialize this instance.
  203. */
  204. destroy: function() {
  205. // TODO: also unregister other event handlers
  206. this.fileActions.off('registerAction', this._onFileActionsUpdated);
  207. this.fileActions.off('setDefault', this._onFileActionsUpdated);
  208. OC.Plugins.detach('OCA.Files.FileList', this);
  209. },
  210. /**
  211. * Initializes the file actions, set up listeners.
  212. *
  213. * @param {OCA.Files.FileActions} fileActions file actions
  214. */
  215. _initFileActions: function(fileActions) {
  216. this.fileActions = fileActions;
  217. if (!this.fileActions) {
  218. this.fileActions = new OCA.Files.FileActions();
  219. this.fileActions.registerDefaultActions();
  220. }
  221. this._onFileActionsUpdated = _.debounce(_.bind(this._onFileActionsUpdated, this), 100);
  222. this.fileActions.on('registerAction', this._onFileActionsUpdated);
  223. this.fileActions.on('setDefault', this._onFileActionsUpdated);
  224. },
  225. /**
  226. * Event handler for when the window size changed
  227. */
  228. _onResize: function() {
  229. var containerWidth = this.$el.width();
  230. var actionsWidth = 0;
  231. $.each(this.$el.find('#controls .actions'), function(index, action) {
  232. actionsWidth += $(action).outerWidth();
  233. });
  234. // substract app navigation toggle when visible
  235. containerWidth -= $('#app-navigation-toggle').width();
  236. this.breadcrumb.setMaxWidth(containerWidth - actionsWidth - 10);
  237. this.updateSearch();
  238. },
  239. /**
  240. * Event handler for when the URL changed
  241. */
  242. _onUrlChanged: function(e) {
  243. if (e && e.dir) {
  244. this.changeDirectory(e.dir, false, true);
  245. }
  246. },
  247. /**
  248. * Selected/deselects the given file element and updated
  249. * the internal selection cache.
  250. *
  251. * @param $tr single file row element
  252. * @param state true to select, false to deselect
  253. */
  254. _selectFileEl: function($tr, state) {
  255. var $checkbox = $tr.find('td.filename>.selectCheckBox');
  256. var oldData = !!this._selectedFiles[$tr.data('id')];
  257. var data;
  258. $checkbox.prop('checked', state);
  259. $tr.toggleClass('selected', state);
  260. // already selected ?
  261. if (state === oldData) {
  262. return;
  263. }
  264. data = this.elementToFile($tr);
  265. if (state) {
  266. this._selectedFiles[$tr.data('id')] = data;
  267. this._selectionSummary.add(data);
  268. }
  269. else {
  270. delete this._selectedFiles[$tr.data('id')];
  271. this._selectionSummary.remove(data);
  272. }
  273. this.$el.find('.select-all').prop('checked', this._selectionSummary.getTotal() === this.files.length);
  274. },
  275. /**
  276. * Event handler for when clicking on files to select them
  277. */
  278. _onClickFile: function(event) {
  279. var $tr = $(event.target).closest('tr');
  280. if (this._allowSelection && (event.ctrlKey || event.shiftKey)) {
  281. event.preventDefault();
  282. if (event.shiftKey) {
  283. var $lastTr = $(this._lastChecked);
  284. var lastIndex = $lastTr.index();
  285. var currentIndex = $tr.index();
  286. var $rows = this.$fileList.children('tr');
  287. // last clicked checkbox below current one ?
  288. if (lastIndex > currentIndex) {
  289. var aux = lastIndex;
  290. lastIndex = currentIndex;
  291. currentIndex = aux;
  292. }
  293. // auto-select everything in-between
  294. for (var i = lastIndex + 1; i < currentIndex; i++) {
  295. this._selectFileEl($rows.eq(i), true);
  296. }
  297. }
  298. else {
  299. this._lastChecked = $tr;
  300. }
  301. var $checkbox = $tr.find('td.filename>.selectCheckBox');
  302. this._selectFileEl($tr, !$checkbox.prop('checked'));
  303. this.updateSelectionSummary();
  304. } else {
  305. var filename = $tr.attr('data-file');
  306. var renaming = $tr.data('renaming');
  307. if (!renaming) {
  308. this.fileActions.currentFile = $tr.find('td');
  309. var mime = this.fileActions.getCurrentMimeType();
  310. var type = this.fileActions.getCurrentType();
  311. var permissions = this.fileActions.getCurrentPermissions();
  312. var action = this.fileActions.getDefault(mime,type, permissions);
  313. if (action) {
  314. event.preventDefault();
  315. // also set on global object for legacy apps
  316. window.FileActions.currentFile = this.fileActions.currentFile;
  317. action(filename, {
  318. $file: $tr,
  319. fileList: this,
  320. fileActions: this.fileActions,
  321. dir: $tr.attr('data-path') || this.getCurrentDirectory()
  322. });
  323. }
  324. // deselect row
  325. $(event.target).closest('a').blur();
  326. }
  327. }
  328. },
  329. /**
  330. * Event handler for when clicking on a file's checkbox
  331. */
  332. _onClickFileCheckbox: function(e) {
  333. var $tr = $(e.target).closest('tr');
  334. this._selectFileEl($tr, !$tr.hasClass('selected'));
  335. this._lastChecked = $tr;
  336. this.updateSelectionSummary();
  337. },
  338. /**
  339. * Event handler for when selecting/deselecting all files
  340. */
  341. _onClickSelectAll: function(e) {
  342. var checked = $(e.target).prop('checked');
  343. this.$fileList.find('td.filename>.selectCheckBox').prop('checked', checked)
  344. .closest('tr').toggleClass('selected', checked);
  345. this._selectedFiles = {};
  346. this._selectionSummary.clear();
  347. if (checked) {
  348. for (var i = 0; i < this.files.length; i++) {
  349. var fileData = this.files[i];
  350. this._selectedFiles[fileData.id] = fileData;
  351. this._selectionSummary.add(fileData);
  352. }
  353. }
  354. this.updateSelectionSummary();
  355. },
  356. /**
  357. * Event handler for when clicking on "Download" for the selected files
  358. */
  359. _onClickDownloadSelected: function(event) {
  360. var files;
  361. var dir = this.getCurrentDirectory();
  362. if (this.isAllSelected()) {
  363. files = OC.basename(dir);
  364. dir = OC.dirname(dir) || '/';
  365. }
  366. else {
  367. files = _.pluck(this.getSelectedFiles(), 'name');
  368. }
  369. OC.redirect(this.getDownloadUrl(files, dir));
  370. return false;
  371. },
  372. /**
  373. * Event handler for when clicking on "Delete" for the selected files
  374. */
  375. _onClickDeleteSelected: function(event) {
  376. var files = null;
  377. if (!this.isAllSelected()) {
  378. files = _.pluck(this.getSelectedFiles(), 'name');
  379. }
  380. this.do_delete(files);
  381. event.preventDefault();
  382. return false;
  383. },
  384. /**
  385. * Event handler when clicking on a table header
  386. */
  387. _onClickHeader: function(e) {
  388. var $target = $(e.target);
  389. var sort;
  390. if (!$target.is('a')) {
  391. $target = $target.closest('a');
  392. }
  393. sort = $target.attr('data-sort');
  394. if (sort) {
  395. if (this._sort === sort) {
  396. this.setSort(sort, (this._sortDirection === 'desc')?'asc':'desc', true);
  397. }
  398. else {
  399. if ( sort === 'name' ) { //default sorting of name is opposite to size and mtime
  400. this.setSort(sort, 'asc', true);
  401. }
  402. else {
  403. this.setSort(sort, 'desc', true);
  404. }
  405. }
  406. }
  407. },
  408. /**
  409. * Event handler when clicking on a bread crumb
  410. */
  411. _onClickBreadCrumb: function(e) {
  412. var $el = $(e.target).closest('.crumb'),
  413. $targetDir = $el.data('dir');
  414. if ($targetDir !== undefined) {
  415. e.preventDefault();
  416. this.changeDirectory($targetDir);
  417. }
  418. this.updateSearch();
  419. },
  420. /**
  421. * Event handler for when scrolling the list container.
  422. * This appends/renders the next page of entries when reaching the bottom.
  423. */
  424. _onScroll: function(e) {
  425. if (this.$container.scrollTop() + this.$container.height() > this.$el.height() - 300) {
  426. this._nextPage(true);
  427. }
  428. },
  429. /**
  430. * Event handler when dropping on a breadcrumb
  431. */
  432. _onDropOnBreadCrumb: function( event, ui ) {
  433. var $target = $(event.target);
  434. if (!$target.is('.crumb')) {
  435. $target = $target.closest('.crumb');
  436. }
  437. var targetPath = $(event.target).data('dir');
  438. var dir = this.getCurrentDirectory();
  439. while (dir.substr(0,1) === '/') {//remove extra leading /'s
  440. dir = dir.substr(1);
  441. }
  442. dir = '/' + dir;
  443. if (dir.substr(-1,1) !== '/') {
  444. dir = dir + '/';
  445. }
  446. // do nothing if dragged on current dir
  447. if (targetPath === dir || targetPath + '/' === dir) {
  448. return;
  449. }
  450. var files = this.getSelectedFiles();
  451. if (files.length === 0) {
  452. // single one selected without checkbox?
  453. files = _.map(ui.helper.find('tr'), this.elementToFile);
  454. }
  455. this.move(_.pluck(files, 'name'), targetPath);
  456. },
  457. /**
  458. * Sets a new page title
  459. */
  460. setPageTitle: function(title){
  461. if (title) {
  462. title += ' - ';
  463. } else {
  464. title = '';
  465. }
  466. title += this.appName;
  467. // Sets the page title with the " - ownCloud" suffix as in templates
  468. window.document.title = title + ' - ' + oc_defaults.title;
  469. return true;
  470. },
  471. /**
  472. * Returns the tr element for a given file name
  473. * @param fileName file name
  474. */
  475. findFileEl: function(fileName){
  476. // use filterAttr to avoid escaping issues
  477. return this.$fileList.find('tr').filterAttr('data-file', fileName);
  478. },
  479. /**
  480. * Returns the file data from a given file element.
  481. * @param $el file tr element
  482. * @return file data
  483. */
  484. elementToFile: function($el){
  485. $el = $($el);
  486. return {
  487. id: parseInt($el.attr('data-id'), 10),
  488. name: $el.attr('data-file'),
  489. mimetype: $el.attr('data-mime'),
  490. type: $el.attr('data-type'),
  491. size: parseInt($el.attr('data-size'), 10),
  492. etag: $el.attr('data-etag'),
  493. permissions: parseInt($el.attr('data-permissions'), 10)
  494. };
  495. },
  496. /**
  497. * Appends the next page of files into the table
  498. * @param animate true to animate the new elements
  499. * @return array of DOM elements of the newly added files
  500. */
  501. _nextPage: function(animate) {
  502. var index = this.$fileList.children().length,
  503. count = this.pageSize(),
  504. hidden,
  505. tr,
  506. fileData,
  507. newTrs = [],
  508. isAllSelected = this.isAllSelected();
  509. if (index >= this.files.length) {
  510. return false;
  511. }
  512. while (count > 0 && index < this.files.length) {
  513. fileData = this.files[index];
  514. if (this._filter) {
  515. hidden = fileData.name.toLowerCase().indexOf(this._filter.toLowerCase()) === -1;
  516. } else {
  517. hidden = false;
  518. }
  519. tr = this._renderRow(fileData, {updateSummary: false, silent: true, hidden: hidden});
  520. this.$fileList.append(tr);
  521. if (isAllSelected || this._selectedFiles[fileData.id]) {
  522. tr.addClass('selected');
  523. tr.find('.selectCheckBox').prop('checked', true);
  524. }
  525. if (animate) {
  526. tr.addClass('appear transparent');
  527. }
  528. newTrs.push(tr);
  529. index++;
  530. count--;
  531. }
  532. // trigger event for newly added rows
  533. if (newTrs.length > 0) {
  534. this.$fileList.trigger($.Event('fileActionsReady', {fileList: this, $files: newTrs}));
  535. }
  536. if (animate) {
  537. // defer, for animation
  538. window.setTimeout(function() {
  539. for (var i = 0; i < newTrs.length; i++ ) {
  540. newTrs[i].removeClass('transparent');
  541. }
  542. }, 0);
  543. }
  544. return newTrs;
  545. },
  546. /**
  547. * Event handler for when file actions were updated.
  548. * This will refresh the file actions on the list.
  549. */
  550. _onFileActionsUpdated: function() {
  551. var self = this;
  552. var $files = this.$fileList.find('tr');
  553. if (!$files.length) {
  554. return;
  555. }
  556. $files.each(function() {
  557. self.fileActions.display($(this).find('td.filename'), false, self);
  558. });
  559. this.$fileList.trigger($.Event('fileActionsReady', {fileList: this, $files: $files}));
  560. },
  561. /**
  562. * Sets the files to be displayed in the list.
  563. * This operation will re-render the list and update the summary.
  564. * @param filesArray array of file data (map)
  565. */
  566. setFiles: function(filesArray) {
  567. // detach to make adding multiple rows faster
  568. this.files = filesArray;
  569. this.$fileList.empty();
  570. // clear "Select all" checkbox
  571. this.$el.find('.select-all').prop('checked', false);
  572. this.isEmpty = this.files.length === 0;
  573. this._nextPage();
  574. this.updateEmptyContent();
  575. this.fileSummary.calculate(filesArray);
  576. this._selectedFiles = {};
  577. this._selectionSummary.clear();
  578. this.updateSelectionSummary();
  579. $(window).scrollTop(0);
  580. this.$fileList.trigger(jQuery.Event("updated"));
  581. },
  582. /**
  583. * Creates a new table row element using the given file data.
  584. * @param {OCA.Files.FileInfo} fileData file info attributes
  585. * @param options map of attributes
  586. * @return new tr element (not appended to the table)
  587. */
  588. _createRow: function(fileData, options) {
  589. var td, simpleSize, basename, extension, sizeColor,
  590. icon = OC.Util.replaceSVGIcon(fileData.icon),
  591. name = fileData.name,
  592. type = fileData.type || 'file',
  593. mtime = parseInt(fileData.mtime, 10),
  594. mime = fileData.mimetype,
  595. path = fileData.path,
  596. linkUrl;
  597. options = options || {};
  598. if (isNaN(mtime)) {
  599. mtime = new Date().getTime()
  600. }
  601. if (type === 'dir') {
  602. mime = mime || 'httpd/unix-directory';
  603. }
  604. //containing tr
  605. var tr = $('<tr></tr>').attr({
  606. "data-id" : fileData.id,
  607. "data-type": type,
  608. "data-size": fileData.size,
  609. "data-file": name,
  610. "data-mime": mime,
  611. "data-mtime": mtime,
  612. "data-etag": fileData.etag,
  613. "data-permissions": fileData.permissions || this.getDirectoryPermissions()
  614. });
  615. if (fileData.mountType) {
  616. tr.attr('data-mounttype', fileData.mountType);
  617. }
  618. if (!_.isUndefined(path)) {
  619. tr.attr('data-path', path);
  620. }
  621. else {
  622. path = this.getCurrentDirectory();
  623. }
  624. if (type === 'dir') {
  625. // use default folder icon
  626. icon = icon || OC.imagePath('core', 'filetypes/folder');
  627. }
  628. else {
  629. icon = icon || OC.imagePath('core', 'filetypes/file');
  630. }
  631. // filename td
  632. td = $('<td class="filename"></td>');
  633. // linkUrl
  634. if (type === 'dir') {
  635. linkUrl = this.linkTo(path + '/' + name);
  636. }
  637. else {
  638. linkUrl = this.getDownloadUrl(name, path);
  639. }
  640. if (this._allowSelection) {
  641. td.append(
  642. '<input id="select-' + this.id + '-' + fileData.id +
  643. '" type="checkbox" class="selectCheckBox"/><label for="select-' + this.id + '-' + fileData.id + '">' +
  644. '<div class="thumbnail" style="background-image:url(' + icon + '); background-size: 32px;"></div>' +
  645. '<span class="hidden-visually">' + t('files', 'Select') + '</span>' +
  646. '</label>'
  647. );
  648. } else {
  649. td.append('<div class="thumbnail" style="background-image:url(' + icon + '); background-size: 32px;"></div>');
  650. }
  651. var linkElem = $('<a></a>').attr({
  652. "class": "name",
  653. "href": linkUrl
  654. });
  655. // from here work on the display name
  656. name = fileData.displayName || name;
  657. // split extension from filename for non dirs
  658. if (type !== 'dir' && name.indexOf('.') !== -1) {
  659. basename = name.substr(0, name.lastIndexOf('.'));
  660. extension = name.substr(name.lastIndexOf('.'));
  661. } else {
  662. basename = name;
  663. extension = false;
  664. }
  665. var nameSpan=$('<span></span>').addClass('nametext');
  666. var innernameSpan = $('<span></span>').addClass('innernametext').text(basename);
  667. nameSpan.append(innernameSpan);
  668. linkElem.append(nameSpan);
  669. if (extension) {
  670. nameSpan.append($('<span></span>').addClass('extension').text(extension));
  671. }
  672. if (fileData.extraData) {
  673. if (fileData.extraData.charAt(0) === '/') {
  674. fileData.extraData = fileData.extraData.substr(1);
  675. }
  676. nameSpan.addClass('extra-data').attr('title', fileData.extraData);
  677. }
  678. // dirs can show the number of uploaded files
  679. if (type === 'dir') {
  680. linkElem.append($('<span></span>').attr({
  681. 'class': 'uploadtext',
  682. 'currentUploads': 0
  683. }));
  684. }
  685. td.append(linkElem);
  686. tr.append(td);
  687. // size column
  688. if (typeof(fileData.size) !== 'undefined' && fileData.size >= 0) {
  689. simpleSize = humanFileSize(parseInt(fileData.size, 10), true);
  690. sizeColor = Math.round(160-Math.pow((fileData.size/(1024*1024)),2));
  691. } else {
  692. simpleSize = t('files', 'Pending');
  693. }
  694. td = $('<td></td>').attr({
  695. "class": "filesize",
  696. "style": 'color:rgb(' + sizeColor + ',' + sizeColor + ',' + sizeColor + ')'
  697. }).text(simpleSize);
  698. tr.append(td);
  699. // date column (1000 milliseconds to seconds, 60 seconds, 60 minutes, 24 hours)
  700. // difference in days multiplied by 5 - brightest shade for files older than 32 days (160/5)
  701. var modifiedColor = Math.round(((new Date()).getTime() - mtime )/1000/60/60/24*5 );
  702. // ensure that the brightest color is still readable
  703. if (modifiedColor >= '160') {
  704. modifiedColor = 160;
  705. }
  706. var formatted;
  707. var text;
  708. if (mtime > 0) {
  709. formatted = formatDate(mtime);
  710. text = OC.Util.relativeModifiedDate(mtime);
  711. } else {
  712. formatted = t('files', 'Unable to determine date');
  713. text = '?';
  714. }
  715. td = $('<td></td>').attr({ "class": "date" });
  716. td.append($('<span></span>').attr({
  717. "class": "modified",
  718. "title": formatted,
  719. "style": 'color:rgb('+modifiedColor+','+modifiedColor+','+modifiedColor+')'
  720. }).text(text));
  721. tr.find('.filesize').text(simpleSize);
  722. tr.append(td);
  723. return tr;
  724. },
  725. /**
  726. * Adds an entry to the files array and also into the DOM
  727. * in a sorted manner.
  728. *
  729. * @param {OCA.Files.FileInfo} fileData map of file attributes
  730. * @param {Object} [options] map of attributes
  731. * @param {boolean} [options.updateSummary] true to update the summary
  732. * after adding (default), false otherwise. Defaults to true.
  733. * @param {boolean} [options.silent] true to prevent firing events like "fileActionsReady",
  734. * defaults to false.
  735. * @param {boolean} [options.animate] true to animate the thumbnail image after load
  736. * defaults to true.
  737. * @return new tr element (not appended to the table)
  738. */
  739. add: function(fileData, options) {
  740. var index = -1;
  741. var $tr;
  742. var $rows;
  743. var $insertionPoint;
  744. options = _.extend({animate: true}, options || {});
  745. // there are three situations to cover:
  746. // 1) insertion point is visible on the current page
  747. // 2) insertion point is on a not visible page (visible after scrolling)
  748. // 3) insertion point is at the end of the list
  749. $rows = this.$fileList.children();
  750. index = this._findInsertionIndex(fileData);
  751. if (index > this.files.length) {
  752. index = this.files.length;
  753. }
  754. else {
  755. $insertionPoint = $rows.eq(index);
  756. }
  757. // is the insertion point visible ?
  758. if ($insertionPoint.length) {
  759. // only render if it will really be inserted
  760. $tr = this._renderRow(fileData, options);
  761. $insertionPoint.before($tr);
  762. }
  763. else {
  764. // if insertion point is after the last visible
  765. // entry, append
  766. if (index === $rows.length) {
  767. $tr = this._renderRow(fileData, options);
  768. this.$fileList.append($tr);
  769. }
  770. }
  771. this.isEmpty = false;
  772. this.files.splice(index, 0, fileData);
  773. if ($tr && options.animate) {
  774. $tr.addClass('appear transparent');
  775. window.setTimeout(function() {
  776. $tr.removeClass('transparent');
  777. });
  778. }
  779. if (options.scrollTo) {
  780. this.scrollTo(fileData.name);
  781. }
  782. // defaults to true if not defined
  783. if (typeof(options.updateSummary) === 'undefined' || !!options.updateSummary) {
  784. this.fileSummary.add(fileData, true);
  785. this.updateEmptyContent();
  786. }
  787. return $tr;
  788. },
  789. /**
  790. * Creates a new row element based on the given attributes
  791. * and returns it.
  792. *
  793. * @param {OCA.Files.FileInfo} fileData map of file attributes
  794. * @param {Object} [options] map of attributes
  795. * @param {int} [options.index] index at which to insert the element
  796. * @param {boolean} [options.updateSummary] true to update the summary
  797. * after adding (default), false otherwise. Defaults to true.
  798. * @param {boolean} [options.animate] true to animate the thumbnail image after load
  799. * defaults to true.
  800. * @return new tr element (not appended to the table)
  801. */
  802. _renderRow: function(fileData, options) {
  803. options = options || {};
  804. var type = fileData.type || 'file',
  805. mime = fileData.mimetype,
  806. path = fileData.path || this.getCurrentDirectory(),
  807. permissions = parseInt(fileData.permissions, 10) || 0;
  808. if (fileData.isShareMountPoint) {
  809. permissions = permissions | OC.PERMISSION_UPDATE;
  810. }
  811. if (type === 'dir') {
  812. mime = mime || 'httpd/unix-directory';
  813. }
  814. var tr = this._createRow(
  815. fileData,
  816. options
  817. );
  818. var filenameTd = tr.find('td.filename');
  819. // TODO: move dragging to FileActions ?
  820. // enable drag only for deletable files
  821. if (this._dragOptions && permissions & OC.PERMISSION_DELETE) {
  822. filenameTd.draggable(this._dragOptions);
  823. }
  824. // allow dropping on folders
  825. if (this._folderDropOptions && fileData.type === 'dir') {
  826. filenameTd.droppable(this._folderDropOptions);
  827. }
  828. if (options.hidden) {
  829. tr.addClass('hidden');
  830. }
  831. // display actions
  832. this.fileActions.display(filenameTd, !options.silent, this);
  833. if (fileData.isPreviewAvailable) {
  834. var iconDiv = filenameTd.find('.thumbnail');
  835. // lazy load / newly inserted td ?
  836. if (options.animate) {
  837. this.lazyLoadPreview({
  838. path: path + '/' + fileData.name,
  839. mime: mime,
  840. etag: fileData.etag,
  841. callback: function(url) {
  842. iconDiv.css('background-image', 'url(' + url + ')');
  843. }
  844. });
  845. }
  846. else {
  847. // set the preview URL directly
  848. var urlSpec = {
  849. file: path + '/' + fileData.name,
  850. c: fileData.etag
  851. };
  852. var previewUrl = this.generatePreviewUrl(urlSpec);
  853. previewUrl = previewUrl.replace('(', '%28').replace(')', '%29');
  854. iconDiv.css('background-image', 'url(' + previewUrl + ')');
  855. }
  856. }
  857. return tr;
  858. },
  859. /**
  860. * Returns the current directory
  861. * @method getCurrentDirectory
  862. * @return current directory
  863. */
  864. getCurrentDirectory: function(){
  865. return this._currentDirectory || this.$el.find('#dir').val() || '/';
  866. },
  867. /**
  868. * Returns the directory permissions
  869. * @return permission value as integer
  870. */
  871. getDirectoryPermissions: function() {
  872. return parseInt(this.$el.find('#permissions').val(), 10);
  873. },
  874. /**
  875. * @brief Changes the current directory and reload the file list.
  876. * @param targetDir target directory (non URL encoded)
  877. * @param changeUrl false if the URL must not be changed (defaults to true)
  878. * @param {boolean} force set to true to force changing directory
  879. */
  880. changeDirectory: function(targetDir, changeUrl, force) {
  881. var self = this;
  882. var currentDir = this.getCurrentDirectory();
  883. targetDir = targetDir || '/';
  884. if (!force && currentDir === targetDir) {
  885. return;
  886. }
  887. this._setCurrentDir(targetDir, changeUrl);
  888. this.reload().then(function(success){
  889. if (!success) {
  890. self.changeDirectory(currentDir, true);
  891. }
  892. });
  893. },
  894. linkTo: function(dir) {
  895. return OC.linkTo('files', 'index.php')+"?dir="+ encodeURIComponent(dir).replace(/%2F/g, '/');
  896. },
  897. /**
  898. * Sets the current directory name and updates the breadcrumb.
  899. * @param targetDir directory to display
  900. * @param changeUrl true to also update the URL, false otherwise (default)
  901. */
  902. _setCurrentDir: function(targetDir, changeUrl) {
  903. var previousDir = this.getCurrentDirectory(),
  904. baseDir = OC.basename(targetDir);
  905. if (baseDir !== '') {
  906. this.setPageTitle(baseDir);
  907. }
  908. else {
  909. this.setPageTitle();
  910. }
  911. this._currentDirectory = targetDir;
  912. // legacy stuff
  913. this.$el.find('#dir').val(targetDir);
  914. if (changeUrl !== false) {
  915. this.$el.trigger(jQuery.Event('changeDirectory', {
  916. dir: targetDir,
  917. previousDir: previousDir
  918. }));
  919. }
  920. this.breadcrumb.setDirectory(this.getCurrentDirectory());
  921. },
  922. /**
  923. * Sets the current sorting and refreshes the list
  924. *
  925. * @param sort sort attribute name
  926. * @param direction sort direction, one of "asc" or "desc"
  927. * @param update true to update the list, false otherwise (default)
  928. */
  929. setSort: function(sort, direction, update) {
  930. var comparator = FileList.Comparators[sort] || FileList.Comparators.name;
  931. this._sort = sort;
  932. this._sortDirection = (direction === 'desc')?'desc':'asc';
  933. this._sortComparator = comparator;
  934. if (direction === 'desc') {
  935. this._sortComparator = function(fileInfo1, fileInfo2) {
  936. return -comparator(fileInfo1, fileInfo2);
  937. };
  938. }
  939. this.$el.find('thead th .sort-indicator')
  940. .removeClass(this.SORT_INDICATOR_ASC_CLASS)
  941. .removeClass(this.SORT_INDICATOR_DESC_CLASS)
  942. .toggleClass('hidden', true)
  943. .addClass(this.SORT_INDICATOR_DESC_CLASS);
  944. this.$el.find('thead th.column-' + sort + ' .sort-indicator')
  945. .removeClass(this.SORT_INDICATOR_ASC_CLASS)
  946. .removeClass(this.SORT_INDICATOR_DESC_CLASS)
  947. .toggleClass('hidden', false)
  948. .addClass(direction === 'desc' ? this.SORT_INDICATOR_DESC_CLASS : this.SORT_INDICATOR_ASC_CLASS);
  949. if (update) {
  950. if (this._clientSideSort) {
  951. this.files.sort(this._sortComparator);
  952. this.setFiles(this.files);
  953. }
  954. else {
  955. this.reload();
  956. }
  957. }
  958. },
  959. /**
  960. * Reloads the file list using ajax call
  961. *
  962. * @return ajax call object
  963. */
  964. reload: function() {
  965. this._selectedFiles = {};
  966. this._selectionSummary.clear();
  967. this.$el.find('.select-all').prop('checked', false);
  968. this.showMask();
  969. if (this._reloadCall) {
  970. this._reloadCall.abort();
  971. }
  972. this._reloadCall = $.ajax({
  973. url: this.getAjaxUrl('list'),
  974. data: {
  975. dir : this.getCurrentDirectory(),
  976. sort: this._sort,
  977. sortdirection: this._sortDirection
  978. }
  979. });
  980. var callBack = this.reloadCallback.bind(this);
  981. return this._reloadCall.then(callBack, callBack);
  982. },
  983. reloadCallback: function(result) {
  984. delete this._reloadCall;
  985. this.hideMask();
  986. if (!result || result.status === 'error') {
  987. // if the error is not related to folder we're trying to load, reload the page to handle logout etc
  988. if (result.data.error === 'authentication_error' ||
  989. result.data.error === 'token_expired' ||
  990. result.data.error === 'application_not_enabled'
  991. ) {
  992. OC.redirect(OC.generateUrl('apps/files'));
  993. }
  994. OC.Notification.show(result.data.message);
  995. return false;
  996. }
  997. if (result.status === 404) {
  998. // go back home
  999. this.changeDirectory('/');
  1000. return false;
  1001. }
  1002. // aborted ?
  1003. if (result.status === 0){
  1004. return true;
  1005. }
  1006. // TODO: should rather return upload file size through
  1007. // the files list ajax call
  1008. this.updateStorageStatistics(true);
  1009. if (result.data.permissions) {
  1010. this.setDirectoryPermissions(result.data.permissions);
  1011. }
  1012. this.setFiles(result.data.files);
  1013. return true;
  1014. },
  1015. updateStorageStatistics: function(force) {
  1016. OCA.Files.Files.updateStorageStatistics(this.getCurrentDirectory(), force);
  1017. },
  1018. getAjaxUrl: function(action, params) {
  1019. return OCA.Files.Files.getAjaxUrl(action, params);
  1020. },
  1021. getDownloadUrl: function(files, dir) {
  1022. return OCA.Files.Files.getDownloadUrl(files, dir || this.getCurrentDirectory());
  1023. },
  1024. /**
  1025. * Generates a preview URL based on the URL space.
  1026. * @param urlSpec attributes for the URL
  1027. * @param {int} urlSpec.x width
  1028. * @param {int} urlSpec.y height
  1029. * @param {String} urlSpec.file path to the file
  1030. * @return preview URL
  1031. */
  1032. generatePreviewUrl: function(urlSpec) {
  1033. urlSpec = urlSpec || {};
  1034. if (!urlSpec.x) {
  1035. urlSpec.x = this.$table.data('preview-x') || 36;
  1036. }
  1037. if (!urlSpec.y) {
  1038. urlSpec.y = this.$table.data('preview-y') || 36;
  1039. }
  1040. urlSpec.y *= window.devicePixelRatio;
  1041. urlSpec.x *= window.devicePixelRatio;
  1042. urlSpec.forceIcon = 0;
  1043. return OC.generateUrl('/core/preview.png?') + $.param(urlSpec);
  1044. },
  1045. /**
  1046. * Lazy load a file's preview.
  1047. *
  1048. * @param path path of the file
  1049. * @param mime mime type
  1050. * @param callback callback function to call when the image was loaded
  1051. * @param etag file etag (for caching)
  1052. */
  1053. lazyLoadPreview : function(options) {
  1054. var self = this;
  1055. var path = options.path;
  1056. var mime = options.mime;
  1057. var ready = options.callback;
  1058. var etag = options.etag;
  1059. // get mime icon url
  1060. OCA.Files.Files.getMimeIcon(mime, function(iconURL) {
  1061. var previewURL,
  1062. urlSpec = {};
  1063. ready(iconURL); // set mimeicon URL
  1064. urlSpec.file = OCA.Files.Files.fixPath(path);
  1065. if (etag){
  1066. // use etag as cache buster
  1067. urlSpec.c = etag;
  1068. }
  1069. else {
  1070. console.warn('OCA.Files.FileList.lazyLoadPreview(): missing etag argument');
  1071. }
  1072. previewURL = self.generatePreviewUrl(urlSpec);
  1073. previewURL = previewURL.replace('(', '%28');
  1074. previewURL = previewURL.replace(')', '%29');
  1075. // preload image to prevent delay
  1076. // this will make the browser cache the image
  1077. var img = new Image();
  1078. img.onload = function(){
  1079. // if loading the preview image failed (no preview for the mimetype) then img.width will < 5
  1080. if (img.width > 5) {
  1081. ready(previewURL);
  1082. }
  1083. };
  1084. img.src = previewURL;
  1085. });
  1086. },
  1087. setDirectoryPermissions: function(permissions) {
  1088. var isCreatable = (permissions & OC.PERMISSION_CREATE) !== 0;
  1089. this.$el.find('#permissions').val(permissions);
  1090. this.$el.find('.creatable').toggleClass('hidden', !isCreatable);
  1091. this.$el.find('.notCreatable').toggleClass('hidden', isCreatable);
  1092. },
  1093. /**
  1094. * Shows/hides action buttons
  1095. *
  1096. * @param show true for enabling, false for disabling
  1097. */
  1098. showActions: function(show){
  1099. this.$el.find('.actions,#file_action_panel').toggleClass('hidden', !show);
  1100. if (show){
  1101. // make sure to display according to permissions
  1102. var permissions = this.getDirectoryPermissions();
  1103. var isCreatable = (permissions & OC.PERMISSION_CREATE) !== 0;
  1104. this.$el.find('.creatable').toggleClass('hidden', !isCreatable);
  1105. this.$el.find('.notCreatable').toggleClass('hidden', isCreatable);
  1106. // remove old style breadcrumbs (some apps might create them)
  1107. this.$el.find('#controls .crumb').remove();
  1108. // refresh breadcrumbs in case it was replaced by an app
  1109. this.breadcrumb.render();
  1110. }
  1111. else{
  1112. this.$el.find('.creatable, .notCreatable').addClass('hidden');
  1113. }
  1114. },
  1115. /**
  1116. * Enables/disables viewer mode.
  1117. * In viewer mode, apps can embed themselves under the controls bar.
  1118. * In viewer mode, the actions of the file list will be hidden.
  1119. * @param show true for enabling, false for disabling
  1120. */
  1121. setViewerMode: function(show){
  1122. this.showActions(!show);
  1123. this.$el.find('#filestable').toggleClass('hidden', show);
  1124. this.$el.trigger(new $.Event('changeViewerMode', {viewerModeEnabled: show}));
  1125. },
  1126. /**
  1127. * Removes a file entry from the list
  1128. * @param name name of the file to remove
  1129. * @param {Object} [options] map of attributes
  1130. * @param {boolean} [options.updateSummary] true to update the summary
  1131. * after removing, false otherwise. Defaults to true.
  1132. * @return deleted element
  1133. */
  1134. remove: function(name, options){
  1135. options = options || {};
  1136. var fileEl = this.findFileEl(name);
  1137. var index = fileEl.index();
  1138. if (!fileEl.length) {
  1139. return null;
  1140. }
  1141. if (this._selectedFiles[fileEl.data('id')]) {
  1142. // remove from selection first
  1143. this._selectFileEl(fileEl, false);
  1144. this.updateSelectionSummary();
  1145. }
  1146. if (this._dragOptions && (fileEl.data('permissions') & OC.PERMISSION_DELETE)) {
  1147. // file is only draggable when delete permissions are set
  1148. fileEl.find('td.filename').draggable('destroy');
  1149. }
  1150. this.files.splice(index, 1);
  1151. fileEl.remove();
  1152. // TODO: improve performance on batch update
  1153. this.isEmpty = !this.files.length;
  1154. if (typeof(options.updateSummary) === 'undefined' || !!options.updateSummary) {
  1155. this.updateEmptyContent();
  1156. this.fileSummary.remove({type: fileEl.attr('data-type'), size: fileEl.attr('data-size')}, true);
  1157. }
  1158. var lastIndex = this.$fileList.children().length;
  1159. // if there are less elements visible than one page
  1160. // but there are still pending elements in the array,
  1161. // then directly append the next page
  1162. if (lastIndex < this.files.length && lastIndex < this.pageSize()) {
  1163. this._nextPage(true);
  1164. }
  1165. return fileEl;
  1166. },
  1167. /**
  1168. * Finds the index of the row before which the given
  1169. * fileData should be inserted, considering the current
  1170. * sorting
  1171. *
  1172. * @param {OCA.Files.FileInfo} fileData file info
  1173. */
  1174. _findInsertionIndex: function(fileData) {
  1175. var index = 0;
  1176. while (index < this.files.length && this._sortComparator(fileData, this.files[index]) > 0) {
  1177. index++;
  1178. }
  1179. return index;
  1180. },
  1181. /**
  1182. * Moves a file to a given target folder.
  1183. *
  1184. * @param fileNames array of file names to move
  1185. * @param targetPath absolute target path
  1186. */
  1187. move: function(fileNames, targetPath) {
  1188. var self = this;
  1189. var dir = this.getCurrentDirectory();
  1190. var target = OC.basename(targetPath);
  1191. if (!_.isArray(fileNames)) {
  1192. fileNames = [fileNames];
  1193. }
  1194. _.each(fileNames, function(fileName) {
  1195. var $tr = self.findFileEl(fileName);
  1196. var $thumbEl = $tr.find('.thumbnail');
  1197. var oldBackgroundImage = $thumbEl.css('background-image');
  1198. $thumbEl.css('background-image', 'url('+ OC.imagePath('core', 'loading.gif') + ')');
  1199. // TODO: improve performance by sending all file names in a single call
  1200. $.post(
  1201. OC.filePath('files', 'ajax', 'move.php'),
  1202. {
  1203. dir: dir,
  1204. file: fileName,
  1205. target: targetPath
  1206. },
  1207. function(result) {
  1208. if (result) {
  1209. if (result.status === 'success') {
  1210. // if still viewing the same directory
  1211. if (self.getCurrentDirectory() === dir) {
  1212. // recalculate folder size
  1213. var oldFile = self.findFileEl(target);
  1214. var newFile = self.findFileEl(fileName);
  1215. var oldSize = oldFile.data('size');
  1216. var newSize = oldSize + newFile.data('size');
  1217. oldFile.data('size', newSize);
  1218. oldFile.find('td.filesize').text(OC.Util.humanFileSize(newSize));
  1219. // TODO: also update entry in FileList.files
  1220. self.remove(fileName);
  1221. }
  1222. } else {
  1223. OC.Notification.hide();
  1224. if (result.status === 'error' && result.data.message) {
  1225. OC.Notification.show(result.data.message);
  1226. }
  1227. else {
  1228. OC.Notification.show(t('files', 'Error moving file.'));
  1229. }
  1230. // hide notification after 10 sec
  1231. setTimeout(function() {
  1232. OC.Notification.hide();
  1233. }, 10000);
  1234. }
  1235. } else {
  1236. OC.dialogs.alert(t('files', 'Error moving file'), t('files', 'Error'));
  1237. }
  1238. $thumbEl.css('background-image', oldBackgroundImage);
  1239. }
  1240. );
  1241. });
  1242. },
  1243. /**
  1244. * Triggers file rename input field for the given file name.
  1245. * If the user enters a new name, the file will be renamed.
  1246. *
  1247. * @param oldname file name of the file to rename
  1248. */
  1249. rename: function(oldname) {
  1250. var self = this;
  1251. var tr, td, input, form;
  1252. tr = this.findFileEl(oldname);
  1253. var oldFileInfo = this.files[tr.index()];
  1254. tr.data('renaming',true);
  1255. td = tr.children('td.filename');
  1256. input = $('<input type="text" class="filename"/>').val(oldname);
  1257. form = $('<form></form>');
  1258. form.append(input);
  1259. td.children('a.name').hide();
  1260. td.append(form);
  1261. input.focus();
  1262. //preselect input
  1263. var len = input.val().lastIndexOf('.');
  1264. if ( len === -1 ||
  1265. tr.data('type') === 'dir' ) {
  1266. len = input.val().length;
  1267. }
  1268. input.selectRange(0, len);
  1269. var checkInput = function () {
  1270. var filename = input.val();
  1271. if (filename !== oldname) {
  1272. // Files.isFileNameValid(filename) throws an exception itself
  1273. OCA.Files.Files.isFileNameValid(filename);
  1274. if (self.inList(filename)) {
  1275. throw t('files', '{new_name} already exists', {new_name: filename});
  1276. }
  1277. }
  1278. return true;
  1279. };
  1280. function restore() {
  1281. input.tipsy('hide');
  1282. tr.data('renaming',false);
  1283. form.remove();
  1284. td.children('a.name').show();
  1285. }
  1286. form.submit(function(event) {
  1287. event.stopPropagation();
  1288. event.preventDefault();
  1289. if (input.hasClass('error')) {
  1290. return;
  1291. }
  1292. try {
  1293. var newName = input.val();
  1294. var $thumbEl = tr.find('.thumbnail');
  1295. input.tipsy('hide');
  1296. form.remove();
  1297. if (newName !== oldname) {
  1298. checkInput();
  1299. // mark as loading (temp element)
  1300. $thumbEl.css('background-image', 'url('+ OC.imagePath('core', 'loading.gif') + ')');
  1301. tr.attr('data-file', newName);
  1302. var basename = newName;
  1303. if (newName.indexOf('.') > 0 && tr.data('type') !== 'dir') {
  1304. basename = newName.substr(0, newName.lastIndexOf('.'));
  1305. }
  1306. td.find('a.name span.nametext').text(basename);
  1307. td.children('a.name').show();
  1308. tr.find('.fileactions, .action').addClass('hidden');
  1309. $.ajax({
  1310. url: OC.filePath('files','ajax','rename.php'),
  1311. data: {
  1312. dir : tr.attr('data-path') || self.getCurrentDirectory(),
  1313. newname: newName,
  1314. file: oldname
  1315. },
  1316. success: function(result) {
  1317. var fileInfo;
  1318. if (!result || result.status === 'error') {
  1319. OC.dialogs.alert(result.data.message, t('files', 'Could not rename file'));
  1320. fileInfo = oldFileInfo;
  1321. if (result.data.code === 'sourcenotfound') {
  1322. self.remove(result.data.newname, {updateSummary: true});
  1323. return;
  1324. }
  1325. }
  1326. else {
  1327. fileInfo = result.data;
  1328. }
  1329. // reinsert row
  1330. self.files.splice(tr.index(), 1);
  1331. tr.remove();
  1332. tr = self.add(fileInfo, {updateSummary: false, silent: true});
  1333. self.$fileList.trigger($.Event('fileActionsReady', {fileList: self, $files: $(tr)}));
  1334. }
  1335. });
  1336. } else {
  1337. // add back the old file info when cancelled
  1338. self.files.splice(tr.index(), 1);
  1339. tr.remove();
  1340. tr = self.add(oldFileInfo, {updateSummary: false, silent: true});
  1341. self.$fileList.trigger($.Event('fileActionsReady', {fileList: self, $files: $(tr)}));
  1342. }
  1343. } catch (error) {
  1344. input.attr('title', error);
  1345. input.tipsy({gravity: 'w', trigger: 'manual'});
  1346. input.tipsy('show');
  1347. input.addClass('error');
  1348. }
  1349. return false;
  1350. });
  1351. input.keyup(function(event) {
  1352. // verify filename on typing
  1353. try {
  1354. checkInput();
  1355. input.tipsy('hide');
  1356. input.removeClass('error');
  1357. } catch (error) {
  1358. input.attr('title', error);
  1359. input.tipsy({gravity: 'w', trigger: 'manual'});
  1360. input.tipsy('show');
  1361. input.addClass('error');
  1362. }
  1363. if (event.keyCode === 27) {
  1364. restore();
  1365. }
  1366. });
  1367. input.click(function(event) {
  1368. event.stopPropagation();
  1369. event.preventDefault();
  1370. });
  1371. input.blur(function() {
  1372. form.trigger('submit');
  1373. });
  1374. },
  1375. inList:function(file) {
  1376. return this.findFileEl(file).length;
  1377. },
  1378. /**
  1379. * Delete the given files from the given dir
  1380. * @param files file names list (without path)
  1381. * @param dir directory in which to delete the files, defaults to the current
  1382. * directory
  1383. */
  1384. do_delete:function(files, dir) {
  1385. var self = this;
  1386. var params;
  1387. if (files && files.substr) {
  1388. files=[files];
  1389. }
  1390. if (files) {
  1391. for (var i=0; i<files.length; i++) {
  1392. var deleteAction = this.findFileEl(files[i]).children("td.date").children(".action.delete");
  1393. deleteAction.removeClass('icon-delete').addClass('icon-loading-small');
  1394. }
  1395. }
  1396. // Finish any existing actions
  1397. if (this.lastAction) {
  1398. this.lastAction();
  1399. }
  1400. params = {
  1401. dir: dir || this.getCurrentDirectory()
  1402. };
  1403. if (files) {
  1404. params.files = JSON.stringify(files);
  1405. }
  1406. else {
  1407. // no files passed, delete all in current dir
  1408. params.allfiles = true;
  1409. // show spinner for all files
  1410. this.$fileList.find('tr>td.date .action.delete').removeClass('icon-delete').addClass('icon-loading-small');
  1411. }
  1412. $.post(OC.filePath('files', 'ajax', 'delete.php'),
  1413. params,
  1414. function(result) {
  1415. if (result.status === 'success') {
  1416. if (params.allfiles) {
  1417. self.setFiles([]);
  1418. }
  1419. else {
  1420. $.each(files,function(index,file) {
  1421. var fileEl = self.remove(file, {updateSummary: false});
  1422. // FIXME: not sure why we need this after the
  1423. // element isn't even in the DOM any more
  1424. fileEl.find('.selectCheckBox').prop('checked', false);
  1425. fileEl.removeClass('selected');
  1426. self.fileSummary.remove({type: fileEl.attr('data-type'), size: fileEl.attr('data-size')});
  1427. });
  1428. }
  1429. // TODO: this info should be returned by the ajax call!
  1430. self.updateEmptyContent();
  1431. self.fileSummary.update();
  1432. self.updateSelectionSummary();
  1433. self.updateStorageStatistics();
  1434. } else {
  1435. if (result.status === 'error' && result.data.message) {
  1436. OC.Notification.show(result.data.message);
  1437. }
  1438. else {
  1439. OC.Notification.show(t('files', 'Error deleting file.'));
  1440. }
  1441. // hide notification after 10 sec
  1442. setTimeout(function() {
  1443. OC.Notification.hide();
  1444. }, 10000);
  1445. if (params.allfiles) {
  1446. // reload the page as we don't know what files were deleted
  1447. // and which ones remain
  1448. self.reload();
  1449. }
  1450. else {
  1451. $.each(files,function(index,file) {
  1452. var deleteAction = self.findFileEl(file).find('.action.delete');
  1453. deleteAction.removeClass('icon-loading-small').addClass('icon-delete');
  1454. });
  1455. }
  1456. }
  1457. });
  1458. },
  1459. /**
  1460. * Creates the file summary section
  1461. */
  1462. _createSummary: function() {
  1463. var $tr = $('<tr class="summary"></tr>');
  1464. this.$el.find('tfoot').append($tr);
  1465. return new OCA.Files.FileSummary($tr);
  1466. },
  1467. updateEmptyContent: function() {
  1468. var permissions = this.getDirectoryPermissions();
  1469. var isCreatable = (permissions & OC.PERMISSION_CREATE) !== 0;
  1470. this.$el.find('#emptycontent').toggleClass('hidden', !isCreatable || !this.isEmpty);
  1471. this.$el.find('#filestable thead th').toggleClass('hidden', this.isEmpty);
  1472. },
  1473. /**
  1474. * Shows the loading mask.
  1475. *
  1476. * @see OCA.Files.FileList#hideMask
  1477. */
  1478. showMask: function() {
  1479. // in case one was shown before
  1480. var $mask = this.$el.find('.mask');
  1481. if ($mask.exists()) {
  1482. return;
  1483. }
  1484. this.$table.addClass('hidden');
  1485. $mask = $('<div class="mask transparent"></div>');
  1486. $mask.css('background-image', 'url('+ OC.imagePath('core', 'loading.gif') + ')');
  1487. $mask.css('background-repeat', 'no-repeat');
  1488. this.$el.append($mask);
  1489. $mask.removeClass('transparent');
  1490. },
  1491. /**
  1492. * Hide the loading mask.
  1493. * @see OCA.Files.FileList#showMask
  1494. */
  1495. hideMask: function() {
  1496. this.$el.find('.mask').remove();
  1497. this.$table.removeClass('hidden');
  1498. },
  1499. scrollTo:function(file) {
  1500. if (!_.isArray(file)) {
  1501. file = [file];
  1502. }
  1503. this.highlightFiles(file, function($tr) {
  1504. $tr.addClass('searchresult');
  1505. $tr.one('hover', function() {
  1506. $tr.removeClass('searchresult');
  1507. });
  1508. });
  1509. },
  1510. /**
  1511. * @deprecated use setFilter(filter)
  1512. */
  1513. filter:function(query) {
  1514. this.setFilter('');
  1515. },
  1516. /**
  1517. * @deprecated use setFilter('')
  1518. */
  1519. unfilter:function() {
  1520. this.setFilter('');
  1521. },
  1522. /**
  1523. * hide files matching the given filter
  1524. * @param filter
  1525. */
  1526. setFilter:function(filter) {
  1527. this._filter = filter;
  1528. this.fileSummary.setFilter(filter, this.files);
  1529. if (!this.$el.find('.mask').exists()) {
  1530. this.hideIrrelevantUIWhenNoFilesMatch();
  1531. }
  1532. var that = this;
  1533. this.$fileList.find('tr').each(function(i,e) {
  1534. var $e = $(e);
  1535. if ($e.data('file').toString().toLowerCase().indexOf(filter.toLowerCase()) === -1) {
  1536. $e.addClass('hidden');
  1537. that.$container.trigger('scroll');
  1538. } else {
  1539. $e.removeClass('hidden');
  1540. }
  1541. });
  1542. },
  1543. hideIrrelevantUIWhenNoFilesMatch:function() {
  1544. if (this._filter && this.fileSummary.summary.totalDirs + this.fileSummary.summary.totalFiles === 0) {
  1545. this.$el.find('#filestable thead th').addClass('hidden');
  1546. this.$el.find('#emptycontent').addClass('hidden');
  1547. if ( $('#searchresults').length === 0 || $('#searchresults').hasClass('hidden') ) {
  1548. this.$el.find('.nofilterresults').removeClass('hidden').
  1549. find('p').text(t('files', "No entries in this folder match '{filter}'", {filter:this._filter}, null, {'escape': false}));
  1550. }
  1551. } else {
  1552. this.$el.find('#filestable thead th').toggleClass('hidden', this.isEmpty);
  1553. if (!this.$el.find('.mask').exists()) {
  1554. this.$el.find('#emptycontent').toggleClass('hidden', !this.isEmpty);
  1555. }
  1556. this.$el.find('.nofilterresults').addClass('hidden');
  1557. }
  1558. },
  1559. /**
  1560. * get the current filter
  1561. * @param filter
  1562. */
  1563. getFilter:function(filter) {
  1564. return this._filter;
  1565. },
  1566. /**
  1567. * update the search object to use this filelist when filtering
  1568. */
  1569. updateSearch:function() {
  1570. if (OCA.Search.files) {
  1571. OCA.Search.files.setFileList(this);
  1572. }
  1573. if (OC.Search) {
  1574. OC.Search.clear();
  1575. }
  1576. },
  1577. /**
  1578. * Update UI based on the current selection
  1579. */
  1580. updateSelectionSummary: function() {
  1581. var summary = this._selectionSummary.summary;
  1582. var canDelete;
  1583. if (summary.totalFiles === 0 && summary.totalDirs === 0) {
  1584. this.$el.find('#headerName a.name>span:first').text(t('files','Name'));
  1585. this.$el.find('#headerSize a>span:first').text(t('files','Size'));
  1586. this.$el.find('#modified a>span:first').text(t('files','Modified'));
  1587. this.$el.find('table').removeClass('multiselect');
  1588. this.$el.find('.selectedActions').addClass('hidden');
  1589. }
  1590. else {
  1591. canDelete = (this.getDirectoryPermissions() & OC.PERMISSION_DELETE) && this.isSelectedDeletable();
  1592. this.$el.find('.selectedActions').removeClass('hidden');
  1593. this.$el.find('#headerSize a>span:first').text(OC.Util.humanFileSize(summary.totalSize));
  1594. var selection = '';
  1595. if (summary.totalDirs > 0) {
  1596. selection += n('files', '%n folder', '%n folders', summary.totalDirs);
  1597. if (summary.totalFiles > 0) {
  1598. selection += ' & ';
  1599. }
  1600. }
  1601. if (summary.totalFiles > 0) {
  1602. selection += n('files', '%n file', '%n files', summary.totalFiles);
  1603. }
  1604. this.$el.find('#headerName a.name>span:first').text(selection);
  1605. this.$el.find('#modified a>span:first').text('');
  1606. this.$el.find('table').addClass('multiselect');
  1607. this.$el.find('.delete-selected').toggleClass('hidden', !canDelete);
  1608. }
  1609. },
  1610. /**
  1611. * Check whether all selected files are deletable
  1612. */
  1613. isSelectedDeletable: function() {
  1614. return _.reduce(this.getSelectedFiles(), function(deletable, file) {
  1615. return deletable && (file.permissions & OC.PERMISSION_DELETE);
  1616. }, true);
  1617. },
  1618. /**
  1619. * Returns whether all files are selected
  1620. * @return true if all files are selected, false otherwise
  1621. */
  1622. isAllSelected: function() {
  1623. return this.$el.find('.select-all').prop('checked');
  1624. },
  1625. /**
  1626. * Returns the file info of the selected files
  1627. *
  1628. * @return array of file names
  1629. */
  1630. getSelectedFiles: function() {
  1631. return _.values(this._selectedFiles);
  1632. },
  1633. getUniqueName: function(name) {
  1634. if (this.findFileEl(name).exists()) {
  1635. var numMatch;
  1636. var parts=name.split('.');
  1637. var extension = "";
  1638. if (parts.length > 1) {
  1639. extension=parts.pop();
  1640. }
  1641. var base=parts.join('.');
  1642. numMatch=base.match(/\((\d+)\)/);
  1643. var num=2;
  1644. if (numMatch && numMatch.length>0) {
  1645. num=parseInt(numMatch[numMatch.length-1], 10)+1;
  1646. base=base.split('(');
  1647. base.pop();
  1648. base=$.trim(base.join('('));
  1649. }
  1650. name=base+' ('+num+')';
  1651. if (extension) {
  1652. name = name+'.'+extension;
  1653. }
  1654. // FIXME: ugly recursion
  1655. return this.getUniqueName(name);
  1656. }
  1657. return name;
  1658. },
  1659. /**
  1660. * Shows a "permission denied" notification
  1661. */
  1662. _showPermissionDeniedNotification: function() {
  1663. var message = t('core', 'You don’t have permission to upload or create files here');
  1664. OC.Notification.show(message);
  1665. //hide notification after 10 sec
  1666. setTimeout(function() {
  1667. OC.Notification.hide();
  1668. }, 5000);
  1669. },
  1670. /**
  1671. * Setup file upload events related to the file-upload plugin
  1672. */
  1673. setupUploadEvents: function() {
  1674. var self = this;
  1675. // handle upload events
  1676. var fileUploadStart = this.$el.find('#file_upload_start');
  1677. // detect the progress bar resize
  1678. fileUploadStart.on('resized', this._onResize);
  1679. fileUploadStart.on('fileuploaddrop', function(e, data) {
  1680. OC.Upload.log('filelist handle fileuploaddrop', e, data);
  1681. if (self.$el.hasClass('hidden')) {
  1682. // do not upload to invisible lists
  1683. return false;
  1684. }
  1685. var dropTarget = $(e.originalEvent.target);
  1686. // check if dropped inside this container and not another one
  1687. if (dropTarget.length
  1688. && !self.$el.is(dropTarget) // dropped on list directly
  1689. && !self.$el.has(dropTarget).length // dropped inside list
  1690. && !dropTarget.is(self.$container) // dropped on main container
  1691. ) {
  1692. return false;
  1693. }
  1694. // find the closest tr or crumb to use as target
  1695. dropTarget = dropTarget.closest('tr, .crumb');
  1696. // if dropping on tr or crumb, drag&drop upload to folder
  1697. if (dropTarget && (dropTarget.data('type') === 'dir' ||
  1698. dropTarget.hasClass('crumb'))) {
  1699. // remember as context
  1700. data.context = dropTarget;
  1701. // if permissions are specified, only allow if create permission is there
  1702. var permissions = dropTarget.data('permissions');
  1703. if (!_.isUndefined(permissions) && (permissions & OC.PERMISSION_CREATE) === 0) {
  1704. self._showPermissionDeniedNotification();
  1705. return false;
  1706. }
  1707. var dir = dropTarget.data('file');
  1708. // if from file list, need to prepend parent dir
  1709. if (dir) {
  1710. var parentDir = self.getCurrentDirectory();
  1711. if (parentDir[parentDir.length - 1] !== '/') {
  1712. parentDir += '/';
  1713. }
  1714. dir = parentDir + dir;
  1715. }
  1716. else{
  1717. // read full path from crumb
  1718. dir = dropTarget.data('dir') || '/';
  1719. }
  1720. // add target dir
  1721. data.targetDir = dir;
  1722. } else {
  1723. // we are dropping somewhere inside the file list, which will
  1724. // upload the file to the current directory
  1725. data.targetDir = self.getCurrentDirectory();
  1726. // cancel uploads to current dir if no permission
  1727. var isCreatable = (self.getDirectoryPermissions() & OC.PERMISSION_CREATE) !== 0;
  1728. if (!isCreatable) {
  1729. self._showPermissionDeniedNotification();
  1730. return false;
  1731. }
  1732. }
  1733. });
  1734. fileUploadStart.on('fileuploadadd', function(e, data) {
  1735. OC.Upload.log('filelist handle fileuploadadd', e, data);
  1736. //finish delete if we are uploading a deleted file
  1737. if (self.deleteFiles && self.deleteFiles.indexOf(data.files[0].name)!==-1) {
  1738. self.finishDelete(null, true); //delete file before continuing
  1739. }
  1740. // add ui visualization to existing folder
  1741. if (data.context && data.context.data('type') === 'dir') {
  1742. // add to existing folder
  1743. // update upload counter ui
  1744. var uploadText = data.context.find('.uploadtext');
  1745. var currentUploads = parseInt(uploadText.attr('currentUploads'), 10);
  1746. currentUploads += 1;
  1747. uploadText.attr('currentUploads', currentUploads);
  1748. var translatedText = n('files', 'Uploading %n file', 'Uploading %n files', currentUploads);
  1749. if (currentUploads === 1) {
  1750. var img = OC.imagePath('core', 'loading.gif');
  1751. data.context.find('.thumbnail').css('background-image', 'url(' + img + ')');
  1752. uploadText.text(translatedText);
  1753. uploadText.show();
  1754. } else {
  1755. uploadText.text(translatedText);
  1756. }
  1757. }
  1758. });
  1759. /*
  1760. * when file upload done successfully add row to filelist
  1761. * update counter when uploading to sub folder
  1762. */
  1763. fileUploadStart.on('fileuploaddone', function(e, data) {
  1764. OC.Upload.log('filelist handle fileuploaddone', e, data);
  1765. var response;
  1766. if (typeof data.result === 'string') {
  1767. response = data.result;
  1768. } else {
  1769. // fetch response from iframe
  1770. response = data.result[0].body.innerText;
  1771. }
  1772. var result=$.parseJSON(response);
  1773. if (typeof result[0] !== 'undefined' && result[0].status === 'success') {
  1774. var file = result[0];
  1775. var size = 0;
  1776. if (data.context && data.context.data('type') === 'dir') {
  1777. // update upload counter ui
  1778. var uploadText = data.context.find('.uploadtext');
  1779. var currentUploads = parseInt(uploadText.attr('currentUploads'), 10);
  1780. currentUploads -= 1;
  1781. uploadText.attr('currentUploads', currentUploads);
  1782. var translatedText = n('files', 'Uploading %n file', 'Uploading %n files', currentUploads);
  1783. if (currentUploads === 0) {
  1784. var img = OC.imagePath('core', 'filetypes/folder');
  1785. data.context.find('.thumbnail').css('background-image', 'url(' + img + ')');
  1786. uploadText.text(translatedText);
  1787. uploadText.hide();
  1788. } else {
  1789. uploadText.text(translatedText);
  1790. }
  1791. // update folder size
  1792. size = parseInt(data.context.data('size'), 10);
  1793. size += parseInt(file.size, 10);
  1794. data.context.attr('data-size', size);
  1795. data.context.find('td.filesize').text(humanFileSize(size));
  1796. } else {
  1797. // only append new file if uploaded into the current folder
  1798. if (file.directory !== self.getCurrentDirectory()) {
  1799. // Uploading folders actually uploads a list of files
  1800. // for which the target directory (file.directory) might lie deeper
  1801. // than the current directory
  1802. var fileDirectory = file.directory.replace('/','').replace(/\/$/, "");
  1803. var currentDirectory = self.getCurrentDirectory().replace('/','').replace(/\/$/, "") + '/';
  1804. if (currentDirectory !== '/') {
  1805. // abort if fileDirectory does not start with current one
  1806. if (fileDirectory.indexOf(currentDirectory) !== 0) {
  1807. return;
  1808. }
  1809. // remove the current directory part
  1810. fileDirectory = fileDirectory.substr(currentDirectory.length);
  1811. }
  1812. // only take the first section of the path
  1813. fileDirectory = fileDirectory.split('/');
  1814. var fd;
  1815. // if the first section exists / is a subdir
  1816. if (fileDirectory.length) {
  1817. fileDirectory = fileDirectory[0];
  1818. // See whether it is already in the list
  1819. fd = self.findFileEl(fileDirectory);
  1820. if (fd.length === 0) {
  1821. var dir = {
  1822. name: fileDirectory,
  1823. type: 'dir',
  1824. mimetype: 'httpd/unix-directory',
  1825. permissions: file.permissions,
  1826. size: 0,
  1827. id: file.parentId
  1828. };
  1829. fd = self.add(dir, {insert: true});
  1830. }
  1831. // update folder size
  1832. size = parseInt(fd.attr('data-size'), 10);
  1833. size += parseInt(file.size, 10);
  1834. fd.attr('data-size', size);
  1835. fd.find('td.filesize').text(OC.Util.humanFileSize(size));
  1836. }
  1837. return;
  1838. }
  1839. // add as stand-alone row to filelist
  1840. size = t('files', 'Pending');
  1841. if (data.files[0].size>=0) {
  1842. size=data.files[0].size;
  1843. }
  1844. //should the file exist in the list remove it
  1845. self.remove(file.name);
  1846. // create new file context
  1847. data.context = self.add(file, {animate: true});
  1848. }
  1849. }
  1850. });
  1851. fileUploadStart.on('fileuploadstop', function(e, data) {
  1852. OC.Upload.log('filelist handle fileuploadstop', e, data);
  1853. //if user pressed cancel hide upload chrome
  1854. if (data.errorThrown === 'abort') {
  1855. //cleanup uploading to a dir
  1856. var uploadText = $('tr .uploadtext');
  1857. var img = OC.imagePath('core', 'filetypes/folder');
  1858. uploadText.parents('td.filename').find('.thumbnail').css('background-image', 'url(' + img + ')');
  1859. uploadText.fadeOut();
  1860. uploadText.attr('currentUploads', 0);
  1861. }
  1862. self.updateStorageStatistics();
  1863. });
  1864. fileUploadStart.on('fileuploadfail', function(e, data) {
  1865. OC.Upload.log('filelist handle fileuploadfail', e, data);
  1866. //if user pressed cancel hide upload chrome
  1867. if (data.errorThrown === 'abort') {
  1868. //cleanup uploading to a dir
  1869. var uploadText = $('tr .uploadtext');
  1870. var img = OC.imagePath('core', 'filetypes/folder');
  1871. uploadText.parents('td.filename').find('.thumbnail').css('background-image', 'url(' + img + ')');
  1872. uploadText.fadeOut();
  1873. uploadText.attr('currentUploads', 0);
  1874. }
  1875. self.updateStorageStatistics();
  1876. });
  1877. },
  1878. /**
  1879. * Scroll to the last file of the given list
  1880. * Highlight the list of files
  1881. * @param files array of filenames,
  1882. * @param {Function} [highlightFunction] optional function
  1883. * to be called after the scrolling is finished
  1884. */
  1885. highlightFiles: function(files, highlightFunction) {
  1886. // Detection of the uploaded element
  1887. var filename = files[files.length - 1];
  1888. var $fileRow = this.findFileEl(filename);
  1889. while(!$fileRow.exists() && this._nextPage(false) !== false) { // Checking element existence
  1890. $fileRow = this.findFileEl(filename);
  1891. }
  1892. if (!$fileRow.exists()) { // Element not present in the file list
  1893. return;
  1894. }
  1895. var currentOffset = this.$container.scrollTop();
  1896. var additionalOffset = this.$el.find("#controls").height()+this.$el.find("#controls").offset().top;
  1897. // Animation
  1898. var _this = this;
  1899. var $scrollContainer = this.$container;
  1900. if ($scrollContainer[0] === window) {
  1901. // need to use "body" to animate scrolling
  1902. // when the scroll container is the window
  1903. $scrollContainer = $('body');
  1904. }
  1905. $scrollContainer.animate({
  1906. // Scrolling to the top of the new element
  1907. scrollTop: currentOffset + $fileRow.offset().top - $fileRow.height() * 2 - additionalOffset
  1908. }, {
  1909. duration: 500,
  1910. complete: function() {
  1911. // Highlighting function
  1912. var highlightRow = highlightFunction;
  1913. if (!highlightRow) {
  1914. highlightRow = function($fileRow) {
  1915. $fileRow.addClass("highlightUploaded");
  1916. setTimeout(function() {
  1917. $fileRow.removeClass("highlightUploaded");
  1918. }, 2500);
  1919. };
  1920. }
  1921. // Loop over uploaded files
  1922. for(var i=0; i<files.length; i++) {
  1923. var $fileRow = _this.findFileEl(files[i]);
  1924. if($fileRow.length !== 0) { // Checking element existence
  1925. highlightRow($fileRow);
  1926. }
  1927. }
  1928. }
  1929. });
  1930. }
  1931. };
  1932. /**
  1933. * Sort comparators.
  1934. * @namespace OCA.Files.FileList.Comparators
  1935. * @private
  1936. */
  1937. FileList.Comparators = {
  1938. /**
  1939. * Compares two file infos by name, making directories appear
  1940. * first.
  1941. *
  1942. * @param {OCA.Files.FileInfo} fileInfo1 file info
  1943. * @param {OCA.Files.FileInfo} fileInfo2 file info
  1944. * @return {int} -1 if the first file must appear before the second one,
  1945. * 0 if they are identify, 1 otherwise.
  1946. */
  1947. name: function(fileInfo1, fileInfo2) {
  1948. if (fileInfo1.type === 'dir' && fileInfo2.type !== 'dir') {
  1949. return -1;
  1950. }
  1951. if (fileInfo1.type !== 'dir' && fileInfo2.type === 'dir') {
  1952. return 1;
  1953. }
  1954. return OC.Util.naturalSortCompare(fileInfo1.name, fileInfo2.name);
  1955. },
  1956. /**
  1957. * Compares two file infos by size.
  1958. *
  1959. * @param {OCA.Files.FileInfo} fileInfo1 file info
  1960. * @param {OCA.Files.FileInfo} fileInfo2 file info
  1961. * @return {int} -1 if the first file must appear before the second one,
  1962. * 0 if they are identify, 1 otherwise.
  1963. */
  1964. size: function(fileInfo1, fileInfo2) {
  1965. return fileInfo1.size - fileInfo2.size;
  1966. },
  1967. /**
  1968. * Compares two file infos by timestamp.
  1969. *
  1970. * @param {OCA.Files.FileInfo} fileInfo1 file info
  1971. * @param {OCA.Files.FileInfo} fileInfo2 file info
  1972. * @return {int} -1 if the first file must appear before the second one,
  1973. * 0 if they are identify, 1 otherwise.
  1974. */
  1975. mtime: function(fileInfo1, fileInfo2) {
  1976. return fileInfo1.mtime - fileInfo2.mtime;
  1977. }
  1978. };
  1979. /**
  1980. * File info attributes.
  1981. *
  1982. * @todo make this a real class in the future
  1983. * @typedef {Object} OCA.Files.FileInfo
  1984. *
  1985. * @property {int} id file id
  1986. * @property {String} name file name
  1987. * @property {String} [path] file path, defaults to the list's current path
  1988. * @property {String} mimetype mime type
  1989. * @property {String} type "file" for files or "dir" for directories
  1990. * @property {int} permissions file permissions
  1991. * @property {int} mtime modification time in milliseconds
  1992. * @property {boolean} [isShareMountPoint] whether the file is a share mount
  1993. * point
  1994. * @property {boolean} [isPreviewAvailable] whether a preview is available
  1995. * for the given file type
  1996. * @property {String} [icon] path to the mime type icon
  1997. * @property {String} etag etag of the file
  1998. */
  1999. OCA.Files.FileList = FileList;
  2000. })();
  2001. $(document).ready(function() {
  2002. // FIXME: unused ?
  2003. OCA.Files.FileList.useUndo = (window.onbeforeunload)?true:false;
  2004. $(window).bind('beforeunload', function () {
  2005. if (OCA.Files.FileList.lastAction) {
  2006. OCA.Files.FileList.lastAction();
  2007. }
  2008. });
  2009. $(window).unload(function () {
  2010. $(window).trigger('beforeunload');
  2011. });
  2012. });