attachments.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 fileName = DOMPurify.sanitize(file.name);
  252. if (fileName !== file.name) {
  253. console.warn('Detected possible XSS in file: ', file.name + '. Renamed to: ', fileName + '.');
  254. }
  255. const config = {
  256. file: file,
  257. fileId: fileId,
  258. fileName: fileName,
  259. meta: Utils.getCommonAttachmentMetaFrom(card),
  260. chunkSize: 'dynamic',
  261. };
  262. config.meta.fileId = fileId;
  263. const uploader = Attachments.insert(
  264. config,
  265. false,
  266. );
  267. uploader.on('start', function() {
  268. uploads.push(this);
  269. templateInstance.uploads.set(uploads);
  270. });
  271. uploader.on('uploaded', (error, fileRef) => {
  272. if (!error) {
  273. if (fileRef.isImage) {
  274. card.setCover(fileRef._id);
  275. }
  276. }
  277. });
  278. uploader.on('end', (error, fileRef) => {
  279. uploads = uploads.filter(_upload => _upload.config.fileId != fileRef._id);
  280. templateInstance.uploads.set(uploads);
  281. if (uploads.length == 0 ) {
  282. Popup.back();
  283. }
  284. });
  285. uploader.start();
  286. }
  287. }
  288. },
  289. 'click .js-computer-upload'(event, templateInstance) {
  290. templateInstance.find('.js-attach-file').click();
  291. event.preventDefault();
  292. },
  293. 'click .js-upload-clipboard-image': Popup.open('previewClipboardImage'),
  294. });
  295. const MAX_IMAGE_PIXEL = Utils.MAX_IMAGE_PIXEL;
  296. const COMPRESS_RATIO = Utils.IMAGE_COMPRESS_RATIO;
  297. let pastedResults = null;
  298. Template.previewClipboardImagePopup.onRendered(() => {
  299. // we can paste image from clipboard
  300. const handle = results => {
  301. if (results.dataURL.startsWith('data:image/')) {
  302. const direct = results => {
  303. $('img.preview-clipboard-image').attr('src', results.dataURL);
  304. pastedResults = results;
  305. };
  306. if (MAX_IMAGE_PIXEL) {
  307. // if has size limitation on image we shrink it before uploading
  308. Utils.shrinkImage({
  309. dataurl: results.dataURL,
  310. maxSize: MAX_IMAGE_PIXEL,
  311. ratio: COMPRESS_RATIO,
  312. callback(changed) {
  313. if (changed !== false && !!changed) {
  314. results.dataURL = changed;
  315. }
  316. direct(results);
  317. },
  318. });
  319. } else {
  320. direct(results);
  321. }
  322. }
  323. };
  324. $(document.body).pasteImageReader(handle);
  325. // we can also drag & drop image file to it
  326. $(document.body).dropImageReader(handle);
  327. });
  328. Template.previewClipboardImagePopup.events({
  329. 'click .js-upload-pasted-image'() {
  330. const card = this;
  331. if (pastedResults && pastedResults.file) {
  332. const file = pastedResults.file;
  333. window.oPasted = pastedResults;
  334. const fileId = new ObjectID().toString();
  335. const config = {
  336. file,
  337. fileId: fileId,
  338. meta: Utils.getCommonAttachmentMetaFrom(card),
  339. fileName: file.name || file.type.replace('image/', 'clipboard.'),
  340. chunkSize: 'dynamic',
  341. };
  342. config.meta.fileId = fileId;
  343. const uploader = Attachments.insert(
  344. config,
  345. false,
  346. );
  347. uploader.on('uploaded', (error, fileRef) => {
  348. if (!error) {
  349. if (fileRef.isImage) {
  350. card.setCover(fileRef._id);
  351. }
  352. }
  353. });
  354. uploader.on('end', (error, fileRef) => {
  355. pastedResults = null;
  356. $(document.body).pasteImageReader(() => {});
  357. Popup.back();
  358. });
  359. uploader.start();
  360. }
  361. },
  362. });
  363. BlazeComponent.extendComponent({
  364. isCover() {
  365. const ret = ReactiveCache.getCard(this.data().meta.cardId).coverId == this.data()._id;
  366. return ret;
  367. },
  368. isBackgroundImage() {
  369. //const currentBoard = Utils.getCurrentBoard();
  370. //return currentBoard.backgroundImageURL === $(".attachment-thumbnail-img").attr("src");
  371. return false;
  372. },
  373. events() {
  374. return [
  375. {
  376. 'click .js-add-cover'() {
  377. ReactiveCache.getCard(this.data().meta.cardId).setCover(this.data()._id);
  378. Popup.back();
  379. },
  380. 'click .js-remove-cover'() {
  381. ReactiveCache.getCard(this.data().meta.cardId).unsetCover();
  382. Popup.back();
  383. },
  384. 'click .js-add-background-image'() {
  385. const currentBoard = Utils.getCurrentBoard();
  386. currentBoard.setBackgroundImageURL(attachmentActionsLink);
  387. Utils.setBackgroundImage(attachmentActionsLink);
  388. Popup.back();
  389. event.preventDefault();
  390. },
  391. 'click .js-remove-background-image'() {
  392. const currentBoard = Utils.getCurrentBoard();
  393. currentBoard.setBackgroundImageURL("");
  394. Utils.setBackgroundImage("");
  395. Popup.back();
  396. Utils.reload();
  397. event.preventDefault();
  398. },
  399. 'click .js-move-storage-fs'() {
  400. Meteor.call('moveAttachmentToStorage', this.data()._id, "fs");
  401. Popup.back();
  402. },
  403. 'click .js-move-storage-gridfs'() {
  404. Meteor.call('moveAttachmentToStorage', this.data()._id, "gridfs");
  405. Popup.back();
  406. },
  407. 'click .js-move-storage-s3'() {
  408. Meteor.call('moveAttachmentToStorage', this.data()._id, "s3");
  409. Popup.back();
  410. },
  411. }
  412. ]
  413. }
  414. }).register('attachmentActionsPopup');
  415. BlazeComponent.extendComponent({
  416. getNameWithoutExtension() {
  417. const ret = this.data().name.replace(new RegExp("\." + this.data().extension + "$"), "");
  418. return ret;
  419. },
  420. events() {
  421. return [
  422. {
  423. 'keydown input.js-edit-attachment-name'(evt) {
  424. // enter = save
  425. if (evt.keyCode === 13) {
  426. this.find('button[type=submit]').click();
  427. }
  428. },
  429. 'click button.js-submit-edit-attachment-name'(event) {
  430. // save button pressed
  431. event.preventDefault();
  432. const name = this.$('.js-edit-attachment-name')[0]
  433. .value
  434. .trim() + this.data().extensionWithDot;
  435. if (name === DOMPurify.sanitize(name)) {
  436. Meteor.call('renameAttachment', this.data()._id, name);
  437. }
  438. Popup.back(2);
  439. },
  440. }
  441. ]
  442. }
  443. }).register('attachmentRenamePopup');