1
0

public.js 15 KB

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