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

filelist.js 113KB

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