filelist.js 110 KB

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