attachments.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. import { ObjectID } from 'bson';
  2. import DOMPurify from 'dompurify';
  3. const filesize = require('filesize');
  4. const prettyMilliseconds = require('pretty-ms');
  5. // We store current card ID and the ID of currently opened attachment in a
  6. // global var. This is used so that we know what's the next attachment to open
  7. // when the user clicks on the prev/next button in the attachment viewer.
  8. let cardId = null;
  9. let openAttachmentId = null;
  10. Template.attachmentGallery.events({
  11. 'click .open-preview'(event) {
  12. openAttachmentId = $(event.currentTarget).attr("data-attachment-id");
  13. cardId = $(event.currentTarget).attr("data-card-id");
  14. openAttachmentViewer(openAttachmentId);
  15. },
  16. 'click .js-add-attachment': Popup.open('cardAttachments'),
  17. // If we let this event bubble, FlowRouter will handle it and empty the page
  18. // content, see #101.
  19. 'click .js-download'(event) {
  20. event.stopPropagation();
  21. },
  22. 'click .js-open-attachment-menu': Popup.open('attachmentActions'),
  23. 'click .js-rename': Popup.open('attachmentRename'),
  24. 'click .js-confirm-delete': Popup.afterConfirm('attachmentDelete', function() {
  25. Attachments.remove(this._id);
  26. Popup.back(2);
  27. }),
  28. });
  29. function getNextAttachmentId(currentAttachmentId) {
  30. const attachments = Attachments.find({'meta.cardId': cardId}).get();
  31. let i = 0;
  32. for (; i < attachments.length; i++) {
  33. if (attachments[i]._id === currentAttachmentId) {
  34. break;
  35. }
  36. }
  37. return attachments[(i + 1 + attachments.length) % attachments.length]._id;
  38. }
  39. function getPrevAttachmentId(currentAttachmentId) {
  40. const attachments = Attachments.find({'meta.cardId': cardId}).get();
  41. let i = 0;
  42. for (; i < attachments.length; i++) {
  43. if (attachments[i]._id === currentAttachmentId) {
  44. break;
  45. }
  46. }
  47. return attachments[(i - 1 + attachments.length) % attachments.length]._id;
  48. }
  49. function openAttachmentViewer(attachmentId){
  50. const attachment = Attachments.findOne({_id: attachmentId});
  51. $("#attachment-name").text(attachment.name);
  52. // IMPORTANT: if you ever add a new viewer, make sure you also implement
  53. // cleanup in the closeAttachmentViewer() function
  54. switch(true){
  55. case (attachment.isImage):
  56. $("#image-viewer").attr("src", attachment.link());
  57. $("#image-viewer").removeClass("hidden");
  58. break;
  59. case (attachment.isPDF):
  60. $("#pdf-viewer").attr("data", attachment.link());
  61. $("#pdf-viewer").removeClass("hidden");
  62. break;
  63. case (attachment.isVideo):
  64. // We have to create a new <source> DOM element and append it to the video
  65. // element, otherwise the video won't load
  66. let videoSource = document.createElement('source');
  67. videoSource.setAttribute('src', attachment.link());
  68. $("#video-viewer").append(videoSource);
  69. $("#video-viewer").removeClass("hidden");
  70. break;
  71. case (attachment.isAudio):
  72. // We have to create a new <source> DOM element and append it to the audio
  73. // element, otherwise the audio won't load
  74. let audioSource = document.createElement('source');
  75. audioSource.setAttribute('src', attachment.link());
  76. $("#audio-viewer").append(audioSource);
  77. $("#audio-viewer").removeClass("hidden");
  78. break;
  79. case (attachment.isText):
  80. case (attachment.isJSON):
  81. $("#txt-viewer").attr("data", attachment.link());
  82. $("#txt-viewer").removeClass("hidden");
  83. break;
  84. }
  85. $("#viewer-overlay").removeClass("hidden");
  86. }
  87. function closeAttachmentViewer() {
  88. $("#viewer-overlay").addClass("hidden");
  89. // We need to reset the viewers to avoid showing previous attachments
  90. $("#image-viewer").attr("src", "");
  91. $("#image-viewer").addClass("hidden");
  92. $("#pdf-viewer").attr("data", "");
  93. $("#pdf-viewer").addClass("hidden");
  94. $("#txt-viewer").attr("data", "");
  95. $("#txt-viewer").addClass("hidden");
  96. $("#video-viewer").get(0).pause(); // Stop playback
  97. $("#video-viewer").get(0).currentTime = 0;
  98. $("#video-viewer").empty();
  99. $("#video-viewer").addClass("hidden");
  100. $("#audio-viewer").get(0).pause(); // Stop playback
  101. $("#audio-viewer").get(0).currentTime = 0;
  102. $("#audio-viewer").empty();
  103. $("#audio-viewer").addClass("hidden");
  104. }
  105. Template.attachmentViewer.events({
  106. 'click #viewer-container'(event) {
  107. // Make sure the click was on #viewer-container and not on any of its children
  108. if(event.target !== event.currentTarget) return;
  109. closeAttachmentViewer();
  110. },
  111. 'click #viewer-content'(event) {
  112. // Make sure the click was on #viewer-content and not on any of its children
  113. if(event.target !== event.currentTarget) return;
  114. closeAttachmentViewer();
  115. },
  116. 'click #viewer-close'() {
  117. closeAttachmentViewer();
  118. },
  119. 'click #next-attachment'(event) {
  120. closeAttachmentViewer()
  121. const id = getNextAttachmentId(openAttachmentId);
  122. openAttachmentId = id;
  123. openAttachmentViewer(id);
  124. },
  125. 'click #prev-attachment'(event) {
  126. closeAttachmentViewer()
  127. const id = getPrevAttachmentId(openAttachmentId);
  128. openAttachmentId = id;
  129. openAttachmentViewer(id);
  130. }
  131. });
  132. Template.attachmentGallery.helpers({
  133. isBoardAdmin() {
  134. return Meteor.user().isBoardAdmin();
  135. },
  136. fileSize(size) {
  137. const ret = filesize(size);
  138. return ret;
  139. },
  140. sanitize(value) {
  141. return DOMPurify.sanitize(value);
  142. },
  143. });
  144. Template.cardAttachmentsPopup.onCreated(function() {
  145. this.uploads = new ReactiveVar([]);
  146. });
  147. Template.cardAttachmentsPopup.helpers({
  148. getEstimateTime(upload) {
  149. const ret = prettyMilliseconds(upload.estimateTime.get());
  150. return ret;
  151. },
  152. getEstimateSpeed(upload) {
  153. const ret = filesize(upload.estimateSpeed.get(), {round: 0}) + "/s";
  154. return ret;
  155. },
  156. uploads() {
  157. return Template.instance().uploads.get();
  158. }
  159. });
  160. Template.cardAttachmentsPopup.events({
  161. 'change .js-attach-file'(event, templateInstance) {
  162. const card = this;
  163. const files = event.currentTarget.files;
  164. if (files) {
  165. let uploads = [];
  166. for (const file of files) {
  167. const fileId = new ObjectID().toString();
  168. // If filename is not same as sanitized filename, has XSS, then cancel upload
  169. if (file.name !== DOMPurify.sanitize(file.name)) {
  170. return false;
  171. }
  172. const config = {
  173. file: file,
  174. fileId: fileId,
  175. meta: Utils.getCommonAttachmentMetaFrom(card),
  176. chunkSize: 'dynamic',
  177. };
  178. config.meta.fileId = fileId;
  179. const uploader = Attachments.insert(
  180. config,
  181. false,
  182. );
  183. uploader.on('start', function() {
  184. uploads.push(this);
  185. templateInstance.uploads.set(uploads);
  186. });
  187. uploader.on('uploaded', (error, fileRef) => {
  188. if (!error) {
  189. if (fileRef.isImage) {
  190. card.setCover(fileRef._id);
  191. }
  192. }
  193. });
  194. uploader.on('end', (error, fileRef) => {
  195. uploads = uploads.filter(_upload => _upload.config.fileId != fileRef._id);
  196. templateInstance.uploads.set(uploads);
  197. if (uploads.length == 0 ) {
  198. Popup.back();
  199. }
  200. });
  201. uploader.start();
  202. }
  203. }
  204. },
  205. 'click .js-computer-upload'(event, templateInstance) {
  206. templateInstance.find('.js-attach-file').click();
  207. event.preventDefault();
  208. },
  209. 'click .js-upload-clipboard-image': Popup.open('previewClipboardImage'),
  210. });
  211. const MAX_IMAGE_PIXEL = Utils.MAX_IMAGE_PIXEL;
  212. const COMPRESS_RATIO = Utils.IMAGE_COMPRESS_RATIO;
  213. let pastedResults = null;
  214. Template.previewClipboardImagePopup.onRendered(() => {
  215. // we can paste image from clipboard
  216. const handle = results => {
  217. if (results.dataURL.startsWith('data:image/')) {
  218. const direct = results => {
  219. $('img.preview-clipboard-image').attr('src', results.dataURL);
  220. pastedResults = results;
  221. };
  222. if (MAX_IMAGE_PIXEL) {
  223. // if has size limitation on image we shrink it before uploading
  224. Utils.shrinkImage({
  225. dataurl: results.dataURL,
  226. maxSize: MAX_IMAGE_PIXEL,
  227. ratio: COMPRESS_RATIO,
  228. callback(changed) {
  229. if (changed !== false && !!changed) {
  230. results.dataURL = changed;
  231. }
  232. direct(results);
  233. },
  234. });
  235. } else {
  236. direct(results);
  237. }
  238. }
  239. };
  240. $(document.body).pasteImageReader(handle);
  241. // we can also drag & drop image file to it
  242. $(document.body).dropImageReader(handle);
  243. });
  244. Template.previewClipboardImagePopup.events({
  245. 'click .js-upload-pasted-image'() {
  246. const card = this;
  247. if (pastedResults && pastedResults.file) {
  248. const file = pastedResults.file;
  249. window.oPasted = pastedResults;
  250. const fileId = new ObjectID().toString();
  251. const config = {
  252. file,
  253. fileId: fileId,
  254. meta: Utils.getCommonAttachmentMetaFrom(card),
  255. fileName: file.name || file.type.replace('image/', 'clipboard.'),
  256. chunkSize: 'dynamic',
  257. };
  258. config.meta.fileId = fileId;
  259. const uploader = Attachments.insert(
  260. config,
  261. false,
  262. );
  263. uploader.on('uploaded', (error, fileRef) => {
  264. if (!error) {
  265. if (fileRef.isImage) {
  266. card.setCover(fileRef._id);
  267. }
  268. }
  269. });
  270. uploader.on('end', (error, fileRef) => {
  271. pastedResults = null;
  272. $(document.body).pasteImageReader(() => {});
  273. Popup.back();
  274. });
  275. uploader.start();
  276. }
  277. },
  278. });
  279. BlazeComponent.extendComponent({
  280. isCover() {
  281. const ret = Cards.findOne(this.data().meta.cardId).coverId == this.data()._id;
  282. return ret;
  283. },
  284. isBackgroundImage() {
  285. //const currentBoard = Boards.findOne(Session.get('currentBoard'));
  286. //return currentBoard.backgroundImageURL === $(".attachment-thumbnail-img").attr("src");
  287. return false;
  288. },
  289. events() {
  290. return [
  291. {
  292. 'click .js-add-cover'() {
  293. Cards.findOne(this.data().meta.cardId).setCover(this.data()._id);
  294. Popup.back();
  295. },
  296. 'click .js-remove-cover'() {
  297. Cards.findOne(this.data().meta.cardId).unsetCover();
  298. Popup.back();
  299. },
  300. 'click .js-add-background-image'() {
  301. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  302. const url=$(".attachment-thumbnail-img").attr("src");
  303. currentBoard.setBackgroundImageURL(url);
  304. Utils.setBackgroundImage(url);
  305. Popup.back();
  306. event.preventDefault();
  307. },
  308. 'click .js-remove-background-image'() {
  309. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  310. currentBoard.setBackgroundImageURL("");
  311. Utils.setBackgroundImage("");
  312. Popup.back();
  313. Utils.reload();
  314. event.preventDefault();
  315. },
  316. 'click .js-move-storage-fs'() {
  317. Meteor.call('moveAttachmentToStorage', this.data()._id, "fs");
  318. Popup.back();
  319. },
  320. 'click .js-move-storage-gridfs'() {
  321. Meteor.call('moveAttachmentToStorage', this.data()._id, "gridfs");
  322. Popup.back();
  323. },
  324. 'click .js-move-storage-s3'() {
  325. Meteor.call('moveAttachmentToStorage', this.data()._id, "s3");
  326. Popup.back();
  327. },
  328. }
  329. ]
  330. }
  331. }).register('attachmentActionsPopup');
  332. BlazeComponent.extendComponent({
  333. getNameWithoutExtension() {
  334. const ret = this.data().name.replace(new RegExp("\." + this.data().extension + "$"), "");
  335. return ret;
  336. },
  337. events() {
  338. return [
  339. {
  340. 'keydown input.js-edit-attachment-name'(evt) {
  341. // enter = save
  342. if (evt.keyCode === 13) {
  343. this.find('button[type=submit]').click();
  344. }
  345. },
  346. 'click button.js-submit-edit-attachment-name'(event) {
  347. // save button pressed
  348. event.preventDefault();
  349. const name = this.$('.js-edit-attachment-name')[0]
  350. .value
  351. .trim() + this.data().extensionWithDot;
  352. if (name === DOMPurify.sanitize(name)) {
  353. Meteor.call('renameAttachment', this.data()._id, name);
  354. }
  355. Popup.back(2);
  356. },
  357. }
  358. ]
  359. }
  360. }).register('attachmentRenamePopup');