1
0

public.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. // file list mode ?
  49. if ($el.find('#filestable').length) {
  50. var filesClient = new OC.Files.Client({
  51. host: OC.getHost(),
  52. port: OC.getPort(),
  53. userName: token,
  54. // note: password not be required, the endpoint
  55. // will recognize previous validation from the session
  56. root: OC.getRootPath() + '/public.php/webdav',
  57. useHTTPS: OC.getProtocol() === 'https'
  58. });
  59. this.fileList = new OCA.Files.FileList(
  60. $el,
  61. {
  62. id: 'files.public',
  63. scrollContainer: $('#content-wrapper'),
  64. dragOptions: dragOptions,
  65. folderDropOptions: folderDropOptions,
  66. fileActions: fileActions,
  67. detailsViewEnabled: false,
  68. filesClient: filesClient
  69. }
  70. );
  71. this.files = OCA.Files.Files;
  72. this.files.initialize();
  73. // TODO: move to PublicFileList.initialize() once
  74. // the code was split into a separate class
  75. OC.Plugins.attach('OCA.Sharing.PublicFileList', this.fileList);
  76. }
  77. var mimetype = $('#mimetype').val();
  78. var mimetypeIcon = $('#mimetypeIcon').val();
  79. mimetypeIcon = mimetypeIcon.substring(0, mimetypeIcon.length - 3);
  80. mimetypeIcon = mimetypeIcon + 'svg';
  81. var previewSupported = $('#previewSupported').val();
  82. if (typeof FileActions !== 'undefined') {
  83. // Show file preview if previewer is available, images are already handled by the template
  84. if (mimetype.substr(0, mimetype.indexOf('/')) !== 'image' && $('.publicpreview').length === 0) {
  85. // Trigger default action if not download TODO
  86. var action = FileActions.getDefault(mimetype, 'file', OC.PERMISSION_READ);
  87. if (typeof action !== 'undefined') {
  88. action($('#filename').val());
  89. }
  90. }
  91. }
  92. // dynamically load image previews
  93. var bottomMargin = 350;
  94. var previewWidth = $(window).width();
  95. var previewHeight = $(window).height() - bottomMargin;
  96. previewHeight = Math.max(200, previewHeight);
  97. var params = {
  98. x: Math.ceil(previewWidth * window.devicePixelRatio),
  99. y: Math.ceil(previewHeight * window.devicePixelRatio),
  100. a: 'true',
  101. file: encodeURIComponent(this.initialDir + $('#filename').val()),
  102. t: token,
  103. scalingup: 0
  104. };
  105. var img = $('<img class="publicpreview" alt="">');
  106. img.css({
  107. 'max-width': previewWidth,
  108. 'max-height': previewHeight
  109. });
  110. var fileSize = parseInt($('#filesize').val(), 10);
  111. var maxGifSize = parseInt($('#maxSizeAnimateGif').val(), 10);
  112. if (mimetype === 'image/gif' &&
  113. (maxGifSize === -1 || fileSize <= (maxGifSize * 1024 * 1024))) {
  114. img.attr('src', $('#downloadURL').val());
  115. img.appendTo('#imgframe');
  116. } else if (mimetype.substr(0, mimetype.indexOf('/')) === 'text' && window.btoa) {
  117. // Undocumented Url to public WebDAV endpoint
  118. var url = parent.location.protocol + '//' + location.host + OC.linkTo('', 'public.php/webdav');
  119. $.ajax({
  120. url: url,
  121. headers: {
  122. Authorization: 'Basic ' + btoa(token + ':'),
  123. Range: 'bytes=0-1000'
  124. }
  125. }).then(function (data) {
  126. self._showTextPreview(data, previewHeight);
  127. });
  128. } else if ((previewSupported === 'true' && mimetype.substr(0, mimetype.indexOf('/')) !== 'video') ||
  129. mimetype.substr(0, mimetype.indexOf('/')) === 'image' &&
  130. mimetype !== 'image/svg+xml') {
  131. img.attr('src', OC.filePath('files_sharing', 'ajax', 'publicpreview.php') + '?' + OC.buildQueryString(params));
  132. img.appendTo('#imgframe');
  133. } else if (mimetype.substr(0, mimetype.indexOf('/')) !== 'video') {
  134. img.attr('src', OC.Util.replaceSVGIcon(mimetypeIcon));
  135. img.attr('width', 128);
  136. img.appendTo('#imgframe');
  137. }
  138. else if (previewSupported === 'true') {
  139. $('#imgframe > video').attr('poster', OC.filePath('files_sharing', 'ajax', 'publicpreview.php') + '?' + OC.buildQueryString(params));
  140. }
  141. if (this.fileList) {
  142. // TODO: move this to a separate PublicFileList class that extends OCA.Files.FileList (+ unit tests)
  143. this.fileList.getDownloadUrl = function (filename, dir, isDir) {
  144. var path = dir || this.getCurrentDirectory();
  145. if (_.isArray(filename)) {
  146. filename = JSON.stringify(filename);
  147. }
  148. var params = {
  149. path: path
  150. };
  151. if (filename) {
  152. params.files = filename;
  153. }
  154. return OC.generateUrl('/s/' + token + '/download') + '?' + OC.buildQueryString(params);
  155. };
  156. this.fileList.getAjaxUrl = function (action, params) {
  157. params = params || {};
  158. params.t = token;
  159. return OC.filePath('files_sharing', 'ajax', action + '.php') + '?' + OC.buildQueryString(params);
  160. };
  161. this.fileList.linkTo = function (dir) {
  162. return OC.generateUrl('/s/' + token + '', {dir: dir});
  163. };
  164. this.fileList.generatePreviewUrl = function (urlSpec) {
  165. urlSpec = urlSpec || {};
  166. if (!urlSpec.x) {
  167. urlSpec.x = 32;
  168. }
  169. if (!urlSpec.y) {
  170. urlSpec.y = 32;
  171. }
  172. urlSpec.x *= window.devicePixelRatio;
  173. urlSpec.y *= window.devicePixelRatio;
  174. urlSpec.x = Math.ceil(urlSpec.x);
  175. urlSpec.y = Math.ceil(urlSpec.y);
  176. urlSpec.t = $('#dirToken').val();
  177. return OC.generateUrl('/apps/files_sharing/ajax/publicpreview.php?') + $.param(urlSpec);
  178. };
  179. this.fileList.updateEmptyContent = function() {
  180. this.$el.find('#emptycontent .uploadmessage').text(
  181. t('files_sharing', 'You can upload into this folder')
  182. );
  183. OCA.Files.FileList.prototype.updateEmptyContent.apply(this, arguments);
  184. };
  185. var file_upload_start = $('#file_upload_start');
  186. file_upload_start.on('fileuploadadd', function (e, data) {
  187. var fileDirectory = '';
  188. if (typeof data.files[0].relativePath !== 'undefined') {
  189. fileDirectory = data.files[0].relativePath;
  190. }
  191. // Add custom data to the upload handler
  192. data.formData = {
  193. requesttoken: $('#publicUploadRequestToken').val(),
  194. dirToken: $('#dirToken').val(),
  195. subdir: data.targetDir || self.fileList.getCurrentDirectory(),
  196. file_directory: fileDirectory
  197. };
  198. });
  199. // do not allow sharing from the public page
  200. delete this.fileList.fileActions.actions.all.Share;
  201. this.fileList.changeDirectory(this.initialDir || '/', false, true);
  202. // URL history handling
  203. this.fileList.$el.on('changeDirectory', _.bind(this._onDirectoryChanged, this));
  204. OC.Util.History.addOnPopStateHandler(_.bind(this._onUrlChanged, this));
  205. $('#download').click(function (e) {
  206. e.preventDefault();
  207. OC.redirect(FileList.getDownloadUrl());
  208. });
  209. }
  210. $(document).on('click', '#directLink', function () {
  211. $(this).focus();
  212. $(this).select();
  213. });
  214. $('.save-form').submit(function (event) {
  215. event.preventDefault();
  216. var remote = $(this).find('input[type="text"]').val();
  217. var token = $('#sharingToken').val();
  218. var owner = $('#save').data('owner');
  219. var ownerDisplayName = $('#save').data('owner-display-name');
  220. var name = $('#save').data('name');
  221. var isProtected = $('#save').data('protected') ? 1 : 0;
  222. OCA.Sharing.PublicApp._createFederatedShare(remote, token, owner, ownerDisplayName, name, isProtected);
  223. });
  224. $('#remote_address').on("keyup paste", function() {
  225. if ($(this).val() === '') {
  226. $('#save-button-confirm').prop('disabled', true);
  227. } else {
  228. $('#save-button-confirm').prop('disabled', false);
  229. }
  230. });
  231. $('#save #save-button').click(function () {
  232. $(this).hide();
  233. $('.save-form').css('display', 'inline');
  234. $('#remote_address').focus();
  235. });
  236. // legacy
  237. window.FileList = this.fileList;
  238. },
  239. _showTextPreview: function (data, previewHeight) {
  240. var textDiv = $('<div/>').addClass('text-preview');
  241. textDiv.text(data);
  242. textDiv.appendTo('#imgframe');
  243. var divHeight = textDiv.height();
  244. if (data.length > 999) {
  245. var ellipsis = $('<div/>').addClass('ellipsis');
  246. ellipsis.html('(&#133;)');
  247. ellipsis.appendTo('#imgframe');
  248. }
  249. if (divHeight > previewHeight) {
  250. textDiv.height(previewHeight);
  251. }
  252. },
  253. _onDirectoryChanged: function (e) {
  254. OC.Util.History.pushState({
  255. // arghhhh, why is this not called "dir" !?
  256. path: e.dir
  257. });
  258. },
  259. _onUrlChanged: function (params) {
  260. this.fileList.changeDirectory(params.path || params.dir, false, true);
  261. },
  262. /**
  263. * fall back to old behaviour where we redirect the user to his server to mount
  264. * the public link instead of creating a dedicated federated share
  265. *
  266. * @param remote
  267. * @param token
  268. * @param owner
  269. * @param ownerDisplayName
  270. * @param name
  271. * @param isProtected
  272. * @private
  273. */
  274. _legacyCreateFederatedShare: function (remote, token, owner, ownerDisplayName, name, isProtected) {
  275. var location = window.location.protocol + '//' + window.location.host + OC.webroot;
  276. if(remote.substr(-1) !== '/') {
  277. remote += '/'
  278. }
  279. var url = remote + 'index.php/apps/files#' + 'remote=' + encodeURIComponent(location) // our location is the remote for the other server
  280. + "&token=" + encodeURIComponent(token) + "&owner=" + encodeURIComponent(owner) +"&ownerDisplayName=" + encodeURIComponent(ownerDisplayName) + "&name=" + encodeURIComponent(name) + "&protected=" + isProtected;
  281. if (remote.indexOf('://') > 0) {
  282. OC.redirect(url);
  283. } else {
  284. // if no protocol is specified, we automatically detect it by testing https and http
  285. // this check needs to happen on the server due to the Content Security Policy directive
  286. $.get(OC.generateUrl('apps/files_sharing/testremote'), {remote: remote}).then(function (protocol) {
  287. if (protocol !== 'http' && protocol !== 'https') {
  288. OC.dialogs.alert(t('files_sharing', 'No compatible server found at {remote}', {remote: remote}),
  289. t('files_sharing', 'Invalid server URL'));
  290. } else {
  291. OC.redirect(protocol + '://' + url);
  292. }
  293. });
  294. }
  295. },
  296. _createFederatedShare: function (remote, token, owner, ownerDisplayName, name, isProtected) {
  297. var toggleLoading = function() {
  298. var iconClass = $('#save-button-confirm').attr('class');
  299. var loading = iconClass.indexOf('icon-loading-small') !== -1;
  300. if(loading) {
  301. $('#save-button-confirm')
  302. .removeClass("icon-loading-small")
  303. .addClass("icon-confirm");
  304. }
  305. else {
  306. $('#save-button-confirm')
  307. .removeClass("icon-confirm")
  308. .addClass("icon-loading-small");
  309. }
  310. };
  311. toggleLoading();
  312. if (remote.indexOf('@') === -1) {
  313. this._legacyCreateFederatedShare(remote, token, owner, ownerDisplayName, name, isProtected);
  314. toggleLoading();
  315. return;
  316. }
  317. $.post(
  318. OC.generateUrl('/apps/federatedfilesharing/createFederatedShare'),
  319. {
  320. 'shareWith': remote,
  321. 'token': token
  322. }
  323. ).done(
  324. function (data) {
  325. var url = data.remoteUrl;
  326. if (url.indexOf('://') > 0) {
  327. OC.redirect(url);
  328. } else {
  329. OC.redirect('http://' + url);
  330. }
  331. }
  332. ).fail(
  333. function (jqXHR) {
  334. OC.dialogs.alert(JSON.parse(jqXHR.responseText).message,
  335. t('files_sharing', 'Failed to add the public link to your Nextcloud'));
  336. toggleLoading();
  337. }
  338. );
  339. }
  340. };
  341. $(document).ready(function () {
  342. // FIXME: replace with OC.Plugins.register()
  343. if (window.TESTING) {
  344. return;
  345. }
  346. var App = OCA.Sharing.PublicApp;
  347. // defer app init, to give a chance to plugins to register file actions
  348. _.defer(function () {
  349. App.initialize($('#preview'));
  350. });
  351. if (window.Files) {
  352. // HACK: for oc-dialogs previews that depends on Files:
  353. Files.generatePreviewUrl = function (urlSpec) {
  354. return App.fileList.generatePreviewUrl(urlSpec);
  355. };
  356. }
  357. });