filelist.js 109 KB

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