2021-01-22 19:41:11 +02:00
|
|
|
import BaseModel, { ModelType } from '../BaseModel';
|
|
|
|
import BaseItem from './BaseItem';
|
|
|
|
import ItemChange from './ItemChange';
|
|
|
|
import Setting from './Setting';
|
|
|
|
import shim from '../shim';
|
|
|
|
import time from '../time';
|
|
|
|
import markdownUtils from '../markdownUtils';
|
|
|
|
import { NoteEntity } from '../services/database/types';
|
2021-04-24 10:16:36 +02:00
|
|
|
import Tag from './Tag';
|
2021-01-22 19:41:11 +02:00
|
|
|
|
2018-03-09 22:59:12 +02:00
|
|
|
const { sprintf } = require('sprintf-js');
|
2021-01-23 17:51:19 +02:00
|
|
|
import Resource from './Resource';
|
2021-10-15 13:24:22 +02:00
|
|
|
import syncDebugLog from '../services/synchronizer/syncDebugLog';
|
2021-10-03 19:41:32 +02:00
|
|
|
const { pregQuote, substrWithEllipsis } = require('../string-utils.js');
|
2020-11-05 18:58:23 +02:00
|
|
|
const { _ } = require('../locale');
|
|
|
|
const ArrayUtils = require('../ArrayUtils.js');
|
2018-03-09 22:59:12 +02:00
|
|
|
const lodash = require('lodash');
|
2020-11-05 18:58:23 +02:00
|
|
|
const urlUtils = require('../urlUtils.js');
|
2020-11-14 12:59:26 +02:00
|
|
|
const { isImageMimeType } = require('../resourceUtils');
|
2020-11-07 17:59:37 +02:00
|
|
|
const { MarkupToHtml } = require('@joplin/renderer');
|
2020-11-05 18:58:23 +02:00
|
|
|
const { ALL_NOTES_FILTER_ID } = require('../reserved-ids');
|
2017-05-10 21:21:09 +02:00
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
export default class Note extends BaseItem {
|
|
|
|
|
|
|
|
public static updateGeolocationEnabled_ = true;
|
|
|
|
private static geolocationUpdating_ = false;
|
|
|
|
private static geolocationCache_: any;
|
|
|
|
private static dueDateObjects_: any;
|
|
|
|
|
2017-05-10 21:51:43 +02:00
|
|
|
static tableName() {
|
2018-03-09 22:59:12 +02:00
|
|
|
return 'notes';
|
2017-05-10 21:51:43 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static fieldToLabel(field: string) {
|
|
|
|
const fieldsToLabels: Record<string, string> = {
|
2018-05-30 19:22:07 +02:00
|
|
|
title: _('title'),
|
|
|
|
user_updated_time: _('updated date'),
|
|
|
|
user_created_time: _('created date'),
|
2020-05-27 18:21:46 +02:00
|
|
|
order: _('custom order'),
|
2018-02-22 20:58:15 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
return field in fieldsToLabels ? fieldsToLabels[field] : field;
|
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async serializeForEdit(note: NoteEntity) {
|
2019-01-20 18:27:33 +02:00
|
|
|
return this.replaceResourceInternalToExternalLinks(await super.serialize(note, ['title', 'body']));
|
2017-07-04 21:12:30 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async unserializeForEdit(content: string) {
|
2019-09-19 23:51:18 +02:00
|
|
|
content += `\n\ntype_: ${BaseModel.TYPE_NOTE}`;
|
2020-03-14 01:46:14 +02:00
|
|
|
const output = await super.unserialize(content);
|
2018-03-09 22:59:12 +02:00
|
|
|
if (!output.title) output.title = '';
|
|
|
|
if (!output.body) output.body = '';
|
2019-01-20 18:27:33 +02:00
|
|
|
output.body = await this.replaceResourceExternalToInternalLinks(output.body);
|
2017-07-13 23:26:45 +02:00
|
|
|
return output;
|
2017-07-05 20:31:11 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async serializeAllProps(note: NoteEntity) {
|
2020-03-14 01:46:14 +02:00
|
|
|
const fieldNames = this.fieldNames();
|
2018-03-09 22:59:12 +02:00
|
|
|
fieldNames.push('type_');
|
|
|
|
lodash.pull(fieldNames, 'title', 'body');
|
2018-10-07 21:11:33 +02:00
|
|
|
return super.serialize(note, fieldNames);
|
2017-07-13 20:47:31 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static minimalSerializeForDisplay(note: NoteEntity) {
|
2020-03-14 01:46:14 +02:00
|
|
|
const n = Object.assign({}, note);
|
2017-10-24 22:35:02 +02:00
|
|
|
|
2020-03-14 01:46:14 +02:00
|
|
|
const fieldNames = this.fieldNames();
|
2017-10-24 22:35:02 +02:00
|
|
|
|
2018-03-09 22:59:12 +02:00
|
|
|
if (!n.is_conflict) lodash.pull(fieldNames, 'is_conflict');
|
|
|
|
if (!Number(n.latitude)) lodash.pull(fieldNames, 'latitude');
|
|
|
|
if (!Number(n.longitude)) lodash.pull(fieldNames, 'longitude');
|
|
|
|
if (!Number(n.altitude)) lodash.pull(fieldNames, 'altitude');
|
|
|
|
if (!n.author) lodash.pull(fieldNames, 'author');
|
|
|
|
if (!n.source_url) lodash.pull(fieldNames, 'source_url');
|
2017-10-24 22:35:02 +02:00
|
|
|
if (!n.is_todo) {
|
2018-03-09 22:59:12 +02:00
|
|
|
lodash.pull(fieldNames, 'is_todo');
|
|
|
|
lodash.pull(fieldNames, 'todo_due');
|
|
|
|
lodash.pull(fieldNames, 'todo_completed');
|
2017-10-24 22:35:02 +02:00
|
|
|
}
|
2018-03-09 22:59:12 +02:00
|
|
|
if (!n.application_data) lodash.pull(fieldNames, 'application_data');
|
2017-10-24 22:35:02 +02:00
|
|
|
|
2018-03-09 22:59:12 +02:00
|
|
|
lodash.pull(fieldNames, 'type_');
|
|
|
|
lodash.pull(fieldNames, 'title');
|
|
|
|
lodash.pull(fieldNames, 'body');
|
|
|
|
lodash.pull(fieldNames, 'created_time');
|
|
|
|
lodash.pull(fieldNames, 'updated_time');
|
|
|
|
lodash.pull(fieldNames, 'order');
|
2017-10-24 22:35:02 +02:00
|
|
|
|
2018-10-07 21:11:33 +02:00
|
|
|
return super.serialize(n, fieldNames);
|
2017-10-24 22:35:02 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static defaultTitle(noteBody: string) {
|
2020-05-02 17:41:07 +02:00
|
|
|
return this.defaultTitleFromBody(noteBody);
|
2018-10-24 20:10:05 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static defaultTitleFromBody(body: string) {
|
2020-05-09 16:55:00 +02:00
|
|
|
return markdownUtils.titleFromBody(body);
|
2017-08-21 22:46:31 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static geolocationUrl(note: NoteEntity) {
|
2018-03-09 22:59:12 +02:00
|
|
|
if (!('latitude' in note) || !('longitude' in note)) throw new Error('Latitude or longitude is missing');
|
|
|
|
if (!Number(note.latitude) && !Number(note.longitude)) throw new Error(_('This note does not have geolocation information.'));
|
2018-09-16 20:37:31 +02:00
|
|
|
return this.geoLocationUrlFromLatLong(note.latitude, note.longitude);
|
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static geoLocationUrlFromLatLong(lat: number, long: number) {
|
2019-07-29 15:43:53 +02:00
|
|
|
return sprintf('https://www.openstreetmap.org/?lat=%s&lon=%s&zoom=20', lat, long);
|
2017-07-18 21:27:10 +02:00
|
|
|
}
|
|
|
|
|
2017-07-03 21:50:45 +02:00
|
|
|
static modelType() {
|
|
|
|
return BaseModel.TYPE_NOTE;
|
2017-05-18 21:58:01 +02:00
|
|
|
}
|
|
|
|
|
2021-05-13 18:57:37 +02:00
|
|
|
public static linkedItemIds(body: string): string[] {
|
2017-08-20 16:29:18 +02:00
|
|
|
if (!body || body.length <= 32) return [];
|
2018-11-21 01:18:56 +02:00
|
|
|
|
2019-09-12 23:48:10 +02:00
|
|
|
const links = urlUtils.extractResourceUrls(body);
|
2021-01-22 19:41:11 +02:00
|
|
|
const itemIds = links.map((l: any) => l.itemId);
|
2019-09-12 23:48:10 +02:00
|
|
|
return ArrayUtils.unique(itemIds);
|
2017-08-20 16:29:18 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async linkedItems(body: string) {
|
2018-05-03 14:11:45 +02:00
|
|
|
const itemIds = this.linkedItemIds(body);
|
2019-07-17 23:50:12 +02:00
|
|
|
const r = await BaseItem.loadItemsByIds(itemIds);
|
|
|
|
return r;
|
2018-05-03 14:11:45 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async linkedItemIdsByType(type: ModelType, body: string) {
|
2018-05-03 14:11:45 +02:00
|
|
|
const items = await this.linkedItems(body);
|
2021-06-15 18:17:12 +02:00
|
|
|
const output: string[] = [];
|
2018-05-03 14:11:45 +02:00
|
|
|
|
|
|
|
for (let i = 0; i < items.length; i++) {
|
|
|
|
const item = items[i];
|
|
|
|
if (item.type_ === type) output.push(item.id);
|
|
|
|
}
|
|
|
|
|
|
|
|
return output;
|
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async linkedResourceIds(body: string) {
|
2019-07-21 01:18:51 +02:00
|
|
|
return this.linkedItemIdsByType(BaseModel.TYPE_RESOURCE, body);
|
2018-05-03 14:11:45 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async linkedNoteIds(body: string) {
|
2020-01-18 15:16:14 +02:00
|
|
|
return this.linkedItemIdsByType(BaseModel.TYPE_NOTE, body);
|
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async replaceResourceInternalToExternalLinks(body: string, options: any = null) {
|
2020-03-10 01:24:57 +02:00
|
|
|
options = Object.assign({}, {
|
|
|
|
useAbsolutePaths: false,
|
|
|
|
}, options);
|
|
|
|
|
2021-01-02 15:32:15 +02:00
|
|
|
// this.logger().debug('replaceResourceInternalToExternalLinks', 'options:', options, 'body:', body);
|
2020-04-12 11:09:24 +02:00
|
|
|
|
2019-01-20 18:27:33 +02:00
|
|
|
const resourceIds = await this.linkedResourceIds(body);
|
|
|
|
const Resource = this.getClass('Resource');
|
|
|
|
|
|
|
|
for (let i = 0; i < resourceIds.length; i++) {
|
|
|
|
const id = resourceIds[i];
|
|
|
|
const resource = await Resource.load(id);
|
2019-01-20 18:28:10 +02:00
|
|
|
if (!resource) continue;
|
2020-11-14 12:59:26 +02:00
|
|
|
|
|
|
|
const isImage = isImageMimeType(resource.mime);
|
|
|
|
|
|
|
|
// We add a timestamp parameter for images, so that when they
|
|
|
|
// change, the preview is updated inside the note. This is not
|
|
|
|
// needed for other resources since they are simple links.
|
|
|
|
const timestampParam = isImage ? `?t=${resource.updated_time}` : '';
|
|
|
|
const resourcePath = options.useAbsolutePaths ? `file://${Resource.fullPath(resource)}${timestampParam}` : Resource.relativePath(resource);
|
2020-05-25 10:52:10 +02:00
|
|
|
body = body.replace(new RegExp(`:/${id}`, 'gi'), markdownUtils.escapeLinkUrl(resourcePath));
|
2019-01-20 18:27:33 +02:00
|
|
|
}
|
|
|
|
|
2021-01-02 15:32:15 +02:00
|
|
|
// this.logger().debug('replaceResourceInternalToExternalLinks result', body);
|
2020-04-14 00:55:24 +02:00
|
|
|
|
2019-01-20 18:27:33 +02:00
|
|
|
return body;
|
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async replaceResourceExternalToInternalLinks(body: string, options: any = null) {
|
2020-03-10 01:24:57 +02:00
|
|
|
options = Object.assign({}, {
|
|
|
|
useAbsolutePaths: false,
|
|
|
|
}, options);
|
|
|
|
|
2020-12-09 14:50:51 +02:00
|
|
|
let pathsToTry = [];
|
2020-03-10 01:24:57 +02:00
|
|
|
if (options.useAbsolutePaths) {
|
2020-04-14 00:55:24 +02:00
|
|
|
pathsToTry.push(`file://${Setting.value('resourceDir')}`);
|
|
|
|
pathsToTry.push(`file://${shim.pathRelativeToCwd(Setting.value('resourceDir'))}`);
|
2020-03-10 01:24:57 +02:00
|
|
|
} else {
|
|
|
|
pathsToTry.push(Resource.baseRelativeDirectoryPath());
|
|
|
|
}
|
|
|
|
|
2020-12-09 14:50:51 +02:00
|
|
|
// We support both the escaped and unescaped versions because both
|
|
|
|
// of those paths are valid:
|
|
|
|
//
|
|
|
|
// [](file://C:/I like spaces in paths/abcdefg.jpg)
|
|
|
|
// [](file://C:/I%20like%20spaces%20in%20paths/abcdefg.jpg)
|
|
|
|
//
|
|
|
|
// https://discourse.joplinapp.org/t/12986/4
|
|
|
|
const temp = [];
|
|
|
|
for (const p of pathsToTry) {
|
|
|
|
temp.push(p);
|
|
|
|
temp.push(markdownUtils.escapeLinkUrl(p));
|
|
|
|
}
|
|
|
|
|
|
|
|
pathsToTry = temp;
|
|
|
|
|
2021-01-02 15:32:15 +02:00
|
|
|
// this.logger().debug('replaceResourceExternalToInternalLinks', 'options:', options, 'pathsToTry:', pathsToTry);
|
2020-04-12 11:09:24 +02:00
|
|
|
|
2020-03-10 01:24:57 +02:00
|
|
|
for (const basePath of pathsToTry) {
|
2020-05-30 16:28:42 +02:00
|
|
|
const reStrings = [
|
|
|
|
// Handles file://path/to/abcdefg.jpg?t=12345678
|
2021-06-08 20:37:44 +02:00
|
|
|
`${pregQuote(`${basePath}/`)}[a-zA-Z0-9]{32}\\.[a-zA-Z0-9]+\\?t=[0-9]+`,
|
2020-05-30 16:28:42 +02:00
|
|
|
// Handles file://path/to/abcdefg.jpg
|
2021-06-08 20:37:44 +02:00
|
|
|
`${pregQuote(`${basePath}/`)}[a-zA-Z0-9]{32}\\.[a-zA-Z0-9]+`,
|
2020-05-30 16:28:42 +02:00
|
|
|
];
|
|
|
|
for (const reString of reStrings) {
|
|
|
|
const re = new RegExp(reString, 'gi');
|
|
|
|
body = body.replace(re, match => {
|
|
|
|
const id = Resource.pathToId(match);
|
|
|
|
return `:/${id}`;
|
|
|
|
});
|
|
|
|
}
|
2020-07-23 21:38:42 +02:00
|
|
|
|
|
|
|
// Handles joplin://af0edffa4a60496bba1b0ba06b8fb39a
|
|
|
|
body = body.replace(/\(joplin:\/\/([a-zA-Z0-9]{32})\)/g, '(:/$1)');
|
2020-03-10 01:24:57 +02:00
|
|
|
}
|
|
|
|
|
2020-11-30 20:37:58 +02:00
|
|
|
// this.logger().debug('replaceResourceExternalToInternalLinks result', body);
|
2020-04-14 00:55:24 +02:00
|
|
|
|
2019-01-20 18:27:33 +02:00
|
|
|
return body;
|
|
|
|
}
|
|
|
|
|
2018-03-09 22:59:12 +02:00
|
|
|
static new(parentId = '') {
|
2020-03-14 01:46:14 +02:00
|
|
|
const output = super.new();
|
2017-05-20 00:16:50 +02:00
|
|
|
output.parent_id = parentId;
|
|
|
|
return output;
|
2017-05-10 21:51:43 +02:00
|
|
|
}
|
|
|
|
|
2018-03-09 22:59:12 +02:00
|
|
|
static newTodo(parentId = '') {
|
2020-03-14 01:46:14 +02:00
|
|
|
const output = this.new(parentId);
|
2017-05-24 22:51:50 +02:00
|
|
|
output.is_todo = true;
|
|
|
|
return output;
|
|
|
|
}
|
|
|
|
|
2017-10-20 00:02:13 +02:00
|
|
|
// Note: sort logic must be duplicated in previews();
|
2021-01-22 19:41:11 +02:00
|
|
|
static sortNotes(notes: NoteEntity[], orders: any[], uncompletedTodosOnTop: boolean) {
|
|
|
|
const noteOnTop = (note: NoteEntity) => {
|
2017-07-27 19:25:42 +02:00
|
|
|
return uncompletedTodosOnTop && note.is_todo && !note.todo_completed;
|
2019-07-29 15:43:53 +02:00
|
|
|
};
|
2017-07-27 19:25:42 +02:00
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
const noteFieldComp = (f1: any, f2: any) => {
|
2017-10-20 00:02:13 +02:00
|
|
|
if (f1 === f2) return 0;
|
|
|
|
return f1 < f2 ? -1 : +1;
|
2019-07-29 15:43:53 +02:00
|
|
|
};
|
2017-10-20 00:02:13 +02:00
|
|
|
|
|
|
|
// Makes the sort deterministic, so that if, for example, a and b have the
|
|
|
|
// same updated_time, they aren't swapped every time a list is refreshed.
|
2021-01-22 19:41:11 +02:00
|
|
|
const sortIdenticalNotes = (a: NoteEntity, b: NoteEntity) => {
|
2017-10-20 00:02:13 +02:00
|
|
|
let r = null;
|
2019-07-29 15:43:53 +02:00
|
|
|
r = noteFieldComp(a.user_updated_time, b.user_updated_time);
|
|
|
|
if (r) return r;
|
|
|
|
r = noteFieldComp(a.user_created_time, b.user_created_time);
|
|
|
|
if (r) return r;
|
2017-12-05 01:38:09 +02:00
|
|
|
|
2018-03-09 22:59:12 +02:00
|
|
|
const titleA = a.title ? a.title.toLowerCase() : '';
|
|
|
|
const titleB = b.title ? b.title.toLowerCase() : '';
|
2019-07-29 15:43:53 +02:00
|
|
|
r = noteFieldComp(titleA, titleB);
|
|
|
|
if (r) return r;
|
2018-05-30 19:22:07 +02:00
|
|
|
|
2017-10-20 00:02:13 +02:00
|
|
|
return noteFieldComp(a.id, b.id);
|
2019-07-29 15:43:53 +02:00
|
|
|
};
|
2017-10-20 00:02:13 +02:00
|
|
|
|
2021-01-07 18:29:53 +02:00
|
|
|
const collator = this.getNaturalSortingCollator();
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
return notes.sort((a: NoteEntity, b: NoteEntity) => {
|
2017-07-27 19:25:42 +02:00
|
|
|
if (noteOnTop(a) && !noteOnTop(b)) return -1;
|
|
|
|
if (!noteOnTop(a) && noteOnTop(b)) return +1;
|
|
|
|
|
|
|
|
let r = 0;
|
|
|
|
|
|
|
|
for (let i = 0; i < orders.length; i++) {
|
|
|
|
const order = orders[i];
|
2021-01-22 19:41:11 +02:00
|
|
|
let aProp = (a as any)[order.by];
|
|
|
|
let bProp = (b as any)[order.by];
|
2019-07-21 14:55:25 +02:00
|
|
|
if (typeof aProp === 'string') aProp = aProp.toLowerCase();
|
|
|
|
if (typeof bProp === 'string') bProp = bProp.toLowerCase();
|
2021-01-07 18:29:53 +02:00
|
|
|
|
|
|
|
if (order.by === 'title') {
|
|
|
|
r = -1 * collator.compare(aProp, bProp);
|
|
|
|
} else {
|
|
|
|
if (aProp < bProp) r = +1;
|
|
|
|
if (aProp > bProp) r = -1;
|
|
|
|
}
|
2018-03-09 22:59:12 +02:00
|
|
|
if (order.dir == 'ASC') r = -r;
|
2017-10-20 00:02:13 +02:00
|
|
|
if (r !== 0) return r;
|
2017-07-27 19:25:42 +02:00
|
|
|
}
|
|
|
|
|
2017-10-20 00:02:13 +02:00
|
|
|
return sortIdenticalNotes(a, b);
|
2017-07-27 19:25:42 +02:00
|
|
|
});
|
|
|
|
}
|
2017-07-15 20:13:31 +02:00
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static previewFieldsWithDefaultValues(options: any = null) {
|
2020-06-02 23:27:36 +02:00
|
|
|
return Note.defaultValues(this.previewFields(options));
|
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static previewFields(options: any = null) {
|
2020-06-02 23:27:36 +02:00
|
|
|
options = Object.assign({
|
|
|
|
includeTimestamps: true,
|
|
|
|
}, options);
|
|
|
|
|
2021-05-16 17:28:49 +02:00
|
|
|
const output = ['id', 'title', 'is_todo', 'todo_completed', 'todo_due', 'parent_id', 'encryption_applied', 'order', 'markup_language', 'is_conflict', 'is_shared'];
|
2020-06-02 23:27:36 +02:00
|
|
|
|
|
|
|
if (options.includeTimestamps) {
|
|
|
|
output.push('updated_time');
|
|
|
|
output.push('user_updated_time');
|
|
|
|
output.push('user_created_time');
|
|
|
|
}
|
|
|
|
|
|
|
|
return output;
|
2017-06-25 14:49:46 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static previewFieldsSql(fields: string[] = null) {
|
2018-09-27 20:35:10 +02:00
|
|
|
if (fields === null) fields = this.previewFields();
|
2021-01-29 20:45:11 +02:00
|
|
|
const escaped = this.db().escapeFields(fields);
|
|
|
|
return Array.isArray(escaped) ? escaped.join(',') : escaped;
|
2017-05-24 23:09:58 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async loadFolderNoteByField(folderId: string, field: string, value: any) {
|
2018-03-09 22:59:12 +02:00
|
|
|
if (!folderId) throw new Error('folderId is undefined');
|
2017-07-15 17:35:40 +02:00
|
|
|
|
2020-03-14 01:46:14 +02:00
|
|
|
const options = {
|
2019-09-19 23:51:18 +02:00
|
|
|
conditions: [`\`${field}\` = ?`],
|
2017-07-15 17:35:40 +02:00
|
|
|
conditionsParams: [value],
|
2018-03-09 22:59:12 +02:00
|
|
|
fields: '*',
|
2019-07-29 15:43:53 +02:00
|
|
|
};
|
2017-07-15 17:35:40 +02:00
|
|
|
|
2020-03-14 01:46:14 +02:00
|
|
|
const results = await this.previews(folderId, options);
|
2017-07-15 17:35:40 +02:00
|
|
|
return results.length ? results[0] : null;
|
2017-06-27 21:48:01 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async previews(parentId: string, options: any = null) {
|
2020-11-14 14:37:18 +02:00
|
|
|
// Note: ordering logic must be duplicated in sortNotes(), which is used
|
|
|
|
// to sort already loaded notes.
|
2017-07-27 19:25:42 +02:00
|
|
|
|
2017-06-25 11:00:54 +02:00
|
|
|
if (!options) options = {};
|
2019-07-29 15:43:53 +02:00
|
|
|
if (!('order' in options)) options.order = [{ by: 'user_updated_time', dir: 'DESC' }, { by: 'user_created_time', dir: 'DESC' }, { by: 'title', dir: 'DESC' }, { by: 'id', dir: 'DESC' }];
|
2017-07-03 20:58:01 +02:00
|
|
|
if (!options.conditions) options.conditions = [];
|
|
|
|
if (!options.conditionsParams) options.conditionsParams = [];
|
|
|
|
if (!options.fields) options.fields = this.previewFields();
|
2017-07-26 20:36:16 +02:00
|
|
|
if (!options.uncompletedTodosOnTop) options.uncompletedTodosOnTop = false;
|
2018-05-09 22:00:05 +02:00
|
|
|
if (!('showCompletedTodos' in options)) options.showCompletedTodos = true;
|
2017-07-03 20:58:01 +02:00
|
|
|
|
2020-11-14 14:37:18 +02:00
|
|
|
const Folder = BaseItem.getClass('Folder');
|
|
|
|
|
|
|
|
// Conflicts are always displayed regardless of options, since otherwise
|
|
|
|
// it's confusing to have conflicts but with an empty conflict folder.
|
|
|
|
if (parentId === Folder.conflictFolderId()) options.showCompletedTodos = true;
|
|
|
|
|
|
|
|
if (parentId == Folder.conflictFolderId()) {
|
2018-03-09 22:59:12 +02:00
|
|
|
options.conditions.push('is_conflict = 1');
|
2017-07-15 17:35:40 +02:00
|
|
|
} else {
|
2018-03-09 22:59:12 +02:00
|
|
|
options.conditions.push('is_conflict = 0');
|
2020-02-22 13:25:16 +02:00
|
|
|
if (parentId && parentId !== ALL_NOTES_FILTER_ID) {
|
2018-03-09 22:59:12 +02:00
|
|
|
options.conditions.push('parent_id = ?');
|
2017-07-17 21:56:14 +02:00
|
|
|
options.conditionsParams.push(parentId);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (options.anywherePattern) {
|
2020-03-14 01:46:14 +02:00
|
|
|
const pattern = options.anywherePattern.replace(/\*/g, '%');
|
2018-03-09 22:59:12 +02:00
|
|
|
options.conditions.push('(title LIKE ? OR body LIKE ?)');
|
2017-07-17 21:56:14 +02:00
|
|
|
options.conditionsParams.push(pattern);
|
|
|
|
options.conditionsParams.push(pattern);
|
|
|
|
}
|
2017-06-25 11:00:54 +02:00
|
|
|
|
2017-07-26 20:36:16 +02:00
|
|
|
let hasNotes = true;
|
|
|
|
let hasTodos = true;
|
2017-06-25 11:00:54 +02:00
|
|
|
if (options.itemTypes && options.itemTypes.length) {
|
2018-03-09 22:59:12 +02:00
|
|
|
if (options.itemTypes.indexOf('note') < 0) {
|
2017-07-26 20:36:16 +02:00
|
|
|
hasNotes = false;
|
2018-03-09 22:59:12 +02:00
|
|
|
} else if (options.itemTypes.indexOf('todo') < 0) {
|
2017-07-26 20:36:16 +02:00
|
|
|
hasTodos = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-09 22:00:05 +02:00
|
|
|
if (!options.showCompletedTodos) {
|
|
|
|
options.conditions.push('todo_completed <= 0');
|
|
|
|
}
|
|
|
|
|
2017-07-26 20:36:16 +02:00
|
|
|
if (options.uncompletedTodosOnTop && hasTodos) {
|
|
|
|
let cond = options.conditions.slice();
|
2018-03-09 22:59:12 +02:00
|
|
|
cond.push('is_todo = 1');
|
|
|
|
cond.push('(todo_completed <= 0 OR todo_completed IS NULL)');
|
2017-07-26 20:36:16 +02:00
|
|
|
let tempOptions = Object.assign({}, options);
|
|
|
|
tempOptions.conditions = cond;
|
|
|
|
|
2020-03-14 01:46:14 +02:00
|
|
|
const uncompletedTodos = await this.search(tempOptions);
|
2021-01-07 18:29:53 +02:00
|
|
|
this.handleTitleNaturalSorting(uncompletedTodos, tempOptions);
|
2017-07-26 20:36:16 +02:00
|
|
|
|
|
|
|
cond = options.conditions.slice();
|
|
|
|
if (hasNotes && hasTodos) {
|
2018-03-09 22:59:12 +02:00
|
|
|
cond.push('(is_todo = 0 OR (is_todo = 1 AND todo_completed > 0))');
|
2017-07-26 20:36:16 +02:00
|
|
|
} else {
|
2018-03-09 22:59:12 +02:00
|
|
|
cond.push('(is_todo = 1 AND todo_completed > 0)');
|
2017-06-25 11:00:54 +02:00
|
|
|
}
|
2017-07-26 20:36:16 +02:00
|
|
|
|
|
|
|
tempOptions = Object.assign({}, options);
|
|
|
|
tempOptions.conditions = cond;
|
2018-03-09 22:59:12 +02:00
|
|
|
if ('limit' in tempOptions) tempOptions.limit -= uncompletedTodos.length;
|
2020-03-14 01:46:14 +02:00
|
|
|
const theRest = await this.search(tempOptions);
|
2021-01-07 18:29:53 +02:00
|
|
|
this.handleTitleNaturalSorting(theRest, tempOptions);
|
2017-07-26 20:36:16 +02:00
|
|
|
|
|
|
|
return uncompletedTodos.concat(theRest);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (hasNotes && hasTodos) {
|
2019-07-30 09:35:42 +02:00
|
|
|
// Nothing
|
2017-07-26 20:36:16 +02:00
|
|
|
} else if (hasNotes) {
|
2018-03-09 22:59:12 +02:00
|
|
|
options.conditions.push('is_todo = 0');
|
2017-07-26 20:36:16 +02:00
|
|
|
} else if (hasTodos) {
|
2018-03-09 22:59:12 +02:00
|
|
|
options.conditions.push('is_todo = 1');
|
2017-06-25 11:00:54 +02:00
|
|
|
}
|
2017-06-25 14:49:46 +02:00
|
|
|
|
2021-01-07 18:29:53 +02:00
|
|
|
const results = await this.search(options);
|
|
|
|
this.handleTitleNaturalSorting(results, options);
|
|
|
|
|
|
|
|
return results;
|
2017-05-11 22:14:01 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static preview(noteId: string, options: any = null) {
|
2018-09-27 20:35:10 +02:00
|
|
|
if (!options) options = { fields: null };
|
2019-09-19 23:51:18 +02:00
|
|
|
return this.modelSelectOne(`SELECT ${this.previewFieldsSql(options.fields)} FROM notes WHERE is_conflict = 0 AND id = ?`, [noteId]);
|
2017-06-20 21:18:19 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async search(options: any = null) {
|
2019-04-03 08:46:41 +02:00
|
|
|
if (!options) options = {};
|
|
|
|
if (!options.conditions) options.conditions = [];
|
|
|
|
if (!options.conditionsParams) options.conditionsParams = [];
|
|
|
|
|
|
|
|
if (options.bodyPattern) {
|
|
|
|
const pattern = options.bodyPattern.replace(/\*/g, '%');
|
|
|
|
options.conditions.push('body LIKE ?');
|
|
|
|
options.conditionsParams.push(pattern);
|
|
|
|
}
|
|
|
|
|
|
|
|
return super.search(options);
|
|
|
|
}
|
|
|
|
|
2017-06-20 21:25:01 +02:00
|
|
|
static conflictedNotes() {
|
2018-03-09 22:59:12 +02:00
|
|
|
return this.modelSelectAll('SELECT * FROM notes WHERE is_conflict = 1');
|
2017-05-24 23:09:58 +02:00
|
|
|
}
|
|
|
|
|
2017-07-15 17:35:40 +02:00
|
|
|
static async conflictedCount() {
|
2020-03-14 01:46:14 +02:00
|
|
|
const r = await this.db().selectOne('SELECT count(*) as total FROM notes WHERE is_conflict = 1');
|
2017-07-15 17:35:40 +02:00
|
|
|
return r && r.total ? r.total : 0;
|
|
|
|
}
|
|
|
|
|
2017-07-02 23:01:37 +02:00
|
|
|
static unconflictedNotes() {
|
2018-03-09 22:59:12 +02:00
|
|
|
return this.modelSelectAll('SELECT * FROM notes WHERE is_conflict = 0');
|
2017-07-02 23:01:37 +02:00
|
|
|
}
|
|
|
|
|
2021-06-20 13:30:45 +02:00
|
|
|
public static async updateGeolocation(noteId: string): Promise<void> {
|
2018-03-09 22:59:12 +02:00
|
|
|
if (!Setting.value('trackLocation')) return;
|
2017-07-10 22:59:58 +02:00
|
|
|
if (!Note.updateGeolocationEnabled_) return;
|
|
|
|
|
2020-03-14 01:46:14 +02:00
|
|
|
const startWait = time.unixMs();
|
2017-07-11 20:17:23 +02:00
|
|
|
while (true) {
|
|
|
|
if (!this.geolocationUpdating_) break;
|
2018-03-09 22:59:12 +02:00
|
|
|
this.logger().info('Waiting for geolocation update...');
|
2017-07-11 20:17:23 +02:00
|
|
|
await time.sleep(1);
|
|
|
|
if (startWait + 1000 * 20 < time.unixMs()) {
|
2019-09-19 23:51:18 +02:00
|
|
|
this.logger().warn(`Failed to update geolocation for: timeout: ${noteId}`);
|
2017-07-11 20:17:23 +02:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
2017-05-15 21:46:34 +02:00
|
|
|
|
2017-05-23 21:01:37 +02:00
|
|
|
let geoData = null;
|
2017-07-11 20:17:23 +02:00
|
|
|
if (this.geolocationCache_ && this.geolocationCache_.timestamp + 1000 * 60 * 10 > time.unixMs()) {
|
|
|
|
geoData = Object.assign({}, this.geolocationCache_);
|
|
|
|
} else {
|
|
|
|
this.geolocationUpdating_ = true;
|
2017-10-22 14:45:56 +02:00
|
|
|
|
2018-03-09 22:59:12 +02:00
|
|
|
this.logger().info('Fetching geolocation...');
|
2017-10-22 14:45:56 +02:00
|
|
|
try {
|
|
|
|
geoData = await shim.Geolocation.currentPosition();
|
|
|
|
} catch (error) {
|
2019-09-19 23:51:18 +02:00
|
|
|
this.logger().error(`Could not get lat/long for note ${noteId}: `, error);
|
2017-10-22 14:45:56 +02:00
|
|
|
geoData = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.geolocationUpdating_ = false;
|
|
|
|
|
|
|
|
if (!geoData) return;
|
|
|
|
|
2018-03-09 22:59:12 +02:00
|
|
|
this.logger().info('Got lat/long');
|
2017-07-11 20:17:23 +02:00
|
|
|
this.geolocationCache_ = geoData;
|
|
|
|
}
|
|
|
|
|
2019-09-19 23:51:18 +02:00
|
|
|
this.logger().info(`Updating lat/long of note ${noteId}`);
|
2017-07-11 20:17:23 +02:00
|
|
|
|
2020-03-14 01:46:14 +02:00
|
|
|
const note = await Note.load(noteId);
|
2017-07-11 20:17:23 +02:00
|
|
|
if (!note) return; // Race condition - note has been deleted in the meantime
|
|
|
|
|
|
|
|
note.longitude = geoData.coords.longitude;
|
|
|
|
note.latitude = geoData.coords.latitude;
|
|
|
|
note.altitude = geoData.coords.altitude;
|
2021-06-20 13:30:45 +02:00
|
|
|
await Note.save(note, { ignoreProvisionalFlag: true });
|
2017-05-15 21:46:34 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static filter(note: NoteEntity) {
|
2017-06-24 19:40:03 +02:00
|
|
|
if (!note) return note;
|
|
|
|
|
2020-03-14 01:46:14 +02:00
|
|
|
const output = super.filter(note);
|
2018-03-09 22:59:12 +02:00
|
|
|
if ('longitude' in output) output.longitude = Number(!output.longitude ? 0 : output.longitude).toFixed(8);
|
|
|
|
if ('latitude' in output) output.latitude = Number(!output.latitude ? 0 : output.latitude).toFixed(8);
|
|
|
|
if ('altitude' in output) output.altitude = Number(!output.altitude ? 0 : output.altitude).toFixed(4);
|
2017-06-24 19:40:03 +02:00
|
|
|
return output;
|
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async copyToFolder(noteId: string, folderId: string) {
|
2020-03-15 23:53:49 +02:00
|
|
|
if (folderId == this.getClass('Folder').conflictFolderId()) throw new Error(_('Cannot copy note to "%s" notebook', this.getClass('Folder').conflictFolderTitle()));
|
2017-07-15 17:35:40 +02:00
|
|
|
|
|
|
|
return Note.duplicate(noteId, {
|
|
|
|
changes: {
|
|
|
|
parent_id: folderId,
|
|
|
|
is_conflict: 0, // Also reset the conflict flag in case we're moving the note out of the conflict folder
|
2021-06-12 09:46:49 +02:00
|
|
|
conflict_original_id: '', // Reset parent id as well.
|
2017-07-15 17:35:40 +02:00
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async moveToFolder(noteId: string, folderId: string) {
|
2020-03-15 23:53:49 +02:00
|
|
|
if (folderId == this.getClass('Folder').conflictFolderId()) throw new Error(_('Cannot move note to "%s" notebook', this.getClass('Folder').conflictFolderTitle()));
|
2017-07-15 17:35:40 +02:00
|
|
|
|
2017-08-20 22:11:32 +02:00
|
|
|
// When moving a note to a different folder, the user timestamp is not updated.
|
|
|
|
// However updated_time is updated so that the note can be synced later on.
|
|
|
|
|
|
|
|
const modifiedNote = {
|
2017-07-15 17:35:40 +02:00
|
|
|
id: noteId,
|
|
|
|
parent_id: folderId,
|
|
|
|
is_conflict: 0,
|
2021-06-12 09:46:49 +02:00
|
|
|
conflict_original_id: '',
|
2017-08-20 22:11:32 +02:00
|
|
|
updated_time: time.unixMs(),
|
|
|
|
};
|
|
|
|
|
|
|
|
return Note.save(modifiedNote, { autoTimestamp: false });
|
2017-07-15 17:35:40 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static changeNoteType(note: NoteEntity, type: string) {
|
2018-03-09 22:59:12 +02:00
|
|
|
if (!('is_todo' in note)) throw new Error('Missing "is_todo" property');
|
2017-07-30 21:51:18 +02:00
|
|
|
|
2018-10-04 19:34:30 +02:00
|
|
|
const newIsTodo = type === 'todo' ? 1 : 0;
|
|
|
|
|
|
|
|
if (Number(note.is_todo) === newIsTodo) return note;
|
|
|
|
|
|
|
|
const output = Object.assign({}, note);
|
|
|
|
output.is_todo = newIsTodo;
|
2017-07-31 20:47:06 +02:00
|
|
|
output.todo_due = 0;
|
|
|
|
output.todo_completed = 0;
|
2017-07-30 21:51:18 +02:00
|
|
|
|
|
|
|
return output;
|
2017-07-17 22:22:05 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static toggleIsTodo(note: NoteEntity) {
|
2019-07-29 15:43:53 +02:00
|
|
|
return this.changeNoteType(note, note.is_todo ? 'note' : 'todo');
|
2018-10-04 19:34:30 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static toggleTodoCompleted(note: NoteEntity) {
|
2019-01-26 17:33:45 +02:00
|
|
|
if (!('todo_completed' in note)) throw new Error('Missing "todo_completed" property');
|
|
|
|
|
|
|
|
note = Object.assign({}, note);
|
|
|
|
if (note.todo_completed) {
|
|
|
|
note.todo_completed = 0;
|
|
|
|
} else {
|
|
|
|
note.todo_completed = Date.now();
|
|
|
|
}
|
2019-07-29 15:43:53 +02:00
|
|
|
|
2019-01-26 17:33:45 +02:00
|
|
|
return note;
|
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async duplicateMultipleNotes(noteIds: string[], options: any = null) {
|
2019-10-14 01:47:21 +02:00
|
|
|
// if options.uniqueTitle is true, a unique title for the duplicated file will be assigned.
|
2019-10-12 00:37:16 +02:00
|
|
|
const ensureUniqueTitle = options && options.ensureUniqueTitle;
|
|
|
|
|
2019-10-14 01:47:21 +02:00
|
|
|
for (const noteId of noteIds) {
|
2021-01-22 19:41:11 +02:00
|
|
|
const noteOptions: any = {};
|
2019-10-12 00:37:16 +02:00
|
|
|
|
2019-10-14 01:47:21 +02:00
|
|
|
// If ensureUniqueTitle is truthy, set the original note's name as root for the unique title.
|
|
|
|
if (ensureUniqueTitle) {
|
2019-10-12 00:37:16 +02:00
|
|
|
const originalNote = await Note.load(noteId);
|
|
|
|
noteOptions.uniqueTitle = originalNote.title;
|
|
|
|
}
|
|
|
|
|
|
|
|
await Note.duplicate(noteId, noteOptions);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async duplicate(noteId: string, options: any = null) {
|
2017-07-11 20:17:23 +02:00
|
|
|
const changes = options && options.changes;
|
2018-06-27 22:45:31 +02:00
|
|
|
const uniqueTitle = options && options.uniqueTitle;
|
2017-07-11 20:17:23 +02:00
|
|
|
|
|
|
|
const originalNote = await Note.load(noteId);
|
2019-09-19 23:51:18 +02:00
|
|
|
if (!originalNote) throw new Error(`Unknown note: ${noteId}`);
|
2017-07-11 20:17:23 +02:00
|
|
|
|
2020-03-14 01:46:14 +02:00
|
|
|
const newNote = Object.assign({}, originalNote);
|
2020-02-05 13:18:14 +02:00
|
|
|
const fieldsToReset = ['id', 'created_time', 'updated_time', 'user_created_time', 'user_updated_time'];
|
|
|
|
|
2020-03-14 01:46:14 +02:00
|
|
|
for (const field of fieldsToReset) {
|
2020-02-05 13:18:14 +02:00
|
|
|
delete newNote[field];
|
|
|
|
}
|
2017-07-11 20:17:23 +02:00
|
|
|
|
2020-03-14 01:46:14 +02:00
|
|
|
for (const n in changes) {
|
2017-07-11 20:17:23 +02:00
|
|
|
if (!changes.hasOwnProperty(n)) continue;
|
|
|
|
newNote[n] = changes[n];
|
|
|
|
}
|
|
|
|
|
2018-06-27 22:45:31 +02:00
|
|
|
if (uniqueTitle) {
|
|
|
|
const title = await Note.findUniqueItemTitle(uniqueTitle);
|
|
|
|
newNote.title = title;
|
|
|
|
}
|
|
|
|
|
2021-04-24 10:16:36 +02:00
|
|
|
const newNoteSaved = await this.save(newNote);
|
|
|
|
const originalTags = await Tag.tagsByNoteId(noteId);
|
|
|
|
for (const tagToAdd of originalTags) {
|
|
|
|
await Tag.addNote(tagToAdd.id, newNoteSaved.id);
|
|
|
|
}
|
|
|
|
|
|
|
|
return this.save(newNoteSaved);
|
2017-07-11 20:17:23 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async noteIsOlderThan(noteId: string, date: number) {
|
2019-05-06 22:35:29 +02:00
|
|
|
const n = await this.db().selectOne('SELECT updated_time FROM notes WHERE id = ?', [noteId]);
|
2019-09-19 23:51:18 +02:00
|
|
|
if (!n) throw new Error(`No such note: ${noteId}`);
|
2019-05-06 22:35:29 +02:00
|
|
|
return n.updated_time < date;
|
|
|
|
}
|
|
|
|
|
2021-06-20 12:19:59 +02:00
|
|
|
public static async save(o: NoteEntity, options: any = null): Promise<NoteEntity> {
|
2020-03-14 01:46:14 +02:00
|
|
|
const isNew = this.isNew(o, options);
|
2021-04-07 18:57:44 +02:00
|
|
|
|
|
|
|
// If true, this is a provisional note - it will be saved permanently
|
|
|
|
// only if the user makes changes to it.
|
2020-02-29 14:59:10 +02:00
|
|
|
const isProvisional = options && !!options.provisional;
|
2021-04-07 18:57:44 +02:00
|
|
|
|
|
|
|
// If true, saving the note will not change the provisional flag of the
|
|
|
|
// note. This is used for background processing that it not initiated by
|
|
|
|
// the user. For example when setting the geolocation of a note.
|
|
|
|
const ignoreProvisionalFlag = options && !!options.ignoreProvisionalFlag;
|
|
|
|
|
2020-05-27 18:21:46 +02:00
|
|
|
const dispatchUpdateAction = options ? options.dispatchUpdateAction !== false : true;
|
2018-03-09 22:59:12 +02:00
|
|
|
if (isNew && !o.source) o.source = Setting.value('appName');
|
|
|
|
if (isNew && !o.source_application) o.source_application = Setting.value('appId');
|
2020-05-27 18:21:46 +02:00
|
|
|
if (isNew && !('order' in o)) o.order = Date.now();
|
2017-06-29 22:52:52 +02:00
|
|
|
|
2019-05-06 22:35:29 +02:00
|
|
|
// We only keep the previous note content for "old notes" (see Revision Service for more info)
|
|
|
|
// In theory, we could simply save all the previous note contents, and let the revision service
|
|
|
|
// decide what to keep and what to ignore, but in practice keeping the previous content is a bit
|
|
|
|
// heavy - the note needs to be reloaded here, the JSON blob needs to be saved, etc.
|
|
|
|
// So the check for old note here is basically an optimisation.
|
2020-10-20 00:24:40 +02:00
|
|
|
|
|
|
|
// 2020-10-19: It's not ideal to reload the previous version of the note before saving it again
|
|
|
|
// but it should be relatively fast anyway. This is so that code that listens to the NOTE_UPDATE_ONE
|
|
|
|
// action can decide what to do based on the fields that have been modified.
|
|
|
|
// This is necessary for example so that the folder list is not refreshed every time a note is changed.
|
|
|
|
// Now it can look at the properties and refresh only if the "parent_id" property is changed.
|
|
|
|
// Trying to fix: https://github.com/laurent22/joplin/issues/3893
|
2020-10-20 12:49:15 +02:00
|
|
|
const oldNote = !isNew && o.id ? await Note.load(o.id) : null;
|
2020-10-20 00:24:40 +02:00
|
|
|
|
2021-10-15 13:24:22 +02:00
|
|
|
syncDebugLog.info('Save Note: P:', oldNote);
|
|
|
|
|
2019-05-06 22:35:29 +02:00
|
|
|
let beforeNoteJson = null;
|
2020-10-20 12:49:15 +02:00
|
|
|
if (oldNote && this.revisionService().isOldNote(o.id)) {
|
|
|
|
beforeNoteJson = JSON.stringify(oldNote);
|
2020-10-20 00:24:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const changedFields = [];
|
|
|
|
|
|
|
|
if (oldNote) {
|
|
|
|
for (const field in o) {
|
|
|
|
if (!o.hasOwnProperty(field)) continue;
|
2021-01-22 19:41:11 +02:00
|
|
|
if ((o as any)[field] !== oldNote[field]) {
|
2020-10-20 00:24:40 +02:00
|
|
|
changedFields.push(field);
|
|
|
|
}
|
|
|
|
}
|
2019-05-06 22:35:29 +02:00
|
|
|
}
|
|
|
|
|
2021-10-15 13:24:22 +02:00
|
|
|
syncDebugLog.info('Save Note: N:', o);
|
|
|
|
|
2018-02-07 21:02:07 +02:00
|
|
|
const note = await super.save(o, options);
|
2017-11-28 00:50:46 +02:00
|
|
|
|
2019-05-06 22:35:29 +02:00
|
|
|
const changeSource = options && options.changeSource ? options.changeSource : null;
|
2021-01-22 19:41:11 +02:00
|
|
|
void ItemChange.add(BaseModel.TYPE_NOTE, note.id, isNew ? ItemChange.TYPE_CREATE : ItemChange.TYPE_UPDATE, changeSource, beforeNoteJson);
|
2018-03-13 01:40:43 +02:00
|
|
|
|
2020-05-27 18:21:46 +02:00
|
|
|
if (dispatchUpdateAction) {
|
|
|
|
this.dispatch({
|
|
|
|
type: 'NOTE_UPDATE_ONE',
|
|
|
|
note: note,
|
|
|
|
provisional: isProvisional,
|
2021-04-07 18:57:44 +02:00
|
|
|
ignoreProvisionalFlag: ignoreProvisionalFlag,
|
2020-10-20 00:24:40 +02:00
|
|
|
changedFields: changedFields,
|
2020-05-27 18:21:46 +02:00
|
|
|
});
|
|
|
|
}
|
2018-02-07 21:02:07 +02:00
|
|
|
|
2018-03-09 22:59:12 +02:00
|
|
|
if ('todo_due' in o || 'todo_completed' in o || 'is_todo' in o || 'is_conflict' in o) {
|
2018-02-07 21:02:07 +02:00
|
|
|
this.dispatch({
|
2018-03-09 22:59:12 +02:00
|
|
|
type: 'EVENT_NOTE_ALARM_FIELD_CHANGE',
|
2018-02-07 21:02:07 +02:00
|
|
|
id: note.id,
|
|
|
|
});
|
|
|
|
}
|
2018-05-30 19:22:07 +02:00
|
|
|
|
2018-02-07 21:02:07 +02:00
|
|
|
return note;
|
2017-05-22 22:22:50 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static async batchDelete(ids: string[], options: any = null) {
|
2019-05-06 22:35:29 +02:00
|
|
|
ids = ids.slice();
|
2018-03-13 01:40:43 +02:00
|
|
|
|
2019-05-06 22:35:29 +02:00
|
|
|
while (ids.length) {
|
|
|
|
const processIds = ids.splice(0, 50);
|
|
|
|
|
|
|
|
const notes = await Note.byIds(processIds);
|
2021-01-22 19:41:11 +02:00
|
|
|
const beforeChangeItems: any = {};
|
2019-05-06 22:35:29 +02:00
|
|
|
for (const note of notes) {
|
|
|
|
beforeChangeItems[note.id] = JSON.stringify(note);
|
|
|
|
}
|
|
|
|
|
2019-07-30 09:35:42 +02:00
|
|
|
await super.batchDelete(processIds, options);
|
2019-05-06 22:35:29 +02:00
|
|
|
const changeSource = options && options.changeSource ? options.changeSource : null;
|
|
|
|
for (let i = 0; i < processIds.length; i++) {
|
|
|
|
const id = processIds[i];
|
2021-01-22 19:41:11 +02:00
|
|
|
void ItemChange.add(BaseModel.TYPE_NOTE, id, ItemChange.TYPE_DELETE, changeSource, beforeChangeItems[id]);
|
2019-05-06 22:35:29 +02:00
|
|
|
|
|
|
|
this.dispatch({
|
|
|
|
type: 'NOTE_DELETE',
|
|
|
|
id: id,
|
|
|
|
});
|
|
|
|
}
|
2017-10-09 21:57:00 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-03 19:41:32 +02:00
|
|
|
static async deleteMessage(noteIds: string[]): Promise<string|null> {
|
|
|
|
let msg = '';
|
|
|
|
if (noteIds.length === 1) {
|
|
|
|
const note = await Note.load(noteIds[0]);
|
|
|
|
if (!note) return null;
|
|
|
|
msg = _('Delete note "%s"?', substrWithEllipsis(note.title, 0, 32));
|
|
|
|
} else {
|
|
|
|
msg = _('Delete these %d notes?', noteIds.length);
|
|
|
|
}
|
|
|
|
return msg;
|
|
|
|
}
|
|
|
|
|
2017-11-28 00:50:46 +02:00
|
|
|
static dueNotes() {
|
2018-03-09 22:59:12 +02:00
|
|
|
return this.modelSelectAll('SELECT id, title, body, is_todo, todo_due, todo_completed, is_conflict FROM notes WHERE is_conflict = 0 AND is_todo = 1 AND todo_completed = 0 AND todo_due > ?', [time.unixMs()]);
|
2017-11-28 00:50:46 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static needAlarm(note: NoteEntity) {
|
2017-11-28 00:50:46 +02:00
|
|
|
return note.is_todo && !note.todo_completed && note.todo_due >= time.unixMs() && !note.is_conflict;
|
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static dueDateObject(note: NoteEntity) {
|
2019-07-12 20:36:12 +02:00
|
|
|
if (!!note.is_todo && note.todo_due) {
|
|
|
|
if (!this.dueDateObjects_) this.dueDateObjects_ = {};
|
|
|
|
if (this.dueDateObjects_[note.todo_due]) return this.dueDateObjects_[note.todo_due];
|
|
|
|
this.dueDateObjects_[note.todo_due] = new Date(note.todo_due);
|
|
|
|
return this.dueDateObjects_[note.todo_due];
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2017-11-03 00:48:17 +02:00
|
|
|
// Tells whether the conflict between the local and remote note can be ignored.
|
2021-01-22 19:41:11 +02:00
|
|
|
static mustHandleConflict(localNote: NoteEntity, remoteNote: NoteEntity) {
|
2017-11-03 00:48:17 +02:00
|
|
|
// That shouldn't happen so throw an exception
|
2018-03-09 22:59:12 +02:00
|
|
|
if (localNote.id !== remoteNote.id) throw new Error('Cannot handle conflict for two different notes');
|
2017-11-03 00:48:17 +02:00
|
|
|
|
2017-12-14 00:53:20 +02:00
|
|
|
// For encrypted notes the conflict must always be handled
|
|
|
|
if (localNote.encryption_cipher_text || remoteNote.encryption_cipher_text) return true;
|
|
|
|
|
|
|
|
// Otherwise only handle the conflict if there's a different on the title or body
|
2017-11-03 00:48:17 +02:00
|
|
|
if (localNote.title !== remoteNote.title) return true;
|
|
|
|
if (localNote.body !== remoteNote.body) return true;
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
2018-03-09 22:59:12 +02:00
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static markupLanguageToLabel(markupLanguageId: number) {
|
2019-12-29 19:58:40 +02:00
|
|
|
if (markupLanguageId === MarkupToHtml.MARKUP_LANGUAGE_MARKDOWN) return 'Markdown';
|
|
|
|
if (markupLanguageId === MarkupToHtml.MARKUP_LANGUAGE_HTML) return 'HTML';
|
2019-09-19 23:51:18 +02:00
|
|
|
throw new Error(`Invalid markup language ID: ${markupLanguageId}`);
|
2019-07-17 23:50:12 +02:00
|
|
|
}
|
2020-05-27 18:21:46 +02:00
|
|
|
|
|
|
|
// When notes are sorted in "custom order", they are sorted by the "order" field first and,
|
|
|
|
// in those cases, where the order field is the same for some notes, by created time.
|
2021-01-22 19:41:11 +02:00
|
|
|
static customOrderByColumns(type: string = null) {
|
2020-05-27 18:21:46 +02:00
|
|
|
if (!type) type = 'object';
|
|
|
|
if (type === 'object') return [{ by: 'order', dir: 'DESC' }, { by: 'user_created_time', dir: 'DESC' }];
|
|
|
|
if (type === 'string') return 'ORDER BY `order` DESC, user_created_time DESC';
|
|
|
|
throw new Error(`Invalid type: ${type}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update the note "order" field without changing the user timestamps,
|
|
|
|
// which is generally what we want.
|
2021-01-22 19:41:11 +02:00
|
|
|
static async updateNoteOrder_(note: NoteEntity, order: any) {
|
2020-05-27 18:21:46 +02:00
|
|
|
return Note.save(Object.assign({}, note, {
|
|
|
|
order: order,
|
|
|
|
user_updated_time: note.user_updated_time,
|
|
|
|
}), { autoTimestamp: false, dispatchUpdateAction: false });
|
|
|
|
}
|
|
|
|
|
|
|
|
// This method will disable the NOTE_UPDATE_ONE action to prevent a lot
|
|
|
|
// of unecessary updates, so it's the caller's responsability to update
|
|
|
|
// the UI once the call is finished. This is done by listening to the
|
|
|
|
// NOTE_IS_INSERTING_NOTES action in the application middleware.
|
2021-01-22 19:41:11 +02:00
|
|
|
static async insertNotesAt(folderId: string, noteIds: string[], index: number) {
|
2020-05-27 18:21:46 +02:00
|
|
|
if (!noteIds.length) return;
|
|
|
|
|
|
|
|
const defer = () => {
|
|
|
|
this.dispatch({
|
|
|
|
type: 'NOTE_IS_INSERTING_NOTES',
|
|
|
|
value: false,
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
this.dispatch({
|
|
|
|
type: 'NOTE_IS_INSERTING_NOTES',
|
|
|
|
value: true,
|
|
|
|
});
|
|
|
|
|
|
|
|
try {
|
|
|
|
const noteSql = `
|
|
|
|
SELECT id, \`order\`, user_created_time, user_updated_time
|
|
|
|
FROM notes
|
|
|
|
WHERE is_conflict = 0 AND parent_id = ?
|
|
|
|
${this.customOrderByColumns('string')}`;
|
|
|
|
|
|
|
|
let notes = await this.modelSelectAll(noteSql, [folderId]);
|
|
|
|
|
|
|
|
// If the target index is the same as the source note index, exit now
|
|
|
|
for (let i = 0; i < notes.length; i++) {
|
|
|
|
const note = notes[i];
|
|
|
|
if (note.id === noteIds[0] && index === i) return defer();
|
|
|
|
}
|
|
|
|
|
|
|
|
// If some of the target notes have order = 0, set the order field to user_created_time
|
|
|
|
// (historically, all notes had the order field set to 0)
|
|
|
|
let hasSetOrder = false;
|
|
|
|
for (let i = 0; i < notes.length; i++) {
|
|
|
|
const note = notes[i];
|
|
|
|
if (!note.order) {
|
|
|
|
const updatedNote = await this.updateNoteOrder_(note, note.user_created_time);
|
|
|
|
notes[i] = updatedNote;
|
|
|
|
hasSetOrder = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (hasSetOrder) notes = await this.modelSelectAll(noteSql, [folderId]);
|
|
|
|
|
|
|
|
// Find the order value for the first note to be inserted,
|
|
|
|
// and the increment between the order values of each inserted notes.
|
|
|
|
let newOrder = 0;
|
|
|
|
let intervalBetweenNotes = 0;
|
|
|
|
const defaultIntevalBetweeNotes = 60 * 60 * 1000;
|
|
|
|
|
|
|
|
if (!notes.length) { // If there's no notes in the target notebook
|
|
|
|
newOrder = Date.now();
|
|
|
|
intervalBetweenNotes = defaultIntevalBetweeNotes;
|
|
|
|
} else if (index >= notes.length) { // Insert at the end
|
|
|
|
intervalBetweenNotes = notes[notes.length - 1].order / (noteIds.length + 1);
|
|
|
|
newOrder = notes[notes.length - 1].order - intervalBetweenNotes;
|
|
|
|
} else if (index === 0) { // Insert at the beginning
|
|
|
|
const firstNoteOrder = notes[0].order;
|
|
|
|
if (firstNoteOrder >= Date.now()) {
|
|
|
|
intervalBetweenNotes = defaultIntevalBetweeNotes;
|
|
|
|
newOrder = firstNoteOrder + defaultIntevalBetweeNotes;
|
|
|
|
} else {
|
|
|
|
intervalBetweenNotes = (Date.now() - firstNoteOrder) / (noteIds.length + 1);
|
|
|
|
newOrder = firstNoteOrder + intervalBetweenNotes * noteIds.length;
|
|
|
|
}
|
|
|
|
} else { // Normal insert
|
|
|
|
let noteBefore = notes[index - 1];
|
|
|
|
let noteAfter = notes[index];
|
|
|
|
|
|
|
|
if (noteBefore.order === noteAfter.order) {
|
|
|
|
let previousOrder = noteBefore.order;
|
|
|
|
for (let i = index; i >= 0; i--) {
|
|
|
|
const n = notes[i];
|
|
|
|
if (n.order <= previousOrder) {
|
|
|
|
const o = previousOrder + defaultIntevalBetweeNotes;
|
|
|
|
const updatedNote = await this.updateNoteOrder_(n, o);
|
|
|
|
notes[i] = Object.assign({}, n, updatedNote);
|
|
|
|
previousOrder = o;
|
|
|
|
} else {
|
|
|
|
previousOrder = n.order;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
noteBefore = notes[index - 1];
|
|
|
|
noteAfter = notes[index];
|
|
|
|
}
|
|
|
|
|
|
|
|
intervalBetweenNotes = (noteBefore.order - noteAfter.order) / (noteIds.length + 1);
|
|
|
|
newOrder = noteAfter.order + intervalBetweenNotes * noteIds.length;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set the order value for all the notes to be inserted
|
|
|
|
for (const noteId of noteIds) {
|
|
|
|
const note = await Note.load(noteId);
|
|
|
|
if (!note) throw new Error(`No such note: ${noteId}`);
|
|
|
|
|
|
|
|
await this.updateNoteOrder_({
|
|
|
|
id: noteId,
|
|
|
|
parent_id: folderId,
|
|
|
|
user_updated_time: note.user_updated_time,
|
|
|
|
}, newOrder);
|
|
|
|
|
|
|
|
newOrder -= intervalBetweenNotes;
|
|
|
|
}
|
|
|
|
} finally {
|
|
|
|
defer();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
static handleTitleNaturalSorting(items: NoteEntity[], options: any) {
|
2021-01-07 18:29:53 +02:00
|
|
|
if (options.order.length > 0 && options.order[0].by === 'title') {
|
|
|
|
const collator = this.getNaturalSortingCollator();
|
|
|
|
items.sort((a, b) => ((options.order[0].dir === 'ASC') ? 1 : -1) * collator.compare(a.title, b.title));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static getNaturalSortingCollator() {
|
|
|
|
return new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
|
|
|
|
}
|
|
|
|
|
2021-06-12 09:46:49 +02:00
|
|
|
|
|
|
|
static async createConflictNote(sourceNote: NoteEntity, changeSource: number): Promise<NoteEntity> {
|
|
|
|
const conflictNote = Object.assign({}, sourceNote);
|
|
|
|
delete conflictNote.id;
|
|
|
|
conflictNote.is_conflict = 1;
|
|
|
|
conflictNote.conflict_original_id = sourceNote.id;
|
|
|
|
return await Note.save(conflictNote, { autoTimestamp: false, changeSource: changeSource });
|
|
|
|
}
|
2017-05-10 21:21:09 +02:00
|
|
|
}
|