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

filelist.js 94KB

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