filelist.js 119 KB

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