filelist.js 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226
  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 && e.which === 1) {
  415. e.preventDefault();
  416. this.changeDirectory($targetDir);
  417. this.updateSearch();
  418. }
  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. var self = this;
  568. // detach to make adding multiple rows faster
  569. this.files = filesArray;
  570. this.$fileList.empty();
  571. // clear "Select all" checkbox
  572. this.$el.find('.select-all').prop('checked', false);
  573. this.isEmpty = this.files.length === 0;
  574. this._nextPage();
  575. this.updateEmptyContent();
  576. this.fileSummary.calculate(filesArray);
  577. this._selectedFiles = {};
  578. this._selectionSummary.clear();
  579. this.updateSelectionSummary();
  580. $(window).scrollTop(0);
  581. this.$fileList.trigger(jQuery.Event('updated'));
  582. _.defer(function() {
  583. self.$el.closest('#app-content').trigger(jQuery.Event('apprendered'));
  584. });
  585. },
  586. /**
  587. * Creates a new table row element using the given file data.
  588. * @param {OCA.Files.FileInfo} fileData file info attributes
  589. * @param options map of attributes
  590. * @return new tr element (not appended to the table)
  591. */
  592. _createRow: function(fileData, options) {
  593. var td, simpleSize, basename, extension, sizeColor,
  594. icon = OC.Util.replaceSVGIcon(fileData.icon),
  595. name = fileData.name,
  596. type = fileData.type || 'file',
  597. mtime = parseInt(fileData.mtime, 10),
  598. mime = fileData.mimetype,
  599. path = fileData.path,
  600. linkUrl;
  601. options = options || {};
  602. if (isNaN(mtime)) {
  603. mtime = new Date().getTime()
  604. }
  605. if (type === 'dir') {
  606. mime = mime || 'httpd/unix-directory';
  607. }
  608. //containing tr
  609. var tr = $('<tr></tr>').attr({
  610. "data-id" : fileData.id,
  611. "data-type": type,
  612. "data-size": fileData.size,
  613. "data-file": name,
  614. "data-mime": mime,
  615. "data-mtime": mtime,
  616. "data-etag": fileData.etag,
  617. "data-permissions": fileData.permissions || this.getDirectoryPermissions()
  618. });
  619. if (fileData.mountType) {
  620. tr.attr('data-mounttype', fileData.mountType);
  621. }
  622. if (!_.isUndefined(path)) {
  623. tr.attr('data-path', path);
  624. }
  625. else {
  626. path = this.getCurrentDirectory();
  627. }
  628. if (type === 'dir') {
  629. // use default folder icon
  630. icon = icon || OC.imagePath('core', 'filetypes/folder');
  631. }
  632. else {
  633. icon = icon || OC.imagePath('core', 'filetypes/file');
  634. }
  635. // filename td
  636. td = $('<td class="filename"></td>');
  637. // linkUrl
  638. if (type === 'dir') {
  639. linkUrl = this.linkTo(path + '/' + name);
  640. }
  641. else {
  642. linkUrl = this.getDownloadUrl(name, path);
  643. }
  644. if (this._allowSelection) {
  645. td.append(
  646. '<input id="select-' + this.id + '-' + fileData.id +
  647. '" type="checkbox" class="selectCheckBox"/><label for="select-' + this.id + '-' + fileData.id + '">' +
  648. '<div class="thumbnail" style="background-image:url(' + icon + '); background-size: 32px;"></div>' +
  649. '<span class="hidden-visually">' + t('files', 'Select') + '</span>' +
  650. '</label>'
  651. );
  652. } else {
  653. td.append('<div class="thumbnail" style="background-image:url(' + icon + '); background-size: 32px;"></div>');
  654. }
  655. var linkElem = $('<a></a>').attr({
  656. "class": "name",
  657. "href": linkUrl
  658. });
  659. // from here work on the display name
  660. name = fileData.displayName || name;
  661. // show hidden files (starting with a dot) completely in gray
  662. if(name.indexOf('.') === 0) {
  663. basename = '';
  664. extension = name;
  665. // split extension from filename for non dirs
  666. } else if (type !== 'dir' && name.indexOf('.') !== -1) {
  667. basename = name.substr(0, name.lastIndexOf('.'));
  668. extension = name.substr(name.lastIndexOf('.'));
  669. } else {
  670. basename = name;
  671. extension = false;
  672. }
  673. var nameSpan=$('<span></span>').addClass('nametext');
  674. var innernameSpan = $('<span></span>').addClass('innernametext').text(basename);
  675. nameSpan.append(innernameSpan);
  676. linkElem.append(nameSpan);
  677. if (extension) {
  678. nameSpan.append($('<span></span>').addClass('extension').text(extension));
  679. }
  680. if (fileData.extraData) {
  681. if (fileData.extraData.charAt(0) === '/') {
  682. fileData.extraData = fileData.extraData.substr(1);
  683. }
  684. nameSpan.addClass('extra-data').attr('title', fileData.extraData);
  685. }
  686. // dirs can show the number of uploaded files
  687. if (type === 'dir') {
  688. linkElem.append($('<span></span>').attr({
  689. 'class': 'uploadtext',
  690. 'currentUploads': 0
  691. }));
  692. }
  693. td.append(linkElem);
  694. tr.append(td);
  695. // size column
  696. if (typeof(fileData.size) !== 'undefined' && fileData.size >= 0) {
  697. simpleSize = humanFileSize(parseInt(fileData.size, 10), true);
  698. sizeColor = Math.round(160-Math.pow((fileData.size/(1024*1024)),2));
  699. } else {
  700. simpleSize = t('files', 'Pending');
  701. }
  702. td = $('<td></td>').attr({
  703. "class": "filesize",
  704. "style": 'color:rgb(' + sizeColor + ',' + sizeColor + ',' + sizeColor + ')'
  705. }).text(simpleSize);
  706. tr.append(td);
  707. // date column (1000 milliseconds to seconds, 60 seconds, 60 minutes, 24 hours)
  708. // difference in days multiplied by 5 - brightest shade for files older than 32 days (160/5)
  709. var modifiedColor = Math.round(((new Date()).getTime() - mtime )/1000/60/60/24*5 );
  710. // ensure that the brightest color is still readable
  711. if (modifiedColor >= '160') {
  712. modifiedColor = 160;
  713. }
  714. var formatted;
  715. var text;
  716. if (mtime > 0) {
  717. formatted = formatDate(mtime);
  718. text = OC.Util.relativeModifiedDate(mtime);
  719. } else {
  720. formatted = t('files', 'Unable to determine date');
  721. text = '?';
  722. }
  723. td = $('<td></td>').attr({ "class": "date" });
  724. td.append($('<span></span>').attr({
  725. "class": "modified",
  726. "title": formatted,
  727. "style": 'color:rgb('+modifiedColor+','+modifiedColor+','+modifiedColor+')'
  728. }).text(text));
  729. tr.find('.filesize').text(simpleSize);
  730. tr.append(td);
  731. return tr;
  732. },
  733. /**
  734. * Adds an entry to the files array and also into the DOM
  735. * in a sorted manner.
  736. *
  737. * @param {OCA.Files.FileInfo} fileData map of file attributes
  738. * @param {Object} [options] map of attributes
  739. * @param {boolean} [options.updateSummary] true to update the summary
  740. * after adding (default), false otherwise. Defaults to true.
  741. * @param {boolean} [options.silent] true to prevent firing events like "fileActionsReady",
  742. * defaults to false.
  743. * @param {boolean} [options.animate] true to animate the thumbnail image after load
  744. * defaults to true.
  745. * @return new tr element (not appended to the table)
  746. */
  747. add: function(fileData, options) {
  748. var index = -1;
  749. var $tr;
  750. var $rows;
  751. var $insertionPoint;
  752. options = _.extend({animate: true}, options || {});
  753. // there are three situations to cover:
  754. // 1) insertion point is visible on the current page
  755. // 2) insertion point is on a not visible page (visible after scrolling)
  756. // 3) insertion point is at the end of the list
  757. $rows = this.$fileList.children();
  758. index = this._findInsertionIndex(fileData);
  759. if (index > this.files.length) {
  760. index = this.files.length;
  761. }
  762. else {
  763. $insertionPoint = $rows.eq(index);
  764. }
  765. // is the insertion point visible ?
  766. if ($insertionPoint.length) {
  767. // only render if it will really be inserted
  768. $tr = this._renderRow(fileData, options);
  769. $insertionPoint.before($tr);
  770. }
  771. else {
  772. // if insertion point is after the last visible
  773. // entry, append
  774. if (index === $rows.length) {
  775. $tr = this._renderRow(fileData, options);
  776. this.$fileList.append($tr);
  777. }
  778. }
  779. this.isEmpty = false;
  780. this.files.splice(index, 0, fileData);
  781. if ($tr && options.animate) {
  782. $tr.addClass('appear transparent');
  783. window.setTimeout(function() {
  784. $tr.removeClass('transparent');
  785. });
  786. }
  787. if (options.scrollTo) {
  788. this.scrollTo(fileData.name);
  789. }
  790. // defaults to true if not defined
  791. if (typeof(options.updateSummary) === 'undefined' || !!options.updateSummary) {
  792. this.fileSummary.add(fileData, true);
  793. this.updateEmptyContent();
  794. }
  795. return $tr;
  796. },
  797. /**
  798. * Creates a new row element based on the given attributes
  799. * and returns it.
  800. *
  801. * @param {OCA.Files.FileInfo} fileData map of file attributes
  802. * @param {Object} [options] map of attributes
  803. * @param {int} [options.index] index at which to insert the element
  804. * @param {boolean} [options.updateSummary] true to update the summary
  805. * after adding (default), false otherwise. Defaults to true.
  806. * @param {boolean} [options.animate] true to animate the thumbnail image after load
  807. * defaults to true.
  808. * @return new tr element (not appended to the table)
  809. */
  810. _renderRow: function(fileData, options) {
  811. options = options || {};
  812. var type = fileData.type || 'file',
  813. mime = fileData.mimetype,
  814. path = fileData.path || this.getCurrentDirectory(),
  815. permissions = parseInt(fileData.permissions, 10) || 0;
  816. if (fileData.isShareMountPoint) {
  817. permissions = permissions | OC.PERMISSION_UPDATE;
  818. }
  819. if (type === 'dir') {
  820. mime = mime || 'httpd/unix-directory';
  821. }
  822. var tr = this._createRow(
  823. fileData,
  824. options
  825. );
  826. var filenameTd = tr.find('td.filename');
  827. // TODO: move dragging to FileActions ?
  828. // enable drag only for deletable files
  829. if (this._dragOptions && permissions & OC.PERMISSION_DELETE) {
  830. filenameTd.draggable(this._dragOptions);
  831. }
  832. // allow dropping on folders
  833. if (this._folderDropOptions && fileData.type === 'dir') {
  834. filenameTd.droppable(this._folderDropOptions);
  835. }
  836. if (options.hidden) {
  837. tr.addClass('hidden');
  838. }
  839. // display actions
  840. this.fileActions.display(filenameTd, !options.silent, this);
  841. if (fileData.isPreviewAvailable) {
  842. var iconDiv = filenameTd.find('.thumbnail');
  843. // lazy load / newly inserted td ?
  844. if (options.animate) {
  845. this.lazyLoadPreview({
  846. path: path + '/' + fileData.name,
  847. mime: mime,
  848. etag: fileData.etag,
  849. callback: function(url) {
  850. iconDiv.css('background-image', 'url("' + url + '")');
  851. }
  852. });
  853. }
  854. else {
  855. // set the preview URL directly
  856. var urlSpec = {
  857. file: path + '/' + fileData.name,
  858. c: fileData.etag
  859. };
  860. var previewUrl = this.generatePreviewUrl(urlSpec);
  861. previewUrl = previewUrl.replace('(', '%28').replace(')', '%29');
  862. iconDiv.css('background-image', 'url("' + previewUrl + '")');
  863. }
  864. }
  865. return tr;
  866. },
  867. /**
  868. * Returns the current directory
  869. * @method getCurrentDirectory
  870. * @return current directory
  871. */
  872. getCurrentDirectory: function(){
  873. return this._currentDirectory || this.$el.find('#dir').val() || '/';
  874. },
  875. /**
  876. * Returns the directory permissions
  877. * @return permission value as integer
  878. */
  879. getDirectoryPermissions: function() {
  880. return parseInt(this.$el.find('#permissions').val(), 10);
  881. },
  882. /**
  883. * @brief Changes the current directory and reload the file list.
  884. * @param targetDir target directory (non URL encoded)
  885. * @param changeUrl false if the URL must not be changed (defaults to true)
  886. * @param {boolean} force set to true to force changing directory
  887. */
  888. changeDirectory: function(targetDir, changeUrl, force) {
  889. var self = this;
  890. var currentDir = this.getCurrentDirectory();
  891. targetDir = targetDir || '/';
  892. if (!force && currentDir === targetDir) {
  893. return;
  894. }
  895. this._setCurrentDir(targetDir, changeUrl);
  896. this.reload().then(function(success){
  897. if (!success) {
  898. self.changeDirectory(currentDir, true);
  899. }
  900. });
  901. },
  902. linkTo: function(dir) {
  903. return OC.linkTo('files', 'index.php')+"?dir="+ encodeURIComponent(dir).replace(/%2F/g, '/');
  904. },
  905. /**
  906. * Sets the current directory name and updates the breadcrumb.
  907. * @param targetDir directory to display
  908. * @param changeUrl true to also update the URL, false otherwise (default)
  909. */
  910. _setCurrentDir: function(targetDir, changeUrl) {
  911. targetDir = targetDir.replace(/\\/g, '/');
  912. var previousDir = this.getCurrentDirectory(),
  913. baseDir = OC.basename(targetDir);
  914. if (baseDir !== '') {
  915. this.setPageTitle(baseDir);
  916. }
  917. else {
  918. this.setPageTitle();
  919. }
  920. this._currentDirectory = targetDir;
  921. // legacy stuff
  922. this.$el.find('#dir').val(targetDir);
  923. if (changeUrl !== false) {
  924. this.$el.trigger(jQuery.Event('changeDirectory', {
  925. dir: targetDir,
  926. previousDir: previousDir
  927. }));
  928. }
  929. this.breadcrumb.setDirectory(this.getCurrentDirectory());
  930. },
  931. /**
  932. * Sets the current sorting and refreshes the list
  933. *
  934. * @param sort sort attribute name
  935. * @param direction sort direction, one of "asc" or "desc"
  936. * @param update true to update the list, false otherwise (default)
  937. */
  938. setSort: function(sort, direction, update) {
  939. var comparator = FileList.Comparators[sort] || FileList.Comparators.name;
  940. this._sort = sort;
  941. this._sortDirection = (direction === 'desc')?'desc':'asc';
  942. this._sortComparator = comparator;
  943. if (direction === 'desc') {
  944. this._sortComparator = function(fileInfo1, fileInfo2) {
  945. return -comparator(fileInfo1, fileInfo2);
  946. };
  947. }
  948. this.$el.find('thead th .sort-indicator')
  949. .removeClass(this.SORT_INDICATOR_ASC_CLASS)
  950. .removeClass(this.SORT_INDICATOR_DESC_CLASS)
  951. .toggleClass('hidden', true)
  952. .addClass(this.SORT_INDICATOR_DESC_CLASS);
  953. this.$el.find('thead th.column-' + sort + ' .sort-indicator')
  954. .removeClass(this.SORT_INDICATOR_ASC_CLASS)
  955. .removeClass(this.SORT_INDICATOR_DESC_CLASS)
  956. .toggleClass('hidden', false)
  957. .addClass(direction === 'desc' ? this.SORT_INDICATOR_DESC_CLASS : this.SORT_INDICATOR_ASC_CLASS);
  958. if (update) {
  959. if (this._clientSideSort) {
  960. this.files.sort(this._sortComparator);
  961. this.setFiles(this.files);
  962. }
  963. else {
  964. this.reload();
  965. }
  966. }
  967. },
  968. /**
  969. * Reloads the file list using ajax call
  970. *
  971. * @return ajax call object
  972. */
  973. reload: function() {
  974. this._selectedFiles = {};
  975. this._selectionSummary.clear();
  976. this.$el.find('.select-all').prop('checked', false);
  977. this.showMask();
  978. if (this._reloadCall) {
  979. this._reloadCall.abort();
  980. }
  981. this._reloadCall = $.ajax({
  982. url: this.getAjaxUrl('list'),
  983. data: {
  984. dir : this.getCurrentDirectory(),
  985. sort: this._sort,
  986. sortdirection: this._sortDirection
  987. }
  988. });
  989. var callBack = this.reloadCallback.bind(this);
  990. return this._reloadCall.then(callBack, callBack);
  991. },
  992. reloadCallback: function(result) {
  993. delete this._reloadCall;
  994. this.hideMask();
  995. if (!result || result.status === 'error') {
  996. // if the error is not related to folder we're trying to load, reload the page to handle logout etc
  997. if (result.data.error === 'authentication_error' ||
  998. result.data.error === 'token_expired' ||
  999. result.data.error === 'application_not_enabled'
  1000. ) {
  1001. OC.redirect(OC.generateUrl('apps/files'));
  1002. }
  1003. OC.Notification.show(result.data.message);
  1004. return false;
  1005. }
  1006. if (result.status === 404) {
  1007. // go back home
  1008. this.changeDirectory('/');
  1009. return false;
  1010. }
  1011. // aborted ?
  1012. if (result.status === 0){
  1013. return true;
  1014. }
  1015. // TODO: should rather return upload file size through
  1016. // the files list ajax call
  1017. this.updateStorageStatistics(true);
  1018. if (result.data.permissions) {
  1019. this.setDirectoryPermissions(result.data.permissions);
  1020. }
  1021. this.setFiles(result.data.files);
  1022. return true;
  1023. },
  1024. updateStorageStatistics: function(force) {
  1025. OCA.Files.Files.updateStorageStatistics(this.getCurrentDirectory(), force);
  1026. },
  1027. getAjaxUrl: function(action, params) {
  1028. return OCA.Files.Files.getAjaxUrl(action, params);
  1029. },
  1030. getDownloadUrl: function(files, dir) {
  1031. return OCA.Files.Files.getDownloadUrl(files, dir || this.getCurrentDirectory());
  1032. },
  1033. /**
  1034. * Generates a preview URL based on the URL space.
  1035. * @param urlSpec attributes for the URL
  1036. * @param {int} urlSpec.x width
  1037. * @param {int} urlSpec.y height
  1038. * @param {String} urlSpec.file path to the file
  1039. * @return preview URL
  1040. */
  1041. generatePreviewUrl: function(urlSpec) {
  1042. urlSpec = urlSpec || {};
  1043. if (!urlSpec.x) {
  1044. urlSpec.x = this.$table.data('preview-x') || 36;
  1045. }
  1046. if (!urlSpec.y) {
  1047. urlSpec.y = this.$table.data('preview-y') || 36;
  1048. }
  1049. urlSpec.y *= window.devicePixelRatio;
  1050. urlSpec.x *= window.devicePixelRatio;
  1051. urlSpec.forceIcon = 0;
  1052. return OC.generateUrl('/core/preview.png?') + $.param(urlSpec);
  1053. },
  1054. /**
  1055. * Lazy load a file's preview.
  1056. *
  1057. * @param path path of the file
  1058. * @param mime mime type
  1059. * @param callback callback function to call when the image was loaded
  1060. * @param etag file etag (for caching)
  1061. */
  1062. lazyLoadPreview : function(options) {
  1063. var self = this;
  1064. var path = options.path;
  1065. var mime = options.mime;
  1066. var ready = options.callback;
  1067. var etag = options.etag;
  1068. // get mime icon url
  1069. OCA.Files.Files.getMimeIcon(mime, function(iconURL) {
  1070. var previewURL,
  1071. urlSpec = {};
  1072. ready(iconURL); // set mimeicon URL
  1073. urlSpec.file = OCA.Files.Files.fixPath(path);
  1074. if (etag){
  1075. // use etag as cache buster
  1076. urlSpec.c = etag;
  1077. }
  1078. else {
  1079. console.warn('OCA.Files.FileList.lazyLoadPreview(): missing etag argument');
  1080. }
  1081. previewURL = self.generatePreviewUrl(urlSpec);
  1082. previewURL = previewURL.replace('(', '%28');
  1083. previewURL = previewURL.replace(')', '%29');
  1084. // preload image to prevent delay
  1085. // this will make the browser cache the image
  1086. var img = new Image();
  1087. img.onload = function(){
  1088. // if loading the preview image failed (no preview for the mimetype) then img.width will < 5
  1089. if (img.width > 5) {
  1090. ready(previewURL);
  1091. }
  1092. };
  1093. img.src = previewURL;
  1094. });
  1095. },
  1096. setDirectoryPermissions: function(permissions) {
  1097. var isCreatable = (permissions & OC.PERMISSION_CREATE) !== 0;
  1098. this.$el.find('#permissions').val(permissions);
  1099. this.$el.find('.creatable').toggleClass('hidden', !isCreatable);
  1100. this.$el.find('.notCreatable').toggleClass('hidden', isCreatable);
  1101. },
  1102. /**
  1103. * Shows/hides action buttons
  1104. *
  1105. * @param show true for enabling, false for disabling
  1106. */
  1107. showActions: function(show){
  1108. this.$el.find('.actions,#file_action_panel').toggleClass('hidden', !show);
  1109. if (show){
  1110. // make sure to display according to permissions
  1111. var permissions = this.getDirectoryPermissions();
  1112. var isCreatable = (permissions & OC.PERMISSION_CREATE) !== 0;
  1113. this.$el.find('.creatable').toggleClass('hidden', !isCreatable);
  1114. this.$el.find('.notCreatable').toggleClass('hidden', isCreatable);
  1115. // remove old style breadcrumbs (some apps might create them)
  1116. this.$el.find('#controls .crumb').remove();
  1117. // refresh breadcrumbs in case it was replaced by an app
  1118. this.breadcrumb.render();
  1119. }
  1120. else{
  1121. this.$el.find('.creatable, .notCreatable').addClass('hidden');
  1122. }
  1123. },
  1124. /**
  1125. * Enables/disables viewer mode.
  1126. * In viewer mode, apps can embed themselves under the controls bar.
  1127. * In viewer mode, the actions of the file list will be hidden.
  1128. * @param show true for enabling, false for disabling
  1129. */
  1130. setViewerMode: function(show){
  1131. this.showActions(!show);
  1132. this.$el.find('#filestable').toggleClass('hidden', show);
  1133. this.$el.trigger(new $.Event('changeViewerMode', {viewerModeEnabled: show}));
  1134. },
  1135. /**
  1136. * Removes a file entry from the list
  1137. * @param name name of the file to remove
  1138. * @param {Object} [options] map of attributes
  1139. * @param {boolean} [options.updateSummary] true to update the summary
  1140. * after removing, false otherwise. Defaults to true.
  1141. * @return deleted element
  1142. */
  1143. remove: function(name, options){
  1144. options = options || {};
  1145. var fileEl = this.findFileEl(name);
  1146. var index = fileEl.index();
  1147. if (!fileEl.length) {
  1148. return null;
  1149. }
  1150. if (this._selectedFiles[fileEl.data('id')]) {
  1151. // remove from selection first
  1152. this._selectFileEl(fileEl, false);
  1153. this.updateSelectionSummary();
  1154. }
  1155. if (this._dragOptions && (fileEl.data('permissions') & OC.PERMISSION_DELETE)) {
  1156. // file is only draggable when delete permissions are set
  1157. fileEl.find('td.filename').draggable('destroy');
  1158. }
  1159. this.files.splice(index, 1);
  1160. fileEl.remove();
  1161. // TODO: improve performance on batch update
  1162. this.isEmpty = !this.files.length;
  1163. if (typeof(options.updateSummary) === 'undefined' || !!options.updateSummary) {
  1164. this.updateEmptyContent();
  1165. this.fileSummary.remove({type: fileEl.attr('data-type'), size: fileEl.attr('data-size')}, true);
  1166. }
  1167. var lastIndex = this.$fileList.children().length;
  1168. // if there are less elements visible than one page
  1169. // but there are still pending elements in the array,
  1170. // then directly append the next page
  1171. if (lastIndex < this.files.length && lastIndex < this.pageSize()) {
  1172. this._nextPage(true);
  1173. }
  1174. return fileEl;
  1175. },
  1176. /**
  1177. * Finds the index of the row before which the given
  1178. * fileData should be inserted, considering the current
  1179. * sorting
  1180. *
  1181. * @param {OCA.Files.FileInfo} fileData file info
  1182. */
  1183. _findInsertionIndex: function(fileData) {
  1184. var index = 0;
  1185. while (index < this.files.length && this._sortComparator(fileData, this.files[index]) > 0) {
  1186. index++;
  1187. }
  1188. return index;
  1189. },
  1190. /**
  1191. * Moves a file to a given target folder.
  1192. *
  1193. * @param fileNames array of file names to move
  1194. * @param targetPath absolute target path
  1195. */
  1196. move: function(fileNames, targetPath) {
  1197. var self = this;
  1198. var dir = this.getCurrentDirectory();
  1199. var target = OC.basename(targetPath);
  1200. if (!_.isArray(fileNames)) {
  1201. fileNames = [fileNames];
  1202. }
  1203. _.each(fileNames, function(fileName) {
  1204. var $tr = self.findFileEl(fileName);
  1205. var $thumbEl = $tr.find('.thumbnail');
  1206. var oldBackgroundImage = $thumbEl.css('background-image');
  1207. $thumbEl.css('background-image', 'url('+ OC.imagePath('core', 'loading.gif') + ')');
  1208. // TODO: improve performance by sending all file names in a single call
  1209. $.post(
  1210. OC.filePath('files', 'ajax', 'move.php'),
  1211. {
  1212. dir: dir,
  1213. file: fileName,
  1214. target: targetPath
  1215. },
  1216. function(result) {
  1217. if (result) {
  1218. if (result.status === 'success') {
  1219. // if still viewing the same directory
  1220. if (self.getCurrentDirectory() === dir) {
  1221. // recalculate folder size
  1222. var oldFile = self.findFileEl(target);
  1223. var newFile = self.findFileEl(fileName);
  1224. var oldSize = oldFile.data('size');
  1225. var newSize = oldSize + newFile.data('size');
  1226. oldFile.data('size', newSize);
  1227. oldFile.find('td.filesize').text(OC.Util.humanFileSize(newSize));
  1228. // TODO: also update entry in FileList.files
  1229. self.remove(fileName);
  1230. }
  1231. } else {
  1232. OC.Notification.hide();
  1233. if (result.status === 'error' && result.data.message) {
  1234. OC.Notification.show(result.data.message);
  1235. }
  1236. else {
  1237. OC.Notification.show(t('files', 'Error moving file.'));
  1238. }
  1239. // hide notification after 10 sec
  1240. setTimeout(function() {
  1241. OC.Notification.hide();
  1242. }, 10000);
  1243. }
  1244. } else {
  1245. OC.dialogs.alert(t('files', 'Error moving file'), t('files', 'Error'));
  1246. }
  1247. $thumbEl.css('background-image', oldBackgroundImage);
  1248. }
  1249. );
  1250. });
  1251. },
  1252. /**
  1253. * Triggers file rename input field for the given file name.
  1254. * If the user enters a new name, the file will be renamed.
  1255. *
  1256. * @param oldname file name of the file to rename
  1257. */
  1258. rename: function(oldname) {
  1259. var self = this;
  1260. var tr, td, input, form;
  1261. tr = this.findFileEl(oldname);
  1262. var oldFileInfo = this.files[tr.index()];
  1263. tr.data('renaming',true);
  1264. td = tr.children('td.filename');
  1265. input = $('<input type="text" class="filename"/>').val(oldname);
  1266. form = $('<form></form>');
  1267. form.append(input);
  1268. td.children('a.name').hide();
  1269. td.append(form);
  1270. input.focus();
  1271. //preselect input
  1272. var len = input.val().lastIndexOf('.');
  1273. if ( len === -1 ||
  1274. tr.data('type') === 'dir' ) {
  1275. len = input.val().length;
  1276. }
  1277. input.selectRange(0, len);
  1278. var checkInput = function () {
  1279. var filename = input.val();
  1280. if (filename !== oldname) {
  1281. // Files.isFileNameValid(filename) throws an exception itself
  1282. OCA.Files.Files.isFileNameValid(filename);
  1283. if (self.inList(filename)) {
  1284. throw t('files', '{new_name} already exists', {new_name: filename});
  1285. }
  1286. }
  1287. return true;
  1288. };
  1289. function restore() {
  1290. input.tipsy('hide');
  1291. tr.data('renaming',false);
  1292. form.remove();
  1293. td.children('a.name').show();
  1294. }
  1295. form.submit(function(event) {
  1296. event.stopPropagation();
  1297. event.preventDefault();
  1298. if (input.hasClass('error')) {
  1299. return;
  1300. }
  1301. try {
  1302. var newName = input.val();
  1303. var $thumbEl = tr.find('.thumbnail');
  1304. input.tipsy('hide');
  1305. form.remove();
  1306. if (newName !== oldname) {
  1307. checkInput();
  1308. // mark as loading (temp element)
  1309. $thumbEl.css('background-image', 'url('+ OC.imagePath('core', 'loading.gif') + ')');
  1310. tr.attr('data-file', newName);
  1311. var basename = newName;
  1312. if (newName.indexOf('.') > 0 && tr.data('type') !== 'dir') {
  1313. basename = newName.substr(0, newName.lastIndexOf('.'));
  1314. }
  1315. td.find('a.name span.nametext').text(basename);
  1316. td.children('a.name').show();
  1317. tr.find('.fileactions, .action').addClass('hidden');
  1318. $.ajax({
  1319. url: OC.filePath('files','ajax','rename.php'),
  1320. data: {
  1321. dir : tr.attr('data-path') || self.getCurrentDirectory(),
  1322. newname: newName,
  1323. file: oldname
  1324. },
  1325. success: function(result) {
  1326. var fileInfo;
  1327. if (!result || result.status === 'error') {
  1328. OC.dialogs.alert(result.data.message, t('files', 'Could not rename file'));
  1329. fileInfo = oldFileInfo;
  1330. if (result.data.code === 'sourcenotfound') {
  1331. self.remove(result.data.newname, {updateSummary: true});
  1332. return;
  1333. }
  1334. }
  1335. else {
  1336. fileInfo = result.data;
  1337. }
  1338. // reinsert row
  1339. self.files.splice(tr.index(), 1);
  1340. tr.remove();
  1341. tr = self.add(fileInfo, {updateSummary: false, silent: true});
  1342. self.$fileList.trigger($.Event('fileActionsReady', {fileList: self, $files: $(tr)}));
  1343. }
  1344. });
  1345. } else {
  1346. // add back the old file info when cancelled
  1347. self.files.splice(tr.index(), 1);
  1348. tr.remove();
  1349. tr = self.add(oldFileInfo, {updateSummary: false, silent: true});
  1350. self.$fileList.trigger($.Event('fileActionsReady', {fileList: self, $files: $(tr)}));
  1351. }
  1352. } catch (error) {
  1353. input.attr('title', error);
  1354. input.tipsy({gravity: 'w', trigger: 'manual'});
  1355. input.tipsy('show');
  1356. input.addClass('error');
  1357. }
  1358. return false;
  1359. });
  1360. input.keyup(function(event) {
  1361. // verify filename on typing
  1362. try {
  1363. checkInput();
  1364. input.tipsy('hide');
  1365. input.removeClass('error');
  1366. } catch (error) {
  1367. input.attr('title', error);
  1368. input.tipsy({gravity: 'w', trigger: 'manual'});
  1369. input.tipsy('show');
  1370. input.addClass('error');
  1371. }
  1372. if (event.keyCode === 27) {
  1373. restore();
  1374. }
  1375. });
  1376. input.click(function(event) {
  1377. event.stopPropagation();
  1378. event.preventDefault();
  1379. });
  1380. input.blur(function() {
  1381. form.trigger('submit');
  1382. });
  1383. },
  1384. inList:function(file) {
  1385. return this.findFileEl(file).length;
  1386. },
  1387. /**
  1388. * Delete the given files from the given dir
  1389. * @param files file names list (without path)
  1390. * @param dir directory in which to delete the files, defaults to the current
  1391. * directory
  1392. */
  1393. do_delete:function(files, dir) {
  1394. var self = this;
  1395. var params;
  1396. if (files && files.substr) {
  1397. files=[files];
  1398. }
  1399. if (files) {
  1400. for (var i=0; i<files.length; i++) {
  1401. var deleteAction = this.findFileEl(files[i]).children("td.date").children(".action.delete");
  1402. deleteAction.removeClass('icon-delete').addClass('icon-loading-small');
  1403. }
  1404. }
  1405. // Finish any existing actions
  1406. if (this.lastAction) {
  1407. this.lastAction();
  1408. }
  1409. params = {
  1410. dir: dir || this.getCurrentDirectory()
  1411. };
  1412. if (files) {
  1413. params.files = JSON.stringify(files);
  1414. }
  1415. else {
  1416. // no files passed, delete all in current dir
  1417. params.allfiles = true;
  1418. // show spinner for all files
  1419. this.$fileList.find('tr>td.date .action.delete').removeClass('icon-delete').addClass('icon-loading-small');
  1420. }
  1421. $.post(OC.filePath('files', 'ajax', 'delete.php'),
  1422. params,
  1423. function(result) {
  1424. if (result.status === 'success') {
  1425. if (params.allfiles) {
  1426. self.setFiles([]);
  1427. }
  1428. else {
  1429. $.each(files,function(index,file) {
  1430. var fileEl = self.remove(file, {updateSummary: false});
  1431. // FIXME: not sure why we need this after the
  1432. // element isn't even in the DOM any more
  1433. fileEl.find('.selectCheckBox').prop('checked', false);
  1434. fileEl.removeClass('selected');
  1435. self.fileSummary.remove({type: fileEl.attr('data-type'), size: fileEl.attr('data-size')});
  1436. });
  1437. }
  1438. // TODO: this info should be returned by the ajax call!
  1439. self.updateEmptyContent();
  1440. self.fileSummary.update();
  1441. self.updateSelectionSummary();
  1442. self.updateStorageStatistics();
  1443. } else {
  1444. if (result.status === 'error' && result.data.message) {
  1445. OC.Notification.show(result.data.message);
  1446. }
  1447. else {
  1448. OC.Notification.show(t('files', 'Error deleting file.'));
  1449. }
  1450. // hide notification after 10 sec
  1451. setTimeout(function() {
  1452. OC.Notification.hide();
  1453. }, 10000);
  1454. if (params.allfiles) {
  1455. // reload the page as we don't know what files were deleted
  1456. // and which ones remain
  1457. self.reload();
  1458. }
  1459. else {
  1460. $.each(files,function(index,file) {
  1461. var deleteAction = self.findFileEl(file).find('.action.delete');
  1462. deleteAction.removeClass('icon-loading-small').addClass('icon-delete');
  1463. });
  1464. }
  1465. }
  1466. });
  1467. },
  1468. /**
  1469. * Creates the file summary section
  1470. */
  1471. _createSummary: function() {
  1472. var $tr = $('<tr class="summary"></tr>');
  1473. this.$el.find('tfoot').append($tr);
  1474. return new OCA.Files.FileSummary($tr);
  1475. },
  1476. updateEmptyContent: function() {
  1477. var permissions = this.getDirectoryPermissions();
  1478. var isCreatable = (permissions & OC.PERMISSION_CREATE) !== 0;
  1479. this.$el.find('#emptycontent').toggleClass('hidden', !isCreatable || !this.isEmpty);
  1480. this.$el.find('#filestable thead th').toggleClass('hidden', this.isEmpty);
  1481. },
  1482. /**
  1483. * Shows the loading mask.
  1484. *
  1485. * @see OCA.Files.FileList#hideMask
  1486. */
  1487. showMask: function() {
  1488. // in case one was shown before
  1489. var $mask = this.$el.find('.mask');
  1490. if ($mask.exists()) {
  1491. return;
  1492. }
  1493. this.$table.addClass('hidden');
  1494. $mask = $('<div class="mask transparent"></div>');
  1495. $mask.css('background-image', 'url('+ OC.imagePath('core', 'loading.gif') + ')');
  1496. $mask.css('background-repeat', 'no-repeat');
  1497. this.$el.append($mask);
  1498. $mask.removeClass('transparent');
  1499. },
  1500. /**
  1501. * Hide the loading mask.
  1502. * @see OCA.Files.FileList#showMask
  1503. */
  1504. hideMask: function() {
  1505. this.$el.find('.mask').remove();
  1506. this.$table.removeClass('hidden');
  1507. },
  1508. scrollTo:function(file) {
  1509. if (!_.isArray(file)) {
  1510. file = [file];
  1511. }
  1512. this.highlightFiles(file, function($tr) {
  1513. $tr.addClass('searchresult');
  1514. $tr.one('hover', function() {
  1515. $tr.removeClass('searchresult');
  1516. });
  1517. });
  1518. },
  1519. /**
  1520. * @deprecated use setFilter(filter)
  1521. */
  1522. filter:function(query) {
  1523. this.setFilter('');
  1524. },
  1525. /**
  1526. * @deprecated use setFilter('')
  1527. */
  1528. unfilter:function() {
  1529. this.setFilter('');
  1530. },
  1531. /**
  1532. * hide files matching the given filter
  1533. * @param filter
  1534. */
  1535. setFilter:function(filter) {
  1536. this._filter = filter;
  1537. this.fileSummary.setFilter(filter, this.files);
  1538. if (!this.$el.find('.mask').exists()) {
  1539. this.hideIrrelevantUIWhenNoFilesMatch();
  1540. }
  1541. var that = this;
  1542. this.$fileList.find('tr').each(function(i,e) {
  1543. var $e = $(e);
  1544. if ($e.data('file').toString().toLowerCase().indexOf(filter.toLowerCase()) === -1) {
  1545. $e.addClass('hidden');
  1546. that.$container.trigger('scroll');
  1547. } else {
  1548. $e.removeClass('hidden');
  1549. }
  1550. });
  1551. },
  1552. hideIrrelevantUIWhenNoFilesMatch:function() {
  1553. if (this._filter && this.fileSummary.summary.totalDirs + this.fileSummary.summary.totalFiles === 0) {
  1554. this.$el.find('#filestable thead th').addClass('hidden');
  1555. this.$el.find('#emptycontent').addClass('hidden');
  1556. if ( $('#searchresults').length === 0 || $('#searchresults').hasClass('hidden') ) {
  1557. this.$el.find('.nofilterresults').removeClass('hidden').
  1558. find('p').text(t('files', "No entries in this folder match '{filter}'", {filter:this._filter}, null, {'escape': false}));
  1559. }
  1560. } else {
  1561. this.$el.find('#filestable thead th').toggleClass('hidden', this.isEmpty);
  1562. if (!this.$el.find('.mask').exists()) {
  1563. this.$el.find('#emptycontent').toggleClass('hidden', !this.isEmpty);
  1564. }
  1565. this.$el.find('.nofilterresults').addClass('hidden');
  1566. }
  1567. },
  1568. /**
  1569. * get the current filter
  1570. * @param filter
  1571. */
  1572. getFilter:function(filter) {
  1573. return this._filter;
  1574. },
  1575. /**
  1576. * update the search object to use this filelist when filtering
  1577. */
  1578. updateSearch:function() {
  1579. if (OCA.Search.files) {
  1580. OCA.Search.files.setFileList(this);
  1581. }
  1582. if (OC.Search) {
  1583. OC.Search.clear();
  1584. }
  1585. },
  1586. /**
  1587. * Update UI based on the current selection
  1588. */
  1589. updateSelectionSummary: function() {
  1590. var summary = this._selectionSummary.summary;
  1591. var canDelete;
  1592. if (summary.totalFiles === 0 && summary.totalDirs === 0) {
  1593. this.$el.find('#headerName a.name>span:first').text(t('files','Name'));
  1594. this.$el.find('#headerSize a>span:first').text(t('files','Size'));
  1595. this.$el.find('#modified a>span:first').text(t('files','Modified'));
  1596. this.$el.find('table').removeClass('multiselect');
  1597. this.$el.find('.selectedActions').addClass('hidden');
  1598. }
  1599. else {
  1600. canDelete = (this.getDirectoryPermissions() & OC.PERMISSION_DELETE) && this.isSelectedDeletable();
  1601. this.$el.find('.selectedActions').removeClass('hidden');
  1602. this.$el.find('#headerSize a>span:first').text(OC.Util.humanFileSize(summary.totalSize));
  1603. var selection = '';
  1604. if (summary.totalDirs > 0) {
  1605. selection += n('files', '%n folder', '%n folders', summary.totalDirs);
  1606. if (summary.totalFiles > 0) {
  1607. selection += ' & ';
  1608. }
  1609. }
  1610. if (summary.totalFiles > 0) {
  1611. selection += n('files', '%n file', '%n files', summary.totalFiles);
  1612. }
  1613. this.$el.find('#headerName a.name>span:first').text(selection);
  1614. this.$el.find('#modified a>span:first').text('');
  1615. this.$el.find('table').addClass('multiselect');
  1616. this.$el.find('.delete-selected').toggleClass('hidden', !canDelete);
  1617. }
  1618. },
  1619. /**
  1620. * Check whether all selected files are deletable
  1621. */
  1622. isSelectedDeletable: function() {
  1623. return _.reduce(this.getSelectedFiles(), function(deletable, file) {
  1624. return deletable && (file.permissions & OC.PERMISSION_DELETE);
  1625. }, true);
  1626. },
  1627. /**
  1628. * Returns whether all files are selected
  1629. * @return true if all files are selected, false otherwise
  1630. */
  1631. isAllSelected: function() {
  1632. return this.$el.find('.select-all').prop('checked');
  1633. },
  1634. /**
  1635. * Returns the file info of the selected files
  1636. *
  1637. * @return array of file names
  1638. */
  1639. getSelectedFiles: function() {
  1640. return _.values(this._selectedFiles);
  1641. },
  1642. getUniqueName: function(name) {
  1643. if (this.findFileEl(name).exists()) {
  1644. var numMatch;
  1645. var parts=name.split('.');
  1646. var extension = "";
  1647. if (parts.length > 1) {
  1648. extension=parts.pop();
  1649. }
  1650. var base=parts.join('.');
  1651. numMatch=base.match(/\((\d+)\)/);
  1652. var num=2;
  1653. if (numMatch && numMatch.length>0) {
  1654. num=parseInt(numMatch[numMatch.length-1], 10)+1;
  1655. base=base.split('(');
  1656. base.pop();
  1657. base=$.trim(base.join('('));
  1658. }
  1659. name=base+' ('+num+')';
  1660. if (extension) {
  1661. name = name+'.'+extension;
  1662. }
  1663. // FIXME: ugly recursion
  1664. return this.getUniqueName(name);
  1665. }
  1666. return name;
  1667. },
  1668. /**
  1669. * Shows a "permission denied" notification
  1670. */
  1671. _showPermissionDeniedNotification: function() {
  1672. var message = t('core', 'You don’t have permission to upload or create files here');
  1673. OC.Notification.show(message);
  1674. //hide notification after 10 sec
  1675. setTimeout(function() {
  1676. OC.Notification.hide();
  1677. }, 5000);
  1678. },
  1679. /**
  1680. * Setup file upload events related to the file-upload plugin
  1681. */
  1682. setupUploadEvents: function() {
  1683. var self = this;
  1684. // handle upload events
  1685. var fileUploadStart = this.$el.find('#file_upload_start');
  1686. // detect the progress bar resize
  1687. fileUploadStart.on('resized', this._onResize);
  1688. fileUploadStart.on('fileuploaddrop', function(e, data) {
  1689. OC.Upload.log('filelist handle fileuploaddrop', e, data);
  1690. if (self.$el.hasClass('hidden')) {
  1691. // do not upload to invisible lists
  1692. return false;
  1693. }
  1694. var dropTarget = $(e.originalEvent.target);
  1695. // check if dropped inside this container and not another one
  1696. if (dropTarget.length
  1697. && !self.$el.is(dropTarget) // dropped on list directly
  1698. && !self.$el.has(dropTarget).length // dropped inside list
  1699. && !dropTarget.is(self.$container) // dropped on main container
  1700. ) {
  1701. return false;
  1702. }
  1703. // find the closest tr or crumb to use as target
  1704. dropTarget = dropTarget.closest('tr, .crumb');
  1705. // if dropping on tr or crumb, drag&drop upload to folder
  1706. if (dropTarget && (dropTarget.data('type') === 'dir' ||
  1707. dropTarget.hasClass('crumb'))) {
  1708. // remember as context
  1709. data.context = dropTarget;
  1710. // if permissions are specified, only allow if create permission is there
  1711. var permissions = dropTarget.data('permissions');
  1712. if (!_.isUndefined(permissions) && (permissions & OC.PERMISSION_CREATE) === 0) {
  1713. self._showPermissionDeniedNotification();
  1714. return false;
  1715. }
  1716. var dir = dropTarget.data('file');
  1717. // if from file list, need to prepend parent dir
  1718. if (dir) {
  1719. var parentDir = self.getCurrentDirectory();
  1720. if (parentDir[parentDir.length - 1] !== '/') {
  1721. parentDir += '/';
  1722. }
  1723. dir = parentDir + dir;
  1724. }
  1725. else{
  1726. // read full path from crumb
  1727. dir = dropTarget.data('dir') || '/';
  1728. }
  1729. // add target dir
  1730. data.targetDir = dir;
  1731. } else {
  1732. // we are dropping somewhere inside the file list, which will
  1733. // upload the file to the current directory
  1734. data.targetDir = self.getCurrentDirectory();
  1735. // cancel uploads to current dir if no permission
  1736. var isCreatable = (self.getDirectoryPermissions() & OC.PERMISSION_CREATE) !== 0;
  1737. if (!isCreatable) {
  1738. self._showPermissionDeniedNotification();
  1739. return false;
  1740. }
  1741. }
  1742. });
  1743. fileUploadStart.on('fileuploadadd', function(e, data) {
  1744. OC.Upload.log('filelist handle fileuploadadd', e, data);
  1745. //finish delete if we are uploading a deleted file
  1746. if (self.deleteFiles && self.deleteFiles.indexOf(data.files[0].name)!==-1) {
  1747. self.finishDelete(null, true); //delete file before continuing
  1748. }
  1749. // add ui visualization to existing folder
  1750. if (data.context && data.context.data('type') === 'dir') {
  1751. // add to existing folder
  1752. // update upload counter ui
  1753. var uploadText = data.context.find('.uploadtext');
  1754. var currentUploads = parseInt(uploadText.attr('currentUploads'), 10);
  1755. currentUploads += 1;
  1756. uploadText.attr('currentUploads', currentUploads);
  1757. var translatedText = n('files', 'Uploading %n file', 'Uploading %n files', currentUploads);
  1758. if (currentUploads === 1) {
  1759. var img = OC.imagePath('core', 'loading.gif');
  1760. data.context.find('.thumbnail').css('background-image', 'url(' + img + ')');
  1761. uploadText.text(translatedText);
  1762. uploadText.show();
  1763. } else {
  1764. uploadText.text(translatedText);
  1765. }
  1766. }
  1767. });
  1768. /*
  1769. * when file upload done successfully add row to filelist
  1770. * update counter when uploading to sub folder
  1771. */
  1772. fileUploadStart.on('fileuploaddone', function(e, data) {
  1773. OC.Upload.log('filelist handle fileuploaddone', e, data);
  1774. var response;
  1775. if (typeof data.result === 'string') {
  1776. response = data.result;
  1777. } else {
  1778. // fetch response from iframe
  1779. response = data.result[0].body.innerText;
  1780. }
  1781. var result=$.parseJSON(response);
  1782. if (typeof result[0] !== 'undefined' && result[0].status === 'success') {
  1783. var file = result[0];
  1784. var size = 0;
  1785. if (data.context && data.context.data('type') === 'dir') {
  1786. // update upload counter ui
  1787. var uploadText = data.context.find('.uploadtext');
  1788. var currentUploads = parseInt(uploadText.attr('currentUploads'), 10);
  1789. currentUploads -= 1;
  1790. uploadText.attr('currentUploads', currentUploads);
  1791. var translatedText = n('files', 'Uploading %n file', 'Uploading %n files', currentUploads);
  1792. if (currentUploads === 0) {
  1793. var img = OC.imagePath('core', 'filetypes/folder');
  1794. data.context.find('.thumbnail').css('background-image', 'url(' + img + ')');
  1795. uploadText.text(translatedText);
  1796. uploadText.hide();
  1797. } else {
  1798. uploadText.text(translatedText);
  1799. }
  1800. // update folder size
  1801. size = parseInt(data.context.data('size'), 10);
  1802. size += parseInt(file.size, 10);
  1803. data.context.attr('data-size', size);
  1804. data.context.find('td.filesize').text(humanFileSize(size));
  1805. } else {
  1806. // only append new file if uploaded into the current folder
  1807. if (file.directory !== self.getCurrentDirectory()) {
  1808. // Uploading folders actually uploads a list of files
  1809. // for which the target directory (file.directory) might lie deeper
  1810. // than the current directory
  1811. var fileDirectory = file.directory.replace('/','').replace(/\/$/, "");
  1812. var currentDirectory = self.getCurrentDirectory().replace('/','').replace(/\/$/, "") + '/';
  1813. if (currentDirectory !== '/') {
  1814. // abort if fileDirectory does not start with current one
  1815. if (fileDirectory.indexOf(currentDirectory) !== 0) {
  1816. return;
  1817. }
  1818. // remove the current directory part
  1819. fileDirectory = fileDirectory.substr(currentDirectory.length);
  1820. }
  1821. // only take the first section of the path
  1822. fileDirectory = fileDirectory.split('/');
  1823. var fd;
  1824. // if the first section exists / is a subdir
  1825. if (fileDirectory.length) {
  1826. fileDirectory = fileDirectory[0];
  1827. // See whether it is already in the list
  1828. fd = self.findFileEl(fileDirectory);
  1829. if (fd.length === 0) {
  1830. var dir = {
  1831. name: fileDirectory,
  1832. type: 'dir',
  1833. mimetype: 'httpd/unix-directory',
  1834. permissions: file.permissions,
  1835. size: 0,
  1836. id: file.parentId
  1837. };
  1838. fd = self.add(dir, {insert: true});
  1839. }
  1840. // update folder size
  1841. size = parseInt(fd.attr('data-size'), 10);
  1842. size += parseInt(file.size, 10);
  1843. fd.attr('data-size', size);
  1844. fd.find('td.filesize').text(OC.Util.humanFileSize(size));
  1845. }
  1846. return;
  1847. }
  1848. // add as stand-alone row to filelist
  1849. size = t('files', 'Pending');
  1850. if (data.files[0].size>=0) {
  1851. size=data.files[0].size;
  1852. }
  1853. //should the file exist in the list remove it
  1854. self.remove(file.name);
  1855. // create new file context
  1856. data.context = self.add(file, {animate: true});
  1857. }
  1858. }
  1859. });
  1860. fileUploadStart.on('fileuploadstop', function(e, data) {
  1861. OC.Upload.log('filelist handle fileuploadstop', e, data);
  1862. //if user pressed cancel hide upload chrome
  1863. if (data.errorThrown === 'abort') {
  1864. //cleanup uploading to a dir
  1865. var uploadText = $('tr .uploadtext');
  1866. var img = OC.imagePath('core', 'filetypes/folder');
  1867. uploadText.parents('td.filename').find('.thumbnail').css('background-image', 'url(' + img + ')');
  1868. uploadText.fadeOut();
  1869. uploadText.attr('currentUploads', 0);
  1870. }
  1871. self.updateStorageStatistics();
  1872. });
  1873. fileUploadStart.on('fileuploadfail', function(e, data) {
  1874. OC.Upload.log('filelist handle fileuploadfail', e, data);
  1875. //if user pressed cancel hide upload chrome
  1876. if (data.errorThrown === 'abort') {
  1877. //cleanup uploading to a dir
  1878. var uploadText = $('tr .uploadtext');
  1879. var img = OC.imagePath('core', 'filetypes/folder');
  1880. uploadText.parents('td.filename').find('.thumbnail').css('background-image', 'url(' + img + ')');
  1881. uploadText.fadeOut();
  1882. uploadText.attr('currentUploads', 0);
  1883. }
  1884. self.updateStorageStatistics();
  1885. });
  1886. },
  1887. /**
  1888. * Scroll to the last file of the given list
  1889. * Highlight the list of files
  1890. * @param files array of filenames,
  1891. * @param {Function} [highlightFunction] optional function
  1892. * to be called after the scrolling is finished
  1893. */
  1894. highlightFiles: function(files, highlightFunction) {
  1895. // Detection of the uploaded element
  1896. var filename = files[files.length - 1];
  1897. var $fileRow = this.findFileEl(filename);
  1898. while(!$fileRow.exists() && this._nextPage(false) !== false) { // Checking element existence
  1899. $fileRow = this.findFileEl(filename);
  1900. }
  1901. if (!$fileRow.exists()) { // Element not present in the file list
  1902. return;
  1903. }
  1904. var currentOffset = this.$container.scrollTop();
  1905. var additionalOffset = this.$el.find("#controls").height()+this.$el.find("#controls").offset().top;
  1906. // Animation
  1907. var _this = this;
  1908. var $scrollContainer = this.$container;
  1909. if ($scrollContainer[0] === window) {
  1910. // need to use "body" to animate scrolling
  1911. // when the scroll container is the window
  1912. $scrollContainer = $('body');
  1913. }
  1914. $scrollContainer.animate({
  1915. // Scrolling to the top of the new element
  1916. scrollTop: currentOffset + $fileRow.offset().top - $fileRow.height() * 2 - additionalOffset
  1917. }, {
  1918. duration: 500,
  1919. complete: function() {
  1920. // Highlighting function
  1921. var highlightRow = highlightFunction;
  1922. if (!highlightRow) {
  1923. highlightRow = function($fileRow) {
  1924. $fileRow.addClass("highlightUploaded");
  1925. setTimeout(function() {
  1926. $fileRow.removeClass("highlightUploaded");
  1927. }, 2500);
  1928. };
  1929. }
  1930. // Loop over uploaded files
  1931. for(var i=0; i<files.length; i++) {
  1932. var $fileRow = _this.findFileEl(files[i]);
  1933. if($fileRow.length !== 0) { // Checking element existence
  1934. highlightRow($fileRow);
  1935. }
  1936. }
  1937. }
  1938. });
  1939. }
  1940. };
  1941. /**
  1942. * Sort comparators.
  1943. * @namespace OCA.Files.FileList.Comparators
  1944. * @private
  1945. */
  1946. FileList.Comparators = {
  1947. /**
  1948. * Compares two file infos by name, making directories appear
  1949. * first.
  1950. *
  1951. * @param {OCA.Files.FileInfo} fileInfo1 file info
  1952. * @param {OCA.Files.FileInfo} fileInfo2 file info
  1953. * @return {int} -1 if the first file must appear before the second one,
  1954. * 0 if they are identify, 1 otherwise.
  1955. */
  1956. name: function(fileInfo1, fileInfo2) {
  1957. if (fileInfo1.type === 'dir' && fileInfo2.type !== 'dir') {
  1958. return -1;
  1959. }
  1960. if (fileInfo1.type !== 'dir' && fileInfo2.type === 'dir') {
  1961. return 1;
  1962. }
  1963. return OC.Util.naturalSortCompare(fileInfo1.name, fileInfo2.name);
  1964. },
  1965. /**
  1966. * Compares two file infos by size.
  1967. *
  1968. * @param {OCA.Files.FileInfo} fileInfo1 file info
  1969. * @param {OCA.Files.FileInfo} fileInfo2 file info
  1970. * @return {int} -1 if the first file must appear before the second one,
  1971. * 0 if they are identify, 1 otherwise.
  1972. */
  1973. size: function(fileInfo1, fileInfo2) {
  1974. return fileInfo1.size - fileInfo2.size;
  1975. },
  1976. /**
  1977. * Compares two file infos by timestamp.
  1978. *
  1979. * @param {OCA.Files.FileInfo} fileInfo1 file info
  1980. * @param {OCA.Files.FileInfo} fileInfo2 file info
  1981. * @return {int} -1 if the first file must appear before the second one,
  1982. * 0 if they are identify, 1 otherwise.
  1983. */
  1984. mtime: function(fileInfo1, fileInfo2) {
  1985. return fileInfo1.mtime - fileInfo2.mtime;
  1986. }
  1987. };
  1988. /**
  1989. * File info attributes.
  1990. *
  1991. * @todo make this a real class in the future
  1992. * @typedef {Object} OCA.Files.FileInfo
  1993. *
  1994. * @property {int} id file id
  1995. * @property {String} name file name
  1996. * @property {String} [path] file path, defaults to the list's current path
  1997. * @property {String} mimetype mime type
  1998. * @property {String} type "file" for files or "dir" for directories
  1999. * @property {int} permissions file permissions
  2000. * @property {int} mtime modification time in milliseconds
  2001. * @property {boolean} [isShareMountPoint] whether the file is a share mount
  2002. * point
  2003. * @property {boolean} [isPreviewAvailable] whether a preview is available
  2004. * for the given file type
  2005. * @property {String} [icon] path to the mime type icon
  2006. * @property {String} etag etag of the file
  2007. */
  2008. OCA.Files.FileList = FileList;
  2009. })();
  2010. $(document).ready(function() {
  2011. // FIXME: unused ?
  2012. OCA.Files.FileList.useUndo = (window.onbeforeunload)?true:false;
  2013. $(window).bind('beforeunload', function () {
  2014. if (OCA.Files.FileList.lastAction) {
  2015. OCA.Files.FileList.lastAction();
  2016. }
  2017. });
  2018. $(window).unload(function () {
  2019. $(window).trigger('beforeunload');
  2020. });
  2021. });