|
| 1 | +import { Meteor } from 'meteor/meteor'; |
| 2 | + |
| 3 | +import Comments from '/imports/models/comments'; |
| 4 | +import Books from '/imports/models/books'; |
| 5 | + |
| 6 | +export default class AnnotationService { |
| 7 | + constructor(props) { |
| 8 | + this.token = props.token; |
| 9 | + this.user = Meteor.users.findOne({ |
| 10 | + 'services.resume.loginTokens.hashedToken': Accounts._hashLoginToken(props.token), |
| 11 | + }); |
| 12 | + } |
| 13 | + |
| 14 | + hasAnnotationPermission(chapterUrl) { |
| 15 | + const book = Books.findOne({'chapters.url': chapterUrl}); |
| 16 | + const authorizedBooks = this.user.canAnnotateBooks || []; |
| 17 | + return !!(this.user && (book || ~authorizedBooks.indexOf(book._id))); |
| 18 | + } |
| 19 | + |
| 20 | + hasAnnotationRevisionPermission(annotationId) { |
| 21 | + const comment = Comments.findOne({_id: annotationId, users: this.user._id}); |
| 22 | + return !!comment; |
| 23 | + } |
| 24 | + |
| 25 | + rewriteRevision(revision) { |
| 26 | + if (revision instanceof Array) { |
| 27 | + const newRevision = []; |
| 28 | + revision.map(singleRevision => { |
| 29 | + newRevision.push({ |
| 30 | + tenantId: singleRevision.tenantId, |
| 31 | + text: singleRevision.text, |
| 32 | + created: new Date(), |
| 33 | + updated: new Date() |
| 34 | + }); |
| 35 | + }); |
| 36 | + return newRevision; |
| 37 | + } |
| 38 | + return { |
| 39 | + tenantId: revision.tenantId, |
| 40 | + text: revision.text, |
| 41 | + created: new Date(), |
| 42 | + updated: new Date() |
| 43 | + }; |
| 44 | + } |
| 45 | + |
| 46 | + createAnnotation(annotation) { |
| 47 | + const newAnnotation = annotation; |
| 48 | + newAnnotation.revisions = this.rewriteRevision(annotation.revisions); |
| 49 | + |
| 50 | + if (this.hasAnnotationPermission(annotation.bookChapterUrl)) { |
| 51 | + const commentId = Comments.insert({...newAnnotation}); |
| 52 | + return Comments.findOne(commentId); |
| 53 | + } |
| 54 | + return new Error('Not authorized'); |
| 55 | + } |
| 56 | + |
| 57 | + deleteAnnotation(annotationId) { |
| 58 | + const annotation = Comments.findOne(annotationId); |
| 59 | + if (this.hasAnnotationPermission(annotation.bookChapterUrl)) { |
| 60 | + return Comments.remove({_id: annotationId}); |
| 61 | + } |
| 62 | + return new Error('Not authorized'); |
| 63 | + } |
| 64 | + |
| 65 | + addRevision(annotationId, revision) { |
| 66 | + const newRevision = this.rewriteRevision(revision); |
| 67 | + if (this.hasAnnotationRevisionPermission(annotationId)) { |
| 68 | + return Comments.update({_id: annotationId}, { |
| 69 | + $addToSet: { |
| 70 | + revisions: newRevision |
| 71 | + } |
| 72 | + }); |
| 73 | + } |
| 74 | + return new Error('Not authorized'); |
| 75 | + } |
| 76 | +} |
0 commit comments