You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

filelist.js 84KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961
  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. var TEMPLATE_ADDBUTTON = '<a href="#" class="button new">' +
  12. '<span class="icon {{iconClass}}"></span>' +
  13. '<span class="hidden-visually">{{addText}}</span>' +
  14. '</a>';
  15. /**
  16. * @class OCA.Files.FileList
  17. * @classdesc
  18. *
  19. * The FileList class manages a file list view.
  20. * A file list view consists of a controls bar and
  21. * a file list table.
  22. *
  23. * @param $el container element with existing markup for the #controls
  24. * and a table
  25. * @param {Object} [options] map of options, see other parameters
  26. * @param {Object} [options.scrollContainer] scrollable container, defaults to $(window)
  27. * @param {Object} [options.dragOptions] drag options, disabled by default
  28. * @param {Object} [options.folderDropOptions] folder drop options, disabled by default
  29. * @param {boolean} [options.detailsViewEnabled=true] whether to enable details view
  30. * @param {OC.Files.Client} [options.filesClient] files client to use
  31. */
  32. var FileList = function($el, options) {
  33. this.initialize($el, options);
  34. };
  35. /**
  36. * @memberof OCA.Files
  37. */
  38. FileList.prototype = {
  39. SORT_INDICATOR_ASC_CLASS: 'icon-triangle-n',
  40. SORT_INDICATOR_DESC_CLASS: 'icon-triangle-s',
  41. id: 'files',
  42. appName: t('files', 'Files'),
  43. isEmpty: true,
  44. useUndo:true,
  45. /**
  46. * Top-level container with controls and file list
  47. */
  48. $el: null,
  49. /**
  50. * Files table
  51. */
  52. $table: null,
  53. /**
  54. * List of rows (table tbody)
  55. */
  56. $fileList: null,
  57. /**
  58. * @type OCA.Files.BreadCrumb
  59. */
  60. breadcrumb: null,
  61. /**
  62. * @type OCA.Files.FileSummary
  63. */
  64. fileSummary: null,
  65. /**
  66. * @type OCA.Files.DetailsView
  67. */
  68. _detailsView: null,
  69. /**
  70. * Files client instance
  71. *
  72. * @type OC.Files.Client
  73. */
  74. filesClient: null,
  75. /**
  76. * Whether the file list was initialized already.
  77. * @type boolean
  78. */
  79. initialized: false,
  80. /**
  81. * Number of files per page
  82. *
  83. * @return {int} page size
  84. */
  85. pageSize: function() {
  86. return Math.ceil(this.$container.height() / 50);
  87. },
  88. /**
  89. * Array of files in the current folder.
  90. * The entries are of file data.
  91. *
  92. * @type Array.<OC.Files.FileInfo>
  93. */
  94. files: [],
  95. /**
  96. * Current directory entry
  97. *
  98. * @type OC.Files.FileInfo
  99. */
  100. dirInfo: null,
  101. /**
  102. * File actions handler, defaults to OCA.Files.FileActions
  103. * @type OCA.Files.FileActions
  104. */
  105. fileActions: null,
  106. /**
  107. * Whether selection is allowed, checkboxes and selection overlay will
  108. * be rendered
  109. */
  110. _allowSelection: true,
  111. /**
  112. * Map of file id to file data
  113. * @type Object.<int, Object>
  114. */
  115. _selectedFiles: {},
  116. /**
  117. * Summary of selected files.
  118. * @type OCA.Files.FileSummary
  119. */
  120. _selectionSummary: null,
  121. /**
  122. * If not empty, only files containing this string will be shown
  123. * @type String
  124. */
  125. _filter: '',
  126. /**
  127. * @type Backbone.Model
  128. */
  129. _filesConfig: undefined,
  130. /**
  131. * Sort attribute
  132. * @type String
  133. */
  134. _sort: 'name',
  135. /**
  136. * Sort direction: 'asc' or 'desc'
  137. * @type String
  138. */
  139. _sortDirection: 'asc',
  140. /**
  141. * Sort comparator function for the current sort
  142. * @type Function
  143. */
  144. _sortComparator: null,
  145. /**
  146. * Whether to do a client side sort.
  147. * When false, clicking on a table header will call reload().
  148. * When true, clicking on a table header will simply resort the list.
  149. */
  150. _clientSideSort: true,
  151. /**
  152. * Current directory
  153. * @type String
  154. */
  155. _currentDirectory: null,
  156. _dragOptions: null,
  157. _folderDropOptions: null,
  158. /**
  159. * Initialize the file list and its components
  160. *
  161. * @param $el container element with existing markup for the #controls
  162. * and a table
  163. * @param options map of options, see other parameters
  164. * @param options.scrollContainer scrollable container, defaults to $(window)
  165. * @param options.dragOptions drag options, disabled by default
  166. * @param options.folderDropOptions folder drop options, disabled by default
  167. * @param options.scrollTo name of file to scroll to after the first load
  168. * @param {OC.Files.Client} [options.filesClient] files API client
  169. * @private
  170. */
  171. initialize: function($el, options) {
  172. var self = this;
  173. options = options || {};
  174. if (this.initialized) {
  175. return;
  176. }
  177. if (options.config) {
  178. this._filesConfig = options.config;
  179. } else if (!_.isUndefined(OCA.Files) && !_.isUndefined(OCA.Files.App)) {
  180. this._filesConfig = OCA.Files.App.getFilesConfig();
  181. }
  182. if (!_.isUndefined(this._filesConfig)) {
  183. this._filesConfig.on('change:showhidden', function() {
  184. self.setFiles(self.files);
  185. });
  186. }
  187. if (options.dragOptions) {
  188. this._dragOptions = options.dragOptions;
  189. }
  190. if (options.folderDropOptions) {
  191. this._folderDropOptions = options.folderDropOptions;
  192. }
  193. if (options.filesClient) {
  194. this.filesClient = options.filesClient;
  195. } else {
  196. // default client if not specified
  197. this.filesClient = OC.Files.getClient();
  198. }
  199. this.$el = $el;
  200. if (options.id) {
  201. this.id = options.id;
  202. }
  203. this.$container = options.scrollContainer || $(window);
  204. this.$table = $el.find('table:first');
  205. this.$fileList = $el.find('#fileList');
  206. if (_.isUndefined(options.detailsViewEnabled) || options.detailsViewEnabled) {
  207. this._detailsView = new OCA.Files.DetailsView();
  208. this._detailsView.$el.insertBefore(this.$el);
  209. this._detailsView.$el.addClass('disappear');
  210. }
  211. this._initFileActions(options.fileActions);
  212. if (this._detailsView) {
  213. this._detailsView.addDetailView(new OCA.Files.MainFileInfoDetailView({fileList: this, fileActions: this.fileActions}));
  214. }
  215. this.files = [];
  216. this._selectedFiles = {};
  217. this._selectionSummary = new OCA.Files.FileSummary();
  218. // dummy root dir info
  219. this.dirInfo = new OC.Files.FileInfo({});
  220. this.fileSummary = this._createSummary();
  221. if (options.sorting) {
  222. this.setSort(options.sorting.mode, options.sorting.direction, false, false);
  223. } else {
  224. this.setSort('name', 'asc', false, false);
  225. }
  226. var breadcrumbOptions = {
  227. onClick: _.bind(this._onClickBreadCrumb, this),
  228. getCrumbUrl: function(part) {
  229. return self.linkTo(part.dir);
  230. }
  231. };
  232. // if dropping on folders is allowed, then also allow on breadcrumbs
  233. if (this._folderDropOptions) {
  234. breadcrumbOptions.onDrop = _.bind(this._onDropOnBreadCrumb, this);
  235. breadcrumbOptions.onOver = function() {
  236. self.$el.find('td.filename.ui-droppable').droppable('disable');
  237. }
  238. breadcrumbOptions.onOut = function() {
  239. self.$el.find('td.filename.ui-droppable').droppable('enable');
  240. }
  241. }
  242. this.breadcrumb = new OCA.Files.BreadCrumb(breadcrumbOptions);
  243. var $controls = this.$el.find('#controls');
  244. if ($controls.length > 0) {
  245. $controls.prepend(this.breadcrumb.$el);
  246. this.$table.addClass('has-controls');
  247. }
  248. this._renderNewButton();
  249. this.$el.find('thead th .columntitle').click(_.bind(this._onClickHeader, this));
  250. this._onResize = _.debounce(_.bind(this._onResize, this), 100);
  251. $('#app-content').on('appresized', this._onResize);
  252. $(window).resize(this._onResize);
  253. this.$el.on('show', this._onResize);
  254. this.updateSearch();
  255. this.$fileList.on('click','td.filename>a.name, td.filesize, td.date', _.bind(this._onClickFile, this));
  256. this.$fileList.on('change', 'td.filename>.selectCheckBox', _.bind(this._onClickFileCheckbox, this));
  257. this.$el.on('urlChanged', _.bind(this._onUrlChanged, this));
  258. this.$el.find('.select-all').click(_.bind(this._onClickSelectAll, this));
  259. this.$el.find('.download').click(_.bind(this._onClickDownloadSelected, this));
  260. this.$el.find('.delete-selected').click(_.bind(this._onClickDeleteSelected, this));
  261. this.$el.find('.selectedActions a').tooltip({placement:'top'});
  262. this.setupUploadEvents();
  263. this.$container.on('scroll', _.bind(this._onScroll, this));
  264. if (options.scrollTo) {
  265. this.$fileList.one('updated', function() {
  266. self.scrollTo(options.scrollTo);
  267. });
  268. }
  269. OC.Plugins.attach('OCA.Files.FileList', this);
  270. },
  271. /**
  272. * Destroy / uninitialize this instance.
  273. */
  274. destroy: function() {
  275. if (this._newFileMenu) {
  276. this._newFileMenu.remove();
  277. }
  278. if (this._newButton) {
  279. this._newButton.remove();
  280. }
  281. if (this._detailsView) {
  282. this._detailsView.remove();
  283. }
  284. // TODO: also unregister other event handlers
  285. this.fileActions.off('registerAction', this._onFileActionsUpdated);
  286. this.fileActions.off('setDefault', this._onFileActionsUpdated);
  287. OC.Plugins.detach('OCA.Files.FileList', this);
  288. $('#app-content').off('appresized', this._onResize);
  289. },
  290. /**
  291. * Initializes the file actions, set up listeners.
  292. *
  293. * @param {OCA.Files.FileActions} fileActions file actions
  294. */
  295. _initFileActions: function(fileActions) {
  296. var self = this;
  297. this.fileActions = fileActions;
  298. if (!this.fileActions) {
  299. this.fileActions = new OCA.Files.FileActions();
  300. this.fileActions.registerDefaultActions();
  301. }
  302. if (this._detailsView) {
  303. this.fileActions.registerAction({
  304. name: 'Details',
  305. displayName: t('files', 'Details'),
  306. mime: 'all',
  307. order: -50,
  308. iconClass: 'icon-details',
  309. permissions: OC.PERMISSION_READ,
  310. actionHandler: function(fileName, context) {
  311. self._updateDetailsView(fileName);
  312. }
  313. });
  314. }
  315. this._onFileActionsUpdated = _.debounce(_.bind(this._onFileActionsUpdated, this), 100);
  316. this.fileActions.on('registerAction', this._onFileActionsUpdated);
  317. this.fileActions.on('setDefault', this._onFileActionsUpdated);
  318. },
  319. /**
  320. * Returns a unique model for the given file name.
  321. *
  322. * @param {string|object} fileName file name or jquery row
  323. * @return {OCA.Files.FileInfoModel} file info model
  324. */
  325. getModelForFile: function(fileName) {
  326. var self = this;
  327. var $tr;
  328. // jQuery object ?
  329. if (fileName.is) {
  330. $tr = fileName;
  331. fileName = $tr.attr('data-file');
  332. } else {
  333. $tr = this.findFileEl(fileName);
  334. }
  335. if (!$tr || !$tr.length) {
  336. return null;
  337. }
  338. // if requesting the selected model, return it
  339. if (this._currentFileModel && this._currentFileModel.get('name') === fileName) {
  340. return this._currentFileModel;
  341. }
  342. // TODO: note, this is a temporary model required for synchronising
  343. // state between different views.
  344. // In the future the FileList should work with Backbone.Collection
  345. // and contain existing models that can be used.
  346. // This method would in the future simply retrieve the matching model from the collection.
  347. var model = new OCA.Files.FileInfoModel(this.elementToFile($tr));
  348. if (!model.get('path')) {
  349. model.set('path', this.getCurrentDirectory(), {silent: true});
  350. }
  351. model.on('change', function(model) {
  352. // re-render row
  353. var highlightState = $tr.hasClass('highlighted');
  354. $tr = self.updateRow(
  355. $tr,
  356. model.toJSON(),
  357. {updateSummary: true, silent: false, animate: true}
  358. );
  359. // restore selection state
  360. var selected = !!self._selectedFiles[$tr.data('id')];
  361. self._selectFileEl($tr, selected);
  362. $tr.toggleClass('highlighted', highlightState);
  363. });
  364. model.on('busy', function(model, state) {
  365. self.showFileBusyState($tr, state);
  366. });
  367. return model;
  368. },
  369. /**
  370. * Displays the details view for the given file and
  371. * selects the given tab
  372. *
  373. * @param {string} fileName file name for which to show details
  374. * @param {string} [tabId] optional tab id to select
  375. */
  376. showDetailsView: function(fileName, tabId) {
  377. this._updateDetailsView(fileName);
  378. if (tabId) {
  379. this._detailsView.selectTab(tabId);
  380. }
  381. OC.Apps.showAppSidebar(this._detailsView.$el);
  382. },
  383. /**
  384. * Update the details view to display the given file
  385. *
  386. * @param {string} fileName file name from the current list
  387. * @param {boolean} [show=true] whether to open the sidebar if it was closed
  388. */
  389. _updateDetailsView: function(fileName, show) {
  390. if (!this._detailsView) {
  391. return;
  392. }
  393. // show defaults to true
  394. show = _.isUndefined(show) || !!show;
  395. var oldFileInfo = this._detailsView.getFileInfo();
  396. if (oldFileInfo) {
  397. // TODO: use more efficient way, maybe track the highlight
  398. this.$fileList.children().filterAttr('data-id', '' + oldFileInfo.get('id')).removeClass('highlighted');
  399. oldFileInfo.off('change', this._onSelectedModelChanged, this);
  400. }
  401. if (!fileName) {
  402. this._detailsView.setFileInfo(null);
  403. if (this._currentFileModel) {
  404. this._currentFileModel.off();
  405. }
  406. this._currentFileModel = null;
  407. OC.Apps.hideAppSidebar(this._detailsView.$el);
  408. return;
  409. }
  410. if (show && this._detailsView.$el.hasClass('disappear')) {
  411. OC.Apps.showAppSidebar(this._detailsView.$el);
  412. }
  413. var $tr = this.findFileEl(fileName);
  414. var model = this.getModelForFile($tr);
  415. this._currentFileModel = model;
  416. $tr.addClass('highlighted');
  417. this._detailsView.setFileInfo(model);
  418. this._detailsView.$el.scrollTop(0);
  419. },
  420. /**
  421. * Event handler for when the window size changed
  422. */
  423. _onResize: function() {
  424. var containerWidth = this.$el.width();
  425. var actionsWidth = 0;
  426. $.each(this.$el.find('#controls .actions'), function(index, action) {
  427. actionsWidth += $(action).outerWidth();
  428. });
  429. // subtract app navigation toggle when visible
  430. containerWidth -= $('#app-navigation-toggle').width();
  431. this.breadcrumb.setMaxWidth(containerWidth - actionsWidth - 10);
  432. this.$table.find('>thead').width($('#app-content').width() - OC.Util.getScrollBarWidth());
  433. },
  434. /**
  435. * Event handler for when the URL changed
  436. */
  437. _onUrlChanged: function(e) {
  438. if (e && e.dir) {
  439. this.changeDirectory(e.dir, false, true);
  440. }
  441. },
  442. /**
  443. * Selected/deselects the given file element and updated
  444. * the internal selection cache.
  445. *
  446. * @param {Object} $tr single file row element
  447. * @param {bool} state true to select, false to deselect
  448. */
  449. _selectFileEl: function($tr, state, showDetailsView) {
  450. var $checkbox = $tr.find('td.filename>.selectCheckBox');
  451. var oldData = !!this._selectedFiles[$tr.data('id')];
  452. var data;
  453. $checkbox.prop('checked', state);
  454. $tr.toggleClass('selected', state);
  455. // already selected ?
  456. if (state === oldData) {
  457. return;
  458. }
  459. data = this.elementToFile($tr);
  460. if (state) {
  461. this._selectedFiles[$tr.data('id')] = data;
  462. this._selectionSummary.add(data);
  463. }
  464. else {
  465. delete this._selectedFiles[$tr.data('id')];
  466. this._selectionSummary.remove(data);
  467. }
  468. if (this._detailsView && !this._detailsView.$el.hasClass('disappear')) {
  469. // hide sidebar
  470. this._updateDetailsView(null);
  471. }
  472. this.$el.find('.select-all').prop('checked', this._selectionSummary.getTotal() === this.files.length);
  473. },
  474. /**
  475. * Event handler for when clicking on files to select them
  476. */
  477. _onClickFile: function(event) {
  478. var $tr = $(event.target).closest('tr');
  479. if ($tr.hasClass('dragging')) {
  480. return;
  481. }
  482. if (this._allowSelection && (event.ctrlKey || event.shiftKey)) {
  483. event.preventDefault();
  484. if (event.shiftKey) {
  485. var $lastTr = $(this._lastChecked);
  486. var lastIndex = $lastTr.index();
  487. var currentIndex = $tr.index();
  488. var $rows = this.$fileList.children('tr');
  489. // last clicked checkbox below current one ?
  490. if (lastIndex > currentIndex) {
  491. var aux = lastIndex;
  492. lastIndex = currentIndex;
  493. currentIndex = aux;
  494. }
  495. // auto-select everything in-between
  496. for (var i = lastIndex + 1; i < currentIndex; i++) {
  497. this._selectFileEl($rows.eq(i), true);
  498. }
  499. }
  500. else {
  501. this._lastChecked = $tr;
  502. }
  503. var $checkbox = $tr.find('td.filename>.selectCheckBox');
  504. this._selectFileEl($tr, !$checkbox.prop('checked'));
  505. this.updateSelectionSummary();
  506. } else {
  507. // clicked directly on the name
  508. if (!this._detailsView || $(event.target).is('.nametext') || $(event.target).closest('.nametext').length) {
  509. var filename = $tr.attr('data-file');
  510. var renaming = $tr.data('renaming');
  511. if (!renaming) {
  512. this.fileActions.currentFile = $tr.find('td');
  513. var mime = this.fileActions.getCurrentMimeType();
  514. var type = this.fileActions.getCurrentType();
  515. var permissions = this.fileActions.getCurrentPermissions();
  516. var action = this.fileActions.getDefault(mime,type, permissions);
  517. if (action) {
  518. event.preventDefault();
  519. // also set on global object for legacy apps
  520. window.FileActions.currentFile = this.fileActions.currentFile;
  521. action(filename, {
  522. $file: $tr,
  523. fileList: this,
  524. fileActions: this.fileActions,
  525. dir: $tr.attr('data-path') || this.getCurrentDirectory()
  526. });
  527. }
  528. // deselect row
  529. $(event.target).closest('a').blur();
  530. }
  531. } else {
  532. this._updateDetailsView($tr.attr('data-file'));
  533. event.preventDefault();
  534. }
  535. }
  536. },
  537. /**
  538. * Event handler for when clicking on a file's checkbox
  539. */
  540. _onClickFileCheckbox: function(e) {
  541. var $tr = $(e.target).closest('tr');
  542. var state = !$tr.hasClass('selected');
  543. this._selectFileEl($tr, state);
  544. this._lastChecked = $tr;
  545. this.updateSelectionSummary();
  546. if (this._detailsView && !this._detailsView.$el.hasClass('disappear')) {
  547. // hide sidebar
  548. this._updateDetailsView(null);
  549. }
  550. },
  551. /**
  552. * Event handler for when selecting/deselecting all files
  553. */
  554. _onClickSelectAll: function(e) {
  555. var checked = $(e.target).prop('checked');
  556. this.$fileList.find('td.filename>.selectCheckBox').prop('checked', checked)
  557. .closest('tr').toggleClass('selected', checked);
  558. this._selectedFiles = {};
  559. this._selectionSummary.clear();
  560. if (checked) {
  561. for (var i = 0; i < this.files.length; i++) {
  562. var fileData = this.files[i];
  563. this._selectedFiles[fileData.id] = fileData;
  564. this._selectionSummary.add(fileData);
  565. }
  566. }
  567. this.updateSelectionSummary();
  568. if (this._detailsView && !this._detailsView.$el.hasClass('disappear')) {
  569. // hide sidebar
  570. this._updateDetailsView(null);
  571. }
  572. },
  573. /**
  574. * Event handler for when clicking on "Download" for the selected files
  575. */
  576. _onClickDownloadSelected: function(event) {
  577. var files;
  578. var dir = this.getCurrentDirectory();
  579. if (this.isAllSelected() && this.getSelectedFiles().length > 1) {
  580. files = OC.basename(dir);
  581. dir = OC.dirname(dir) || '/';
  582. }
  583. else {
  584. files = _.pluck(this.getSelectedFiles(), 'name');
  585. }
  586. var downloadFileaction = $('#selectedActionsList').find('.download');
  587. // don't allow a second click on the download action
  588. if(downloadFileaction.hasClass('disabled')) {
  589. event.preventDefault();
  590. return;
  591. }
  592. var disableLoadingState = function(){
  593. OCA.Files.FileActions.updateFileActionSpinner(downloadFileaction, false);
  594. };
  595. OCA.Files.FileActions.updateFileActionSpinner(downloadFileaction, true);
  596. if(this.getSelectedFiles().length > 1) {
  597. OCA.Files.Files.handleDownload(this.getDownloadUrl(files, dir, true), disableLoadingState);
  598. }
  599. else {
  600. first = this.getSelectedFiles()[0];
  601. OCA.Files.Files.handleDownload(this.getDownloadUrl(first.name, dir, true), disableLoadingState);
  602. }
  603. return false;
  604. },
  605. /**
  606. * Event handler for when clicking on "Delete" for the selected files
  607. */
  608. _onClickDeleteSelected: function(event) {
  609. var files = null;
  610. if (!this.isAllSelected()) {
  611. files = _.pluck(this.getSelectedFiles(), 'name');
  612. }
  613. this.do_delete(files);
  614. event.preventDefault();
  615. return false;
  616. },
  617. /**
  618. * Event handler when clicking on a table header
  619. */
  620. _onClickHeader: function(e) {
  621. if (this.$table.hasClass('multiselect')) {
  622. return;
  623. }
  624. var $target = $(e.target);
  625. var sort;
  626. if (!$target.is('a')) {
  627. $target = $target.closest('a');
  628. }
  629. sort = $target.attr('data-sort');
  630. if (sort) {
  631. if (this._sort === sort) {
  632. this.setSort(sort, (this._sortDirection === 'desc')?'asc':'desc', true, true);
  633. }
  634. else {
  635. if ( sort === 'name' ) { //default sorting of name is opposite to size and mtime
  636. this.setSort(sort, 'asc', true, true);
  637. }
  638. else {
  639. this.setSort(sort, 'desc', true, true);
  640. }
  641. }
  642. }
  643. },
  644. /**
  645. * Event handler when clicking on a bread crumb
  646. */
  647. _onClickBreadCrumb: function(e) {
  648. var $el = $(e.target).closest('.crumb'),
  649. $targetDir = $el.data('dir');
  650. if ($targetDir !== undefined && e.which === 1) {
  651. e.preventDefault();
  652. this.changeDirectory($targetDir);
  653. this.updateSearch();
  654. }
  655. },
  656. /**
  657. * Event handler for when scrolling the list container.
  658. * This appends/renders the next page of entries when reaching the bottom.
  659. */
  660. _onScroll: function(e) {
  661. if (this.$container.scrollTop() + this.$container.height() > this.$el.height() - 300) {
  662. this._nextPage(true);
  663. }
  664. },
  665. /**
  666. * Event handler when dropping on a breadcrumb
  667. */
  668. _onDropOnBreadCrumb: function( event, ui ) {
  669. var self = this;
  670. var $target = $(event.target);
  671. if (!$target.is('.crumb')) {
  672. $target = $target.closest('.crumb');
  673. }
  674. var targetPath = $(event.target).data('dir');
  675. var dir = this.getCurrentDirectory();
  676. while (dir.substr(0,1) === '/') {//remove extra leading /'s
  677. dir = dir.substr(1);
  678. }
  679. dir = '/' + dir;
  680. if (dir.substr(-1,1) !== '/') {
  681. dir = dir + '/';
  682. }
  683. // do nothing if dragged on current dir
  684. if (targetPath === dir || targetPath + '/' === dir) {
  685. return;
  686. }
  687. var files = this.getSelectedFiles();
  688. if (files.length === 0) {
  689. // single one selected without checkbox?
  690. files = _.map(ui.helper.find('tr'), function(el) {
  691. return self.elementToFile($(el));
  692. });
  693. }
  694. this.move(_.pluck(files, 'name'), targetPath);
  695. // re-enable td elements to be droppable
  696. // sometimes the filename drop handler is still called after re-enable,
  697. // it seems that waiting for a short time before re-enabling solves the problem
  698. setTimeout(function() {
  699. self.$el.find('td.filename.ui-droppable').droppable('enable');
  700. }, 10);
  701. },
  702. /**
  703. * Sets a new page title
  704. */
  705. setPageTitle: function(title){
  706. if (title) {
  707. title += ' - ';
  708. } else {
  709. title = '';
  710. }
  711. title += this.appName;
  712. // Sets the page title with the " - ownCloud" suffix as in templates
  713. window.document.title = title + ' - ' + oc_defaults.title;
  714. return true;
  715. },
  716. /**
  717. * Returns the file info for the given file name from the internal collection.
  718. *
  719. * @param {string} fileName file name
  720. * @return {OCA.Files.FileInfo} file info or null if it was not found
  721. *
  722. * @since 8.2
  723. */
  724. findFile: function(fileName) {
  725. return _.find(this.files, function(aFile) {
  726. return (aFile.name === fileName);
  727. }) || null;
  728. },
  729. /**
  730. * Returns the tr element for a given file name, but only if it was already rendered.
  731. *
  732. * @param {string} fileName file name
  733. * @return {Object} jQuery object of the matching row
  734. */
  735. findFileEl: function(fileName){
  736. // use filterAttr to avoid escaping issues
  737. return this.$fileList.find('tr').filterAttr('data-file', fileName);
  738. },
  739. /**
  740. * Returns the file data from a given file element.
  741. * @param $el file tr element
  742. * @return file data
  743. */
  744. elementToFile: function($el){
  745. $el = $($el);
  746. var data = {
  747. id: parseInt($el.attr('data-id'), 10),
  748. name: $el.attr('data-file'),
  749. mimetype: $el.attr('data-mime'),
  750. mtime: parseInt($el.attr('data-mtime'), 10),
  751. type: $el.attr('data-type'),
  752. size: parseInt($el.attr('data-size'), 10),
  753. etag: $el.attr('data-etag'),
  754. permissions: parseInt($el.attr('data-permissions'), 10)
  755. };
  756. var icon = $el.attr('data-icon');
  757. if (icon) {
  758. data.icon = icon;
  759. }
  760. var mountType = $el.attr('data-mounttype');
  761. if (mountType) {
  762. data.mountType = mountType;
  763. }
  764. var path = $el.attr('data-path');
  765. if (path) {
  766. data.path = path;
  767. }
  768. return data;
  769. },
  770. /**
  771. * Appends the next page of files into the table
  772. * @param animate true to animate the new elements
  773. * @return array of DOM elements of the newly added files
  774. */
  775. _nextPage: function(animate) {
  776. // Save full files list while rendering
  777. var allFiles = this.files;
  778. this.files = this._filterHiddenFiles(this.files);
  779. var index = this.$fileList.children().length,
  780. count = this.pageSize(),
  781. hidden,
  782. tr,
  783. fileData,
  784. newTrs = [],
  785. isAllSelected = this.isAllSelected();
  786. if (index >= this.files.length) {
  787. return false;
  788. }
  789. while (count > 0 && index < this.files.length) {
  790. fileData = this.files[index];
  791. if (this._filter) {
  792. hidden = fileData.name.toLowerCase().indexOf(this._filter.toLowerCase()) === -1;
  793. } else {
  794. hidden = false;
  795. }
  796. tr = this._renderRow(fileData, {updateSummary: false, silent: true, hidden: hidden});
  797. this.$fileList.append(tr);
  798. if (isAllSelected || this._selectedFiles[fileData.id]) {
  799. tr.addClass('selected');
  800. tr.find('.selectCheckBox').prop('checked', true);
  801. }
  802. if (animate) {
  803. tr.addClass('appear transparent');
  804. }
  805. newTrs.push(tr);
  806. index++;
  807. count--;
  808. }
  809. // trigger event for newly added rows
  810. if (newTrs.length > 0) {
  811. this.$fileList.trigger($.Event('fileActionsReady', {fileList: this, $files: newTrs}));
  812. }
  813. if (animate) {
  814. // defer, for animation
  815. window.setTimeout(function() {
  816. for (var i = 0; i < newTrs.length; i++ ) {
  817. newTrs[i].removeClass('transparent');
  818. }
  819. }, 0);
  820. }
  821. // Restore full files list after rendering
  822. this.files = allFiles;
  823. return newTrs;
  824. },
  825. /**
  826. * Event handler for when file actions were updated.
  827. * This will refresh the file actions on the list.
  828. */
  829. _onFileActionsUpdated: function() {
  830. var self = this;
  831. var $files = this.$fileList.find('tr');
  832. if (!$files.length) {
  833. return;
  834. }
  835. $files.each(function() {
  836. self.fileActions.display($(this).find('td.filename'), false, self);
  837. });
  838. this.$fileList.trigger($.Event('fileActionsReady', {fileList: this, $files: $files}));
  839. },
  840. /**
  841. * Sets the files to be displayed in the list.
  842. * This operation will re-render the list and update the summary.
  843. * @param filesArray array of file data (map)
  844. */
  845. setFiles: function(filesArray) {
  846. var self = this;
  847. // detach to make adding multiple rows faster
  848. this.files = filesArray;
  849. this.$fileList.empty();
  850. // clear "Select all" checkbox
  851. this.$el.find('.select-all').prop('checked', false);
  852. // Save full files list while rendering
  853. var allFiles = this.files;
  854. this.files = this._filterHiddenFiles(this.files);
  855. this.isEmpty = this.files.length === 0;
  856. this._nextPage();
  857. this.updateEmptyContent();
  858. this.fileSummary.calculate(this.files);
  859. this._selectedFiles = {};
  860. this._selectionSummary.clear();
  861. this.updateSelectionSummary();
  862. $(window).scrollTop(0);
  863. // Restore full files list after rendering
  864. this.files = allFiles;
  865. this.$fileList.trigger(jQuery.Event('updated'));
  866. _.defer(function() {
  867. self.$el.closest('#app-content').trigger(jQuery.Event('apprendered'));
  868. });
  869. },
  870. /**
  871. * Filter hidden files of the given filesArray (dot-files)
  872. *
  873. * @param filesArray files to be filtered
  874. * @returns {array}
  875. */
  876. _filterHiddenFiles: function(files) {
  877. if (_.isUndefined(this._filesConfig) || this._filesConfig.get('showhidden')) {
  878. return files;
  879. }
  880. return _.filter(files, function(file) {
  881. return file.name.indexOf('.') !== 0;
  882. });
  883. },
  884. /**
  885. * Returns the icon URL matching the given file info
  886. *
  887. * @param {OC.Files.FileInfo} fileInfo file info
  888. *
  889. * @return {string} icon URL
  890. */
  891. _getIconUrl: function(fileInfo) {
  892. var mimeType = fileInfo.mimetype || 'application/octet-stream';
  893. if (mimeType === 'httpd/unix-directory') {
  894. // use default folder icon
  895. if (fileInfo.mountType === 'shared' || fileInfo.mountType === 'shared-root') {
  896. return OC.MimeType.getIconUrl('dir-shared');
  897. } else if (fileInfo.mountType === 'external-root') {
  898. return OC.MimeType.getIconUrl('dir-external');
  899. }
  900. return OC.MimeType.getIconUrl('dir');
  901. }
  902. return OC.MimeType.getIconUrl(mimeType);
  903. },
  904. /**
  905. * Creates a new table row element using the given file data.
  906. * @param {OC.Files.FileInfo} fileData file info attributes
  907. * @param options map of attributes
  908. * @return new tr element (not appended to the table)
  909. */
  910. _createRow: function(fileData, options) {
  911. var td, simpleSize, basename, extension, sizeColor,
  912. icon = fileData.icon || this._getIconUrl(fileData),
  913. name = fileData.name,
  914. // TODO: get rid of type, only use mime type
  915. type = fileData.type || 'file',
  916. mtime = parseInt(fileData.mtime, 10),
  917. mime = fileData.mimetype,
  918. path = fileData.path,
  919. dataIcon = null,
  920. linkUrl;
  921. options = options || {};
  922. if (isNaN(mtime)) {
  923. mtime = new Date().getTime();
  924. }
  925. if (type === 'dir') {
  926. mime = mime || 'httpd/unix-directory';
  927. if (fileData.mountType && fileData.mountType.indexOf('external') === 0) {
  928. icon = OC.MimeType.getIconUrl('dir-external');
  929. dataIcon = icon;
  930. }
  931. }
  932. //containing tr
  933. var tr = $('<tr></tr>').attr({
  934. "data-id" : fileData.id,
  935. "data-type": type,
  936. "data-size": fileData.size,
  937. "data-file": name,
  938. "data-mime": mime,
  939. "data-mtime": mtime,
  940. "data-etag": fileData.etag,
  941. "data-permissions": fileData.permissions || this.getDirectoryPermissions()
  942. });
  943. if (dataIcon) {
  944. // icon override
  945. tr.attr('data-icon', dataIcon);
  946. }
  947. if (fileData.mountType) {
  948. // dirInfo (parent) only exist for the "real" file list
  949. if (this.dirInfo.id) {
  950. // FIXME: HACK: detect shared-root
  951. if (fileData.mountType === 'shared' && this.dirInfo.mountType !== 'shared' && this.dirInfo.mountType !== 'shared-root') {
  952. // if parent folder isn't share, assume the displayed folder is a share root
  953. fileData.mountType = 'shared-root';
  954. } else if (fileData.mountType === 'external' && this.dirInfo.mountType !== 'external' && this.dirInfo.mountType !== 'external-root') {
  955. // if parent folder isn't external, assume the displayed folder is the external storage root
  956. fileData.mountType = 'external-root';
  957. }
  958. }
  959. tr.attr('data-mounttype', fileData.mountType);
  960. }
  961. if (!_.isUndefined(path)) {
  962. tr.attr('data-path', path);
  963. }
  964. else {
  965. path = this.getCurrentDirectory();
  966. }
  967. // filename td
  968. td = $('<td class="filename"></td>');
  969. // linkUrl
  970. if (mime === 'httpd/unix-directory') {
  971. linkUrl = this.linkTo(path + '/' + name);
  972. }
  973. else {
  974. linkUrl = this.getDownloadUrl(name, path, type === 'dir');
  975. }
  976. if (this._allowSelection) {
  977. td.append(
  978. '<input id="select-' + this.id + '-' + fileData.id +
  979. '" type="checkbox" class="selectCheckBox checkbox"/><label for="select-' + this.id + '-' + fileData.id + '">' +
  980. '<div class="thumbnail" style="background-image:url(' + icon + '); background-size: 32px;"></div>' +
  981. '<span class="hidden-visually">' + t('files', 'Select') + '</span>' +
  982. '</label>'
  983. );
  984. } else {
  985. td.append('<div class="thumbnail" style="background-image:url(' + icon + '); background-size: 32px;"></div>');
  986. }
  987. var linkElem = $('<a></a>').attr({
  988. "class": "name",
  989. "href": linkUrl
  990. });
  991. // from here work on the display name
  992. name = fileData.displayName || name;
  993. // show hidden files (starting with a dot) completely in gray
  994. if(name.indexOf('.') === 0) {
  995. basename = '';
  996. extension = name;
  997. // split extension from filename for non dirs
  998. } else if (mime !== 'httpd/unix-directory' && name.indexOf('.') !== -1) {
  999. basename = name.substr(0, name.lastIndexOf('.'));
  1000. extension = name.substr(name.lastIndexOf('.'));
  1001. } else {
  1002. basename = name;
  1003. extension = false;
  1004. }
  1005. var nameSpan=$('<span></span>').addClass('nametext');
  1006. var innernameSpan = $('<span></span>').addClass('innernametext').text(basename);
  1007. nameSpan.append(innernameSpan);
  1008. linkElem.append(nameSpan);
  1009. if (extension) {
  1010. nameSpan.append($('<span></span>').addClass('extension').text(extension));
  1011. }
  1012. if (fileData.extraData) {
  1013. if (fileData.extraData.charAt(0) === '/') {
  1014. fileData.extraData = fileData.extraData.substr(1);
  1015. }
  1016. nameSpan.addClass('extra-data').attr('title', fileData.extraData);
  1017. nameSpan.tooltip({placement: 'right'});
  1018. }
  1019. // dirs can show the number of uploaded files
  1020. if (mime === 'httpd/unix-directory') {
  1021. linkElem.append($('<span></span>').attr({
  1022. 'class': 'uploadtext',
  1023. 'currentUploads': 0
  1024. }));
  1025. }
  1026. td.append(linkElem);
  1027. tr.append(td);
  1028. // size column
  1029. if (typeof(fileData.size) !== 'undefined' && fileData.size >= 0) {
  1030. simpleSize = humanFileSize(parseInt(fileData.size, 10), true);
  1031. sizeColor = Math.round(160-Math.pow((fileData.size/(1024*1024)),2));
  1032. } else {
  1033. simpleSize = t('files', 'Pending');
  1034. }
  1035. td = $('<td></td>').attr({
  1036. "class": "filesize",
  1037. "style": 'color:rgb(' + sizeColor + ',' + sizeColor + ',' + sizeColor + ')'
  1038. }).text(simpleSize);
  1039. tr.append(td);
  1040. // date column (1000 milliseconds to seconds, 60 seconds, 60 minutes, 24 hours)
  1041. // difference in days multiplied by 5 - brightest shade for files older than 32 days (160/5)
  1042. var modifiedColor = Math.round(((new Date()).getTime() - mtime )/1000/60/60/24*5 );
  1043. // ensure that the brightest color is still readable
  1044. if (modifiedColor >= '160') {
  1045. modifiedColor = 160;
  1046. }
  1047. var formatted;
  1048. var text;
  1049. if (mtime > 0) {
  1050. formatted = OC.Util.formatDate(mtime);
  1051. text = OC.Util.relativeModifiedDate(mtime);
  1052. } else {
  1053. formatted = t('files', 'Unable to determine date');
  1054. text = '?';
  1055. }
  1056. td = $('<td></td>').attr({ "class": "date" });
  1057. td.append($('<span></span>').attr({
  1058. "class": "modified",
  1059. "title": formatted,
  1060. "style": 'color:rgb('+modifiedColor+','+modifiedColor+','+modifiedColor+')'
  1061. }).text(text)
  1062. .tooltip({placement: 'top'})
  1063. );
  1064. tr.find('.filesize').text(simpleSize);
  1065. tr.append(td);
  1066. return tr;
  1067. },
  1068. /**
  1069. * Adds an entry to the files array and also into the DOM
  1070. * in a sorted manner.
  1071. *
  1072. * @param {OC.Files.FileInfo} fileData map of file attributes
  1073. * @param {Object} [options] map of attributes
  1074. * @param {boolean} [options.updateSummary] true to update the summary
  1075. * after adding (default), false otherwise. Defaults to true.
  1076. * @param {boolean} [options.silent] true to prevent firing events like "fileActionsReady",
  1077. * defaults to false.
  1078. * @param {boolean} [options.animate] true to animate the thumbnail image after load
  1079. * defaults to true.
  1080. * @return new tr element (not appended to the table)
  1081. */
  1082. add: function(fileData, options) {
  1083. var index = -1;
  1084. var $tr;
  1085. var $rows;
  1086. var $insertionPoint;
  1087. options = _.extend({animate: true}, options || {});
  1088. // there are three situations to cover:
  1089. // 1) insertion point is visible on the current page
  1090. // 2) insertion point is on a not visible page (visible after scrolling)
  1091. // 3) insertion point is at the end of the list
  1092. $rows = this.$fileList.children();
  1093. index = this._findInsertionIndex(fileData);
  1094. if (index > this.files.length) {
  1095. index = this.files.length;
  1096. }
  1097. else {
  1098. $insertionPoint = $rows.eq(index);
  1099. }
  1100. // is the insertion point visible ?
  1101. if ($insertionPoint.length) {
  1102. // only render if it will really be inserted
  1103. $tr = this._renderRow(fileData, options);
  1104. $insertionPoint.before($tr);
  1105. }
  1106. else {
  1107. // if insertion point is after the last visible
  1108. // entry, append
  1109. if (index === $rows.length) {
  1110. $tr = this._renderRow(fileData, options);
  1111. this.$fileList.append($tr);
  1112. }
  1113. }
  1114. this.isEmpty = false;
  1115. this.files.splice(index, 0, fileData);
  1116. if ($tr && options.animate) {
  1117. $tr.addClass('appear transparent');
  1118. window.setTimeout(function() {
  1119. $tr.removeClass('transparent');
  1120. });
  1121. }
  1122. if (options.scrollTo) {
  1123. this.scrollTo(fileData.name);
  1124. }
  1125. // defaults to true if not defined
  1126. if (typeof(options.updateSummary) === 'undefined' || !!options.updateSummary) {
  1127. this.fileSummary.add(fileData, true);
  1128. this.updateEmptyContent();
  1129. }
  1130. return $tr;
  1131. },
  1132. /**
  1133. * Creates a new row element based on the given attributes
  1134. * and returns it.
  1135. *
  1136. * @param {OC.Files.FileInfo} fileData map of file attributes
  1137. * @param {Object} [options] map of attributes
  1138. * @param {int} [options.index] index at which to insert the element
  1139. * @param {boolean} [options.updateSummary] true to update the summary
  1140. * after adding (default), false otherwise. Defaults to true.
  1141. * @param {boolean} [options.animate] true to animate the thumbnail image after load
  1142. * defaults to true.
  1143. * @return new tr element (not appended to the table)
  1144. */
  1145. _renderRow: function(fileData, options) {
  1146. options = options || {};
  1147. var type = fileData.type || 'file',
  1148. mime = fileData.mimetype,
  1149. path = fileData.path || this.getCurrentDirectory(),
  1150. permissions = parseInt(fileData.permissions, 10) || 0;
  1151. if (fileData.isShareMountPoint) {
  1152. permissions = permissions | OC.PERMISSION_UPDATE;
  1153. }
  1154. if (type === 'dir') {
  1155. mime = mime || 'httpd/unix-directory';
  1156. }
  1157. var tr = this._createRow(
  1158. fileData,
  1159. options
  1160. );
  1161. var filenameTd = tr.find('td.filename');
  1162. // TODO: move dragging to FileActions ?
  1163. // enable drag only for deletable files
  1164. if (this._dragOptions && permissions & OC.PERMISSION_DELETE) {
  1165. filenameTd.draggable(this._dragOptions);
  1166. }
  1167. // allow dropping on folders
  1168. if (this._folderDropOptions && mime === 'httpd/unix-directory') {
  1169. tr.droppable(this._folderDropOptions);
  1170. }
  1171. if (options.hidden) {
  1172. tr.addClass('hidden');
  1173. }
  1174. // display actions
  1175. this.fileActions.display(filenameTd, !options.silent, this);
  1176. if (mime !== 'httpd/unix-directory') {
  1177. var iconDiv = filenameTd.find('.thumbnail');
  1178. // lazy load / newly inserted td ?
  1179. // the typeof check ensures that the default value of animate is true
  1180. if (typeof(options.animate) === 'undefined' || !!options.animate) {
  1181. this.lazyLoadPreview({
  1182. path: path + '/' + fileData.name,
  1183. mime: mime,
  1184. etag: fileData.etag,
  1185. callback: function(url) {
  1186. iconDiv.css('background-image', 'url("' + url + '")');
  1187. }
  1188. });
  1189. }
  1190. else {
  1191. // set the preview URL directly
  1192. var urlSpec = {
  1193. file: path + '/' + fileData.name,
  1194. c: fileData.etag
  1195. };
  1196. var previewUrl = this.generatePreviewUrl(urlSpec);
  1197. previewUrl = previewUrl.replace('(', '%28').replace(')', '%29');
  1198. iconDiv.css('background-image', 'url("' + previewUrl + '")');
  1199. }
  1200. }
  1201. return tr;
  1202. },
  1203. /**
  1204. * Returns the current directory
  1205. * @method getCurrentDirectory
  1206. * @return current directory
  1207. */
  1208. getCurrentDirectory: function(){
  1209. return this._currentDirectory || this.$el.find('#dir').val() || '/';
  1210. },
  1211. /**
  1212. * Returns the directory permissions
  1213. * @return permission value as integer
  1214. */
  1215. getDirectoryPermissions: function() {
  1216. return parseInt(this.$el.find('#permissions').val(), 10);
  1217. },
  1218. /**
  1219. * Changes the current directory and reload the file list.
  1220. * @param {string} targetDir target directory (non URL encoded)
  1221. * @param {boolean} [changeUrl=true] if the URL must not be changed (defaults to true)
  1222. * @param {boolean} [force=false] set to true to force changing directory
  1223. * @param {string} [fileId] optional file id, if known, to be appended in the URL
  1224. */
  1225. changeDirectory: function(targetDir, changeUrl, force, fileId) {
  1226. var self = this;
  1227. var currentDir = this.getCurrentDirectory();
  1228. targetDir = targetDir || '/';
  1229. if (!force && currentDir === targetDir) {
  1230. return;
  1231. }
  1232. this._setCurrentDir(targetDir, changeUrl, fileId);
  1233. this.reload().then(function(success){
  1234. if (!success) {
  1235. self.changeDirectory(currentDir, true);
  1236. }
  1237. });
  1238. },
  1239. linkTo: function(dir) {
  1240. return OC.linkTo('files', 'index.php')+"?dir="+ encodeURIComponent(dir).replace(/%2F/g, '/');
  1241. },
  1242. /**
  1243. * Sets the current directory name and updates the breadcrumb.
  1244. * @param targetDir directory to display
  1245. * @param changeUrl true to also update the URL, false otherwise (default)
  1246. * @param {string} [fileId] file id
  1247. */
  1248. _setCurrentDir: function(targetDir, changeUrl, fileId) {
  1249. targetDir = targetDir.replace(/\\/g, '/');
  1250. var previousDir = this.getCurrentDirectory(),
  1251. baseDir = OC.basename(targetDir);
  1252. if (baseDir !== '') {
  1253. this.setPageTitle(baseDir);
  1254. }
  1255. else {
  1256. this.setPageTitle();
  1257. }
  1258. this._currentDirectory = targetDir;
  1259. // legacy stuff
  1260. this.$el.find('#dir').val(targetDir);
  1261. if (changeUrl !== false) {
  1262. var params = {
  1263. dir: targetDir,
  1264. previousDir: previousDir
  1265. };
  1266. if (fileId) {
  1267. params.fileId = fileId;
  1268. }
  1269. this.$el.trigger(jQuery.Event('changeDirectory', params));
  1270. }
  1271. this.breadcrumb.setDirectory(this.getCurrentDirectory());
  1272. },
  1273. /**
  1274. * Sets the current sorting and refreshes the list
  1275. *
  1276. * @param sort sort attribute name
  1277. * @param direction sort direction, one of "asc" or "desc"
  1278. * @param update true to update the list, false otherwise (default)
  1279. * @param persist true to save changes in the database (default)
  1280. */
  1281. setSort: function(sort, direction, update, persist) {
  1282. var comparator = FileList.Comparators[sort] || FileList.Comparators.name;
  1283. this._sort = sort;
  1284. this._sortDirection = (direction === 'desc')?'desc':'asc';
  1285. this._sortComparator = comparator;
  1286. if (direction === 'desc') {
  1287. this._sortComparator = function(fileInfo1, fileInfo2) {
  1288. return -comparator(fileInfo1, fileInfo2);
  1289. };
  1290. }
  1291. this.$el.find('thead th .sort-indicator')
  1292. .removeClass(this.SORT_INDICATOR_ASC_CLASS)
  1293. .removeClass(this.SORT_INDICATOR_DESC_CLASS)
  1294. .toggleClass('hidden', true)
  1295. .addClass(this.SORT_INDICATOR_DESC_CLASS);
  1296. this.$el.find('thead th.column-' + sort + ' .sort-indicator')
  1297. .removeClass(this.SORT_INDICATOR_ASC_CLASS)
  1298. .removeClass(this.SORT_INDICATOR_DESC_CLASS)
  1299. .toggleClass('hidden', false)
  1300. .addClass(direction === 'desc' ? this.SORT_INDICATOR_DESC_CLASS : this.SORT_INDICATOR_ASC_CLASS);
  1301. if (update) {
  1302. if (this._clientSideSort) {
  1303. this.files.sort(this._sortComparator);
  1304. this.setFiles(this.files);
  1305. }
  1306. else {
  1307. this.reload();
  1308. }
  1309. }
  1310. if (persist) {
  1311. $.post(OC.generateUrl('/apps/files/api/v1/sorting'), {
  1312. mode: sort,
  1313. direction: direction
  1314. });
  1315. }
  1316. },
  1317. /**
  1318. * Returns list of webdav properties to request
  1319. */
  1320. _getWebdavProperties: function() {
  1321. return [].concat(this.filesClient.getPropfindProperties());
  1322. },
  1323. /**
  1324. * Reloads the file list using ajax call
  1325. *
  1326. * @return ajax call object
  1327. */
  1328. reload: function() {
  1329. this._selectedFiles = {};
  1330. this._selectionSummary.clear();
  1331. if (this._currentFileModel) {
  1332. this._currentFileModel.off();
  1333. }
  1334. this._currentFileModel = null;
  1335. this.$el.find('.select-all').prop('checked', false);
  1336. this.showMask();
  1337. this._reloadCall = this.filesClient.getFolderContents(
  1338. this.getCurrentDirectory(), {
  1339. includeParent: true,
  1340. properties: this._getWebdavProperties()
  1341. }
  1342. );
  1343. if (this._detailsView) {
  1344. // close sidebar
  1345. this._updateDetailsView(null);
  1346. }
  1347. var callBack = this.reloadCallback.bind(this);
  1348. return this._reloadCall.then(callBack, callBack);
  1349. },
  1350. reloadCallback: function(status, result) {
  1351. delete this._reloadCall;
  1352. this.hideMask();
  1353. if (status === 401) {
  1354. return false;
  1355. }
  1356. // Firewall Blocked request?
  1357. if (status === 403) {
  1358. // Go home
  1359. this.changeDirectory('/');
  1360. OC.Notification.showTemporary(t('files', 'This operation is forbidden'));
  1361. return false;
  1362. }
  1363. // Did share service die or something else fail?
  1364. if (status === 500) {
  1365. // Go home
  1366. this.changeDirectory('/');
  1367. OC.Notification.showTemporary(
  1368. t('files', 'This directory is unavailable, please check the logs or contact the administrator')
  1369. );
  1370. return false;
  1371. }
  1372. if (status === 503) {
  1373. // Go home
  1374. if (this.getCurrentDirectory() !== '/') {
  1375. this.changeDirectory('/');
  1376. // TODO: read error message from exception
  1377. OC.Notification.showTemporary(
  1378. t('files', 'Storage not available')
  1379. );
  1380. }
  1381. return false;
  1382. }
  1383. if (status === 404) {
  1384. // go back home
  1385. this.changeDirectory('/');
  1386. return false;
  1387. }
  1388. // aborted ?
  1389. if (status === 0){
  1390. return true;
  1391. }
  1392. // TODO: parse remaining quota from PROPFIND response
  1393. this.updateStorageStatistics(true);
  1394. // first entry is the root
  1395. this.dirInfo = result.shift();
  1396. if (this.dirInfo.permissions) {
  1397. this.setDirectoryPermissions(this.dirInfo.permissions);
  1398. }
  1399. result.sort(this._sortComparator);
  1400. this.setFiles(result);
  1401. if (this.dirInfo) {
  1402. var newFileId = this.dirInfo.id;
  1403. // update fileid in URL
  1404. var params = {
  1405. dir: this.getCurrentDirectory()
  1406. };
  1407. if (newFileId) {
  1408. params.fileId = newFileId;
  1409. }
  1410. this.$el.trigger(jQuery.Event('afterChangeDirectory', params));
  1411. }
  1412. return true;
  1413. },
  1414. updateStorageStatistics: function(force) {
  1415. OCA.Files.Files.updateStorageStatistics(this.getCurrentDirectory(), force);
  1416. },
  1417. /**
  1418. * @deprecated do not use nor override
  1419. */
  1420. getAjaxUrl: function(action, params) {
  1421. return OCA.Files.Files.getAjaxUrl(action, params);
  1422. },
  1423. getDownloadUrl: function(files, dir, isDir) {
  1424. return OCA.Files.Files.getDownloadUrl(files, dir || this.getCurrentDirectory(), isDir);
  1425. },
  1426. /**
  1427. * Generates a preview URL based on the URL space.
  1428. * @param urlSpec attributes for the URL
  1429. * @param {int} urlSpec.x width
  1430. * @param {int} urlSpec.y height
  1431. * @param {String} urlSpec.file path to the file
  1432. * @return preview URL
  1433. */
  1434. generatePreviewUrl: function(urlSpec) {
  1435. urlSpec = urlSpec || {};
  1436. if (!urlSpec.x) {
  1437. urlSpec.x = this.$table.data('preview-x') || 32;
  1438. }
  1439. if (!urlSpec.y) {
  1440. urlSpec.y = this.$table.data('preview-y') || 32;
  1441. }
  1442. urlSpec.x *= window.devicePixelRatio;
  1443. urlSpec.y *= window.devicePixelRatio;
  1444. urlSpec.x = Math.ceil(urlSpec.x);
  1445. urlSpec.y = Math.ceil(urlSpec.y);
  1446. urlSpec.forceIcon = 0;
  1447. return OC.generateUrl('/core/preview.png?') + $.param(urlSpec);
  1448. },
  1449. /**
  1450. * Lazy load a file's preview.
  1451. *
  1452. * @param path path of the file
  1453. * @param mime mime type
  1454. * @param callback callback function to call when the image was loaded
  1455. * @param etag file etag (for caching)
  1456. */
  1457. lazyLoadPreview : function(options) {
  1458. var self = this;
  1459. var path = options.path;
  1460. var mime = options.mime;
  1461. var ready = options.callback;
  1462. var etag = options.etag;
  1463. // get mime icon url
  1464. var iconURL = OC.MimeType.getIconUrl(mime);
  1465. var previewURL,
  1466. urlSpec = {};
  1467. ready(iconURL); // set mimeicon URL
  1468. urlSpec.file = OCA.Files.Files.fixPath(path);
  1469. if (options.x) {
  1470. urlSpec.x = options.x;
  1471. }
  1472. if (options.y) {
  1473. urlSpec.y = options.y;
  1474. }
  1475. if (options.a) {
  1476. urlSpec.a = options.a;
  1477. }
  1478. if (options.mode) {
  1479. urlSpec.mode = options.mode;
  1480. }
  1481. if (etag){
  1482. // use etag as cache buster
  1483. urlSpec.c = etag;
  1484. }
  1485. previewURL = self.generatePreviewUrl(urlSpec);
  1486. previewURL = previewURL.replace('(', '%28');
  1487. previewURL = previewURL.replace(')', '%29');
  1488. // preload image to prevent delay
  1489. // this will make the browser cache the image
  1490. var img = new Image();
  1491. img.onload = function(){
  1492. // if loading the preview image failed (no preview for the mimetype) then img.width will < 5
  1493. if (img.width > 5) {
  1494. ready(previewURL, img);
  1495. } else if (options.error) {
  1496. options.error();
  1497. }
  1498. };
  1499. if (options.error) {
  1500. img.onerror = options.error;
  1501. }
  1502. img.src = previewURL;
  1503. },
  1504. /**
  1505. * @deprecated
  1506. */
  1507. setDirectoryPermissions: function(permissions) {
  1508. var isCreatable = (permissions & OC.PERMISSION_CREATE) !== 0;
  1509. this.$el.find('#permissions').val(permissions);
  1510. this.$el.find('.creatable').toggleClass('hidden', !isCreatable);
  1511. this.$el.find('.notCreatable').toggleClass('hidden', isCreatable);
  1512. },
  1513. /**
  1514. * Shows/hides action buttons
  1515. *
  1516. * @param show true for enabling, false for disabling
  1517. */
  1518. showActions: function(show){
  1519. this.$el.find('.actions,#file_action_panel').toggleClass('hidden', !show);
  1520. if (show){
  1521. // make sure to display according to permissions
  1522. var permissions = this.getDirectoryPermissions();
  1523. var isCreatable = (permissions & OC.PERMISSION_CREATE) !== 0;
  1524. this.$el.find('.creatable').toggleClass('hidden', !isCreatable);
  1525. this.$el.find('.notCreatable').toggleClass('hidden', isCreatable);
  1526. // remove old style breadcrumbs (some apps might create them)
  1527. this.$el.find('#controls .crumb').remove();
  1528. // refresh breadcrumbs in case it was replaced by an app
  1529. this.breadcrumb.render();
  1530. }
  1531. else{
  1532. this.$el.find('.creatable, .notCreatable').addClass('hidden');
  1533. }
  1534. },
  1535. /**
  1536. * Enables/disables viewer mode.
  1537. * In viewer mode, apps can embed themselves under the controls bar.
  1538. * In viewer mode, the actions of the file list will be hidden.
  1539. * @param show true for enabling, false for disabling
  1540. */
  1541. setViewerMode: function(show){
  1542. this.showActions(!show);
  1543. this.$el.find('#filestable').toggleClass('hidden', show);
  1544. this.$el.trigger(new $.Event('changeViewerMode', {viewerModeEnabled: show}));
  1545. },
  1546. /**
  1547. * Removes a file entry from the list
  1548. * @param name name of the file to remove
  1549. * @param {Object} [options] map of attributes
  1550. * @param {boolean} [options.updateSummary] true to update the summary
  1551. * after removing, false otherwise. Defaults to true.
  1552. * @return deleted element
  1553. */
  1554. remove: function(name, options){
  1555. options = options || {};
  1556. var fileEl = this.findFileEl(name);
  1557. var fileId = fileEl.data('id');
  1558. var index = fileEl.index();
  1559. if (!fileEl.length) {
  1560. return null;
  1561. }
  1562. if (this._selectedFiles[fileId]) {
  1563. // remove from selection first
  1564. this._selectFileEl(fileEl, false);
  1565. this.updateSelectionSummary();
  1566. }
  1567. if (this._dragOptions && (fileEl.data('permissions') & OC.PERMISSION_DELETE)) {
  1568. // file is only draggable when delete permissions are set
  1569. fileEl.find('td.filename').draggable('destroy');
  1570. }
  1571. this.files.splice(index, 1);
  1572. if (this._currentFileModel && this._currentFileModel.get('id') === fileId) {
  1573. // Note: in the future we should call destroy() directly on the model
  1574. // and the model will take care of the deletion.
  1575. // Here we only trigger the event to notify listeners that
  1576. // the file was removed.
  1577. this._currentFileModel.trigger('destroy');
  1578. this._updateDetailsView(null);
  1579. }
  1580. fileEl.remove();
  1581. // TODO: improve performance on batch update
  1582. this.isEmpty = !this.files.length;
  1583. if (typeof(options.updateSummary) === 'undefined' || !!options.updateSummary) {
  1584. this.updateEmptyContent();
  1585. this.fileSummary.remove({type: fileEl.attr('data-type'), size: fileEl.attr('data-size')}, true);
  1586. }
  1587. var lastIndex = this.$fileList.children().length;
  1588. // if there are less elements visible than one page
  1589. // but there are still pending elements in the array,
  1590. // then directly append the next page
  1591. if (lastIndex < this.files.length && lastIndex < this.pageSize()) {
  1592. this._nextPage(true);
  1593. }
  1594. return fileEl;
  1595. },
  1596. /**
  1597. * Finds the index of the row before which the given
  1598. * fileData should be inserted, considering the current
  1599. * sorting
  1600. *
  1601. * @param {OC.Files.FileInfo} fileData file info
  1602. */
  1603. _findInsertionIndex: function(fileData) {
  1604. var index = 0;
  1605. while (index < this.files.length && this._sortComparator(fileData, this.files[index]) > 0) {
  1606. index++;
  1607. }
  1608. return index;
  1609. },
  1610. /**
  1611. * Moves a file to a given target folder.
  1612. *
  1613. * @param fileNames array of file names to move
  1614. * @param targetPath absolute target path
  1615. */
  1616. move: function(fileNames, targetPath) {
  1617. var self = this;
  1618. var dir = this.getCurrentDirectory();
  1619. if (dir.charAt(dir.length - 1) !== '/') {
  1620. dir += '/';
  1621. }
  1622. var target = OC.basename(targetPath);
  1623. if (!_.isArray(fileNames)) {
  1624. fileNames = [fileNames];
  1625. }
  1626. _.each(fileNames, function(fileName) {
  1627. var $tr = self.findFileEl(fileName);
  1628. self.showFileBusyState($tr, true);
  1629. if (targetPath.charAt(targetPath.length - 1) !== '/') {
  1630. // make sure we move the files into the target dir,
  1631. // not overwrite it
  1632. targetPath = targetPath + '/';
  1633. }
  1634. self.filesClient.move(dir + fileName, targetPath + fileName)
  1635. .done(function() {
  1636. // if still viewing the same directory
  1637. if (OC.joinPaths(self.getCurrentDirectory(), '/') === dir) {
  1638. // recalculate folder size
  1639. var oldFile = self.findFileEl(target);
  1640. var newFile = self.findFileEl(fileName);
  1641. var oldSize = oldFile.data('size');
  1642. var newSize = oldSize + newFile.data('size');
  1643. oldFile.data('size', newSize);
  1644. oldFile.find('td.filesize').text(OC.Util.humanFileSize(newSize));
  1645. // TODO: also update entry in FileList.files
  1646. self.remove(fileName);
  1647. }
  1648. })
  1649. .fail(function(status) {
  1650. if (status === 412) {
  1651. // TODO: some day here we should invoke the conflict dialog
  1652. OC.Notification.showTemporary(
  1653. t('files', 'Could not move "{file}", target exists', {file: fileName})
  1654. );
  1655. } else {
  1656. OC.Notification.showTemporary(
  1657. t('files', 'Could not move "{file}"', {file: fileName})
  1658. );
  1659. }
  1660. })
  1661. .always(function() {
  1662. self.showFileBusyState($tr, false);
  1663. });
  1664. });
  1665. },
  1666. /**
  1667. * Updates the given row with the given file info
  1668. *
  1669. * @param {Object} $tr row element
  1670. * @param {OCA.Files.FileInfo} fileInfo file info
  1671. * @param {Object} options options
  1672. *
  1673. * @return {Object} new row element
  1674. */
  1675. updateRow: function($tr, fileInfo, options) {
  1676. this.files.splice($tr.index(), 1);
  1677. $tr.remove();
  1678. options = _.extend({silent: true}, options);
  1679. options = _.extend(options, {updateSummary: false});
  1680. $tr = this.add(fileInfo, options);
  1681. this.$fileList.trigger($.Event('fileActionsReady', {fileList: this, $files: $tr}));
  1682. return $tr;
  1683. },
  1684. /**
  1685. * Triggers file rename input field for the given file name.
  1686. * If the user enters a new name, the file will be renamed.
  1687. *
  1688. * @param oldName file name of the file to rename
  1689. */
  1690. rename: function(oldName) {
  1691. var self = this;
  1692. var tr, td, input, form;
  1693. tr = this.findFileEl(oldName);
  1694. var oldFileInfo = this.files[tr.index()];
  1695. tr.data('renaming',true);
  1696. td = tr.children('td.filename');
  1697. input = $('<input type="text" class="filename"/>').val(oldName);
  1698. form = $('<form></form>');
  1699. form.append(input);
  1700. td.children('a.name').hide();
  1701. td.append(form);
  1702. input.focus();
  1703. //preselect input
  1704. var len = input.val().lastIndexOf('.');
  1705. if ( len === -1 ||
  1706. tr.data('type') === 'dir' ) {
  1707. len = input.val().length;
  1708. }
  1709. input.selectRange(0, len);
  1710. var checkInput = function () {
  1711. var filename = input.val();
  1712. if (filename !== oldName) {
  1713. // Files.isFileNameValid(filename) throws an exception itself
  1714. OCA.Files.Files.isFileNameValid(filename);
  1715. if (self.inList(filename)) {
  1716. throw t('files', '{newName} already exists', {newName: filename});
  1717. }
  1718. }
  1719. return true;
  1720. };
  1721. function restore() {
  1722. input.tooltip('hide');
  1723. tr.data('renaming',false);
  1724. form.remove();
  1725. td.children('a.name').show();
  1726. }
  1727. function updateInList(fileInfo) {
  1728. self.updateRow(tr, fileInfo);
  1729. self._updateDetailsView(fileInfo.name, false);
  1730. }
  1731. // TODO: too many nested blocks, move parts into functions
  1732. form.submit(function(event) {
  1733. event.stopPropagation();
  1734. event.preventDefault();
  1735. if (input.hasClass('error')) {
  1736. return;
  1737. }
  1738. try {
  1739. var newName = input.val();
  1740. input.tooltip('hide');
  1741. form.remove();
  1742. if (newName !== oldName) {
  1743. checkInput();
  1744. // mark as loading (temp element)
  1745. self.showFileBusyState(tr, true);
  1746. tr.attr('data-file', newName);
  1747. var basename = newName;
  1748. if (newName.indexOf('.') > 0 && tr.data('type') !== 'dir') {
  1749. basename = newName.substr(0, newName.lastIndexOf('.'));
  1750. }
  1751. td.find('a.name span.nametext').text(basename);
  1752. td.children('a.name').show();
  1753. var path = tr.attr('data-path') || self.getCurrentDirectory();
  1754. self.filesClient.move(OC.joinPaths(path, oldName), OC.joinPaths(path, newName))
  1755. .done(function() {
  1756. oldFileInfo.name = newName;
  1757. updateInList(oldFileInfo);
  1758. })
  1759. .fail(function(status) {
  1760. // TODO: 409 means current folder does not exist, redirect ?
  1761. if (status === 404) {
  1762. // source not found, so remove it from the list
  1763. OC.Notification.showTemporary(
  1764. t(
  1765. 'files',
  1766. 'Could not rename "{fileName}", it does not exist any more',
  1767. {fileName: oldName}
  1768. )
  1769. );
  1770. self.remove(newName, {updateSummary: true});
  1771. return;
  1772. } else if (status === 412) {
  1773. // target exists
  1774. OC.Notification.showTemporary(
  1775. t(
  1776. 'files',
  1777. 'The name "{targetName}" is already used in the folder "{dir}". Please choose a different name.',
  1778. {
  1779. targetName: newName,
  1780. dir: self.getCurrentDirectory()
  1781. }
  1782. )
  1783. );
  1784. } else {
  1785. // restore the item to its previous state
  1786. OC.Notification.showTemporary(
  1787. t('files', 'Could not rename "{fileName}"', {fileName: oldName})
  1788. );
  1789. }
  1790. updateInList(oldFileInfo);
  1791. });
  1792. } else {
  1793. // add back the old file info when cancelled
  1794. self.files.splice(tr.index(), 1);
  1795. tr.remove();
  1796. tr = self.add(oldFileInfo, {updateSummary: false, silent: true});
  1797. self.$fileList.trigger($.Event('fileActionsReady', {fileList: self, $files: $(tr)}));
  1798. }
  1799. } catch (error) {
  1800. input.attr('title', error);
  1801. input.tooltip({placement: 'right', trigger: 'manual'});
  1802. input.tooltip('show');
  1803. input.addClass('error');
  1804. }
  1805. return false;
  1806. });
  1807. input.keyup(function(event) {
  1808. // verify filename on typing
  1809. try {
  1810. checkInput();
  1811. input.tooltip('hide');
  1812. input.removeClass('error');
  1813. } catch (error) {
  1814. input.attr('title', error);
  1815. input.tooltip({placement: 'right', trigger: 'manual'});
  1816. input.tooltip('show');
  1817. input.addClass('error');
  1818. }
  1819. if (event.keyCode === 27) {
  1820. restore();
  1821. }
  1822. });
  1823. input.click(function(event) {
  1824. event.stopPropagation();
  1825. event.preventDefault();
  1826. });
  1827. input.blur(function() {
  1828. form.trigger('submit');
  1829. });
  1830. },
  1831. /**
  1832. * Create an empty file inside the current directory.
  1833. *
  1834. * @param {string} name name of the file
  1835. *
  1836. * @return {Promise} promise that will be resolved after the
  1837. * file was created
  1838. *
  1839. * @since 8.2
  1840. */
  1841. createFile: function(name) {
  1842. var self = this;
  1843. var deferred = $.Deferred();
  1844. var promise = deferred.promise();
  1845. OCA.Files.Files.isFileNameValid(name);
  1846. if (this.lastAction) {
  1847. this.lastAction();
  1848. }
  1849. name = this.getUniqueName(name);
  1850. var targetPath = this.getCurrentDirectory() + '/' + name;
  1851. self.filesClient.putFileContents(
  1852. targetPath,
  1853. '',
  1854. {
  1855. contentType: 'text/plain',
  1856. overwrite: true
  1857. }
  1858. )
  1859. .done(function() {
  1860. // TODO: error handling / conflicts
  1861. self.filesClient.getFileInfo(
  1862. targetPath, {
  1863. properties: self._getWebdavProperties()
  1864. }
  1865. )
  1866. .then(function(status, data) {
  1867. self.add(data, {animate: true, scrollTo: true});
  1868. deferred.resolve(status, data);
  1869. })
  1870. .fail(function(status) {
  1871. OC.Notification.showTemporary(t('files', 'Could not create file "{file}"', {file: name}));
  1872. deferred.reject(status);
  1873. });
  1874. })
  1875. .fail(function(status) {
  1876. if (status === 412) {
  1877. OC.Notification.showTemporary(
  1878. t('files', 'Could not create file "{file}" because it already exists', {file: name})
  1879. );
  1880. } else {
  1881. OC.Notification.showTemporary(t('files', 'Could not create file "{file}"', {file: name}));
  1882. }
  1883. deferred.reject(status);
  1884. });
  1885. return promise;
  1886. },
  1887. /**
  1888. * Create a directory inside the current directory.
  1889. *
  1890. * @param {string} name name of the directory
  1891. *
  1892. * @return {Promise} promise that will be resolved after the
  1893. * directory was created
  1894. *
  1895. * @since 8.2
  1896. */
  1897. createDirectory: function(name) {
  1898. var self = this;
  1899. var deferred = $.Deferred();
  1900. var promise = deferred.promise();
  1901. OCA.Files.Files.isFileNameValid(name);
  1902. if (this.lastAction) {
  1903. this.lastAction();
  1904. }
  1905. name = this.getUniqueName(name);
  1906. var targetPath = this.getCurrentDirectory() + '/' + name;
  1907. this.filesClient.createDirectory(targetPath)
  1908. .done(function(createStatus) {
  1909. self.filesClient.getFileInfo(
  1910. targetPath, {
  1911. properties: self._getWebdavProperties()
  1912. }
  1913. )
  1914. .done(function(status, data) {
  1915. self.add(data, {animate: true, scrollTo: true});
  1916. deferred.resolve(status, data);
  1917. })
  1918. .fail(function() {
  1919. OC.Notification.showTemporary(t('files', 'Could not create folder "{dir}"', {dir: name}));
  1920. deferred.reject(createStatus);
  1921. });
  1922. })
  1923. .fail(function(createStatus) {
  1924. // method not allowed, folder might exist already
  1925. if (createStatus === 405) {
  1926. self.filesClient.getFileInfo(
  1927. targetPath, {
  1928. properties: self._getWebdavProperties()
  1929. }
  1930. )
  1931. .done(function(status, data) {
  1932. // add it to the list, for completeness
  1933. self.add(data, {animate: true, scrollTo: true});
  1934. OC.Notification.showTemporary(
  1935. t('files', 'Could not create folder "{dir}" because it already exists', {dir: name})
  1936. );
  1937. // still consider a failure
  1938. deferred.reject(createStatus, data);
  1939. })
  1940. .fail(function() {
  1941. OC.Notification.showTemporary(
  1942. t('files', 'Could not create folder "{dir}"', {dir: name})
  1943. );
  1944. deferred.reject(status);
  1945. });
  1946. } else {
  1947. OC.Notification.showTemporary(t('files', 'Could not create folder "{dir}"', {dir: name}));
  1948. deferred.reject(createStatus);
  1949. }
  1950. });
  1951. return promise;
  1952. },
  1953. /**
  1954. * Returns whether the given file name exists in the list
  1955. *
  1956. * @param {string} file file name
  1957. *
  1958. * @return {bool} true if the file exists in the list, false otherwise
  1959. */
  1960. inList:function(file) {
  1961. return this.findFile(file);
  1962. },
  1963. /**
  1964. * Shows busy state on a given file row or multiple
  1965. *
  1966. * @param {string|Array.<string>} files file name or array of file names
  1967. * @param {bool} [busy=true] busy state, true for busy, false to remove busy state
  1968. *
  1969. * @since 8.2
  1970. */
  1971. showFileBusyState: function(files, state) {
  1972. var self = this;
  1973. if (!_.isArray(files) && !files.is) {
  1974. files = [files];
  1975. }
  1976. if (_.isUndefined(state)) {
  1977. state = true;
  1978. }
  1979. _.each(files, function(fileName) {
  1980. // jquery element already ?
  1981. var $tr;
  1982. if (_.isString(fileName)) {
  1983. $tr = self.findFileEl(fileName);
  1984. } else {
  1985. $tr = $(fileName);
  1986. }
  1987. var $thumbEl = $tr.find('.thumbnail');
  1988. $tr.toggleClass('busy', state);
  1989. if (state) {
  1990. $thumbEl.attr('data-oldimage', $thumbEl.css('background-image'));
  1991. $thumbEl.css('background-image', 'url('+ OC.imagePath('core', 'loading.gif') + ')');
  1992. } else {
  1993. $thumbEl.css('background-image', $thumbEl.attr('data-oldimage'));
  1994. $thumbEl.removeAttr('data-oldimage');
  1995. }
  1996. });
  1997. },
  1998. /**
  1999. * Delete the given files from the given dir
  2000. * @param files file names list (without path)
  2001. * @param dir directory in which to delete the files, defaults to the current
  2002. * directory
  2003. */
  2004. do_delete:function(files, dir) {
  2005. var self = this;
  2006. if (files && files.substr) {
  2007. files=[files];
  2008. }
  2009. if (!files) {
  2010. // delete all files in directory
  2011. files = _.pluck(this.files, 'name');
  2012. }
  2013. if (files) {
  2014. this.showFileBusyState(files, true);
  2015. }
  2016. // Finish any existing actions
  2017. if (this.lastAction) {
  2018. this.lastAction();
  2019. }
  2020. dir = dir || this.getCurrentDirectory();
  2021. function removeFromList(file) {
  2022. var fileEl = self.remove(file, {updateSummary: false});
  2023. // FIXME: not sure why we need this after the
  2024. // element isn't even in the DOM any more
  2025. fileEl.find('.selectCheckBox').prop('checked', false);
  2026. fileEl.removeClass('selected');
  2027. self.fileSummary.remove({type: fileEl.attr('data-type'), size: fileEl.attr('data-size')});
  2028. // TODO: this info should be returned by the ajax call!
  2029. self.updateEmptyContent();
  2030. self.fileSummary.update();
  2031. self.updateSelectionSummary();
  2032. // FIXME: don't repeat this, do it once all files are done
  2033. self.updateStorageStatistics();
  2034. }
  2035. _.each(files, function(file) {
  2036. self.filesClient.remove(dir + '/' + file)
  2037. .done(function() {
  2038. removeFromList(file);
  2039. })
  2040. .fail(function(status) {
  2041. if (status === 404) {
  2042. // the file already did not exist, remove it from the list
  2043. removeFromList(file);
  2044. } else {
  2045. // only reset the spinner for that one file
  2046. OC.Notification.showTemporary(
  2047. t('files', 'Error deleting file "{fileName}".', {fileName: file}),
  2048. {timeout: 10}
  2049. );
  2050. var deleteAction = self.findFileEl(file).find('.action.delete');
  2051. deleteAction.removeClass('icon-loading-small').addClass('icon-delete');
  2052. self.showFileBusyState(files, false);
  2053. }
  2054. });
  2055. });
  2056. },
  2057. /**
  2058. * Creates the file summary section
  2059. */
  2060. _createSummary: function() {
  2061. var $tr = $('<tr class="summary"></tr>');
  2062. this.$el.find('tfoot').append($tr);
  2063. return new OCA.Files.FileSummary($tr);
  2064. },
  2065. updateEmptyContent: function() {
  2066. var permissions = this.getDirectoryPermissions();
  2067. var isCreatable = (permissions & OC.PERMISSION_CREATE) !== 0;
  2068. this.$el.find('#emptycontent').toggleClass('hidden', !this.isEmpty);
  2069. this.$el.find('#emptycontent .uploadmessage').toggleClass('hidden', !isCreatable || !this.isEmpty);
  2070. this.$el.find('#filestable thead th').toggleClass('hidden', this.isEmpty);
  2071. },
  2072. /**
  2073. * Shows the loading mask.
  2074. *
  2075. * @see OCA.Files.FileList#hideMask
  2076. */
  2077. showMask: function() {
  2078. // in case one was shown before
  2079. var $mask = this.$el.find('.mask');
  2080. if ($mask.exists()) {
  2081. return;
  2082. }
  2083. this.$table.addClass('hidden');
  2084. this.$el.find('#emptycontent').addClass('hidden');
  2085. $mask = $('<div class="mask transparent"></div>');
  2086. $mask.css('background-image', 'url('+ OC.imagePath('core', 'loading.gif') + ')');
  2087. $mask.css('background-repeat', 'no-repeat');
  2088. this.$el.append($mask);
  2089. $mask.removeClass('transparent');
  2090. },
  2091. /**
  2092. * Hide the loading mask.
  2093. * @see OCA.Files.FileList#showMask
  2094. */
  2095. hideMask: function() {
  2096. this.$el.find('.mask').remove();
  2097. this.$table.removeClass('hidden');
  2098. },
  2099. scrollTo:function(file) {
  2100. if (!_.isArray(file)) {
  2101. file = [file];
  2102. }
  2103. this.highlightFiles(file, function($tr) {
  2104. $tr.addClass('searchresult');
  2105. $tr.one('hover', function() {
  2106. $tr.removeClass('searchresult');
  2107. });
  2108. });
  2109. },
  2110. /**
  2111. * @deprecated use setFilter(filter)
  2112. */
  2113. filter:function(query) {
  2114. this.setFilter('');
  2115. },
  2116. /**
  2117. * @deprecated use setFilter('')
  2118. */
  2119. unfilter:function() {
  2120. this.setFilter('');
  2121. },
  2122. /**
  2123. * hide files matching the given filter
  2124. * @param filter
  2125. */
  2126. setFilter:function(filter) {
  2127. var total = 0;
  2128. this._filter = filter;
  2129. this.fileSummary.setFilter(filter, this.files);
  2130. total = this.fileSummary.getTotal();
  2131. if (!this.$el.find('.mask').exists()) {
  2132. this.hideIrrelevantUIWhenNoFilesMatch();
  2133. }
  2134. var that = this;
  2135. var visibleCount = 0;
  2136. filter = filter.toLowerCase();
  2137. function filterRows(tr) {
  2138. var $e = $(tr);
  2139. if ($e.data('file').toString().toLowerCase().indexOf(filter) === -1) {
  2140. $e.addClass('hidden');
  2141. } else {
  2142. visibleCount++;
  2143. $e.removeClass('hidden');
  2144. }
  2145. }
  2146. var $trs = this.$fileList.find('tr');
  2147. do {
  2148. _.each($trs, filterRows);
  2149. if (visibleCount < total) {
  2150. $trs = this._nextPage(false);
  2151. }
  2152. } while (visibleCount < total);
  2153. this.$container.trigger('scroll');
  2154. },
  2155. hideIrrelevantUIWhenNoFilesMatch:function() {
  2156. if (this._filter && this.fileSummary.summary.totalDirs + this.fileSummary.summary.totalFiles === 0) {
  2157. this.$el.find('#filestable thead th').addClass('hidden');
  2158. this.$el.find('#emptycontent').addClass('hidden');
  2159. $('#searchresults').addClass('filter-empty');
  2160. $('#searchresults .emptycontent').addClass('emptycontent-search');
  2161. if ( $('#searchresults').length === 0 || $('#searchresults').hasClass('hidden') ) {
  2162. this.$el.find('.nofilterresults').removeClass('hidden').
  2163. find('p').text(t('files', "No entries in this folder match '{filter}'", {filter:this._filter}, null, {'escape': false}));
  2164. }
  2165. } else {
  2166. $('#searchresults').removeClass('filter-empty');
  2167. $('#searchresults .emptycontent').removeClass('emptycontent-search');
  2168. this.$el.find('#filestable thead th').toggleClass('hidden', this.isEmpty);
  2169. if (!this.$el.find('.mask').exists()) {
  2170. this.$el.find('#emptycontent').toggleClass('hidden', !this.isEmpty);
  2171. }
  2172. this.$el.find('.nofilterresults').addClass('hidden');
  2173. }
  2174. },
  2175. /**
  2176. * get the current filter
  2177. * @param filter
  2178. */
  2179. getFilter:function(filter) {
  2180. return this._filter;
  2181. },
  2182. /**
  2183. * update the search object to use this filelist when filtering
  2184. */
  2185. updateSearch:function() {
  2186. if (OCA.Search.files) {
  2187. OCA.Search.files.setFileList(this);
  2188. }
  2189. if (OC.Search) {
  2190. OC.Search.clear();
  2191. }
  2192. },
  2193. /**
  2194. * Update UI based on the current selection
  2195. */
  2196. updateSelectionSummary: function() {
  2197. var summary = this._selectionSummary.summary;
  2198. var selection;
  2199. if (summary.totalFiles === 0 && summary.totalDirs === 0) {
  2200. this.$el.find('#headerName a.name>span:first').text(t('files','Name'));
  2201. this.$el.find('#headerSize a>span:first').text(t('files','Size'));
  2202. this.$el.find('#modified a>span:first').text(t('files','Modified'));
  2203. this.$el.find('table').removeClass('multiselect');
  2204. this.$el.find('.selectedActions').addClass('hidden');
  2205. }
  2206. else {
  2207. this.$el.find('.selectedActions').removeClass('hidden');
  2208. this.$el.find('#headerSize a>span:first').text(OC.Util.humanFileSize(summary.totalSize));
  2209. var directoryInfo = n('files', '%n folder', '%n folders', summary.totalDirs);
  2210. var fileInfo = n('files', '%n file', '%n files', summary.totalFiles);
  2211. if (summary.totalDirs > 0 && summary.totalFiles > 0) {
  2212. var selectionVars = {
  2213. dirs: directoryInfo,
  2214. files: fileInfo
  2215. };
  2216. selection = t('files', '{dirs} and {files}', selectionVars);
  2217. } else if (summary.totalDirs > 0) {
  2218. selection = directoryInfo;
  2219. } else {
  2220. selection = fileInfo;
  2221. }
  2222. this.$el.find('#headerName a.name>span:first').text(selection);
  2223. this.$el.find('#modified a>span:first').text('');
  2224. this.$el.find('table').addClass('multiselect');
  2225. this.$el.find('.delete-selected').toggleClass('hidden', !this.isSelectedDeletable());
  2226. }
  2227. },
  2228. /**
  2229. * Check whether all selected files are deletable
  2230. */
  2231. isSelectedDeletable: function() {
  2232. return _.reduce(this.getSelectedFiles(), function(deletable, file) {
  2233. return deletable && (file.permissions & OC.PERMISSION_DELETE);
  2234. }, true);
  2235. },
  2236. /**
  2237. * Returns whether all files are selected
  2238. * @return true if all files are selected, false otherwise
  2239. */
  2240. isAllSelected: function() {
  2241. return this.$el.find('.select-all').prop('checked');
  2242. },
  2243. /**
  2244. * Returns the file info of the selected files
  2245. *
  2246. * @return array of file names
  2247. */
  2248. getSelectedFiles: function() {
  2249. return _.values(this._selectedFiles);
  2250. },
  2251. getUniqueName: function(name) {
  2252. if (this.findFileEl(name).exists()) {
  2253. var numMatch;
  2254. var parts=name.split('.');
  2255. var extension = "";
  2256. if (parts.length > 1) {
  2257. extension=parts.pop();
  2258. }
  2259. var base=parts.join('.');
  2260. numMatch=base.match(/\((\d+)\)/);
  2261. var num=2;
  2262. if (numMatch && numMatch.length>0) {
  2263. num=parseInt(numMatch[numMatch.length-1], 10)+1;
  2264. base=base.split('(');
  2265. base.pop();
  2266. base=$.trim(base.join('('));
  2267. }
  2268. name=base+' ('+num+')';
  2269. if (extension) {
  2270. name = name+'.'+extension;
  2271. }
  2272. // FIXME: ugly recursion
  2273. return this.getUniqueName(name);
  2274. }
  2275. return name;
  2276. },
  2277. /**
  2278. * Shows a "permission denied" notification
  2279. */
  2280. _showPermissionDeniedNotification: function() {
  2281. var message = t('core', 'You don’t have permission to upload or create files here');
  2282. OC.Notification.showTemporary(message);
  2283. },
  2284. /**
  2285. * Setup file upload events related to the file-upload plugin
  2286. */
  2287. setupUploadEvents: function() {
  2288. var self = this;
  2289. // handle upload events
  2290. var fileUploadStart = this.$el;
  2291. var delegatedElement = '#file_upload_start';
  2292. // detect the progress bar resize
  2293. fileUploadStart.on('resized', this._onResize);
  2294. fileUploadStart.on('fileuploaddrop', delegatedElement, function(e, data) {
  2295. OC.Upload.log('filelist handle fileuploaddrop', e, data);
  2296. if (self.$el.hasClass('hidden')) {
  2297. // do not upload to invisible lists
  2298. return false;
  2299. }
  2300. var dropTarget = $(e.delegatedEvent.target);
  2301. // check if dropped inside this container and not another one
  2302. if (dropTarget.length
  2303. && !self.$el.is(dropTarget) // dropped on list directly
  2304. && !self.$el.has(dropTarget).length // dropped inside list
  2305. && !dropTarget.is(self.$container) // dropped on main container
  2306. ) {
  2307. return false;
  2308. }
  2309. // find the closest tr or crumb to use as target
  2310. dropTarget = dropTarget.closest('tr, .crumb');
  2311. // if dropping on tr or crumb, drag&drop upload to folder
  2312. if (dropTarget && (dropTarget.data('type') === 'dir' ||
  2313. dropTarget.hasClass('crumb'))) {
  2314. // remember as context
  2315. data.context = dropTarget;
  2316. // if permissions are specified, only allow if create permission is there
  2317. var permissions = dropTarget.data('permissions');
  2318. if (!_.isUndefined(permissions) && (permissions & OC.PERMISSION_CREATE) === 0) {
  2319. self._showPermissionDeniedNotification();
  2320. return false;
  2321. }
  2322. var dir = dropTarget.data('file');
  2323. // if from file list, need to prepend parent dir
  2324. if (dir) {
  2325. var parentDir = self.getCurrentDirectory();
  2326. if (parentDir[parentDir.length - 1] !== '/') {
  2327. parentDir += '/';
  2328. }
  2329. dir = parentDir + dir;
  2330. }
  2331. else{
  2332. // read full path from crumb
  2333. dir = dropTarget.data('dir') || '/';
  2334. }
  2335. // add target dir
  2336. data.targetDir = dir;
  2337. } else {
  2338. // we are dropping somewhere inside the file list, which will
  2339. // upload the file to the current directory
  2340. data.targetDir = self.getCurrentDirectory();
  2341. // cancel uploads to current dir if no permission
  2342. var isCreatable = (self.getDirectoryPermissions() & OC.PERMISSION_CREATE) !== 0;
  2343. if (!isCreatable) {
  2344. self._showPermissionDeniedNotification();
  2345. return false;
  2346. }
  2347. }
  2348. });
  2349. fileUploadStart.on('fileuploadadd', function(e, data) {
  2350. OC.Upload.log('filelist handle fileuploadadd', e, data);
  2351. //finish delete if we are uploading a deleted file
  2352. if (self.deleteFiles && self.deleteFiles.indexOf(data.files[0].name)!==-1) {
  2353. self.finishDelete(null, true); //delete file before continuing
  2354. }
  2355. // add ui visualization to existing folder
  2356. if (data.context && data.context.data('type') === 'dir') {
  2357. // add to existing folder
  2358. // update upload counter ui
  2359. var uploadText = data.context.find('.uploadtext');
  2360. var currentUploads = parseInt(uploadText.attr('currentUploads'), 10);
  2361. currentUploads += 1;
  2362. uploadText.attr('currentUploads', currentUploads);
  2363. var translatedText = n('files', 'Uploading %n file', 'Uploading %n files', currentUploads);
  2364. if (currentUploads === 1) {
  2365. self.showFileBusyState(uploadText.closest('tr'), true);
  2366. uploadText.text(translatedText);
  2367. uploadText.show();
  2368. } else {
  2369. uploadText.text(translatedText);
  2370. }
  2371. }
  2372. });
  2373. /*
  2374. * when file upload done successfully add row to filelist
  2375. * update counter when uploading to sub folder
  2376. */
  2377. fileUploadStart.on('fileuploaddone', function(e, data) {
  2378. OC.Upload.log('filelist handle fileuploaddone', e, data);
  2379. var response;
  2380. if (typeof data.result === 'string') {
  2381. response = data.result;
  2382. } else {
  2383. // fetch response from iframe
  2384. response = data.result[0].body.innerText;
  2385. }
  2386. var result = JSON.parse(response);
  2387. if (typeof result[0] !== 'undefined' && result[0].status === 'success') {
  2388. var file = result[0];
  2389. var size = 0;
  2390. if (data.context && data.context.data('type') === 'dir') {
  2391. // update upload counter ui
  2392. var uploadText = data.context.find('.uploadtext');
  2393. var currentUploads = parseInt(uploadText.attr('currentUploads'), 10);
  2394. currentUploads -= 1;
  2395. uploadText.attr('currentUploads', currentUploads);
  2396. var translatedText = n('files', 'Uploading %n file', 'Uploading %n files', currentUploads);
  2397. if (currentUploads === 0) {
  2398. self.showFileBusyState(uploadText.closest('tr'), false);
  2399. uploadText.text(translatedText);
  2400. uploadText.hide();
  2401. } else {
  2402. uploadText.text(translatedText);
  2403. }
  2404. // update folder size
  2405. size = parseInt(data.context.data('size'), 10);
  2406. size += parseInt(file.size, 10);
  2407. data.context.attr('data-size', size);
  2408. data.context.find('td.filesize').text(humanFileSize(size));
  2409. } else {
  2410. // only append new file if uploaded into the current folder
  2411. if (file.directory !== self.getCurrentDirectory()) {
  2412. // Uploading folders actually uploads a list of files
  2413. // for which the target directory (file.directory) might lie deeper
  2414. // than the current directory
  2415. var fileDirectory = file.directory.replace('/','').replace(/\/$/, "");
  2416. var currentDirectory = self.getCurrentDirectory().replace('/','').replace(/\/$/, "") + '/';
  2417. if (currentDirectory !== '/') {
  2418. // abort if fileDirectory does not start with current one
  2419. if (fileDirectory.indexOf(currentDirectory) !== 0) {
  2420. return;
  2421. }
  2422. // remove the current directory part
  2423. fileDirectory = fileDirectory.substr(currentDirectory.length);
  2424. }
  2425. // only take the first section of the path
  2426. fileDirectory = fileDirectory.split('/');
  2427. var fd;
  2428. // if the first section exists / is a subdir
  2429. if (fileDirectory.length) {
  2430. fileDirectory = fileDirectory[0];
  2431. // See whether it is already in the list
  2432. fd = self.findFileEl(fileDirectory);
  2433. if (fd.length === 0) {
  2434. var dir = {
  2435. name: fileDirectory,
  2436. type: 'dir',
  2437. mimetype: 'httpd/unix-directory',
  2438. permissions: file.permissions,
  2439. size: 0,
  2440. id: file.parentId
  2441. };
  2442. fd = self.add(dir, {insert: true});
  2443. }
  2444. // update folder size
  2445. size = parseInt(fd.attr('data-size'), 10);
  2446. size += parseInt(file.size, 10);
  2447. fd.attr('data-size', size);
  2448. fd.find('td.filesize').text(OC.Util.humanFileSize(size));
  2449. }
  2450. return;
  2451. }
  2452. // add as stand-alone row to filelist
  2453. size = t('files', 'Pending');
  2454. if (data.files[0].size>=0) {
  2455. size=data.files[0].size;
  2456. }
  2457. //should the file exist in the list remove it
  2458. self.remove(file.name);
  2459. // create new file context
  2460. data.context = self.add(file, {animate: true});
  2461. }
  2462. }
  2463. });
  2464. fileUploadStart.on('fileuploadstop', function() {
  2465. OC.Upload.log('filelist handle fileuploadstop');
  2466. //cleanup uploading to a dir
  2467. var uploadText = self.$fileList.find('tr .uploadtext');
  2468. self.showFileBusyState(uploadText.closest('tr'), false);
  2469. uploadText.fadeOut();
  2470. uploadText.attr('currentUploads', 0);
  2471. self.updateStorageStatistics();
  2472. });
  2473. fileUploadStart.on('fileuploadfail', function(e, data) {
  2474. OC.Upload.log('filelist handle fileuploadfail', e, data);
  2475. //if user pressed cancel hide upload chrome
  2476. if (data.errorThrown === 'abort') {
  2477. //cleanup uploading to a dir
  2478. var uploadText = self.$fileList.find('tr .uploadtext');
  2479. self.showFileBusyState(uploadText.closest('tr'), false);
  2480. uploadText.fadeOut();
  2481. uploadText.attr('currentUploads', 0);
  2482. }
  2483. self.updateStorageStatistics();
  2484. });
  2485. },
  2486. /**
  2487. * Scroll to the last file of the given list
  2488. * Highlight the list of files
  2489. * @param files array of filenames,
  2490. * @param {Function} [highlightFunction] optional function
  2491. * to be called after the scrolling is finished
  2492. */
  2493. highlightFiles: function(files, highlightFunction) {
  2494. // Detection of the uploaded element
  2495. var filename = files[files.length - 1];
  2496. var $fileRow = this.findFileEl(filename);
  2497. while(!$fileRow.exists() && this._nextPage(false) !== false) { // Checking element existence
  2498. $fileRow = this.findFileEl(filename);
  2499. }
  2500. if (!$fileRow.exists()) { // Element not present in the file list
  2501. return;
  2502. }
  2503. var currentOffset = this.$container.scrollTop();
  2504. var additionalOffset = this.$el.find("#controls").height()+this.$el.find("#controls").offset().top;
  2505. // Animation
  2506. var _this = this;
  2507. var $scrollContainer = this.$container;
  2508. if ($scrollContainer[0] === window) {
  2509. // need to use "body" to animate scrolling
  2510. // when the scroll container is the window
  2511. $scrollContainer = $('body');
  2512. }
  2513. $scrollContainer.animate({
  2514. // Scrolling to the top of the new element
  2515. scrollTop: currentOffset + $fileRow.offset().top - $fileRow.height() * 2 - additionalOffset
  2516. }, {
  2517. duration: 500,
  2518. complete: function() {
  2519. // Highlighting function
  2520. var highlightRow = highlightFunction;
  2521. if (!highlightRow) {
  2522. highlightRow = function($fileRow) {
  2523. $fileRow.addClass("highlightUploaded");
  2524. setTimeout(function() {
  2525. $fileRow.removeClass("highlightUploaded");
  2526. }, 2500);
  2527. };
  2528. }
  2529. // Loop over uploaded files
  2530. for(var i=0; i<files.length; i++) {
  2531. var $fileRow = _this.findFileEl(files[i]);
  2532. if($fileRow.length !== 0) { // Checking element existence
  2533. highlightRow($fileRow);
  2534. }
  2535. }
  2536. }
  2537. });
  2538. },
  2539. _renderNewButton: function() {
  2540. // if an upload button (legacy) already exists or no actions container exist, skip
  2541. var $actionsContainer = this.$el.find('#controls .actions');
  2542. if (!$actionsContainer.length || this.$el.find('.button.upload').length) {
  2543. return;
  2544. }
  2545. if (!this._addButtonTemplate) {
  2546. this._addButtonTemplate = Handlebars.compile(TEMPLATE_ADDBUTTON);
  2547. }
  2548. var $newButton = $(this._addButtonTemplate({
  2549. addText: t('files', 'New'),
  2550. iconClass: 'icon-add'
  2551. }));
  2552. $actionsContainer.prepend($newButton);
  2553. $newButton.tooltip({'placement': 'bottom'});
  2554. $newButton.click(_.bind(this._onClickNewButton, this));
  2555. this._newButton = $newButton;
  2556. },
  2557. _onClickNewButton: function(event) {
  2558. var $target = $(event.target);
  2559. if (!$target.hasClass('.button')) {
  2560. $target = $target.closest('.button');
  2561. }
  2562. this._newButton.tooltip('hide');
  2563. event.preventDefault();
  2564. if ($target.hasClass('disabled')) {
  2565. return false;
  2566. }
  2567. if (!this._newFileMenu) {
  2568. this._newFileMenu = new OCA.Files.NewFileMenu({
  2569. fileList: this
  2570. });
  2571. $('body').append(this._newFileMenu.$el);
  2572. }
  2573. this._newFileMenu.showAt($target);
  2574. return false;
  2575. },
  2576. /**
  2577. * Register a tab view to be added to all views
  2578. */
  2579. registerTabView: function(tabView) {
  2580. if (this._detailsView) {
  2581. this._detailsView.addTabView(tabView);
  2582. }
  2583. },
  2584. /**
  2585. * Register a detail view to be added to all views
  2586. */
  2587. registerDetailView: function(detailView) {
  2588. if (this._detailsView) {
  2589. this._detailsView.addDetailView(detailView);
  2590. }
  2591. }
  2592. };
  2593. /**
  2594. * Sort comparators.
  2595. * @namespace OCA.Files.FileList.Comparators
  2596. * @private
  2597. */
  2598. FileList.Comparators = {
  2599. /**
  2600. * Compares two file infos by name, making directories appear
  2601. * first.
  2602. *
  2603. * @param {OC.Files.FileInfo} fileInfo1 file info
  2604. * @param {OC.Files.FileInfo} fileInfo2 file info
  2605. * @return {int} -1 if the first file must appear before the second one,
  2606. * 0 if they are identify, 1 otherwise.
  2607. */
  2608. name: function(fileInfo1, fileInfo2) {
  2609. if (fileInfo1.type === 'dir' && fileInfo2.type !== 'dir') {
  2610. return -1;
  2611. }
  2612. if (fileInfo1.type !== 'dir' && fileInfo2.type === 'dir') {
  2613. return 1;
  2614. }
  2615. return OC.Util.naturalSortCompare(fileInfo1.name, fileInfo2.name);
  2616. },
  2617. /**
  2618. * Compares two file infos by size.
  2619. *
  2620. * @param {OC.Files.FileInfo} fileInfo1 file info
  2621. * @param {OC.Files.FileInfo} fileInfo2 file info
  2622. * @return {int} -1 if the first file must appear before the second one,
  2623. * 0 if they are identify, 1 otherwise.
  2624. */
  2625. size: function(fileInfo1, fileInfo2) {
  2626. return fileInfo1.size - fileInfo2.size;
  2627. },
  2628. /**
  2629. * Compares two file infos by timestamp.
  2630. *
  2631. * @param {OC.Files.FileInfo} fileInfo1 file info
  2632. * @param {OC.Files.FileInfo} fileInfo2 file info
  2633. * @return {int} -1 if the first file must appear before the second one,
  2634. * 0 if they are identify, 1 otherwise.
  2635. */
  2636. mtime: function(fileInfo1, fileInfo2) {
  2637. return fileInfo1.mtime - fileInfo2.mtime;
  2638. }
  2639. };
  2640. /**
  2641. * File info attributes.
  2642. *
  2643. * @typedef {Object} OC.Files.FileInfo
  2644. *
  2645. * @lends OC.Files.FileInfo
  2646. *
  2647. * @deprecated use OC.Files.FileInfo instead
  2648. *
  2649. */
  2650. OCA.Files.FileInfo = OC.Files.FileInfo;
  2651. OCA.Files.FileList = FileList;
  2652. })();
  2653. $(document).ready(function() {
  2654. // FIXME: unused ?
  2655. OCA.Files.FileList.useUndo = (window.onbeforeunload)?true:false;
  2656. $(window).bind('beforeunload', function () {
  2657. if (OCA.Files.FileList.lastAction) {
  2658. OCA.Files.FileList.lastAction();
  2659. }
  2660. });
  2661. $(window).on('unload', function () {
  2662. $(window).trigger('beforeunload');
  2663. });
  2664. });