filelist.js 103 KB

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