attachments.js 17 KB

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