sharedfilelist.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. /*
  2. * Copyright (c) 2014 Vincent Petry <pvince81@owncloud.com>
  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.Sharing.FileList
  13. * @augments OCA.Files.FileList
  14. *
  15. * @classdesc Sharing file list.
  16. * Contains both "shared with others" and "shared with you" modes.
  17. *
  18. * @param $el container element with existing markup for the #controls
  19. * and a table
  20. * @param [options] map of options, see other parameters
  21. * @param {boolean} [options.sharedWithUser] true to return files shared with
  22. * the current user, false to return files that the user shared with others.
  23. * Defaults to false.
  24. * @param {boolean} [options.linksOnly] true to return only link shares
  25. */
  26. var FileList = function($el, options) {
  27. this.initialize($el, options);
  28. };
  29. FileList.prototype = _.extend({}, OCA.Files.FileList.prototype,
  30. /** @lends OCA.Sharing.FileList.prototype */ {
  31. appName: 'Shares',
  32. /**
  33. * Whether the list shows the files shared with the user (true) or
  34. * the files that the user shared with others (false).
  35. */
  36. _sharedWithUser: false,
  37. _linksOnly: false,
  38. _clientSideSort: true,
  39. _allowSelection: false,
  40. /**
  41. * @private
  42. */
  43. initialize: function($el, options) {
  44. OCA.Files.FileList.prototype.initialize.apply(this, arguments);
  45. if (this.initialized) {
  46. return;
  47. }
  48. // TODO: consolidate both options
  49. if (options && options.sharedWithUser) {
  50. this._sharedWithUser = true;
  51. }
  52. if (options && options.linksOnly) {
  53. this._linksOnly = true;
  54. }
  55. },
  56. _renderRow: function() {
  57. // HACK: needed to call the overridden _renderRow
  58. // this is because at the time this class is created
  59. // the overriding hasn't been done yet...
  60. return OCA.Files.FileList.prototype._renderRow.apply(this, arguments);
  61. },
  62. _createRow: function(fileData) {
  63. // TODO: hook earlier and render the whole row here
  64. var $tr = OCA.Files.FileList.prototype._createRow.apply(this, arguments);
  65. $tr.find('.filesize').remove();
  66. $tr.find('td.date').before($tr.children('td:first'));
  67. $tr.find('td.filename input:checkbox').remove();
  68. $tr.attr('data-share-id', _.pluck(fileData.shares, 'id').join(','));
  69. if (this._sharedWithUser) {
  70. $tr.attr('data-share-owner', fileData.shareOwner);
  71. $tr.attr('data-mounttype', 'shared-root');
  72. var permission = parseInt($tr.attr('data-permissions')) | OC.PERMISSION_DELETE;
  73. $tr.attr('data-permissions', permission);
  74. }
  75. // add row with expiration date for link only shares - influenced by _createRow of filelist
  76. if (this._linksOnly) {
  77. var expirationTimestamp = 0;
  78. if(fileData.shares && fileData.shares[0].expiration !== null) {
  79. expirationTimestamp = moment(fileData.shares[0].expiration).valueOf();
  80. }
  81. $tr.attr('data-expiration', expirationTimestamp);
  82. // date column (1000 milliseconds to seconds, 60 seconds, 60 minutes, 24 hours)
  83. // difference in days multiplied by 5 - brightest shade for expiry dates in more than 32 days (160/5)
  84. var modifiedColor = Math.round((expirationTimestamp - (new Date()).getTime()) / 1000 / 60 / 60 / 24 * 5);
  85. // ensure that the brightest color is still readable
  86. if (modifiedColor >= 160) {
  87. modifiedColor = 160;
  88. }
  89. if (expirationTimestamp > 0) {
  90. formatted = OC.Util.formatDate(expirationTimestamp);
  91. text = OC.Util.relativeModifiedDate(expirationTimestamp);
  92. } else {
  93. formatted = t('files_sharing', 'No expiration date set');
  94. text = '';
  95. modifiedColor = 160;
  96. }
  97. td = $('<td></td>').attr({"class": "date"});
  98. td.append($('<span></span>').attr({
  99. "class": "modified",
  100. "title": formatted,
  101. "style": 'color:rgb(' + modifiedColor + ',' + modifiedColor + ',' + modifiedColor + ')'
  102. }).text(text)
  103. .tooltip({placement: 'top'})
  104. );
  105. $tr.append(td);
  106. }
  107. return $tr;
  108. },
  109. /**
  110. * Set whether the list should contain outgoing shares
  111. * or incoming shares.
  112. *
  113. * @param state true for incoming shares, false otherwise
  114. */
  115. setSharedWithUser: function(state) {
  116. this._sharedWithUser = !!state;
  117. },
  118. updateEmptyContent: function() {
  119. var dir = this.getCurrentDirectory();
  120. if (dir === '/') {
  121. // root has special permissions
  122. this.$el.find('#emptycontent').toggleClass('hidden', !this.isEmpty);
  123. this.$el.find('#filestable thead th').toggleClass('hidden', this.isEmpty);
  124. // hide expiration date header for non link only shares
  125. if (!this._linksOnly) {
  126. this.$el.find('th.column-expiration').addClass('hidden');
  127. }
  128. }
  129. else {
  130. OCA.Files.FileList.prototype.updateEmptyContent.apply(this, arguments);
  131. }
  132. },
  133. getDirectoryPermissions: function() {
  134. return OC.PERMISSION_READ | OC.PERMISSION_DELETE;
  135. },
  136. updateStorageStatistics: function() {
  137. // no op because it doesn't have
  138. // storage info like free space / used space
  139. },
  140. updateRow: function($tr, fileInfo, options) {
  141. if(!fileInfo instanceof OCA.Sharing.SharedFileInfo) {
  142. // recycle SharedFileInfo values if something tries to overwrite it
  143. var oldModel = this.getModelForFile($tr);
  144. if(_.isUndefined(fileInfo.recipientData) && oldModel.recipientData) {
  145. fileInfo.recipientData = oldModel.recipientData;
  146. }
  147. if(_.isUndefined(fileInfo.recipients) && oldModel.recipientData) {
  148. fileInfo.recipientData = oldModel.recipientData;
  149. }
  150. if(_.isUndefined(fileInfo.shares) && oldModel.shares) {
  151. fileInfo.shares = oldModel.shares;
  152. }
  153. if(_.isUndefined(fileInfo.shareOwner) && oldModel.shareOwner) {
  154. fileInfo.shareOwner = oldModel.shareOwner;
  155. }
  156. }
  157. OCA.Files.FileList.prototype._createRow.updateRow(this, arguments);
  158. },
  159. reload: function() {
  160. this.showMask();
  161. if (this._reloadCall) {
  162. this._reloadCall.abort();
  163. }
  164. // there is only root
  165. this._setCurrentDir('/', false);
  166. var promises = [];
  167. var shares = $.ajax({
  168. url: OC.linkToOCS('apps/files_sharing/api/v1') + 'shares',
  169. /* jshint camelcase: false */
  170. data: {
  171. format: 'json',
  172. shared_with_me: !!this._sharedWithUser,
  173. include_tags: true
  174. },
  175. type: 'GET',
  176. beforeSend: function(xhr) {
  177. xhr.setRequestHeader('OCS-APIREQUEST', 'true');
  178. },
  179. });
  180. promises.push(shares);
  181. if (!!this._sharedWithUser) {
  182. var remoteShares = $.ajax({
  183. url: OC.linkToOCS('apps/files_sharing/api/v1') + 'remote_shares',
  184. /* jshint camelcase: false */
  185. data: {
  186. format: 'json',
  187. include_tags: true
  188. },
  189. type: 'GET',
  190. beforeSend: function(xhr) {
  191. xhr.setRequestHeader('OCS-APIREQUEST', 'true');
  192. },
  193. });
  194. promises.push(remoteShares);
  195. } else {
  196. //Push empty promise so callback gets called the same way
  197. promises.push($.Deferred().resolve());
  198. }
  199. this._reloadCall = $.when.apply($, promises);
  200. var callBack = this.reloadCallback.bind(this);
  201. return this._reloadCall.then(callBack, callBack);
  202. },
  203. reloadCallback: function(shares, remoteShares) {
  204. delete this._reloadCall;
  205. this.hideMask();
  206. this.$el.find('#headerSharedWith').text(
  207. t('files_sharing', this._sharedWithUser ? 'Shared by' : 'Shared with')
  208. );
  209. var files = [];
  210. if (shares[0].ocs && shares[0].ocs.data) {
  211. files = files.concat(this._makeFilesFromShares(shares[0].ocs.data));
  212. }
  213. if (remoteShares && remoteShares[0].ocs && remoteShares[0].ocs.data) {
  214. files = files.concat(this._makeFilesFromRemoteShares(remoteShares[0].ocs.data));
  215. }
  216. this.setFiles(files);
  217. return true;
  218. },
  219. _makeFilesFromRemoteShares: function(data) {
  220. var files = data;
  221. files = _.chain(files)
  222. // convert share data to file data
  223. .map(function(share) {
  224. var file = {
  225. shareOwner: share.owner + '@' + share.remote.replace(/.*?:\/\//g, ""),
  226. name: OC.basename(share.mountpoint),
  227. mtime: share.mtime * 1000,
  228. mimetype: share.mimetype,
  229. type: share.type,
  230. id: share.file_id,
  231. path: OC.dirname(share.mountpoint),
  232. permissions: share.permissions,
  233. tags: share.tags || []
  234. };
  235. file.shares = [{
  236. id: share.id,
  237. type: OC.Share.SHARE_TYPE_REMOTE
  238. }];
  239. return file;
  240. })
  241. .value();
  242. return files;
  243. },
  244. /**
  245. * Converts the OCS API share response data to a file info
  246. * list
  247. * @param {Array} data OCS API share array
  248. * @return {Array.<OCA.Sharing.SharedFileInfo>} array of shared file info
  249. */
  250. _makeFilesFromShares: function(data) {
  251. /* jshint camelcase: false */
  252. var self = this;
  253. var files = data;
  254. if (this._linksOnly) {
  255. files = _.filter(data, function(share) {
  256. return share.share_type === OC.Share.SHARE_TYPE_LINK;
  257. });
  258. }
  259. // OCS API uses non-camelcased names
  260. files = _.chain(files)
  261. // convert share data to file data
  262. .map(function(share) {
  263. // TODO: use OC.Files.FileInfo
  264. var file = {
  265. id: share.file_source,
  266. icon: OC.MimeType.getIconUrl(share.mimetype),
  267. mimetype: share.mimetype,
  268. tags: share.tags || []
  269. };
  270. if (share.item_type === 'folder') {
  271. file.type = 'dir';
  272. file.mimetype = 'httpd/unix-directory';
  273. }
  274. else {
  275. file.type = 'file';
  276. }
  277. file.share = {
  278. id: share.id,
  279. type: share.share_type,
  280. target: share.share_with,
  281. stime: share.stime * 1000,
  282. expiration: share.expiration,
  283. };
  284. if (self._sharedWithUser) {
  285. file.shareOwner = share.displayname_owner;
  286. file.shareOwnerId = share.uid_owner;
  287. file.name = OC.basename(share.file_target);
  288. file.path = OC.dirname(share.file_target);
  289. file.permissions = share.permissions;
  290. if (file.path) {
  291. file.extraData = share.file_target;
  292. }
  293. }
  294. else {
  295. if (share.share_type !== OC.Share.SHARE_TYPE_LINK) {
  296. file.share.targetDisplayName = share.share_with_displayname;
  297. file.share.targetShareWithId = share.share_with;
  298. }
  299. file.name = OC.basename(share.path);
  300. file.path = OC.dirname(share.path);
  301. file.permissions = OC.PERMISSION_ALL;
  302. if (file.path) {
  303. file.extraData = share.path;
  304. }
  305. }
  306. return file;
  307. })
  308. // Group all files and have a "shares" array with
  309. // the share info for each file.
  310. //
  311. // This uses a hash memo to cumulate share information
  312. // inside the same file object (by file id).
  313. .reduce(function(memo, file) {
  314. var data = memo[file.id];
  315. var recipient = file.share.targetDisplayName;
  316. var recipientId = file.share.targetShareWithId;
  317. if (!data) {
  318. data = memo[file.id] = file;
  319. data.shares = [file.share];
  320. // using a hash to make them unique,
  321. // this is only a list to be displayed
  322. data.recipients = {};
  323. data.recipientData = {};
  324. // share types
  325. data.shareTypes = {};
  326. // counter is cheaper than calling _.keys().length
  327. data.recipientsCount = 0;
  328. data.mtime = file.share.stime;
  329. }
  330. else {
  331. // always take the most recent stime
  332. if (file.share.stime > data.mtime) {
  333. data.mtime = file.share.stime;
  334. }
  335. data.shares.push(file.share);
  336. }
  337. if (recipient) {
  338. // limit counterparts for output
  339. if (data.recipientsCount < 4) {
  340. // only store the first ones, they will be the only ones
  341. // displayed
  342. data.recipients[recipient] = true;
  343. data.recipientData[data.recipientsCount] = {
  344. 'shareWith': recipientId,
  345. 'shareWithDisplayName': recipient
  346. };
  347. }
  348. data.recipientsCount++;
  349. }
  350. data.shareTypes[file.share.type] = true;
  351. delete file.share;
  352. return memo;
  353. }, {})
  354. // Retrieve only the values of the returned hash
  355. .values()
  356. // Clean up
  357. .each(function(data) {
  358. // convert the recipients map to a flat
  359. // array of sorted names
  360. data.mountType = 'shared';
  361. delete data.recipientsCount;
  362. if (self._sharedWithUser) {
  363. // only for outgoing shres
  364. delete data.shareTypes;
  365. } else {
  366. data.shareTypes = _.keys(data.shareTypes);
  367. }
  368. })
  369. // Finish the chain by getting the result
  370. .value();
  371. // Sort by expected sort comparator
  372. return files.sort(this._sortComparator);
  373. },
  374. _onUrlChanged: function(e) {
  375. if (e && _.isString(e.dir)) {
  376. this.changeDirectory(e.dir, false, true);
  377. }
  378. }
  379. });
  380. /**
  381. * Share info attributes.
  382. *
  383. * @typedef {Object} OCA.Sharing.ShareInfo
  384. *
  385. * @property {int} id share ID
  386. * @property {int} type share type
  387. * @property {String} target share target, either user name or group name
  388. * @property {int} stime share timestamp in milliseconds
  389. * @property {String} [targetDisplayName] display name of the recipient
  390. * (only when shared with others)
  391. * @property {String} [targetShareWithId] id of the recipient
  392. *
  393. */
  394. /**
  395. * Recipient attributes
  396. *
  397. * @typedef {Object} OCA.Sharing.RecipientInfo
  398. * @property {String} shareWith the id of the recipient
  399. * @property {String} shareWithDisplayName the display name of the recipient
  400. */
  401. /**
  402. * Shared file info attributes.
  403. *
  404. * @typedef {OCA.Files.FileInfo} OCA.Sharing.SharedFileInfo
  405. *
  406. * @property {Array.<OCA.Sharing.ShareInfo>} shares array of shares for
  407. * this file
  408. * @property {int} mtime most recent share time (if multiple shares)
  409. * @property {String} shareOwner name of the share owner
  410. * @property {Array.<String>} recipients name of the first 4 recipients
  411. * (this is mostly for display purposes)
  412. * @property {Object.<OCA.Sharing.RecipientInfo>} recipientData (as object for easier
  413. * passing to HTML data attributes with jQuery)
  414. */
  415. OCA.Sharing.FileList = FileList;
  416. })();