filelist.js 120 KB

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