public.js 13 KB

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