Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

feat: remove old api

thecodrr248bc4e3b64a
diff --git a/packages/core/__tests__/database.test.js b/packages/core/__tests__/database.test.js
deleted file mode 100644
index 39ea31786..000000000
--- a/packages/core/__tests__/database.test.js
+++ /dev/null
@@ -1,551 +0,0 @@
-import Database from "../api/database";
-import StorageInterface from "../__mocks__/storage.mock";
-import { getLastWeekTimestamp } from "../utils/date";
-
-function databaseTest() {
- let db = new Database(StorageInterface);
- return db.init().then(() => db);
-}
-
-const noteTest = (note = TEST_NOTE) =>
- databaseTest().then(async db => {
- let timestamp = await db.addNote(note);
- return { db, timestamp };
- });
-
-const notebookTest = (notebook = TEST_NOTEBOOK) =>
- databaseTest().then(async db => {
- let timestamp = await db.addNotebook(notebook);
- return { db, timestamp };
- });
-
-const topicTest = (topic = "Home") =>
- notebookTest().then(async ({ db, timestamp }) => {
- await db.addTopicToNotebook(timestamp, topic);
- return { db, timestamp, topic };
- });
-
-const topicNoteTest = (topic = "Home") =>
- topicTest(topic).then(async ({ db, timestamp, topic }) => {
- let noteTimestamp = await db.addNote(TEST_NOTE);
- await db.addNoteToTopic(timestamp, topic, noteTimestamp);
- return { db, timestamp, topic, noteTimestamp };
- });
-
-const groupedTest = (type, special = false) =>
- noteTest().then(async ({ db }) => {
- await db.addNote({ ...TEST_NOTE, title: "HELLO WHAT!" });
- await db.addNote({
- ...TEST_NOTE,
- title: "Some title",
- dateCreated: getLastWeekTimestamp() - 604800000
- });
- await db.addNote({
- ...TEST_NOTE,
- title: "Some title and title title",
- dateCreated: getLastWeekTimestamp() - 604800000 * 2
- });
- let grouped = db.groupNotes(type, special);
- if (special) {
- expect(grouped.items.length).toBeGreaterThan(0);
- expect(grouped.groups.length).toBeGreaterThan(0);
- expect(grouped.groupCounts.length).toBeGreaterThan(0);
- return;
- }
- expect(grouped.length).toBeGreaterThan(0);
- expect(grouped[0].data.length).toBeGreaterThan(0);
- expect(grouped[0].title.length).toBeGreaterThan(0);
- });
-
-var TEST_NOTE;
-
-const LONG_TEXT =
- "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
-
-var TEST_NOTEBOOK;
-var TEST_NOTEBOOK2;
-
-beforeEach(() => {
- StorageInterface.clear();
- TEST_NOTE = {
- content: { delta: "I am a delta", text: "I am a text" }
- };
- TEST_NOTEBOOK2 = {
- title: "Test Notebook 2",
- description: "Test Description 2",
- topics: ["Home2"]
- };
- TEST_NOTEBOOK = {
- title: "Test Notebook",
- description: "Test Description",
- topics: ["hello", "hello", " "]
- };
-});
-
-test("add invalid note", () =>
- databaseTest().then(async db => {
- let timestamp = await db.addNote();
- expect(timestamp).toBeUndefined();
- timestamp = await db.addNote({});
- expect(timestamp).toBeUndefined();
- timestamp = await db.addNote({ hello: "world" });
- expect(timestamp).toBeUndefined();
- }));
-
-test("add a note", () =>
- noteTest().then(({ timestamp }) => expect(timestamp).toBeGreaterThan(0)));
-
-test("get all notes", () =>
- noteTest().then(({ db }) => {
- let notes = db.getNotes();
- expect(notes.length).toBeGreaterThan(0);
- }));
-
-test("search all notes", () =>
- noteTest({
- content: { delta: "5", text: "5" }
- }).then(({ db }) => {
- let filtered = db.searchNotes("5");
- expect(filtered.length).toBeGreaterThan(0);
- }));
-
-test("get a note", () =>
- noteTest().then(({ db, timestamp }) => {
- let note = db.getNote(timestamp);
- expect(note.dateCreated).toBe(timestamp);
- }));
-
-test("note without a title should get title from content", () =>
- noteTest().then(({ db, timestamp }) => {
- let note = db.getNote(timestamp);
- expect(note.title).toBe("I am a");
- }));
-
-test("update note", () =>
- noteTest().then(async ({ db, timestamp }) => {
- let updateTimestamp = await db.addNote({
- dateCreated: timestamp,
- title: "I am a new title",
- content: {
- text: LONG_TEXT,
- delta: []
- },
- pinned: true,
- favorite: true,
- colors: ["red", "blue"]
- });
- expect(updateTimestamp).toBe(timestamp);
- let note = db.getNote(updateTimestamp);
- expect(note.pinned).toBe(true);
- expect(note.favorite).toBe(true);
- expect(note.colors).toStrictEqual(["red", "blue"]);
- }));
-
-test("updating empty note should delete it", () =>
- noteTest().then(async ({ db, timestamp }) => {
- let updateTimestamp = await db.addNote({
- dateCreated: timestamp,
- title: "\n\n",
- content: {
- text: "",
- delta: []
- },
- pinned: true,
- favorite: true,
- colors: ["red", "blue"]
- });
- expect(updateTimestamp).toBeUndefined();
- }));
-
-test("updating note with duplicate colors", () =>
- noteTest({
- ...TEST_NOTE,
- colors: ["red", "blue"]
- }).then(async ({ db, timestamp }) => {
- let updateTimestamp = await db.addNote({
- dateCreated: timestamp,
- colors: ["red", "red", "blue", "blue"]
- });
- expect(updateTimestamp).toBe(timestamp);
- let note = db.getNote(updateTimestamp);
- expect(note.colors).toStrictEqual(["red", "blue"]);
- }));
-
-test("add tag to note", () =>
- noteTest().then(async ({ db, timestamp }) => {
- await db.addTag(timestamp, "hello");
- expect(db.getNote(timestamp).tags[0]).toBe("hello");
- expect(db.getTags()[0].title).toBe("hello");
- }));
-
-test("remove tag from note", () =>
- noteTest().then(async ({ db, timestamp }) => {
- await db.addTag(timestamp, "hello");
- expect(db.getNote(timestamp).tags[0]).toBe("hello");
- expect(db.getTags()[0].title).toBe("hello");
- await db.removeTag(timestamp, "hello");
- expect(db.getNote(timestamp).tags.length).toBe(0);
- expect(db.getTags().length).toBe(0);
- }));
-
-test("note with text longer than 150 characters should have ... in the headline", () =>
- noteTest({
- content: {
- text: LONG_TEXT,
- delta: []
- }
- }).then(({ db, timestamp }) => {
- let note = db.getNote(timestamp);
- expect(note.headline.includes("...")).toBe(true);
- }));
-
-test("get tags", () =>
- noteTest({
- ...TEST_NOTE,
- tags: ["new", "tag", "goes", "here"]
- }).then(async ({ db }) => {
- expect(db.getTags().length).toBeGreaterThan(0);
- }));
-
-test("get notes in tag", () =>
- noteTest({
- ...TEST_NOTE,
- tags: ["new", "tag", "goes", "here"]
- }).then(async ({ db }) => {
- expect(db.getTag("tag")[0].tags.includes("tag")).toBe(true);
- }));
-
-test("get favorites", () =>
- noteTest({
- pinned: true,
- favorite: true,
- content: { delta: "Hello", text: "Hello" }
- }).then(({ db }) => {
- let favorites = db.getFavorites();
- expect(favorites.length).toBeGreaterThan(0);
- }));
-
-test("add a notebook", () =>
- notebookTest().then(({ timestamp }) => {
- expect(timestamp).toBeGreaterThan(0);
- }));
-
-test("duplicate notebook should not be added", () =>
- notebookTest().then(async ({ db }) => {
- let id = await db.addNotebook(TEST_NOTEBOOK);
- expect(id).toBeUndefined();
- }));
-
-test("get all notebooks", () =>
- notebookTest().then(({ db }) => {
- let notebooks = db.getNotebooks();
- expect(notebooks.length).toBeGreaterThan(0);
- }));
-
-test("search all notebooks", () =>
- notebookTest({
- ...TEST_NOTEBOOK,
- title: "I will be searched.",
- description: "searched description"
- }).then(({ db }) => {
- let filtered = db.searchNotebooks("searhed");
- expect(filtered.length).toBeGreaterThan(0);
- }));
-
-test("get a notebook", () =>
- notebookTest().then(({ db, timestamp }) => {
- let notebook = db.getNotebook(timestamp);
- expect(notebook).toBeDefined();
- }));
-
-test("get empty topic", () =>
- notebookTest().then(({ db, timestamp }) => {
- let notes = db.getTopic(timestamp, "General");
- expect(notes.length).toBe(0);
- }));
-
-test("getting invalid topic should return undefined", () =>
- notebookTest().then(({ db, timestamp }) => {
- let notes = db.getTopic(timestamp, "invalid");
- expect(notes).toBeUndefined();
- }));
-
-test("add topic to notebook", () =>
- topicTest().then(({ db, timestamp, topic }) => {
- let notebook = db.getNotebook(timestamp);
- let topicIndex = notebook.topics.findIndex(t => t.title === topic);
- expect(topicIndex).toBeGreaterThan(-1);
- }));
-
-test("duplicate topic to notebook should not be added", () =>
- topicTest().then(async ({ db, timestamp, topic }) => {
- let res = await db.addTopicToNotebook(timestamp, topic);
- expect(res).toBe(false);
- }));
-
-test("add note to topic", async () =>
- topicNoteTest().then(async ({ db, timestamp, topic, noteTimestamp }) => {
- let notebook = db.getNotebook(timestamp);
- let topicIndex = notebook.topics.findIndex(t => t.title === topic);
- expect(notebook.topics[topicIndex].notes[0]).toBe(noteTimestamp);
- let note = db.getNote(noteTimestamp);
- expect(note.notebook.id).toBe(timestamp);
- }));
-
-test("duplicate note to topic should not be added", async () =>
- topicNoteTest().then(async ({ db, timestamp, topic, noteTimestamp }) => {
- let res = await db.addNoteToTopic(timestamp, topic, noteTimestamp);
- expect(res).toBe(false);
- }));
-
-test("get topic", async () =>
- topicNoteTest().then(async ({ db, timestamp, topic }) => {
- let notes = db.getTopic(timestamp, topic);
- expect(notes.length).toBeGreaterThan(0);
- }));
-
-test("move note", async () =>
- noteTest().then(async ({ db, timestamp }) => {
- let notebook1 = await db.addNotebook(TEST_NOTEBOOK);
- await db.addTopicToNotebook(notebook1, "Home");
- await db.addNoteToTopic(notebook1, "Home", timestamp);
- setTimeout(async () => {
- let notebook2 = await db.addNotebook(TEST_NOTEBOOK2);
- await db.moveNotes(
- { id: notebook1, topic: "Home" },
- { id: notebook2, topic: "Home2" },
- timestamp
- );
- let note = db.getNote(timestamp);
- expect(note.notebook.id).toBe(notebook2);
- }, 1000);
- }));
-
-test("deletion of note from invalid topic should return false", () =>
- noteTest().then(async ({ db, noteId = timestamp }) => {
- let timestamp = await db.addNotebook(TEST_NOTEBOOK);
- let res = await db.deleteNoteFromTopic(timestamp, "invalid_topic", noteId);
- expect(res).toBe(false);
- }));
-
-test("delete note from topic", () =>
- topicNoteTest().then(async ({ db, timestamp, topic, noteTimestamp }) => {
- let notebook = db.getNotebook(timestamp);
- expect(await db.deleteNoteFromTopic(timestamp, topic, noteTimestamp)).toBe(
- true
- );
- notebook = db.getNotebook(timestamp);
- let topicIndex = notebook.topics.findIndex(t => t.title === topic);
- expect(notebook.topics[topicIndex].notes[0]).toBeUndefined();
- }));
-
-test("delete topic from notebook", () =>
- topicTest().then(async ({ db, timestamp, topic }) => {
- await db.deleteTopicFromNotebook(timestamp, topic);
- let notebook = db.getNotebook(timestamp);
- let topicIndex = notebook.topics.findIndex(t => t.title === topic);
- expect(topicIndex).toBe(-1);
- }));
-
-test("delete note", () =>
- noteTest().then(async ({ db, timestamp }) => {
- expect(await db.deleteNotes(timestamp)).toBe(true);
- let note = db.getNote(timestamp);
- expect(note).toBeUndefined();
- }));
-
-test("deleting note that is in a notebook should delete it from the notebook", () =>
- topicNoteTest().then(async ({ db, timestamp, topic, noteTimestamp }) => {
- expect(await db.deleteNotes(noteTimestamp)).toBe(true);
- let notebook = db.getNotebook(timestamp);
- let topicIndex = notebook.topics.findIndex(t => t.title === topic);
- expect(notebook.topics[topicIndex].notes.includes(noteTimestamp)).toBe(
- false
- );
- }));
-
-test("delete notebook", () =>
- notebookTest().then(async ({ db, timestamp }) => {
- expect(await db.deleteNotebooks(timestamp)).toBe(true);
- let notebook = db.getNotebook(timestamp);
- expect(notebook).toBeUndefined();
- }));
-
-test("trash should not be empty", () =>
- notebookTest().then(async ({ db, timestamp }) => {
- expect(await db.deleteNotebooks(timestamp)).toBe(true);
- let trash = db.getTrash();
- expect(trash.length).toBeGreaterThan(0);
- }));
-
-test("restore an item from trash", () =>
- notebookTest().then(async ({ db, timestamp }) => {
- expect(await db.deleteNotebooks(timestamp)).toBe(true);
- let trash = db.getTrash();
- expect(trash.length).toBeGreaterThan(0);
- await db.restoreItem(timestamp);
- trash = db.getTrash();
- expect(trash.length).toBe(0);
- let notebook = db.getNotebook(timestamp);
- expect(notebook.dateCreated).toBe(timestamp);
- }));
-
-test("clear trash should clear the trash", () =>
- notebookTest().then(async ({ db, timestamp }) => {
- expect(await db.deleteNotebooks(timestamp)).toBe(true);
- let trash = db.getTrash();
- expect(trash.length).toBeGreaterThan(0);
- await db.clearTrash();
- trash = db.getTrash();
- expect(trash.length).toBe(0);
- }));
-
-//null & undefined checks
-
-test("empty note should not be added", () =>
- databaseTest().then(async db => {
- let res = await db.addNote({});
- expect(res).toBeUndefined();
- }));
-
-test("note with empty text should not be added", () =>
- databaseTest().then(async db => {
- let res = await db.addNote({ content: { text: "", delta: [] } });
- expect(res).toBeUndefined();
- }));
-
-test("note with invalid delta should not be added", () =>
- databaseTest().then(async db => {
- let res = await db.addNote({
- content: { text: "i am a valid text", delta: undefined }
- });
- expect(res).toBeUndefined();
- }));
-
-test("empty notebook should not be added", () =>
- databaseTest().then(async db => {
- let res = await db.addNotebook({});
- expect(res).toBeUndefined();
- }));
-
-test("deletion of invalid items should cause continue and return true", () =>
- databaseTest().then(async db => {
- let res = await db.deleteNotes(null, null, "something");
- expect(res).toBe(true);
- }));
-
-test("deletion of invalid topic from notebook should return false", () =>
- topicTest().then(async ({ db, timestamp }) => {
- let res = await db.deleteTopicFromNotebook(timestamp, "invalid_topic");
- expect(res).toBe(false);
- }));
-
-test("moving note with wrong id should throw", () =>
- databaseTest().then(async db => {
- db.moveNotes(undefined, undefined, 0).catch(err =>
- expect(err.message).toContain("Failed to move note.")
- );
- }));
-
-test("moving note to non-existent notebook should return false", () =>
- databaseTest().then(async db => {
- await db.moveNotes({ id: 2, topic: "2" }, { id: 5, topic: "123" }, 23);
- }));
-
-test("moving note to same notebook should throw", () =>
- databaseTest().then(async db => {
- db.moveNotes({ id: 2, topic: "2" }, { id: 2, topic: "2" }, 23).catch(err =>
- expect(err.message).toContain(
- "Moving to the same notebook and topic is not possible."
- )
- );
- }));
-
-test("search with empty query should return []", () =>
- databaseTest().then(async db => {
- let filtered = db.searchNotes("");
- expect(filtered).toStrictEqual([]);
- }));
-
-test("getting invalid topic from invalid notebook should return undefined", () =>
- databaseTest().then(async db => {
- let res = await db.getTopic(1213, "invalid_topic");
- expect(res).toBeUndefined();
- }));
-
-test("Operations on uninitialized database should throw", () => {
- let db = new Database(StorageInterface);
- expect(db.getNotes.bind(db)).toThrowError("Database is not initialized.");
-});
-
-test("edit item with wrong id should throw", () =>
- databaseTest().then(async db => {
- db.pinNotebook(1242141).catch(err => {
- expect(err.message).toContain("Wrong notebook id");
- });
- }));
-
-test("restoring an invalid item from trash should throw", () =>
- databaseTest().then(async db => {
- db.restoreItem(21412).catch(err =>
- expect(err.message).toContain("Cannot restore")
- );
- }));
-
-test("get grouped notes by abc", () => groupedTest("abc"));
-
-test("get grouped notes by abc (special)", () => groupedTest("abc", true));
-
-test("get grouped notes by month", () => groupedTest("month"));
-
-test("get grouped notes by month (special)", () => groupedTest("month", true));
-
-test("get grouped notes by year", () => groupedTest("year"));
-
-test("get grouped notes by year (special)", () => groupedTest("year", true));
-
-test("get grouped notes by weak", () => groupedTest("week"));
-
-test("get grouped notes by weak (special)", () => groupedTest("week", true));
-
-test("get grouped notes default", () => groupedTest());
-
-test("get grouped notes default (special)", () => groupedTest("", true));
-
-test("pin note", () =>
- noteTest().then(async ({ db, timestamp }) => {
- await db.pinNote(timestamp);
- expect(db.getNote(timestamp).pinned).toBe(true);
- }));
-
-test("pin notebook", () =>
- notebookTest().then(async ({ db, timestamp }) => {
- await db.pinNotebook(timestamp);
- expect(db.getNotebook(timestamp).pinned).toBe(true);
- }));
-
-test("favorite note", () =>
- noteTest().then(async ({ db, timestamp }) => {
- await db.favoriteNotes(timestamp);
- expect(db.getNote(timestamp).favorite).toBe(true);
- }));
-
-test("favorite notebook", () =>
- notebookTest().then(async ({ db, timestamp }) => {
- await db.favoriteNotebooks(timestamp);
- expect(db.getNotebook(timestamp).favorite).toBe(true);
- }));
-
-test("lock and unlock note", () =>
- noteTest().then(async ({ db, timestamp }) => {
- expect(await db.lockNote(timestamp, "password123")).toBe(true);
- let note = db.getNote(timestamp);
- expect(note.locked).toBe(true);
- expect(note.content.iv).toBeDefined();
- note = await db.unlockNote(timestamp, "password123");
- expect(note.dateCreated).toBe(timestamp);
- expect(note.content.text).toBe(TEST_NOTE.content.text);
- await db.unlockNote(timestamp, "password123", true);
- note = db.getNote(timestamp);
- expect(note.locked).toBe(false);
- }));
diff --git a/packages/core/api/database.js b/packages/core/api/database.js
deleted file mode 100644
index 255d08219..000000000
--- a/packages/core/api/database.js
+++ /dev/null
@@ -1,650 +0,0 @@
-import Storage from "../helpers/storage";
-import fuzzysearch from "fuzzysearch";
-var tfun = require("transfun/transfun.js").tfun;
-if (!tfun) {
- tfun = global.tfun;
-}
-import { extractValues, groupBy } from "../utils";
-import {
- getWeekGroupFromTimestamp,
- months,
- getLastWeekTimestamp
-} from "../utils/date";
-import setManipulator from "../utils/set";
-
-const KEYS = {
- notes: "notes",
- notebooks: "notebooks",
- trash: "trash",
- tags: "tags",
- user: "user"
-};
-
-const TYPES = {
- note: "note"
-};
-
-function checkInitialized() {
- if (!this.isInitialized) {
- throw new Error(
- "Database is not initialized. Make sure to call await init() on startup."
- );
- }
-}
-
-class Database {
- constructor(storage) {
- this.storage = new Storage(storage);
- this.notes = {};
- this.notebooks = {};
- this.trash = {};
- this.tags = {};
- this.user = {};
- this.isInitialized = false;
- }
-
- init() {
- return new Promise((resolve, reject) => {
- for (let key of extractValues(KEYS)) {
- this.storage.read(key).then(data => {
- this[key] = data || {};
- if (key === KEYS.user) {
- this.isInitialized = true;
- //TODO use index here
- resolve(true);
- }
- });
- }
- });
- }
-
- getNotes() {
- checkInitialized.call(this);
- return extractValues(this.notes).reverse();
- }
-
- getFavorites() {
- return tfun.filter(".favorite === true")([
- ...this.getNotes(),
- ...this.getNotebooks()
- ]);
- }
-
- getPinned() {
- return tfun.filter(".pinned === true")(this.getNotes());
- }
-
- getTag(tag) {
- return tfun.filter(`.tags.includes('${tag}')`)(this.getNotes());
- }
-
- /**
- * @param {string} by One from 'abc', 'month', 'year' or 'week'. Leave it empty for default grouping.
- * @param {boolean} special Should only be used in the React app.
- */
- groupNotes(by, special = false) {
- let notes = !special
- ? tfun.filter(".pinned === false")(this.getNotes())
- : this.getNotes();
- switch (by) {
- case "abc":
- return groupBy(
- notes.sort((a, b) => a.title.localeCompare(b.title)),
- note => note.title[0].toUpperCase(),
- special
- );
- case "month":
- return groupBy(
- notes,
- note => months[new Date(note.dateCreated).getMonth()],
- special
- );
- case "week":
- return groupBy(
- notes,
- note => getWeekGroupFromTimestamp(note.dateCreated),
- special
- );
- case "year":
- return groupBy(
- notes,
- note => new Date(note.dateCreated).getFullYear().toString(),
- special
- );
- default:
- let timestamps = {
- recent: getLastWeekTimestamp(7),
- lastWeek: getLastWeekTimestamp(7) - 604800000 //seven day timestamp value
- };
- return groupBy(
- notes,
- note =>
- note.dateCreated >= timestamps.recent
- ? "Recent"
- : note.dateCreated >= timestamps.lastWeek
- ? "Last week"
- : "Older",
- special
- );
- }
- }
-
- async addNote(n) {
- if (!n) return;
-
- let timestamp = n.dateCreated || Date.now();
- let oldNote = this.notes[timestamp];
- let note = {
- ...oldNote,
- ...n
- };
-
- if (isNoteEmpty(note)) {
- if (oldNote) await this.deleteNotes(note);
- return;
- }
-
- note = {
- type: TYPES.note,
- title: getNoteTitle(note),
- content: getNoteContent(note),
- pinned: !!note.pinned,
- locked: !!note.locked,
- notebook: note.notebook || {},
- colors: note.colors || [],
- tags: note.tags || [],
- favorite: !!note.favorite,
- headline: getNoteHeadline(note),
- dateEditted: Date.now(),
- dateCreated: timestamp
- };
-
- if (oldNote) {
- note.colors = setManipulator.union(oldNote.colors, note.colors);
- } else {
- await addTags.call(this, note.tags);
- }
-
- this.notes[timestamp] = note;
- await this.storage.write(KEYS.notes, this.notes);
- return timestamp;
- }
-
- async addTag(noteId, tag) {
- if (!this.notes[noteId])
- throw new Error("Couldn't add tag. This note doesn't exist.");
- this.notes[noteId].tags.push(tag);
- await addTags.call(this, [tag]);
- await this.storage.write(KEYS.notes, this.notes);
- }
-
- async removeTag(noteId, tag) {
- if (!this.notes[noteId])
- throw new Error("Couldn't remove tag. This note doesn't exist.");
- let tags = this.notes[noteId].tags;
- if (tags.indexOf(tag) <= -1)
- throw new Error("This note is not tagged by the specified tag.");
- this.notes[noteId].tags.splice(tags.indexOf(tag), 1);
- await removeTags.call(this, [tag]);
- await this.storage.write(KEYS.notes, this.notes);
- }
-
- pinNote(id) {
- return editItems.call(this, "note", "pinned", id);
- }
-
- favoriteNotes(...ids) {
- return editItems.call(this, "note", "favorite", ids);
- }
-
- async deleteNotes(...noteIds) {
- return await deleteItems.call(this, noteIds, KEYS.notes);
- }
-
- getNote(id) {
- return getItem.call(this, id, KEYS.notes);
- }
-
- searchNotes(query, notes = null) {
- if (!query) return [];
- if (!notes) notes = this.getNotes();
- return tfun.filter(v => fuzzysearch(query, v.title + " " + v.content.text))(
- notes
- );
- }
-
- async lockNote(noteId, password) {
- if (!this.notes[noteId]) {
- throw new Error(`Cannot lock note. Invalid ID: ${noteId} given.`);
- }
-
- this.notes[noteId].content = await this.storage.encrypt(
- password,
- JSON.stringify(this.notes[noteId].content)
- );
- this.notes[noteId].locked = true;
- await this.storage.write(KEYS.notes, this.notes);
- return true;
- }
-
- async unlockNote(noteId, password, perm = false) {
- if (!this.notes[noteId]) {
- throw new Error(`Cannot unlock note. Invalid ID: ${noteId} given.`);
- }
- let decrypted = await this.storage.decrypt(
- password,
- this.notes[noteId].content
- );
- if (perm) {
- this.notes[noteId].locked = false;
- this.notes[noteId].content = JSON.parse(decrypted);
- await this.storage.write(KEYS.notes, this.notes);
- }
- return { ...this.notes[noteId], content: JSON.parse(decrypted) };
- }
-
- getNotebooks() {
- checkInitialized.call(this);
- return extractValues(this.notebooks);
- }
-
- searchNotebooks(query) {
- if (!query) return [];
- return tfun.filter(v => fuzzysearch(query, v.title + " " + v.description))(
- this.getNotebooks()
- );
- }
-
- async addNotebook(notebook) {
- if (!notebook || !notebook.title) {
- return;
- }
- if (
- extractValues(this.notebooks).findIndex(
- nb =>
- nb.title === notebook.title && nb.dateCreated !== notebook.dateCreated
- ) > -1
- ) {
- return;
- }
-
- const id = notebook.dateCreated || Date.now();
- let topics =
- !notebook.topics || notebook.topics.length <= 0 ? [] : notebook.topics; //
- if (topics.findIndex(topic => topic.title === "General") <= -1) {
- topics.splice(0, 0, makeTopic("General", id));
- }
- let index = 0;
-
- for (let topic of topics) {
- if (
- !topic ||
- topics.findIndex(t => t.title === (topic || topic.title)) > -1 //check for duplicate
- ) {
- topics.splice(index, 1);
- continue;
- }
- if (typeof topic === "string") {
- if (topic.trim().length <= 0) topics.splice(index, 1);
- topics[index] = makeTopic(topic, id);
- }
- index++;
- }
-
- this.notebooks[id] = {
- type: "notebook",
- title: notebook.title,
- description: notebook.description,
- dateCreated: id,
- pinned: notebook.pinned || false,
- favorite: notebook.favorite || false,
- topics,
- totalNotes: 0,
- tags: [],
- colors: []
- };
- await this.storage.write(KEYS.notebooks, this.notebooks);
- return id;
- }
-
- pinNotebook(id) {
- return editItems.call(this, "notebook", "pinned", id);
- }
-
- favoriteNotebooks(...ids) {
- return editItems.call(this, "notebook", "favorite", ids);
- }
-
- addTopicToNotebook(notebookId, topic) {
- return notebookTopicFn.call(this, notebookId, topic, notebook => {
- if (notebook.topics.findIndex(t => t.title === topic) > -1)
- return Promise.resolve(false); //check for duplicates
- notebook.topics[notebook.topics.length] = makeTopic(topic, notebookId);
- return Promise.resolve(true);
- });
- }
-
- deleteTopicFromNotebook(notebookId, topic) {
- return notebookTopicFn.call(this, notebookId, topic, notebook => {
- let topicIndex = notebook.topics.findIndex(t => t.title === topic);
- if (topicIndex === -1) return Promise.resolve(false);
- notebook.topics.splice(topicIndex, 1);
- return Promise.resolve(true);
- });
- }
-
- addNoteToTopic(notebookId, topic, noteId) {
- return topicNoteFn.call(
- this,
- notebookId,
- topic,
- noteId,
- (notebook, topicIndex) => {
- if (notebook.topics[topicIndex].notes.includes(noteId)) {
- return Promise.resolve(false); //duplicate check
- }
- notebook.topics[topicIndex].notes.push(noteId);
- //increment totalNotes count
- notebook.topics[topicIndex].totalNotes++;
- notebook.totalNotes++;
- //add notebook to the note
- this.notes[noteId].notebook = {
- id: notebookId,
- topic: notebook.topics[topicIndex].title
- };
- return Promise.resolve(true);
- }
- );
- }
-
- deleteNoteFromTopic(notebookId, topic, noteId) {
- return topicNoteFn.call(
- this,
- notebookId,
- topic,
- noteId,
- (notebook, topicIndex) => {
- let index = notebook.topics[topicIndex].notes.indexOf(noteId);
- if (index <= -1) return Promise.resolve(false);
- notebook.topics[topicIndex].notes.splice(index, 1);
- //delete notebook from note
- this.notes[noteId].notebook = {};
- //decrement totalNotes count
- if (notebook.topics[topicIndex].totalNotes > 0)
- notebook.topics[topicIndex].totalNotes--;
- if (notebook.totalNotes > 0) notebook.totalNotes--;
- return Promise.resolve(true);
- }
- );
- }
-
- getTopic(notebookId, topic) {
- if (!notebookId || !topic || !this.notebooks[notebookId]) return;
- let notebook = this.notebooks[notebookId];
- let topicIndex = notebook.topics.findIndex(t => t.title === topic);
- if (topicIndex === -1) return;
- let nbTopic = notebook.topics[topicIndex];
- if (nbTopic.notes.length <= 0) return [];
- return nbTopic.notes.map(note => this.getNote(note));
- }
-
- getNotebook(id) {
- return getItem.call(this, id, KEYS.notebooks);
- }
-
- async deleteNotebooks(...notebookIds) {
- return await deleteItems.call(this, notebookIds, KEYS.notebooks);
- }
-
- async moveNotes(from, to, ...noteIds) {
- for (let noteId of noteIds) {
- if (!noteId || !to || !to.id || !to.topic) {
- throw new Error(`Error: Failed to move note.`);
- }
- if (!from.id && !from.topic) {
- await this.addNoteToTopic(to.id, to.topic, noteId);
- } else {
- if (from.id === to.id && from.topic === to.topic) {
- throw new Error(
- "Moving to the same notebook and topic is not possible."
- );
- }
-
- if (await this.deleteNoteFromTopic(from.id, from.topic, noteId)) {
- await this.addNoteToTopic(to.id, to.topic, noteId);
- }
- }
- }
- }
-
- async restoreItem(id) {
- if (!this.trash.hasOwnProperty(id)) {
- throw new Error("Cannot restore: This item is not present in trash.");
- }
- let type = this.trash[id].dType;
- delete this.trash[id].dateDeleted;
- delete this.trash[id].dType;
- let item = this.trash[id];
- this[type][id] = item;
- delete this.trash[id];
- await this.storage.write(KEYS.trash, this.trash);
- await this.storage.write(type, this[type]);
- }
-
- getTrash() {
- checkInitialized.call(this);
- return extractValues(this.trash).reverse();
- }
-
- async clearTrash() {
- this[KEYS.trash] = {};
- await this.storage.write(KEYS.trash, this[KEYS.trash]);
- }
-
- async createUser(user) {
- this.user = { ...this.user, ...user };
- await this.storage.write(KEYS.user, user);
- }
- getUser() {
- return this.user;
- }
-
- getTags() {
- return extractValues(this.tags);
- }
-}
-
-export default Database;
-
-async function deleteItems(ids, key) {
- if (!ids || ids.length <= 0 || !this[key] || this[key].length <= 0) {
- return false;
- }
- for (let id of ids) {
- let item = key === KEYS.notes ? this.getNote(id) : this.getNotebook(id);
- if (!id || !item) continue;
-
- //delete note from the notebook too.
- switch (item.type) {
- case "note":
- if (
- item.notebook.hasOwnProperty("topic") &&
- !(await this.deleteNoteFromTopic(
- item.notebook.id,
- item.notebook.topic,
- item.dateCreated
- ))
- ) {
- continue;
- }
- for (let tag of item.tags) {
- this.tags[tag] = {
- ...this.tags[tag],
- count: this.tags[tag].count - 1
- };
- }
- break;
- case "notebook":
- let skip = false;
- for (let topic in item.topics) {
- for (let note in topic.notes) {
- if (
- !(await this.deleteNoteFromTopic(item.dateCreated, topic, note))
- ) {
- skip = true;
- break;
- }
- }
- }
- if (skip) continue;
- break;
- }
-
- //put into trash
- this[KEYS.trash][item.dateCreated] = this[key][item.dateCreated];
- this[KEYS.trash][item.dateCreated]["dateDeleted"] = Date.now();
- this[KEYS.trash][item.dateCreated]["dType"] = key;
-
- delete this[key][item.dateCreated];
- }
-
- return this.storage
- .write(key, this[key])
- .then(s =>
- this.storage.write(KEYS.trash, this[KEYS.trash]).then(s => true)
- );
-}
-
-function notebookTopicFn(notebookId, topic, fn) {
- if (!notebookId || !topic || !this.notebooks[notebookId])
- return Promise.resolve(false);
- const notebook = this.notebooks[notebookId];
-
- return fn(notebook).then(res => {
- if (res === true) {
- this.notebooks[notebookId] = notebook;
- return this.storage.write(KEYS.notebooks, this.notebooks).then(s => true);
- }
- return false;
- });
-}
-
-function topicNoteFn(notebookId, topic, noteId, fn) {
- return notebookTopicFn.call(this, notebookId, topic, notebook => {
- let topicIndex = notebook.topics.findIndex(t => t.title === topic);
- if (topicIndex === -1 || !this.notes.hasOwnProperty(noteId))
- return Promise.resolve(false);
-
- return fn(notebook, topicIndex).then(async res => {
- if (res) {
- return await this.storage.write(KEYS.notes, this.notes).then(s => true);
- } else {
- return Promise.resolve(false);
- }
- });
- });
-}
-
-function getItem(id, key) {
- checkInitialized.call(this);
- if (this[key].hasOwnProperty(id)) {
- return this[key][id];
- }
-}
-
-function makeTopic(topic, notebookId) {
- return {
- type: "topic",
- notebookId,
- title: topic,
- dateCreated: Date.now(),
- totalNotes: 0,
- notes: []
- };
-}
-
-async function editItems(type, prop, ...ids) {
- if (type === "note" || type === "notebook") {
- for (let id of ids) {
- let col = type == "note" ? this.notes : this.notebooks;
- let func = type == "note" ? this.addNote : this.addNotebook;
- if (col[id] === undefined) {
- throw new Error(`Wrong ${type} id.`);
- }
- let state = col[id][prop];
- let edit = { [prop]: !state };
- await func.call(this, { ...col[id], ...edit });
- }
- } else {
- throw new Error("Invalid type given to pinItem");
- }
-}
-
-function mergeDedupe(arr) {
- return [...new Set([].concat(...arr))];
-}
-
-function isNoteEmpty(note) {
- return (
- !note.content ||
- !note.content.delta ||
- (!note.locked &&
- (!note.title || note.title.trim().length <= 0) &&
- (!note.content.text || note.content.text.trim().length <= 0))
- );
-}
-
-function getNoteHeadline(note) {
- if (note.locked) return "";
- return (
- note.content.text.substring(0, 150) +
- (note.content.text.length > 150 ? "..." : "")
- );
-}
-
-function getNoteTitle(note) {
- if (note.title && note.title.length > 0) return note.title.trim();
- return note.content.text
- .split(" ")
- .slice(0, 3)
- .join(" ")
- .trim();
-}
-
-function getNoteContent(note) {
- if (note.locked) {
- return note.content;
- }
- return {
- text: note.content.text.trim(),
- delta: note.content.delta
- };
-}
-
-async function addTags(tags) {
- for (let tag of tags) {
- if (!tag || tag.trim().length <= 0) continue;
- let oldCount = this.tags[tag] ? this.tags[tag].count : 0;
- this.tags[tag] = {
- title: tag,
- count: oldCount + 1
- };
- }
- await this.storage.write(KEYS.tags, this.tags);
-}
-
-async function removeTags(tags) {
- for (let tag of tags) {
- if (!tag || tag.trim().length <= 0 || !this.tags[tag]) continue;
- let oldCount = this.tags[tag].count;
- if (oldCount <= 1) {
- delete this.tags[tag];
- } else {
- this.tags[tag] = {
- title: tag,
- count: oldCount - 1
- };
- }
- }
- await this.storage.write(KEYS.tags, this.tags);
-}