filelist.js 113 KB

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