filelist.js 88 KB

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