NotesService: Finished hardcoded functions

Signed-off-by: Philip Molares <philip.molares@udo.edu>
This commit is contained in:
Philip Molares 2021-02-20 16:09:02 +01:00
parent 8b29e32e45
commit 4332b039d6
2 changed files with 117 additions and 65 deletions

View file

@ -7,7 +7,11 @@
import { forwardRef, Inject, Injectable } from '@nestjs/common'; import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm'; import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm'; import { Repository } from 'typeorm';
import { NotInDBError } from '../errors/errors'; import {
AlreadyInDBError,
NotInDBError,
PermissionsUpdateInconsistentError,
} from '../errors/errors';
import { ConsoleLoggerService } from '../logger/console-logger.service'; import { ConsoleLoggerService } from '../logger/console-logger.service';
import { Revision } from '../revisions/revision.entity'; import { Revision } from '../revisions/revision.entity';
import { RevisionsService } from '../revisions/revisions.service'; import { RevisionsService } from '../revisions/revisions.service';
@ -25,6 +29,7 @@ import { HistoryEntry } from '../history/history-entry.entity';
import { NoteUserPermission } from '../permissions/note-user-permission.entity'; import { NoteUserPermission } from '../permissions/note-user-permission.entity';
import { NoteGroupPermission } from '../permissions/note-group-permission.entity'; import { NoteGroupPermission } from '../permissions/note-group-permission.entity';
import { GroupsService } from '../groups/groups.service'; import { GroupsService } from '../groups/groups.service';
import { checkArrayForDuplicates } from '../utils/arrayDuplicatCheck';
@Injectable() @Injectable()
export class NotesService { export class NotesService {
@ -46,25 +51,21 @@ export class NotesService {
* @param {User} user - the user who owns the notes * @param {User} user - the user who owns the notes
* @return {Note[]} arary of notes owned by the user * @return {Note[]} arary of notes owned by the user
*/ */
getUserNotes(user: User): Note[] { async getUserNotes(user: User): Promise<Note[]> {
this.logger.warn('Using hardcoded data!'); const notes = await this.noteRepository.find({
return [ where: { owner: user },
{ relations: [
id: 'foobar-barfoo', 'owner',
alias: null, 'userPermissions',
shortid: 'abc', 'groupPermissions',
owner: user, 'authorColors',
description: 'Very descriptive text.', 'tags',
userPermissions: [], ],
groupPermissions: [], });
historyEntries: [], if (notes === undefined) {
tags: [], return [];
revisions: Promise.resolve([]), }
authorColors: [], return notes;
title: 'Title!',
viewcount: 42,
},
];
} }
/** /**
@ -81,8 +82,8 @@ export class NotesService {
owner?: User, owner?: User,
): Promise<Note> { ): Promise<Note> {
const newNote = Note.create(); const newNote = Note.create();
newNote.revisions = Promise.resolve([
//TODO: Calculate patch //TODO: Calculate patch
newNote.revisions = Promise.resolve([
Revision.create(noteContent, noteContent), Revision.create(noteContent, noteContent),
]); ]);
if (alias) { if (alias) {
@ -122,7 +123,7 @@ export class NotesService {
* @return {Revision} the first revision of the note * @return {Revision} the first revision of the note
*/ */
async getLatestRevision(note: Note): Promise<Revision> { async getLatestRevision(note: Note): Promise<Revision> {
return this.revisionsService.getLatestRevision(note.id); return await this.revisionsService.getLatestRevision(note.id);
} }
/** /**
@ -132,7 +133,7 @@ export class NotesService {
* @return {Revision} the last revision of the note * @return {Revision} the last revision of the note
*/ */
async getFirstRevision(note: Note): Promise<Revision> { async getFirstRevision(note: Note): Promise<Revision> {
return this.revisionsService.getFirstRevision(note.id); return await this.revisionsService.getFirstRevision(note.id);
} }
/** /**
@ -161,6 +162,7 @@ export class NotesService {
'owner', 'owner',
'groupPermissions', 'groupPermissions',
'userPermissions', 'userPermissions',
'tags',
], ],
}); });
if (note === undefined) { if (note === undefined) {
@ -215,44 +217,90 @@ export class NotesService {
* @param {NotePermissionsUpdateDto} newPermissions - the permissions the not should be set to * @param {NotePermissionsUpdateDto} newPermissions - the permissions the not should be set to
* @return {Note} the note with the new permissions * @return {Note} the note with the new permissions
* @throws {NotInDBError} there is no note with this id or alias * @throws {NotInDBError} there is no note with this id or alias
* @throws {PermissionsUpdateInconsistent} the new permissions specify a user or group twice. * @throws {PermissionsUpdateInconsistentError} the new permissions specify a user or group twice.
*/ */
async updateNotePermissions( async updateNotePermissions(
noteIdOrAlias: string, noteIdOrAlias: string,
newPermissions: NotePermissionsUpdateDto, newPermissions: NotePermissionsUpdateDto,
): Note { ): Promise<Note> {
this.logger.warn('Using hardcoded data!', 'updateNotePermissions'); const note = await this.getNoteByIdOrAlias(noteIdOrAlias);
return {
id: 'foobar-barfoo', const users = newPermissions.sharedToUsers.map(
alias: null, (userPermission) => userPermission.username,
shortid: 'abc', );
owner: {
authTokens: [], const groups = newPermissions.sharedToGroups.map(
createdAt: new Date(), (groupPermission) => groupPermission.groupname,
displayName: 'hardcoded', );
id: '1',
identities: [], if (checkArrayForDuplicates(users) || checkArrayForDuplicates(groups)) {
ownedNotes: [], this.logger.debug(
historyEntries: [], `The PermissionUpdate requested specifies the same user or group multiple times.`,
updatedAt: new Date(), 'updateNotePermissions',
userName: 'Testy', );
groups: [], throw new PermissionsUpdateInconsistentError(
}, 'The PermissionUpdate requested specifies the same user or group multiple times.',
description: 'Very descriptive text.', );
userPermissions: [],
groupPermissions: [],
historyEntries: [],
tags: [],
revisions: Promise.resolve([]),
authorColors: [],
title: 'Title!',
viewcount: 42,
};
} }
async getNoteContent(noteIdOrAlias: string): Promise<string> { note.userPermissions = [];
note.groupPermissions = [];
// Create new userPermissions
for (const newUserPermission of newPermissions.sharedToUsers) {
const user = await this.usersService.getUserByUsername(
newUserPermission.username,
);
const createdPermission = NoteUserPermission.create(
user,
newUserPermission.canEdit,
);
note.userPermissions.push(createdPermission);
}
// Create groupPermissions
for (const newGroupPermission of newPermissions.sharedToGroups) {
const group = await this.groupsService.getGroupByName(
newGroupPermission.groupname,
);
const createdPermission = NoteGroupPermission.create(
group,
newGroupPermission.canEdit,
);
note.groupPermissions.push(createdPermission);
}
return await this.noteRepository.save(note);
}
/**
* @async
* Get the current content of the note by either their id or alias.
* @param {string} noteIdOrAlias - the notes id or alias
* @return {string} the content of the note
*/
async getNoteContentByIdOrAlias(noteIdOrAlias: string): Promise<string> {
const note = await this.getNoteByIdOrAlias(noteIdOrAlias); const note = await this.getNoteByIdOrAlias(noteIdOrAlias);
return this.getCurrentContent(note); return this.getNoteContentByNote(note);
}
/**
* @async
* Calculate the updateUser (for the NoteDto) for a Note.
* @param {Note} note - the note to use
* @return {User} user to be used as updateUser in the NoteDto
*/
async calculateUpdateUser(note: Note): Promise<User> {
const lastRevision = await this.getLatestRevision(note);
if (lastRevision && lastRevision.authorships) {
// Sort the last Revisions Authorships by their updatedAt Date to get the latest one
// the user of that Authorship is the updateUser
return lastRevision.authorships.sort(
(a, b) => b.updatedAt.getTime() - a.updatedAt.getTime(),
)[0].user;
}
// If there are no Authorships, the owner is the updateUser
return note.owner;
} }
/** /**
@ -278,7 +326,7 @@ export class NotesService {
canEdit: noteUserPermission.canEdit, canEdit: noteUserPermission.canEdit,
})), })),
sharedToGroups: note.groupPermissions.map((noteGroupPermission) => ({ sharedToGroups: note.groupPermissions.map((noteGroupPermission) => ({
group: noteGroupPermission.group, group: this.groupsService.toGroupDto(noteGroupPermission.group),
canEdit: noteGroupPermission.canEdit, canEdit: noteGroupPermission.canEdit,
})), })),
}; };
@ -301,18 +349,13 @@ export class NotesService {
editedBy: note.authorColors.map( editedBy: note.authorColors.map(
(authorColor) => authorColor.user.userName, (authorColor) => authorColor.user.userName,
), ),
// TODO: Extract into method
permissions: await this.toNotePermissionsDto(note), permissions: await this.toNotePermissionsDto(note),
tags: this.toTagList(note), tags: this.toTagList(note),
updateTime: (await this.getLatestRevision(note)).createdAt, updateTime: (await this.getLatestRevision(note)).createdAt,
// TODO: Get actual updateUser updateUser: this.usersService.toUserDto(
updateUser: { await this.calculateUpdateUser(note),
displayName: 'Hardcoded User', ),
userName: 'hardcoded', viewCount: note.viewcount,
email: 'foo@example.com',
photo: '',
},
viewCount: 42,
}; };
} }
@ -324,7 +367,7 @@ export class NotesService {
*/ */
async toNoteDto(note: Note): Promise<NoteDto> { async toNoteDto(note: Note): Promise<NoteDto> {
return { return {
content: await this.getCurrentContent(note), content: await this.getNoteContentByNote(note),
metadata: await this.toNoteMetadataDto(note), metadata: await this.toNoteMetadataDto(note),
editedByAtPosition: [], editedByAtPosition: [],
}; };

View file

@ -0,0 +1,9 @@
/*
* SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
export function checkArrayForDuplicates<T>(array: Array<T>): boolean {
return new Set(array).size !== array.length;
}