1
0

filelist.js 120 KB

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