You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

filelist.js 110KB

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