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

filelist.js 119KB

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