filelist.js 110 KB

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