filelist.js 106 KB

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