attachments.js 14 KB

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