attachments.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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();
  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) {
  198. event.stopPropagation();
  199. return;
  200. }
  201. closeAttachmentViewer();
  202. },
  203. 'click #viewer-content'(event) {
  204. // Make sure the click was on #viewer-content and not on any of its children
  205. if(event.target !== event.currentTarget) {
  206. event.stopPropagation();
  207. return;
  208. }
  209. closeAttachmentViewer();
  210. },
  211. 'click #viewer-close'() {
  212. closeAttachmentViewer();
  213. },
  214. 'click #next-attachment'() {
  215. openNextAttachment();
  216. },
  217. 'click #prev-attachment'() {
  218. openPrevAttachment();
  219. },
  220. });
  221. Template.attachmentGallery.helpers({
  222. isBoardAdmin() {
  223. return ReactiveCache.getCurrentUser().isBoardAdmin();
  224. },
  225. fileSize(size) {
  226. const ret = filesize(size);
  227. return ret;
  228. },
  229. sanitize(value) {
  230. return DOMPurify.sanitize(value);
  231. },
  232. });
  233. Template.cardAttachmentsPopup.onCreated(function() {
  234. this.uploads = new ReactiveVar([]);
  235. });
  236. Template.cardAttachmentsPopup.helpers({
  237. getEstimateTime(upload) {
  238. const ret = prettyMilliseconds(upload.estimateTime.get());
  239. return ret;
  240. },
  241. getEstimateSpeed(upload) {
  242. const ret = filesize(upload.estimateSpeed.get(), {round: 0}) + "/s";
  243. return ret;
  244. },
  245. uploads() {
  246. return Template.instance().uploads.get();
  247. }
  248. });
  249. Template.cardAttachmentsPopup.events({
  250. 'change .js-attach-file'(event, templateInstance) {
  251. const card = this;
  252. const files = event.currentTarget.files;
  253. if (files) {
  254. let uploads = [];
  255. for (const file of files) {
  256. const fileId = new ObjectID().toString();
  257. let fileName = DOMPurify.sanitize(file.name);
  258. // If sanitized filename is not same as original filename,
  259. // it could be XSS that is already fixed with sanitize,
  260. // or just normal mistake, so it is not a problem.
  261. // That is why here is no warning.
  262. if (fileName !== file.name) {
  263. // If filename is empty, only in that case add some filename
  264. if (fileName.length === 0) {
  265. fileName = 'Empty-filename-after-sanitize.txt';
  266. }
  267. }
  268. const config = {
  269. file: file,
  270. fileId: fileId,
  271. fileName: fileName,
  272. meta: Utils.getCommonAttachmentMetaFrom(card),
  273. chunkSize: 'dynamic',
  274. };
  275. config.meta.fileId = fileId;
  276. const uploader = Attachments.insert(
  277. config,
  278. false,
  279. );
  280. uploader.on('start', function() {
  281. uploads.push(this);
  282. templateInstance.uploads.set(uploads);
  283. });
  284. uploader.on('uploaded', (error, fileRef) => {
  285. if (!error) {
  286. if (fileRef.isImage) {
  287. card.setCover(fileRef._id);
  288. }
  289. }
  290. });
  291. uploader.on('end', (error, fileRef) => {
  292. uploads = uploads.filter(_upload => _upload.config.fileId != fileRef._id);
  293. templateInstance.uploads.set(uploads);
  294. if (uploads.length == 0 ) {
  295. Popup.back();
  296. }
  297. });
  298. uploader.start();
  299. }
  300. }
  301. },
  302. 'click .js-computer-upload'(event, templateInstance) {
  303. templateInstance.find('.js-attach-file').click();
  304. event.preventDefault();
  305. },
  306. 'click .js-upload-clipboard-image': Popup.open('previewClipboardImage'),
  307. });
  308. const MAX_IMAGE_PIXEL = Utils.MAX_IMAGE_PIXEL;
  309. const COMPRESS_RATIO = Utils.IMAGE_COMPRESS_RATIO;
  310. let pastedResults = null;
  311. Template.previewClipboardImagePopup.onRendered(() => {
  312. // we can paste image from clipboard
  313. const handle = results => {
  314. if (results.dataURL.startsWith('data:image/')) {
  315. const direct = results => {
  316. $('img.preview-clipboard-image').attr('src', results.dataURL);
  317. pastedResults = results;
  318. };
  319. if (MAX_IMAGE_PIXEL) {
  320. // if has size limitation on image we shrink it before uploading
  321. Utils.shrinkImage({
  322. dataurl: results.dataURL,
  323. maxSize: MAX_IMAGE_PIXEL,
  324. ratio: COMPRESS_RATIO,
  325. callback(changed) {
  326. if (changed !== false && !!changed) {
  327. results.dataURL = changed;
  328. }
  329. direct(results);
  330. },
  331. });
  332. } else {
  333. direct(results);
  334. }
  335. }
  336. };
  337. $(document.body).pasteImageReader(handle);
  338. // we can also drag & drop image file to it
  339. $(document.body).dropImageReader(handle);
  340. });
  341. Template.previewClipboardImagePopup.events({
  342. 'click .js-upload-pasted-image'() {
  343. const card = this;
  344. if (pastedResults && pastedResults.file) {
  345. const file = pastedResults.file;
  346. window.oPasted = pastedResults;
  347. const fileId = new ObjectID().toString();
  348. const config = {
  349. file,
  350. fileId: fileId,
  351. meta: Utils.getCommonAttachmentMetaFrom(card),
  352. fileName: file.name || file.type.replace('image/', 'clipboard.'),
  353. chunkSize: 'dynamic',
  354. };
  355. config.meta.fileId = fileId;
  356. const uploader = Attachments.insert(
  357. config,
  358. false,
  359. );
  360. uploader.on('uploaded', (error, fileRef) => {
  361. if (!error) {
  362. if (fileRef.isImage) {
  363. card.setCover(fileRef._id);
  364. }
  365. }
  366. });
  367. uploader.on('end', (error, fileRef) => {
  368. pastedResults = null;
  369. $(document.body).pasteImageReader(() => {});
  370. Popup.back();
  371. });
  372. uploader.start();
  373. }
  374. },
  375. });
  376. BlazeComponent.extendComponent({
  377. isCover() {
  378. const ret = ReactiveCache.getCard(this.data().meta.cardId).coverId == this.data()._id;
  379. return ret;
  380. },
  381. isBackgroundImage() {
  382. //const currentBoard = Utils.getCurrentBoard();
  383. //return currentBoard.backgroundImageURL === $(".attachment-thumbnail-img").attr("src");
  384. return false;
  385. },
  386. events() {
  387. return [
  388. {
  389. 'click .js-add-cover'() {
  390. ReactiveCache.getCard(this.data().meta.cardId).setCover(this.data()._id);
  391. Popup.back();
  392. },
  393. 'click .js-remove-cover'() {
  394. ReactiveCache.getCard(this.data().meta.cardId).unsetCover();
  395. Popup.back();
  396. },
  397. 'click .js-add-background-image'() {
  398. const currentBoard = Utils.getCurrentBoard();
  399. currentBoard.setBackgroundImageURL(attachmentActionsLink);
  400. Utils.setBackgroundImage(attachmentActionsLink);
  401. Popup.back();
  402. event.preventDefault();
  403. },
  404. 'click .js-remove-background-image'() {
  405. const currentBoard = Utils.getCurrentBoard();
  406. currentBoard.setBackgroundImageURL("");
  407. Utils.setBackgroundImage("");
  408. Popup.back();
  409. Utils.reload();
  410. event.preventDefault();
  411. },
  412. 'click .js-move-storage-fs'() {
  413. Meteor.call('moveAttachmentToStorage', this.data()._id, "fs");
  414. Popup.back();
  415. },
  416. 'click .js-move-storage-gridfs'() {
  417. Meteor.call('moveAttachmentToStorage', this.data()._id, "gridfs");
  418. Popup.back();
  419. },
  420. 'click .js-move-storage-s3'() {
  421. Meteor.call('moveAttachmentToStorage', this.data()._id, "s3");
  422. Popup.back();
  423. },
  424. }
  425. ]
  426. }
  427. }).register('attachmentActionsPopup');
  428. BlazeComponent.extendComponent({
  429. getNameWithoutExtension() {
  430. const ret = this.data().name.replace(new RegExp("\." + this.data().extension + "$"), "");
  431. return ret;
  432. },
  433. events() {
  434. return [
  435. {
  436. 'keydown input.js-edit-attachment-name'(evt) {
  437. // enter = save
  438. if (evt.keyCode === 13) {
  439. this.find('button[type=submit]').click();
  440. }
  441. },
  442. 'click button.js-submit-edit-attachment-name'(event) {
  443. // save button pressed
  444. event.preventDefault();
  445. const name = this.$('.js-edit-attachment-name')[0]
  446. .value
  447. .trim() + this.data().extensionWithDot;
  448. if (name === DOMPurify.sanitize(name)) {
  449. Meteor.call('renameAttachment', this.data()._id, name);
  450. }
  451. Popup.back();
  452. },
  453. }
  454. ]
  455. }
  456. }).register('attachmentRenamePopup');