attachments.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. import { ReactiveCache } from '/imports/reactiveCache';
  2. import { ObjectID } from 'bson';
  3. import DOMPurify from 'dompurify';
  4. const filesize = require('filesize');
  5. const prettyMilliseconds = require('pretty-ms');
  6. // We store current card ID and the ID of currently opened attachment in a
  7. // global var. This is used so that we know what's the next attachment to open
  8. // when the user clicks on the prev/next button in the attachment viewer.
  9. let cardId = null;
  10. let openAttachmentId = null;
  11. // Used to store the start and end coordinates of a touch event for attachment swiping
  12. let touchStartCoords = null;
  13. let touchEndCoords = null;
  14. // Stores link to the attachment for which attachment actions popup was opened
  15. attachmentActionsLink = null;
  16. Template.attachmentGallery.events({
  17. 'click .open-preview'(event) {
  18. openAttachmentId = $(event.currentTarget).attr("data-attachment-id");
  19. cardId = $(event.currentTarget).attr("data-card-id");
  20. openAttachmentViewer(openAttachmentId);
  21. },
  22. 'click .js-add-attachment': Popup.open('cardAttachments'),
  23. // If we let this event bubble, FlowRouter will handle it and empty the page
  24. // content, see #101.
  25. 'click .js-download'(event) {
  26. event.stopPropagation();
  27. },
  28. 'click .js-open-attachment-menu': Popup.open('attachmentActions'),
  29. 'mouseover .js-open-attachment-menu'(event) { // For some reason I cannot combine handlers for "click .js-open-attachment-menu" and "mouseover .js-open-attachment-menu" events so this is a quick workaround.
  30. attachmentActionsLink = event.currentTarget.getAttribute("data-attachment-link");
  31. },
  32. 'click .js-rename': Popup.open('attachmentRename'),
  33. 'click .js-confirm-delete': Popup.afterConfirm('attachmentDelete', function() {
  34. Attachments.remove(this._id);
  35. Popup.back(2);
  36. }),
  37. });
  38. function getNextAttachmentId(currentAttachmentId, offset = 0) {
  39. const attachments = ReactiveCache.getAttachments({'meta.cardId': cardId});
  40. let i = 0;
  41. for (; i < attachments.length; i++) {
  42. if (attachments[i]._id === currentAttachmentId) {
  43. break;
  44. }
  45. }
  46. return attachments[(i + offset + 1 + attachments.length) % attachments.length]._id;
  47. }
  48. function getPrevAttachmentId(currentAttachmentId, offset = 0) {
  49. const attachments = ReactiveCache.getAttachments({'meta.cardId': cardId});
  50. let i = 0;
  51. for (; i < attachments.length; i++) {
  52. if (attachments[i]._id === currentAttachmentId) {
  53. break;
  54. }
  55. }
  56. return attachments[(i + offset - 1 + attachments.length) % attachments.length]._id;
  57. }
  58. function attachmentCanBeOpened(attachment) {
  59. return (
  60. attachment.isImage ||
  61. attachment.isPDF ||
  62. attachment.isText ||
  63. attachment.isJSON ||
  64. attachment.isVideo ||
  65. attachment.isAudio
  66. );
  67. }
  68. function openAttachmentViewer(attachmentId) {
  69. const attachment = ReactiveCache.getAttachment(attachmentId);
  70. // Check if we can open the attachment (if we have a viewer for it) and exit if not
  71. if (!attachmentCanBeOpened(attachment)) {
  72. return;
  73. }
  74. /*
  75. Instructions for adding a new viewer:
  76. - add a new case to the switch statement below
  77. - implement cleanup in the closeAttachmentViewer() function, if necessary
  78. - mark attachment type as openable by adding a new condition to the attachmentCanBeOpened function
  79. */
  80. switch(true){
  81. case (attachment.isImage):
  82. $("#image-viewer").attr("src", attachment.link());
  83. $("#image-viewer").removeClass("hidden");
  84. break;
  85. case (attachment.isPDF):
  86. $("#pdf-viewer").attr("data", attachment.link());
  87. $("#pdf-viewer").removeClass("hidden");
  88. break;
  89. case (attachment.isVideo):
  90. // We have to create a new <source> DOM element and append it to the video
  91. // element, otherwise the video won't load
  92. let videoSource = document.createElement('source');
  93. videoSource.setAttribute('src', attachment.link());
  94. $("#video-viewer").append(videoSource);
  95. $("#video-viewer").removeClass("hidden");
  96. break;
  97. case (attachment.isAudio):
  98. // We have to create a new <source> DOM element and append it to the audio
  99. // element, otherwise the audio won't load
  100. let audioSource = document.createElement('source');
  101. audioSource.setAttribute('src', attachment.link());
  102. $("#audio-viewer").append(audioSource);
  103. $("#audio-viewer").removeClass("hidden");
  104. break;
  105. case (attachment.isText):
  106. case (attachment.isJSON):
  107. $("#txt-viewer").attr("data", attachment.link());
  108. $("#txt-viewer").removeClass("hidden");
  109. break;
  110. }
  111. $('#attachment-name').text(attachment.name);
  112. $('#viewer-overlay').removeClass('hidden');
  113. }
  114. function closeAttachmentViewer() {
  115. $("#viewer-overlay").addClass("hidden");
  116. // We need to reset the viewers to avoid showing previous attachments
  117. $("#image-viewer").attr("src", "");
  118. $("#image-viewer").addClass("hidden");
  119. $("#pdf-viewer").attr("data", "");
  120. $("#pdf-viewer").addClass("hidden");
  121. $("#txt-viewer").attr("data", "");
  122. $("#txt-viewer").addClass("hidden");
  123. $("#video-viewer").get(0).pause(); // Stop playback
  124. $("#video-viewer").get(0).currentTime = 0;
  125. $("#video-viewer").empty();
  126. $("#video-viewer").addClass("hidden");
  127. $("#audio-viewer").get(0).pause(); // Stop playback
  128. $("#audio-viewer").get(0).currentTime = 0;
  129. $("#audio-viewer").empty();
  130. $("#audio-viewer").addClass("hidden");
  131. }
  132. function openNextAttachment() {
  133. closeAttachmentViewer();
  134. let i = 0;
  135. // Find an attachment that can be opened
  136. while (true) {
  137. const id = getNextAttachmentId(openAttachmentId, i);
  138. const attachment = ReactiveCache.getAttachment(id);
  139. if (attachmentCanBeOpened(attachment)) {
  140. openAttachmentId = id;
  141. openAttachmentViewer(id);
  142. break;
  143. }
  144. i++;
  145. }
  146. }
  147. function openPrevAttachment() {
  148. closeAttachmentViewer();
  149. let i = 0;
  150. // Find an attachment that can be opened
  151. while (true) {
  152. const id = getPrevAttachmentId(openAttachmentId, i);
  153. const attachment = ReactiveCache.getAttachment(id);
  154. if (attachmentCanBeOpened(attachment)) {
  155. openAttachmentId = id;
  156. openAttachmentViewer(id);
  157. break;
  158. }
  159. i--;
  160. }
  161. }
  162. function processTouch(){
  163. xDist = touchEndCoords.x - touchStartCoords.x;
  164. yDist = touchEndCoords.y - touchStartCoords.y;
  165. console.log("xDist: " + xDist);
  166. // Left swipe
  167. if (Math.abs(xDist) > Math.abs(yDist) && xDist < 0) {
  168. openNextAttachment();
  169. }
  170. // Right swipe
  171. if (Math.abs(xDist) > Math.abs(yDist) && xDist > 0) {
  172. openPrevAttachment();
  173. }
  174. // Up swipe
  175. if (Math.abs(yDist) > Math.abs(xDist) && yDist < 0) {
  176. closeAttachmentViewer();
  177. }
  178. }
  179. Template.attachmentViewer.events({
  180. 'touchstart #viewer-container'(event) {
  181. console.log("touchstart")
  182. touchStartCoords = {
  183. x: event.changedTouches[0].screenX,
  184. y: event.changedTouches[0].screenY
  185. }
  186. },
  187. 'touchend #viewer-container'(event) {
  188. console.log("touchend")
  189. touchEndCoords = {
  190. x: event.changedTouches[0].screenX,
  191. y: event.changedTouches[0].screenY
  192. }
  193. processTouch();
  194. },
  195. 'click #viewer-container'(event) {
  196. // Make sure the click was on #viewer-container and not on any of its children
  197. if(event.target !== event.currentTarget) return;
  198. closeAttachmentViewer();
  199. },
  200. 'click #viewer-content'(event) {
  201. // Make sure the click was on #viewer-content and not on any of its children
  202. if(event.target !== event.currentTarget) return;
  203. closeAttachmentViewer();
  204. },
  205. 'click #viewer-close'() {
  206. closeAttachmentViewer();
  207. },
  208. 'click #next-attachment'() {
  209. openNextAttachment();
  210. },
  211. 'click #prev-attachment'() {
  212. openPrevAttachment();
  213. },
  214. });
  215. Template.attachmentGallery.helpers({
  216. isBoardAdmin() {
  217. return ReactiveCache.getCurrentUser().isBoardAdmin();
  218. },
  219. fileSize(size) {
  220. const ret = filesize(size);
  221. return ret;
  222. },
  223. sanitize(value) {
  224. return DOMPurify.sanitize(value);
  225. },
  226. });
  227. Template.cardAttachmentsPopup.onCreated(function() {
  228. this.uploads = new ReactiveVar([]);
  229. });
  230. Template.cardAttachmentsPopup.helpers({
  231. getEstimateTime(upload) {
  232. const ret = prettyMilliseconds(upload.estimateTime.get());
  233. return ret;
  234. },
  235. getEstimateSpeed(upload) {
  236. const ret = filesize(upload.estimateSpeed.get(), {round: 0}) + "/s";
  237. return ret;
  238. },
  239. uploads() {
  240. return Template.instance().uploads.get();
  241. }
  242. });
  243. Template.cardAttachmentsPopup.events({
  244. 'change .js-attach-file'(event, templateInstance) {
  245. const card = this;
  246. const files = event.currentTarget.files;
  247. if (files) {
  248. let uploads = [];
  249. for (const file of files) {
  250. const fileId = new ObjectID().toString();
  251. const warning = "WARNING-XSS-SANITIZED-";
  252. let fileName = DOMPurify.sanitize(file.name);
  253. if (fileName !== file.name) {
  254. // console.warn('Detected possible XSS in file: ', file.name + '. Renamed to: ', fileName + '.');
  255. // Add warning about XSS sanitized:
  256. fileName = warning.concat(fileName);
  257. }
  258. const config = {
  259. file: file,
  260. fileId: fileId,
  261. fileName: fileName,
  262. meta: Utils.getCommonAttachmentMetaFrom(card),
  263. chunkSize: 'dynamic',
  264. };
  265. config.meta.fileId = fileId;
  266. const uploader = Attachments.insert(
  267. config,
  268. false,
  269. );
  270. uploader.on('start', function() {
  271. uploads.push(this);
  272. templateInstance.uploads.set(uploads);
  273. });
  274. uploader.on('uploaded', (error, fileRef) => {
  275. if (!error) {
  276. if (fileRef.isImage) {
  277. card.setCover(fileRef._id);
  278. }
  279. }
  280. });
  281. uploader.on('end', (error, fileRef) => {
  282. uploads = uploads.filter(_upload => _upload.config.fileId != fileRef._id);
  283. templateInstance.uploads.set(uploads);
  284. if (uploads.length == 0 ) {
  285. Popup.back();
  286. }
  287. });
  288. uploader.start();
  289. }
  290. }
  291. },
  292. 'click .js-computer-upload'(event, templateInstance) {
  293. templateInstance.find('.js-attach-file').click();
  294. event.preventDefault();
  295. },
  296. 'click .js-upload-clipboard-image': Popup.open('previewClipboardImage'),
  297. });
  298. const MAX_IMAGE_PIXEL = Utils.MAX_IMAGE_PIXEL;
  299. const COMPRESS_RATIO = Utils.IMAGE_COMPRESS_RATIO;
  300. let pastedResults = null;
  301. Template.previewClipboardImagePopup.onRendered(() => {
  302. // we can paste image from clipboard
  303. const handle = results => {
  304. if (results.dataURL.startsWith('data:image/')) {
  305. const direct = results => {
  306. $('img.preview-clipboard-image').attr('src', results.dataURL);
  307. pastedResults = results;
  308. };
  309. if (MAX_IMAGE_PIXEL) {
  310. // if has size limitation on image we shrink it before uploading
  311. Utils.shrinkImage({
  312. dataurl: results.dataURL,
  313. maxSize: MAX_IMAGE_PIXEL,
  314. ratio: COMPRESS_RATIO,
  315. callback(changed) {
  316. if (changed !== false && !!changed) {
  317. results.dataURL = changed;
  318. }
  319. direct(results);
  320. },
  321. });
  322. } else {
  323. direct(results);
  324. }
  325. }
  326. };
  327. $(document.body).pasteImageReader(handle);
  328. // we can also drag & drop image file to it
  329. $(document.body).dropImageReader(handle);
  330. });
  331. Template.previewClipboardImagePopup.events({
  332. 'click .js-upload-pasted-image'() {
  333. const card = this;
  334. if (pastedResults && pastedResults.file) {
  335. const file = pastedResults.file;
  336. window.oPasted = pastedResults;
  337. const fileId = new ObjectID().toString();
  338. const config = {
  339. file,
  340. fileId: fileId,
  341. meta: Utils.getCommonAttachmentMetaFrom(card),
  342. fileName: file.name || file.type.replace('image/', 'clipboard.'),
  343. chunkSize: 'dynamic',
  344. };
  345. config.meta.fileId = fileId;
  346. const uploader = Attachments.insert(
  347. config,
  348. false,
  349. );
  350. uploader.on('uploaded', (error, fileRef) => {
  351. if (!error) {
  352. if (fileRef.isImage) {
  353. card.setCover(fileRef._id);
  354. }
  355. }
  356. });
  357. uploader.on('end', (error, fileRef) => {
  358. pastedResults = null;
  359. $(document.body).pasteImageReader(() => {});
  360. Popup.back();
  361. });
  362. uploader.start();
  363. }
  364. },
  365. });
  366. BlazeComponent.extendComponent({
  367. isCover() {
  368. const ret = ReactiveCache.getCard(this.data().meta.cardId).coverId == this.data()._id;
  369. return ret;
  370. },
  371. isBackgroundImage() {
  372. //const currentBoard = Utils.getCurrentBoard();
  373. //return currentBoard.backgroundImageURL === $(".attachment-thumbnail-img").attr("src");
  374. return false;
  375. },
  376. events() {
  377. return [
  378. {
  379. 'click .js-add-cover'() {
  380. ReactiveCache.getCard(this.data().meta.cardId).setCover(this.data()._id);
  381. Popup.back();
  382. },
  383. 'click .js-remove-cover'() {
  384. ReactiveCache.getCard(this.data().meta.cardId).unsetCover();
  385. Popup.back();
  386. },
  387. 'click .js-add-background-image'() {
  388. const currentBoard = Utils.getCurrentBoard();
  389. currentBoard.setBackgroundImageURL(attachmentActionsLink);
  390. Utils.setBackgroundImage(attachmentActionsLink);
  391. Popup.back();
  392. event.preventDefault();
  393. },
  394. 'click .js-remove-background-image'() {
  395. const currentBoard = Utils.getCurrentBoard();
  396. currentBoard.setBackgroundImageURL("");
  397. Utils.setBackgroundImage("");
  398. Popup.back();
  399. Utils.reload();
  400. event.preventDefault();
  401. },
  402. 'click .js-move-storage-fs'() {
  403. Meteor.call('moveAttachmentToStorage', this.data()._id, "fs");
  404. Popup.back();
  405. },
  406. 'click .js-move-storage-gridfs'() {
  407. Meteor.call('moveAttachmentToStorage', this.data()._id, "gridfs");
  408. Popup.back();
  409. },
  410. 'click .js-move-storage-s3'() {
  411. Meteor.call('moveAttachmentToStorage', this.data()._id, "s3");
  412. Popup.back();
  413. },
  414. }
  415. ]
  416. }
  417. }).register('attachmentActionsPopup');
  418. BlazeComponent.extendComponent({
  419. getNameWithoutExtension() {
  420. const ret = this.data().name.replace(new RegExp("\." + this.data().extension + "$"), "");
  421. return ret;
  422. },
  423. events() {
  424. return [
  425. {
  426. 'keydown input.js-edit-attachment-name'(evt) {
  427. // enter = save
  428. if (evt.keyCode === 13) {
  429. this.find('button[type=submit]').click();
  430. }
  431. },
  432. 'click button.js-submit-edit-attachment-name'(event) {
  433. // save button pressed
  434. event.preventDefault();
  435. const name = this.$('.js-edit-attachment-name')[0]
  436. .value
  437. .trim() + this.data().extensionWithDot;
  438. if (name === DOMPurify.sanitize(name)) {
  439. Meteor.call('renameAttachment', this.data()._id, name);
  440. }
  441. Popup.back(2);
  442. },
  443. }
  444. ]
  445. }
  446. }).register('attachmentRenamePopup');