1
0

filelist.js 120 KB

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