1
0

filelist.js 120 KB

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