smaller refactorings continued

This commit is contained in:
azivner 2018-04-01 17:38:24 -04:00
parent 15d951b04e
commit 96dab5d51e
14 changed files with 122 additions and 109 deletions

25
src/entities/api_token.js Normal file
View File

@ -0,0 +1,25 @@
"use strict";
const Entity = require('./entity');
const utils = require('../services/utils');
class ApiToken extends Entity {
static get tableName() { return "api_tokens"; }
static get primaryKeyName() { return "apiTokenId"; }
beforeSaving() {
if (!this.apiTokenId) {
this.apiTokenId = utils.newApiTokenId();
}
if (!this.isDeleted) {
this.isDeleted = false;
}
if (!this.dateCreated) {
this.dateCreated = utils.nowDate();
}
}
}
module.exports = ApiToken;

View File

@ -13,6 +13,14 @@ class Branch extends Entity {
} }
beforeSaving() { beforeSaving() {
if (!this.branchId) {
this.branchId = utils.newBranchId();
}
if (!this.isDeleted) {
this.isDeleted = false;
}
this.dateModified = utils.nowDate() this.dateModified = utils.nowDate()
} }
} }

View File

@ -5,6 +5,7 @@ const NoteImage = require('../entities/note_image');
const Branch = require('../entities/branch'); const Branch = require('../entities/branch');
const Label = require('../entities/label'); const Label = require('../entities/label');
const RecentNote = require('../entities/recent_note'); const RecentNote = require('../entities/recent_note');
const ApiToken = require('../entities/api_token');
const repository = require('../services/repository'); const repository = require('../services/repository');
function createEntityFromRow(row) { function createEntityFromRow(row) {
@ -25,6 +26,9 @@ function createEntityFromRow(row) {
else if (row.branchId && row.notePath) { else if (row.branchId && row.notePath) {
entity = new RecentNote(row); entity = new RecentNote(row);
} }
else if (row.apiTokenId) {
entity = new ApiToken(row);
}
else if (row.branchId) { else if (row.branchId) {
entity = new Branch(row); entity = new Branch(row);
} }

View File

@ -8,6 +8,14 @@ class Image extends Entity {
static get primaryKeyName() { return "imageId"; } static get primaryKeyName() { return "imageId"; }
beforeSaving() { beforeSaving() {
if (!this.imageId) {
this.imageId = utils.newImageId();
}
if (!this.isDeleted) {
this.isDeleted = false;
}
if (!this.dateCreated) { if (!this.dateCreated) {
this.dateCreated = utils.nowDate(); this.dateCreated = utils.nowDate();
} }

View File

@ -131,6 +131,10 @@ class Note extends Entity {
} }
beforeSaving() { beforeSaving() {
if (!this.noteId) {
this.noteId = utils.newNoteId();
}
if (this.isJson()) { if (this.isJson()) {
this.content = JSON.stringify(this.jsonContent, null, '\t'); this.content = JSON.stringify(this.jsonContent, null, '\t');
} }
@ -139,6 +143,10 @@ class Note extends Entity {
protected_session.encryptNote(this); protected_session.encryptNote(this);
} }
if (!this.isDeleted) {
this.isDeleted = false;
}
if (!this.dateCreated) { if (!this.dateCreated) {
this.dateCreated = utils.nowDate(); this.dateCreated = utils.nowDate();
} }

View File

@ -17,6 +17,14 @@ class NoteImage extends Entity {
} }
beforeSaving() { beforeSaving() {
if (!this.noteImageId) {
this.noteImageId = utils.newNoteImageId();
}
if (!this.isDeleted) {
this.isDeleted = false;
}
if (!this.dateCreated) { if (!this.dateCreated) {
this.dateCreated = utils.nowDate(); this.dateCreated = utils.nowDate();
} }

View File

@ -2,6 +2,7 @@
const Entity = require('./entity'); const Entity = require('./entity');
const protected_session = require('../services/protected_session'); const protected_session = require('../services/protected_session');
const utils = require('../services/utils');
const repository = require('../services/repository'); const repository = require('../services/repository');
class NoteRevision extends Entity { class NoteRevision extends Entity {
@ -21,6 +22,10 @@ class NoteRevision extends Entity {
} }
beforeSaving() { beforeSaving() {
if (!this.noteRevisionId) {
this.noteRevisionId = utils.newNoteRevisionId();
}
if (this.isProtected) { if (this.isProtected) {
protected_session.encryptNoteRevision(this); protected_session.encryptNoteRevision(this);
} }

View File

@ -21,14 +21,11 @@ async function cloneNoteToParent(req) {
const newNotePos = maxNotePos === null ? 0 : maxNotePos + 1; const newNotePos = maxNotePos === null ? 0 : maxNotePos + 1;
const branch = new Branch({ const branch = new Branch({
branchId: utils.newBranchId(),
noteId: childNoteId, noteId: childNoteId,
parentNoteId: parentNoteId, parentNoteId: parentNoteId,
prefix: prefix, prefix: prefix,
notePosition: newNotePos, notePosition: newNotePos,
isExpanded: 0, isExpanded: 0
dateModified: utils.nowDate(),
isDeleted: 0
}); });
await branch.save(); await branch.save();
@ -58,13 +55,10 @@ async function cloneNoteAfter(req) {
await sync_table.addNoteReorderingSync(afterNote.parentNoteId); await sync_table.addNoteReorderingSync(afterNote.parentNoteId);
const branch = new Branch({ const branch = new Branch({
branchId: utils.newBranchId(),
noteId: noteId, noteId: noteId,
parentNoteId: afterNote.parentNoteId, parentNoteId: afterNote.parentNoteId,
notePosition: afterNote.notePosition + 1, notePosition: afterNote.notePosition + 1,
isExpanded: 0, isExpanded: 0
dateModified: utils.nowDate(),
isDeleted: 0
}); });
await branch.save(); await branch.save();

View File

@ -29,7 +29,6 @@ async function updateNoteLabels(req) {
} }
labelEntity = new Label(); labelEntity = new Label();
labelEntity.labelId = utils.newLabelId();
labelEntity.noteId = noteId; labelEntity.noteId = noteId;
} }

View File

@ -1,10 +1,7 @@
"use strict"; "use strict";
const sql = require('../../services/sql');
const notes = require('../../services/notes'); const notes = require('../../services/notes');
const utils = require('../../services/utils');
const tree = require('../../services/tree'); const tree = require('../../services/tree');
const sync_table = require('../../services/sync_table');
const repository = require('../../services/repository'); const repository = require('../../services/repository');
async function getNote(req) { async function getNote(req) {
@ -57,14 +54,12 @@ async function protectBranch(req) {
} }
async function setNoteTypeMime(req) { async function setNoteTypeMime(req) {
const noteId = req.params[0]; const [noteId, type, mime] = req.params;
const type = req.params[1];
const mime = req.params[2];
await sql.execute("UPDATE notes SET type = ?, mime = ?, dateModified = ? WHERE noteId = ?", const note = await repository.getNote(noteId);
[type, mime, utils.nowDate(), noteId]); note.type = type;
note.mime = mime;
await sync_table.addNoteSync(noteId); await note.save();
} }
module.exports = { module.exports = {

View File

@ -7,7 +7,7 @@ const sql = require('../../services/sql');
const notes = require('../../services/notes'); const notes = require('../../services/notes');
const password_encryption = require('../../services/password_encryption'); const password_encryption = require('../../services/password_encryption');
const options = require('../../services/options'); const options = require('../../services/options');
const sync_table = require('../../services/sync_table'); const ApiToken = require('../../entities/api_token');
async function login(req) { async function login(req) {
const username = req.body.username; const username = req.body.username;
@ -20,21 +20,11 @@ async function login(req) {
return [401, "Incorrect username/password"]; return [401, "Incorrect username/password"];
} }
const token = utils.randomSecureToken(); const apiToken = new ApiToken({ token: utils.randomSecureToken() });
await apiToken.save();
const apiTokenId = utils.newApiTokenId();
await sql.insert("api_tokens", {
apiTokenId: apiTokenId,
token: token,
dateCreated: utils.nowDate(),
isDeleted: false
});
await sync_table.addApiTokenSync(apiTokenId);
return { return {
token: token token: apiToken.token
}; };
} }

View File

@ -46,7 +46,7 @@ async function forceNoteSync(req) {
} }
for (const noteRevisionId of await sql.getColumn("SELECT noteRevisionId FROM note_revisions WHERE noteId = ?", [noteId])) { for (const noteRevisionId of await sql.getColumn("SELECT noteRevisionId FROM note_revisions WHERE noteId = ?", [noteId])) {
await sync_table.addNoteRevisionsSync(noteRevisionId); await sync_table.addNoteRevisionSync(noteRevisionId);
} }
log.info("Forcing note sync for " + noteId); log.info("Forcing note sync for " + noteId);

View File

@ -1,8 +1,8 @@
"use strict"; "use strict";
const utils = require('./utils'); const utils = require('./utils');
const sql = require('./sql'); const Image = require('../entities/image');
const sync_table = require('./sync_table'); const NoteImage = require('../entities/note_image');
const imagemin = require('imagemin'); const imagemin = require('imagemin');
const imageminMozJpeg = require('imagemin-mozjpeg'); const imageminMozJpeg = require('imagemin-mozjpeg');
const imageminPngQuant = require('imagemin-pngquant'); const imageminPngQuant = require('imagemin-pngquant');
@ -20,37 +20,23 @@ async function saveImage(file, noteId) {
const fileNameWithouExtension = file.originalname.replace(/\.[^/.]+$/, ""); const fileNameWithouExtension = file.originalname.replace(/\.[^/.]+$/, "");
const fileName = sanitizeFilename(fileNameWithouExtension + "." + imageFormat.ext); const fileName = sanitizeFilename(fileNameWithouExtension + "." + imageFormat.ext);
const imageId = utils.newImageId(); const image = new Image({
const now = utils.nowDate();
await sql.doInTransaction(async () => {
await sql.insert("images", {
imageId: imageId,
format: imageFormat.ext, format: imageFormat.ext,
name: fileName, name: fileName,
checksum: utils.hash(optimizedImage), checksum: utils.hash(optimizedImage),
data: optimizedImage, data: optimizedImage
isDeleted: 0,
dateModified: now,
dateCreated: now
}); });
await sync_table.addImageSync(imageId); await image.save();
const noteImageId = utils.newNoteImageId(); const noteImage = new NoteImage({
await sql.insert("note_images", {
noteImageId: noteImageId,
noteId: noteId, noteId: noteId,
imageId: imageId, imageId: image.imageId
isDeleted: 0,
dateModified: now,
dateCreated: now
}); });
await sync_table.addNoteImageSync(noteImageId); await noteImage.save();
});
return {fileName, imageId}; return {fileName, imageId: image.imageId};
} }
const MAX_SIZE = 1000; const MAX_SIZE = 1000;

View File

@ -9,16 +9,16 @@ const NoteImage = require('../entities/note_image');
const NoteRevision = require('../entities/note_revision'); const NoteRevision = require('../entities/note_revision');
const Branch = require('../entities/branch'); const Branch = require('../entities/branch');
async function getNewNotePosition(parentNoteId, noteOpts) { async function getNewNotePosition(parentNoteId, noteData) {
let newNotePos = 0; let newNotePos = 0;
if (noteOpts.target === 'into') { if (noteData.target === 'into') {
const maxNotePos = await sql.getValue('SELECT MAX(notePosition) FROM branches WHERE parentNoteId = ? AND isDeleted = 0', [parentNoteId]); const maxNotePos = await sql.getValue('SELECT MAX(notePosition) FROM branches WHERE parentNoteId = ? AND isDeleted = 0', [parentNoteId]);
newNotePos = maxNotePos === null ? 0 : maxNotePos + 1; newNotePos = maxNotePos === null ? 0 : maxNotePos + 1;
} }
else if (noteOpts.target === 'after') { else if (noteData.target === 'after') {
const afterNote = await sql.getRow('SELECT notePosition FROM branches WHERE branchId = ?', [noteOpts.target_branchId]); const afterNote = await sql.getRow('SELECT notePosition FROM branches WHERE branchId = ?', [noteData.target_branchId]);
newNotePos = afterNote.notePosition + 1; newNotePos = afterNote.notePosition + 1;
@ -29,44 +29,36 @@ async function getNewNotePosition(parentNoteId, noteOpts) {
await sync_table.addNoteReorderingSync(parentNoteId); await sync_table.addNoteReorderingSync(parentNoteId);
} }
else { else {
throw new Error('Unknown target: ' + noteOpts.target); throw new Error('Unknown target: ' + noteData.target);
} }
return newNotePos; return newNotePos;
} }
async function createNewNote(parentNoteId, noteOpts) { async function createNewNote(parentNoteId, noteData) {
const newNotePos = await getNewNotePosition(parentNoteId, noteOpts); const newNotePos = await getNewNotePosition(parentNoteId, noteData);
if (parentNoteId !== 'root') { if (parentNoteId !== 'root') {
const parent = await repository.getNote(parentNoteId); const parent = await repository.getNote(parentNoteId);
if (!noteOpts.type) { noteData.type = noteData.type || parent.type;
noteOpts.type = parent.type; noteData.mime = noteData.mime || parent.mime;
}
if (!noteOpts.mime) {
noteOpts.mime = parent.mime;
}
} }
const note = new Note({ const note = new Note({
noteId: utils.newNoteId(), title: noteData.title,
title: noteOpts.title, content: noteData.content || '',
content: noteOpts.content ? noteOpts.content : '', isProtected: noteData.isProtected,
isProtected: noteOpts.isProtected, type: noteData.type || 'text',
type: noteOpts.type ? noteOpts.type : 'text', mime: noteData.mime || 'text/html'
mime: noteOpts.mime ? noteOpts.mime : 'text/html'
}); });
await note.save(); await note.save();
const branch = new Branch({ const branch = new Branch({
branchId: utils.newBranchId(),
noteId: note.noteId, noteId: note.noteId,
parentNoteId: parentNoteId, parentNoteId: parentNoteId,
notePosition: newNotePos, notePosition: newNotePos,
isExpanded: 0, isExpanded: 0
isDeleted: 0
}); });
await branch.save(); await branch.save();
@ -85,7 +77,7 @@ async function createNote(parentNoteId, title, content = "", extraOptions = {})
title: title, title: title,
content: extraOptions.json ? JSON.stringify(content, null, '\t') : content, content: extraOptions.json ? JSON.stringify(content, null, '\t') : content,
target: 'into', target: 'into',
isProtected: extraOptions.isProtected !== undefined ? extraOptions.isProtected : false, isProtected: !!extraOptions.isProtected,
type: extraOptions.type, type: extraOptions.type,
mime: extraOptions.mime mime: extraOptions.mime
}; };
@ -95,11 +87,6 @@ async function createNote(parentNoteId, title, content = "", extraOptions = {})
noteData.mime = "application/json"; noteData.mime = "application/json";
} }
if (!noteData.type) {
noteData.type = "text";
noteData.mime = "text/html";
}
const {note} = await createNewNote(parentNoteId, noteData); const {note} = await createNewNote(parentNoteId, noteData);
if (extraOptions.labels) { if (extraOptions.labels) {
@ -123,7 +110,7 @@ async function protectNote(note, protect) {
if (protect !== note.isProtected) { if (protect !== note.isProtected) {
note.isProtected = protect; note.isProtected = protect;
await repository.updateEntity(note); await note.save();
} }
await protectNoteRevisions(note); await protectNoteRevisions(note);
@ -134,7 +121,7 @@ async function protectNoteRevisions(note) {
if (note.isProtected !== revision.isProtected) { if (note.isProtected !== revision.isProtected) {
revision.isProtected = note.isProtected; revision.isProtected = note.isProtected;
await repository.updateEntity(revision); await revision.save();
} }
} }
} }
@ -154,12 +141,10 @@ async function saveNoteImages(note) {
const existingNoteImage = existingNoteImages.find(ni => ni.imageId === imageId); const existingNoteImage = existingNoteImages.find(ni => ni.imageId === imageId);
if (!existingNoteImage) { if (!existingNoteImage) {
await repository.updateEntity(new NoteImage({ await (new NoteImage({
noteImageId: utils.newNoteImageId(),
noteId: note.noteId, noteId: note.noteId,
imageId: imageId, imageId: imageId
isDeleted: 0 })).save();
}));
} }
// else we don't need to do anything // else we don't need to do anything
@ -170,9 +155,9 @@ async function saveNoteImages(note) {
const unusedNoteImages = existingNoteImages.filter(ni => !foundImageIds.includes(ni.imageId)); const unusedNoteImages = existingNoteImages.filter(ni => !foundImageIds.includes(ni.imageId));
for (const unusedNoteImage of unusedNoteImages) { for (const unusedNoteImage of unusedNoteImages) {
unusedNoteImage.isDeleted = 1; unusedNoteImage.isDeleted = true;
await repository.updateEntity(unusedNoteImage); await unusedNoteImage.save();
} }
} }
@ -194,8 +179,7 @@ async function saveNoteRevision(note) {
&& !existingnoteRevisionId && !existingnoteRevisionId
&& msSinceDateCreated >= noteRevisionSnapshotTimeInterval * 1000) { && msSinceDateCreated >= noteRevisionSnapshotTimeInterval * 1000) {
await repository.updateEntity(new NoteRevision({ await (new NoteRevision({
noteRevisionId: utils.newNoteRevisionId(),
noteId: note.noteId, noteId: note.noteId,
// title and text should be decrypted now // title and text should be decrypted now
title: note.title, title: note.title,
@ -203,7 +187,7 @@ async function saveNoteRevision(note) {
isProtected: 0, // will be fixed in the protectNoteRevisions() call isProtected: 0, // will be fixed in the protectNoteRevisions() call
dateModifiedFrom: note.dateModified, dateModifiedFrom: note.dateModified,
dateModifiedTo: utils.nowDate() dateModifiedTo: utils.nowDate()
})); })).save();
} }
} }
@ -220,8 +204,7 @@ async function updateNote(noteId, noteUpdates) {
note.title = noteUpdates.title; note.title = noteUpdates.title;
note.content = noteUpdates.content; note.content = noteUpdates.content;
note.isProtected = noteUpdates.isProtected; note.isProtected = noteUpdates.isProtected;
await note.save();
await repository.updateEntity(note);
await saveNoteImages(note); await saveNoteImages(note);