public.js 12 KB

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