attachments.js 16 KB

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