filelist.js 110 KB

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