1
0

public.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. /*
  2. * Copyright (c) 2014
  3. * @copyright Copyright (c) 2016, Björn Schießle <bjoern@schiessle.org>
  4. *
  5. * This file is licensed under the Affero General Public License version 3
  6. * or later.
  7. *
  8. * See the COPYING-README file.
  9. *
  10. */
  11. /* global FileActions, Files, FileList */
  12. /* global dragOptions, folderDropOptions */
  13. if (!OCA.Sharing) {
  14. OCA.Sharing = {};
  15. }
  16. if (!OCA.Files) {
  17. OCA.Files = {};
  18. }
  19. /**
  20. * @namespace
  21. */
  22. OCA.Sharing.PublicApp = {
  23. _initialized: false,
  24. /**
  25. * Initializes the public share app.
  26. *
  27. * @param $el container
  28. */
  29. initialize: function ($el) {
  30. var self = this;
  31. var fileActions;
  32. if (this._initialized) {
  33. return;
  34. }
  35. fileActions = new OCA.Files.FileActions();
  36. // default actions
  37. fileActions.registerDefaultActions();
  38. // regular actions
  39. fileActions.merge(OCA.Files.fileActions);
  40. // in case apps would decide to register file actions later,
  41. // replace the global object with this one
  42. OCA.Files.fileActions = fileActions;
  43. this._initialized = true;
  44. var urlParams = OC.Util.History.parseUrlQuery();
  45. this.initialDir = urlParams.path || '/';
  46. var token = $('#sharingToken').val();
  47. var hideDownload = $('#hideDownload').val();
  48. // Prevent all right-click options if hideDownload is enabled
  49. if (hideDownload === 'true') {
  50. window.oncontextmenu = function(event) {
  51. event.preventDefault();
  52. event.stopPropagation();
  53. return false;
  54. };
  55. }
  56. // file list mode ?
  57. if ($el.find('.files-filestable').length) {
  58. // Toggle for grid view
  59. this.$showGridView = $('input#showgridview');
  60. this.$showGridView.on('change', _.bind(this._onGridviewChange, this));
  61. var filesClient = new OC.Files.Client({
  62. host: OC.getHost(),
  63. port: OC.getPort(),
  64. userName: token,
  65. // note: password not be required, the endpoint
  66. // will recognize previous validation from the session
  67. root: OC.getRootPath() + '/public.php/webdav',
  68. useHTTPS: OC.getProtocol() === 'https'
  69. });
  70. this.fileList = new OCA.Files.FileList(
  71. $el,
  72. {
  73. id: 'files.public',
  74. dragOptions: dragOptions,
  75. folderDropOptions: folderDropOptions,
  76. fileActions: fileActions,
  77. detailsViewEnabled: false,
  78. filesClient: filesClient,
  79. enableUpload: true,
  80. multiSelectMenu: [
  81. {
  82. name: 'copyMove',
  83. displayName: t('files', 'Move or copy'),
  84. iconClass: 'icon-external',
  85. },
  86. {
  87. name: 'download',
  88. displayName: t('files', 'Download'),
  89. iconClass: 'icon-download',
  90. },
  91. {
  92. name: 'delete',
  93. displayName: t('files', 'Delete'),
  94. iconClass: 'icon-delete',
  95. }
  96. ]
  97. }
  98. );
  99. if (hideDownload === 'true') {
  100. this.fileList._allowSelection = false;
  101. }
  102. this.files = OCA.Files.Files;
  103. this.files.initialize();
  104. // TODO: move to PublicFileList.initialize() once
  105. // the code was split into a separate class
  106. OC.Plugins.attach('OCA.Sharing.PublicFileList', this.fileList);
  107. }
  108. var mimetype = $('#mimetype').val();
  109. var mimetypeIcon = $('#mimetypeIcon').val();
  110. mimetypeIcon = mimetypeIcon.substring(0, mimetypeIcon.length - 3);
  111. mimetypeIcon = mimetypeIcon + 'svg';
  112. var previewSupported = $('#previewSupported').val();
  113. if (typeof FileActions !== 'undefined') {
  114. // Show file preview if previewer is available, images are already handled by the template
  115. if (mimetype.substr(0, mimetype.indexOf('/')) !== 'image' && $('.publicpreview').length === 0) {
  116. // Trigger default action if not download TODO
  117. var spec = FileActions.getDefaultFileAction(mimetype, 'file', OC.PERMISSION_READ);
  118. if (spec && spec.action) {
  119. spec.action($('#filename').val());
  120. }
  121. }
  122. }
  123. // dynamically load image previews
  124. var bottomMargin = 350;
  125. var previewWidth = $(window).width();
  126. var previewHeight = $(window).height() - bottomMargin;
  127. previewHeight = Math.max(200, previewHeight);
  128. var params = {
  129. x: Math.ceil(previewWidth * window.devicePixelRatio),
  130. y: Math.ceil(previewHeight * window.devicePixelRatio),
  131. a: 'true',
  132. file: encodeURIComponent(this.initialDir + $('#filename').val()),
  133. scalingup: 0
  134. };
  135. var imgcontainer = $('<img class="publicpreview" alt="">');
  136. if (hideDownload === 'false') {
  137. imgcontainer = $('<a href="' + $('#previewURL').val() + '" target="_blank"></a>').append(imgcontainer);
  138. }
  139. var img = imgcontainer.hasClass('publicpreview')? imgcontainer: imgcontainer.find('.publicpreview');
  140. img.css({
  141. 'max-width': previewWidth,
  142. 'max-height': previewHeight
  143. });
  144. if (OCA.Viewer && OCA.Viewer.mimetypes.includes(mimetype)
  145. && (mimetype.startsWith('image/') || mimetype.startsWith('video/') || mimetype.startsWith('audio'))) {
  146. OCA.Viewer.setRootElement('#imgframe')
  147. OCA.Viewer.open({ path: '/' })
  148. } else if (mimetype.substr(0, mimetype.indexOf('/')) === 'text' && window.btoa) {
  149. if (OC.appswebroots['files_texteditor'] !== undefined ||
  150. OC.appswebroots['text'] !== undefined) {
  151. // the text editor handles the previewing
  152. return;
  153. }
  154. // Undocumented Url to public WebDAV endpoint
  155. var url = parent.location.protocol + '//' + location.host + OC.linkTo('', 'public.php/webdav');
  156. $.ajax({
  157. url: url,
  158. headers: {
  159. Authorization: 'Basic ' + btoa(token + ':'),
  160. Range: 'bytes=0-10000'
  161. }
  162. }).then(function (data) {
  163. self._showTextPreview(data, previewHeight);
  164. });
  165. } else if ((previewSupported === 'true' && mimetype.substr(0, mimetype.indexOf('/')) !== 'video') ||
  166. mimetype.substr(0, mimetype.indexOf('/')) === 'image' &&
  167. mimetype !== 'image/svg+xml') {
  168. img.attr('src', OC.generateUrl('/apps/files_sharing/publicpreview/' + token + '?' + OC.buildQueryString(params)));
  169. imgcontainer.appendTo('#imgframe');
  170. } else if (mimetype.substr(0, mimetype.indexOf('/')) !== 'video') {
  171. img.attr('src', mimetypeIcon);
  172. img.attr('width', 128);
  173. // "#imgframe" is either empty or it contains an audio preview that
  174. // the icon should appear before, so the container should be
  175. // prepended to the frame.
  176. imgcontainer.prependTo('#imgframe');
  177. } else if (previewSupported === 'true') {
  178. $('#imgframe > video').attr('poster', OC.generateUrl('/apps/files_sharing/publicpreview/' + token + '?' + OC.buildQueryString(params)));
  179. }
  180. if (this.fileList) {
  181. // TODO: move this to a separate PublicFileList class that extends OCA.Files.FileList (+ unit tests)
  182. this.fileList.getDownloadUrl = function (filename, dir, isDir) {
  183. var path = dir || this.getCurrentDirectory();
  184. if (_.isArray(filename)) {
  185. filename = JSON.stringify(filename);
  186. }
  187. var params = {
  188. path: path
  189. };
  190. if (filename) {
  191. params.files = filename;
  192. }
  193. return OC.generateUrl('/s/' + token + '/download') + '?' + OC.buildQueryString(params);
  194. };
  195. this.fileList._createRow = function(fileData) {
  196. var $tr = OCA.Files.FileList.prototype._createRow.apply(this, arguments);
  197. if (hideDownload === 'true') {
  198. this.fileActions.currentFile = $tr.find('td');
  199. // Remove the link. This means that files without a default action fail hard
  200. $tr.find('a.name').attr('href', '#');
  201. delete this.fileActions.actions.all.Download;
  202. }
  203. return $tr;
  204. };
  205. this.fileList.isSelectedDownloadable = function () {
  206. return hideDownload !== 'true';
  207. };
  208. this.fileList.getUploadUrl = function(fileName, dir) {
  209. if (_.isUndefined(dir)) {
  210. dir = this.getCurrentDirectory();
  211. }
  212. var pathSections = dir.split('/');
  213. if (!_.isUndefined(fileName)) {
  214. pathSections.push(fileName);
  215. }
  216. var encodedPath = '';
  217. _.each(pathSections, function(section) {
  218. if (section !== '') {
  219. encodedPath += '/' + encodeURIComponent(section);
  220. }
  221. });
  222. var base = '';
  223. if (!this._uploader.isXHRUpload()) {
  224. // also add auth in URL due to POST workaround
  225. base = OC.getProtocol() + '://' + token + '@' + OC.getHost() + (OC.getPort() ? ':' + OC.getPort() : '');
  226. }
  227. return base + OC.getRootPath() + '/public.php/webdav' + encodedPath;
  228. };
  229. this.fileList.getAjaxUrl = function (action, params) {
  230. params = params || {};
  231. params.t = token;
  232. return OC.filePath('files_sharing', 'ajax', action + '.php') + '?' + OC.buildQueryString(params);
  233. };
  234. this.fileList.linkTo = function (dir) {
  235. return OC.generateUrl('/s/' + token + '') + '?' + OC.buildQueryString({path: dir});
  236. };
  237. this.fileList.generatePreviewUrl = function (urlSpec) {
  238. urlSpec = urlSpec || {};
  239. if (!urlSpec.x) {
  240. urlSpec.x = this.$table.data('preview-x') || 250;
  241. }
  242. if (!urlSpec.y) {
  243. urlSpec.y = this.$table.data('preview-y') || 250;
  244. }
  245. urlSpec.x *= window.devicePixelRatio;
  246. urlSpec.y *= window.devicePixelRatio;
  247. urlSpec.x = Math.ceil(urlSpec.x);
  248. urlSpec.y = Math.ceil(urlSpec.y);
  249. var token = $('#dirToken').val();
  250. return OC.generateUrl('/apps/files_sharing/publicpreview/' + token + '?' + OC.buildQueryString(urlSpec));
  251. };
  252. this.fileList.updateEmptyContent = function() {
  253. this.$el.find('.emptycontent .uploadmessage').text(
  254. t('files_sharing', 'You can upload into this folder')
  255. );
  256. OCA.Files.FileList.prototype.updateEmptyContent.apply(this, arguments);
  257. };
  258. this.fileList._uploader.on('fileuploadadd', function(e, data) {
  259. if (!data.headers) {
  260. data.headers = {};
  261. }
  262. data.headers.Authorization = 'Basic ' + btoa(token + ':');
  263. });
  264. // do not allow sharing from the public page
  265. delete this.fileList.fileActions.actions.all.Share;
  266. this.fileList.changeDirectory(this.initialDir || '/', false, true);
  267. // URL history handling
  268. this.fileList.$el.on('changeDirectory', _.bind(this._onDirectoryChanged, this));
  269. OC.Util.History.addOnPopStateHandler(_.bind(this._onUrlChanged, this));
  270. $('#download').click(function (e) {
  271. e.preventDefault();
  272. OC.redirect(FileList.getDownloadUrl());
  273. });
  274. if (hideDownload === 'true') {
  275. this.fileList.$el.find('.summary').find('td:first-child').remove();
  276. }
  277. }
  278. $(document).on('click', '#directLink', function () {
  279. $(this).focus();
  280. $(this).select();
  281. });
  282. $('.save-form').submit(function (event) {
  283. event.preventDefault();
  284. var remote = $(this).find('#remote_address').val();
  285. var token = $('#sharingToken').val();
  286. var owner = $('#save-external-share').data('owner');
  287. var ownerDisplayName = $('#save-external-share').data('owner-display-name');
  288. var name = $('#save-external-share').data('name');
  289. var isProtected = $('#save-external-share').data('protected') ? 1 : 0;
  290. OCA.Sharing.PublicApp._createFederatedShare(remote, token, owner, ownerDisplayName, name, isProtected);
  291. });
  292. $('#remote_address').on("keyup paste", function() {
  293. if ($(this).val() === '' || $('#save-external-share > .icon.icon-loading-small').length > 0) {
  294. $('#save-button-confirm').prop('disabled', true);
  295. } else {
  296. $('#save-button-confirm').prop('disabled', false);
  297. }
  298. });
  299. self._bindShowTermsAction();
  300. // legacy
  301. window.FileList = this.fileList;
  302. },
  303. /**
  304. * Binds the click action for the "terms of service" action.
  305. * Shows an OC info dialog on click.
  306. *
  307. * @private
  308. */
  309. _bindShowTermsAction: function() {
  310. $('#show-terms-dialog').on('click', function() {
  311. OC.dialogs.info($('#disclaimerText').val(), t('files_sharing', 'Terms of service'));
  312. });
  313. },
  314. _showTextPreview: function (data, previewHeight) {
  315. var textDiv = $('<div></div>').addClass('text-preview');
  316. textDiv.text(data);
  317. textDiv.appendTo('#imgframe');
  318. var divHeight = textDiv.height();
  319. if (data.length > 999) {
  320. var ellipsis = $('<div></div>').addClass('ellipsis');
  321. ellipsis.html('(&#133;)');
  322. ellipsis.appendTo('#imgframe');
  323. }
  324. if (divHeight > previewHeight) {
  325. textDiv.height(previewHeight);
  326. }
  327. },
  328. /**
  329. * Toggle showing gridview by default or not
  330. *
  331. * @returns {undefined}
  332. */
  333. _onGridviewChange: function() {
  334. const isGridView = this.$showGridView.is(':checked');
  335. this.$showGridView.next('#view-toggle')
  336. .removeClass('icon-toggle-filelist icon-toggle-pictures')
  337. .addClass(isGridView ? 'icon-toggle-filelist' : 'icon-toggle-pictures')
  338. this.$showGridView.next('#view-toggle').attr(
  339. 'title',
  340. isGridView ? t('files', 'Show list view') : t('files', 'Show grid view'),
  341. )
  342. if (this.fileList) {
  343. this.fileList.setGridView(isGridView);
  344. }
  345. },
  346. _onDirectoryChanged: function (e) {
  347. OC.Util.History.pushState({
  348. // arghhhh, why is this not called "dir" !?
  349. path: e.dir
  350. });
  351. },
  352. _onUrlChanged: function (params) {
  353. this.fileList.changeDirectory(params.path || params.dir, false, true);
  354. },
  355. /**
  356. * fall back to old behaviour where we redirect the user to his server to mount
  357. * the public link instead of creating a dedicated federated share
  358. *
  359. * @param {any} remote -
  360. * @param {any} token -
  361. * @param {any} owner -
  362. * @param {any} ownerDisplayName -
  363. * @param {any} name -
  364. * @param {any} isProtected -
  365. * @private
  366. */
  367. _legacyCreateFederatedShare: function (remote, token, owner, ownerDisplayName, name, isProtected) {
  368. var self = this;
  369. var location = window.location.protocol + '//' + window.location.host + OC.getRootPath();
  370. if(remote.substr(-1) !== '/') {
  371. remote += '/'
  372. }
  373. var url = remote + 'index.php/apps/files#' + 'remote=' + encodeURIComponent(location) // our location is the remote for the other server
  374. + "&token=" + encodeURIComponent(token) + "&owner=" + encodeURIComponent(owner) +"&ownerDisplayName=" + encodeURIComponent(ownerDisplayName) + "&name=" + encodeURIComponent(name) + "&protected=" + isProtected;
  375. if (remote.indexOf('://') > 0) {
  376. OC.redirect(url);
  377. } else {
  378. // if no protocol is specified, we automatically detect it by testing https and http
  379. // this check needs to happen on the server due to the Content Security Policy directive
  380. $.get(OC.generateUrl('apps/files_sharing/testremote'), {remote: remote}).then(function (protocol) {
  381. if (protocol !== 'http' && protocol !== 'https') {
  382. self._toggleLoading();
  383. OC.dialogs.alert(t('files_sharing', 'No compatible server found at {remote}', {remote: remote}),
  384. t('files_sharing', 'Invalid server URL'));
  385. } else {
  386. OC.redirect(protocol + '://' + url);
  387. }
  388. });
  389. }
  390. },
  391. _toggleLoading: function() {
  392. var loading = $('#save-external-share > .icon.icon-loading-small').length === 0;
  393. if (loading) {
  394. $('#save-external-share > .icon-external')
  395. .removeClass("icon-external")
  396. .addClass("icon-loading-small");
  397. $('#save-external-share #save-button-confirm').prop("disabled", true);
  398. } else {
  399. $('#save-external-share > .icon-loading-small')
  400. .addClass("icon-external")
  401. .removeClass("icon-loading-small");
  402. $('#save-external-share #save-button-confirm').prop("disabled", false);
  403. }
  404. },
  405. _createFederatedShare: function (remote, token, owner, ownerDisplayName, name, isProtected) {
  406. var self = this;
  407. this._toggleLoading();
  408. if (remote.indexOf('@') === -1) {
  409. this._legacyCreateFederatedShare(remote, token, owner, ownerDisplayName, name, isProtected);
  410. return;
  411. }
  412. $.post(
  413. OC.generateUrl('/apps/federatedfilesharing/createFederatedShare'),
  414. {
  415. 'shareWith': remote,
  416. 'token': token
  417. }
  418. ).done(
  419. function (data) {
  420. var url = data.remoteUrl;
  421. if (url.indexOf('://') > 0) {
  422. OC.redirect(url);
  423. } else {
  424. OC.redirect('http://' + url);
  425. }
  426. }
  427. ).fail(
  428. function (jqXHR) {
  429. OC.dialogs.alert(JSON.parse(jqXHR.responseText).message,
  430. t('files_sharing', 'Failed to add the public link to your Nextcloud'));
  431. self._toggleLoading();
  432. }
  433. );
  434. }
  435. };
  436. window.addEventListener('DOMContentLoaded', function () {
  437. // FIXME: replace with OC.Plugins.register()
  438. if (window.TESTING) {
  439. return;
  440. }
  441. var App = OCA.Sharing.PublicApp;
  442. // defer app init, to give a chance to plugins to register file actions
  443. _.defer(function () {
  444. App.initialize($('#preview'));
  445. });
  446. if (window.Files) {
  447. // HACK: for oc-dialogs previews that depends on Files:
  448. Files.generatePreviewUrl = function (urlSpec) {
  449. return App.fileList.generatePreviewUrl(urlSpec);
  450. };
  451. }
  452. });