filelist.js 119 KB

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