1
0
mirror of https://github.com/laurent22/joplin.git synced 2025-06-15 23:00:36 +02:00

All: Finished service to clean up resources

This commit is contained in:
Laurent Cozic
2018-03-15 18:08:46 +00:00
parent 945018b698
commit c1bb51c12b
10 changed files with 205 additions and 28 deletions

View File

@ -10,21 +10,39 @@ class NoteResource extends BaseModel {
return BaseModel.TYPE_NOTE_RESOURCE;
}
static async associate(noteId, resourceIds) {
let queries = [];
queries.push({ sql: 'DELETE FROM note_resources WHERE note_id = ?', params: [noteId] });
static async setAssociatedResources(noteId, resourceIds) {
const existingRows = await this.modelSelectAll('SELECT * FROM note_resources WHERE note_id = ?', [noteId]);
for (let i = 0; i < resourceIds.length; i++) {
queries.push({ sql: 'INSERT INTO note_resources (note_id, resource_id) VALUES (?, ?)', params: [noteId, resourceIds[i]] });
const notProcessedResourceIds = resourceIds.slice();
const queries = [];
for (let i = 0; i < existingRows.length; i++) {
const row = existingRows[i];
const resourceIndex = resourceIds.indexOf(row.resource_id);
if (resourceIndex >= 0) {
queries.push({ sql: 'UPDATE note_resources SET last_seen_time = ?, is_associated = 1 WHERE id = ?', params: [Date.now(), row.id] });
notProcessedResourceIds.splice(notProcessedResourceIds.indexOf(row.resource_id), 1);
} else {
queries.push({ sql: 'UPDATE note_resources SET is_associated = 0 WHERE id = ?', params: [row.id] });
}
}
await this.db().transactionExecBatch(queries);
for (let i = 0; i < notProcessedResourceIds.length; i++) {
queries.push({ sql: 'INSERT INTO note_resources (note_id, resource_id, is_associated, last_seen_time) VALUES (?, ?, ?, ?)', params: [noteId, notProcessedResourceIds[i], 1, Date.now()] });
}
await this.db().transactionExecBatch(queries);
}
static async remove(noteId) {
let queries = [];
queries.push({ sql: 'DELETE FROM note_resources WHERE note_id = ?', params: [noteId] });
await this.db().transactionExecBatch(queries);
await this.db().exec({ sql: 'UPDATE note_resources SET is_associated = 0 WHERE note_id = ?', params: [noteId] });
}
static async orphanResources(expiryDelay = null) {
if (expiryDelay === null) expiryDelay = 1000 * 60 * 60 * 24;
const cutOffTime = Date.now() - expiryDelay;
const output = await this.modelSelectAll('SELECT DISTINCT resource_id FROM note_resources WHERE is_associated = 0 AND last_seen_time < ?', [cutOffTime]);
return output.map(r => r.resource_id);
}
}