-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathNotesService.js
More file actions
558 lines (505 loc) · 17.3 KB
/
NotesService.js
File metadata and controls
558 lines (505 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
/**
* SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'
import { showError } from '@nextcloud/dialogs'
import store from './store.js'
import { copyNote } from './Util.js'
function url(url) {
url = `apps/notes${url}`
return generateUrl(url)
}
function handleSyncError(message, err = null) {
if (err?.response) {
const statusCode = err.response?.status
switch (statusCode) {
case 404:
showError(message + ' ' + t('notes', 'Note not found.'))
break
case 423:
showError(message + ' ' + t('notes', 'Note is locked.'))
break
case 507:
showError(message + ' ' + t('notes', 'Insufficient storage.'))
break
default:
showError(message + ' HTTP ' + statusCode + ' (' + err.response.data?.errorType + ')')
}
} else {
showError(message + ' ' + t('notes', 'See JavaScript console and server log for details.'))
}
}
export const setSettings = settings => {
return axios
.put(url('/settings'), settings)
.then(response => {
const settings = response.data
store.commit('setSettings', settings)
return settings
})
.catch(err => {
console.error(err)
handleSyncError(t('notes', 'Updating settings has failed.'), err)
throw err
})
}
export const deleteEditorMode = () => {
return axios
.post(url('/settings/migrate'))
.catch(err => {
console.error(err)
throw err
})
}
export const getDashboardData = () => {
return axios
.get(url('/notes/dashboard'))
.then(response => {
return response.data
})
.catch(err => {
console.error(err)
handleSyncError(t('notes', 'Fetching notes for dashboard has failed.'), err)
throw err
})
}
export const fetchNotes = async (chunkSize = 50, chunkCursor = null) => {
console.log('[fetchNotes] Called with chunkSize:', chunkSize, 'cursor:', chunkCursor)
const lastETag = store.state.sync.etag
const lastModified = store.state.sync.lastModified
const headers = {}
if (lastETag) {
headers['If-None-Match'] = lastETag
}
try {
// Signal start of loading
store.commit('setNotesLoadingInProgress', true)
// Fetch settings first (only on first load)
if (!store.state.app.settings || Object.keys(store.state.app.settings).length === 0) {
try {
const settingsResponse = await axios.get(generateUrl('/apps/notes/api/v1/settings'))
store.commit('setSettings', settingsResponse.data)
} catch (err) {
console.warn('Failed to fetch settings, will continue with defaults', err)
}
}
// Load notes metadata in chunks excluding content for performance
// Content is loaded on-demand when user selects a note
const params = new URLSearchParams()
if (lastModified) {
params.append('pruneBefore', lastModified)
}
params.append('exclude', 'content') // Exclude heavy content field
params.append('chunkSize', chunkSize.toString()) // Request chunked data
if (chunkCursor) {
params.append('chunkCursor', chunkCursor) // Continue from previous chunk
}
const url = generateUrl('/apps/notes/api/v1/notes' + (params.toString() ? '?' + params.toString() : ''))
console.log('[fetchNotes] Requesting:', url)
const response = await axios.get(url, { headers })
console.log('[fetchNotes] Response received, status:', response.status)
console.log('[fetchNotes] Response data type:', Array.isArray(response.data) ? 'array' : typeof response.data)
console.log('[fetchNotes] Response headers:', response.headers)
// Backend returns array of notes directly
const notes = Array.isArray(response.data) ? response.data : []
const noteIds = notes.map(note => note.id)
// Cursor is in response headers, not body
const nextCursor = response.headers['x-notes-chunk-cursor'] || null
const pendingCount = response.headers['x-notes-chunk-pending'] ? parseInt(response.headers['x-notes-chunk-pending']) : 0
const isLastChunk = !nextCursor
// Category statistics and total count from first chunk (if available)
const categoryStats = response.headers['x-notes-category-stats']
if (categoryStats) {
try {
const stats = JSON.parse(categoryStats)
console.log('[fetchNotes] Received category stats:', Object.keys(stats).length, 'categories')
store.commit('setCategoryStats', stats)
} catch (e) {
console.warn('[fetchNotes] Failed to parse category stats:', e)
}
}
const totalCount = response.headers['x-notes-total-count']
if (totalCount) {
const count = parseInt(totalCount)
console.log('[fetchNotes] Total notes count:', count)
store.commit('setTotalNotesCount', count)
}
console.log('[fetchNotes] Processed:', notes.length, 'notes, noteIds:', noteIds.length)
console.log('[fetchNotes] Cursor:', nextCursor, 'Pending:', pendingCount, 'isLastChunk:', isLastChunk)
// Update notes incrementally
if (chunkCursor) {
// Subsequent chunk - use incremental update
console.log('[fetchNotes] Using incremental update for subsequent chunk')
store.dispatch('updateNotesIncremental', { notes, isLastChunk })
if (isLastChunk) {
// Final chunk - clean up deleted notes
console.log('[fetchNotes] Final chunk - cleaning up deleted notes')
store.dispatch('finalizeNotesUpdate', noteIds)
}
} else {
// First chunk - use full update
console.log('[fetchNotes] Using full update for first chunk')
store.dispatch('updateNotes', { noteIds, notes })
}
// Update ETag and last modified
store.commit('setSyncETag', response.headers.etag)
store.commit('setSyncLastModified', response.headers['last-modified'])
store.commit('setNotesLoadingInProgress', false)
console.log('[fetchNotes] Completed successfully')
return {
noteIds,
chunkCursor: nextCursor,
isLastChunk,
}
} catch (err) {
store.commit('setNotesLoadingInProgress', false)
if (err?.response?.status === 304) {
console.log('[fetchNotes] 304 Not Modified - no changes')
store.commit('setSyncLastModified', err.response.headers['last-modified'])
return null
} else {
console.error('[fetchNotes] Error:', err)
handleSyncError(t('notes', 'Fetching notes has failed.'), err)
throw err
}
}
}
export const searchNotes = async (searchQuery, chunkSize = 50, chunkCursor = null) => {
console.log('[searchNotes] Called with query:', searchQuery, 'chunkSize:', chunkSize, 'cursor:', chunkCursor)
try {
// Signal start of loading
store.commit('setNotesLoadingInProgress', true)
// Build search parameters
const params = new URLSearchParams()
params.append('search', searchQuery)
params.append('exclude', 'content') // Exclude heavy content field
params.append('chunkSize', chunkSize.toString())
if (chunkCursor) {
params.append('chunkCursor', chunkCursor)
}
const url = generateUrl('/apps/notes/api/v1/notes' + (params.toString() ? '?' + params.toString() : ''))
console.log('[searchNotes] Requesting:', url)
const response = await axios.get(url)
console.log('[searchNotes] Response received, status:', response.status)
// Backend returns array of notes directly
const notes = Array.isArray(response.data) ? response.data : []
const noteIds = notes.map(note => note.id)
// Cursor is in response headers, not body
const nextCursor = response.headers['x-notes-chunk-cursor'] || null
const isLastChunk = !nextCursor
console.log('[searchNotes] Processed:', notes.length, 'notes, cursor:', nextCursor)
// For search, we want to replace notes on first chunk, then append on subsequent chunks
if (chunkCursor) {
// Subsequent chunk - use incremental update
console.log('[searchNotes] Using incremental update for subsequent chunk')
store.dispatch('updateNotesIncremental', { notes, isLastChunk })
} else {
// First chunk - replace with search results
console.log('[searchNotes] Using full update for first chunk')
store.dispatch('updateNotes', { noteIds, notes })
}
store.commit('setNotesLoadingInProgress', false)
console.log('[searchNotes] Completed successfully')
return {
noteIds,
chunkCursor: nextCursor,
isLastChunk,
}
} catch (err) {
store.commit('setNotesLoadingInProgress', false)
console.error('[searchNotes] Error:', err)
handleSyncError(t('notes', 'Searching notes has failed.'), err)
throw err
}
}
export const fetchNote = noteId => {
return axios
.get(url('/notes/' + noteId))
.then(response => {
const localNote = store.getters.getNote(parseInt(noteId))
// only overwrite if there are no unsaved changes
if (!localNote || !localNote.unsaved) {
_updateLocalNote(response.data)
}
return response.data
})
.catch(err => {
if (err?.response?.status === 404) {
throw err
} else {
console.error(err)
const msg = t('notes', 'Fetching note {id} has failed.', { id: noteId })
store.commit('setNoteAttribute', { noteId, attribute: 'error', value: true })
store.commit('setNoteAttribute', { noteId, attribute: 'errorType', value: msg })
return store.getter.getNote(noteId)
}
})
}
export const refreshNote = (noteId, lastETag) => {
const headers = {}
if (lastETag) {
headers['If-None-Match'] = lastETag
}
const note = store.getters.getNote(noteId)
const oldContent = note.content
return axios
.get(
url('/notes/' + noteId),
{ headers },
)
.then(response => {
if (note.conflict) {
store.commit('setNoteAttribute', { noteId, attribute: 'conflict', value: response.data })
return response.headers.etag
}
const currentContent = store.getters.getNote(noteId).content
store.commit('setNoteAttribute', { noteId, attribute: 'internalPath', value: response.data.internalPath })
// only update if local content has not changed
if (oldContent === currentContent) {
_updateLocalNote(response.data)
return response.headers.etag
}
return null
})
.catch(err => {
if (err?.response?.status === 304 || note.deleting) {
// ignore error if note is deleting or not changed
return null
} else if (err?.code === 'ECONNABORTED') {
// ignore cancelled request
console.debug('Refresh Note request was cancelled.')
return null
} else {
console.error(err)
handleSyncError(t('notes', 'Refreshing note {id} has failed.', { id: noteId }), err)
}
return null
})
}
export const setTitle = (noteId, title) => {
return axios
.put(url('/notes/' + noteId + '/title'), { title })
.then(response => {
store.commit('setNoteAttribute', { noteId, attribute: 'title', value: response.data.title })
// need to update the internal path as well since sharing sidebar uses it
store.commit('setNoteAttribute', { noteId, attribute: 'internalPath', value: response.data?.internalPath })
})
.catch(err => {
console.error(err)
handleSyncError(t('notes', 'Renaming note {id} has failed.', { id: noteId }), err)
throw err
})
}
export const createNote = (category, title, content) => {
return axios
.post(url('/notes'), {
category: category || '',
content: content || '',
title: title || '',
})
.then(response => {
_updateLocalNote(response.data)
return response.data
})
.catch(err => {
console.error(err)
handleSyncError(t('notes', 'Creating new note has failed.'), err)
throw err
})
}
function _updateLocalNote(note, reference) {
if (reference === undefined) {
reference = copyNote(note, {})
}
store.commit('updateNote', note)
store.commit('setNoteAttribute', { noteId: note.id, attribute: 'reference', value: reference })
}
function _updateNote(note) {
const requestOptions = { headers: { 'If-Match': '"' + note.etag + '"' } }
return axios
.put(url('/notes/' + note.id), { content: note.content }, requestOptions)
.then(response => {
note.saveError = false
store.commit('setNoteAttribute', { noteId: note.id, attribute: 'conflict', value: undefined })
const updated = response.data
if (updated.content === note.content) {
// everything is fine
// => update note with remote data
_updateLocalNote(
{ ...updated, unsaved: false },
)
} else {
// content has changed locally in the meanwhile
// => merge note, but exclude content
_updateLocalNote(
copyNote(updated, note, ['content']),
copyNote(updated, {}),
)
}
})
.catch(err => {
if (err?.response?.status === 412) {
// ETag does not match, try to merge changes
note.saveError = false
store.commit('setNoteAttribute', { noteId: note.id, attribute: 'conflict', value: undefined })
const reference = note.reference
const remote = err.response.data
if (remote.content === note.content) {
// content is already up-to-date
// => update note with remote data
_updateLocalNote(
{ ...remote, unsaved: false },
)
} else if (remote.content === reference.content) {
// remote content has not changed
// => use all other attributes and sync again
_updateLocalNote(
copyNote(remote, note, ['content']),
copyNote(remote, {}),
)
queueCommand(note.id, 'content')
} else {
console.info('Note update conflict. Manual resolution required.')
store.commit('setNoteAttribute', { noteId: note.id, attribute: 'conflict', value: remote })
}
} else {
store.commit('setNoteAttribute', { noteId: note.id, attribute: 'saveError', value: true })
console.error(err)
handleSyncError(t('notes', 'Saving note {id} has failed.', { id: note.id }), err)
}
})
}
export const conflictSolutionLocal = note => {
note.etag = note.conflict.etag
_updateLocalNote(
copyNote(note.conflict, note, ['content']),
copyNote(note.conflict, {}),
)
store.commit('setNoteAttribute', { noteId: note.id, attribute: 'conflict', value: undefined })
queueCommand(note.id, 'content')
}
export const conflictSolutionRemote = note => {
_updateLocalNote(
{ ...note.conflict, unsaved: false },
)
store.commit('setNoteAttribute', { noteId: note.id, attribute: 'conflict', value: undefined })
}
export const autotitleNote = noteId => {
return axios
.put(url('/notes/' + noteId + '/autotitle'))
.then((response) => {
store.commit('setNoteAttribute', { noteId, attribute: 'title', value: response.data })
refreshNote(noteId)
})
.catch(err => {
console.error(err)
handleSyncError(t('notes', 'Updating title for note {id} has failed.', { id: noteId }), err)
})
}
export const undoDeleteNote = (note) => {
return axios
.post(url('/notes/undo'), note)
.then(response => {
_updateLocalNote(response.data)
return response.data
})
.catch(err => {
console.error(err)
handleSyncError(t('notes', 'Undo delete has failed for note {title}.', { title: note.title }), err)
throw err
})
}
export const deleteNote = async (noteId, onNoteDeleted) => {
store.commit('setNoteAttribute', { noteId, attribute: 'deleting', value: 'deleting' })
try {
await axios.delete(url('/notes/' + noteId))
} catch (err) {
console.error(err)
handleSyncError(t('notes', 'Deleting note {id} has failed.', { id: noteId }), err)
}
// remove note always since we don't know when exactly the error happened
// (note could be deleted on server even if an error was thrown)
onNoteDeleted()
store.commit('removeNote', noteId)
}
export const setFavorite = (noteId, favorite) => {
return axios
.put(url('/notes/' + noteId + '/favorite'), { favorite })
.then(response => {
store.commit('setNoteAttribute', { noteId, attribute: 'favorite', value: response.data })
})
.catch(err => {
console.error(err)
handleSyncError(t('notes', 'Toggling favorite for note {id} has failed.', { id: noteId }), err)
throw err
})
}
export const setCategory = (noteId, category) => {
return axios
.put(url('/notes/' + noteId + '/category'), { category })
.then(response => {
const realCategory = response.data
if (category !== realCategory) {
handleSyncError(t('notes', 'Updating the note\'s category has failed. Is the target directory writable?'))
}
store.commit('setNoteAttribute', { noteId, attribute: 'category', value: realCategory })
})
.catch(err => {
console.error(err)
handleSyncError(t('notes', 'Updating the category for note {id} has failed.', { id: noteId }), err)
throw err
})
}
export const queueCommand = (noteId, type) => {
store.commit('addToQueue', { noteId, type })
_processQueue()
}
function _processQueue() {
const queue = Object.values(store.state.sync.queue)
if (store.state.app.isSaving || queue.length === 0) {
return
}
store.commit('setSaving', true)
store.commit('clearQueue')
async function _executeQueueCommands() {
for (const cmd of queue) {
try {
switch (cmd.type) {
case 'content':
await _updateNote(store.state.notes.notesIds[cmd.noteId])
break
case 'autotitle':
await autotitleNote(cmd.noteId)
break
default:
console.error('Unknown queue command: ' + cmd.type)
}
} catch (e) {
console.error('Command has failed with error:')
console.error(e)
}
}
store.commit('setSaving', false)
store.commit('setManualSave', false)
_processQueue()
}
_executeQueueCommands()
}
export const saveNoteManually = (noteId) => {
store.commit('setNoteAttribute', { noteId, attribute: 'saveError', value: false })
store.commit('setManualSave', true)
queueCommand(noteId, 'content')
}
export const noteExists = (noteId) => {
return store.getters.noteExists(noteId)
}
export const getCategories = (maxLevel, details) => {
const categories = store.getters.getCategories(maxLevel, details)
if (maxLevel === 0) {
return [...new Set([...categories, ...store.state.notes.categories])]
} else {
return categories
}
}