attachments.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. const uploaders = handleFileUpload(card, files);
  256. uploaders.forEach(uploader => {
  257. uploader.on('start', function() {
  258. uploads.push(this);
  259. templateInstance.uploads.set(uploads);
  260. });
  261. uploader.on('end', (error, fileRef) => {
  262. uploads = uploads.filter(_upload => _upload.config.fileId != fileRef._id);
  263. templateInstance.uploads.set(uploads);
  264. if (uploads.length == 0 ) {
  265. Popup.back();
  266. }
  267. });
  268. });
  269. }
  270. },
  271. 'click .js-computer-upload'(event, templateInstance) {
  272. templateInstance.find('.js-attach-file').click();
  273. event.preventDefault();
  274. },
  275. 'click .js-upload-clipboard-image': Popup.open('previewClipboardImage'),
  276. });
  277. const MAX_IMAGE_PIXEL = Utils.MAX_IMAGE_PIXEL;
  278. const COMPRESS_RATIO = Utils.IMAGE_COMPRESS_RATIO;
  279. let pastedResults = null;
  280. // Shared upload logic for drag-and-drop functionality
  281. export function handleFileUpload(card, files) {
  282. if (!files || files.length === 0) {
  283. return [];
  284. }
  285. // Check if board allows attachments
  286. const board = card.board();
  287. if (!board || !board.allowsAttachments) {
  288. console.warn('Attachments not allowed on this board');
  289. return [];
  290. }
  291. // Check if user can modify the card
  292. if (!card.canModifyCard()) {
  293. console.warn('User does not have permission to modify this card');
  294. return [];
  295. }
  296. const uploads = [];
  297. for (const file of files) {
  298. // Basic file validation
  299. if (!file || !file.name) {
  300. console.warn('Invalid file object');
  301. continue;
  302. }
  303. const fileId = new ObjectID().toString();
  304. let fileName = DOMPurify.sanitize(file.name);
  305. // If sanitized filename is not same as original filename,
  306. // it could be XSS that is already fixed with sanitize,
  307. // or just normal mistake, so it is not a problem.
  308. // That is why here is no warning.
  309. if (fileName !== file.name) {
  310. // If filename is empty, only in that case add some filename
  311. if (fileName.length === 0) {
  312. fileName = 'Empty-filename-after-sanitize.txt';
  313. }
  314. }
  315. const config = {
  316. file: file,
  317. fileId: fileId,
  318. fileName: fileName,
  319. meta: Utils.getCommonAttachmentMetaFrom(card),
  320. chunkSize: 'dynamic',
  321. };
  322. config.meta.fileId = fileId;
  323. try {
  324. const uploader = Attachments.insert(
  325. config,
  326. false,
  327. );
  328. uploader.on('uploaded', (error, fileRef) => {
  329. if (!error) {
  330. if (fileRef.isImage) {
  331. card.setCover(fileRef._id);
  332. }
  333. } else {
  334. console.error('Upload error:', error);
  335. }
  336. });
  337. uploader.on('error', (error) => {
  338. console.error('Upload error:', error);
  339. });
  340. uploads.push(uploader);
  341. uploader.start();
  342. } catch (error) {
  343. console.error('Failed to create uploader:', error);
  344. }
  345. }
  346. return uploads;
  347. }
  348. Template.previewClipboardImagePopup.onRendered(() => {
  349. // we can paste image from clipboard
  350. const handle = results => {
  351. if (results.dataURL.startsWith('data:image/')) {
  352. const direct = results => {
  353. $('img.preview-clipboard-image').attr('src', results.dataURL);
  354. pastedResults = results;
  355. };
  356. if (MAX_IMAGE_PIXEL) {
  357. // if has size limitation on image we shrink it before uploading
  358. Utils.shrinkImage({
  359. dataurl: results.dataURL,
  360. maxSize: MAX_IMAGE_PIXEL,
  361. ratio: COMPRESS_RATIO,
  362. callback(changed) {
  363. if (changed !== false && !!changed) {
  364. results.dataURL = changed;
  365. }
  366. direct(results);
  367. },
  368. });
  369. } else {
  370. direct(results);
  371. }
  372. }
  373. };
  374. $(document.body).pasteImageReader(handle);
  375. // we can also drag & drop image file to it
  376. $(document.body).dropImageReader(handle);
  377. });
  378. Template.previewClipboardImagePopup.events({
  379. 'click .js-upload-pasted-image'() {
  380. const card = this;
  381. if (pastedResults && pastedResults.file) {
  382. const file = pastedResults.file;
  383. window.oPasted = pastedResults;
  384. const fileId = new ObjectID().toString();
  385. const config = {
  386. file,
  387. fileId: fileId,
  388. meta: Utils.getCommonAttachmentMetaFrom(card),
  389. fileName: file.name || file.type.replace('image/', 'clipboard.'),
  390. chunkSize: 'dynamic',
  391. };
  392. config.meta.fileId = fileId;
  393. const uploader = Attachments.insert(
  394. config,
  395. false,
  396. );
  397. uploader.on('uploaded', (error, fileRef) => {
  398. if (!error) {
  399. if (fileRef.isImage) {
  400. card.setCover(fileRef._id);
  401. }
  402. }
  403. });
  404. uploader.on('end', (error, fileRef) => {
  405. pastedResults = null;
  406. $(document.body).pasteImageReader(() => {});
  407. Popup.back();
  408. });
  409. uploader.start();
  410. }
  411. },
  412. });
  413. BlazeComponent.extendComponent({
  414. isCover() {
  415. const ret = ReactiveCache.getCard(this.data().meta.cardId).coverId == this.data()._id;
  416. return ret;
  417. },
  418. isBackgroundImage() {
  419. //const currentBoard = Utils.getCurrentBoard();
  420. //return currentBoard.backgroundImageURL === $(".attachment-thumbnail-img").attr("src");
  421. return false;
  422. },
  423. events() {
  424. return [
  425. {
  426. 'click .js-add-cover'() {
  427. ReactiveCache.getCard(this.data().meta.cardId).setCover(this.data()._id);
  428. Popup.back();
  429. },
  430. 'click .js-remove-cover'() {
  431. ReactiveCache.getCard(this.data().meta.cardId).unsetCover();
  432. Popup.back();
  433. },
  434. 'click .js-add-background-image'() {
  435. const currentBoard = Utils.getCurrentBoard();
  436. currentBoard.setBackgroundImageURL(attachmentActionsLink);
  437. Utils.setBackgroundImage(attachmentActionsLink);
  438. Popup.back();
  439. event.preventDefault();
  440. },
  441. 'click .js-remove-background-image'() {
  442. const currentBoard = Utils.getCurrentBoard();
  443. currentBoard.setBackgroundImageURL("");
  444. Utils.setBackgroundImage("");
  445. Popup.back();
  446. Utils.reload();
  447. event.preventDefault();
  448. },
  449. 'click .js-move-storage-fs'() {
  450. Meteor.call('moveAttachmentToStorage', this.data()._id, "fs");
  451. Popup.back();
  452. },
  453. 'click .js-move-storage-gridfs'() {
  454. Meteor.call('moveAttachmentToStorage', this.data()._id, "gridfs");
  455. Popup.back();
  456. },
  457. 'click .js-move-storage-s3'() {
  458. Meteor.call('moveAttachmentToStorage', this.data()._id, "s3");
  459. Popup.back();
  460. },
  461. }
  462. ]
  463. }
  464. }).register('attachmentActionsPopup');
  465. BlazeComponent.extendComponent({
  466. getNameWithoutExtension() {
  467. const ret = this.data().name.replace(new RegExp("\." + this.data().extension + "$"), "");
  468. return ret;
  469. },
  470. events() {
  471. return [
  472. {
  473. 'keydown input.js-edit-attachment-name'(evt) {
  474. // enter = save
  475. if (evt.keyCode === 13) {
  476. this.find('button[type=submit]').click();
  477. }
  478. },
  479. 'click button.js-submit-edit-attachment-name'(event) {
  480. // save button pressed
  481. event.preventDefault();
  482. const name = this.$('.js-edit-attachment-name')[0]
  483. .value
  484. .trim() + this.data().extensionWithDot;
  485. if (name === DOMPurify.sanitize(name)) {
  486. Meteor.call('renameAttachment', this.data()._id, name);
  487. }
  488. Popup.back();
  489. },
  490. }
  491. ]
  492. }
  493. }).register('attachmentRenamePopup');