-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathNotesService.js
More file actions
450 lines (421 loc) · 12.7 KB
/
NotesService.js
File metadata and controls
450 lines (421 loc) · 12.7 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
import axios from '@nextcloud/axios'
import { getCurrentUser } from '@nextcloud/auth'
import { generateUrl, generateRemoteUrl } 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 = () => {
const lastETag = store.state.sync.etag
const lastModified = store.state.sync.lastModified
const headers = {}
if (lastETag) {
headers['If-None-Match'] = lastETag
}
return axios
.get(
url('/notes' + (lastModified ? '?pruneBefore=' + lastModified : '')),
{ headers },
)
.then(response => {
store.commit('setSettings', response.data.settings)
if (response.data.categories) {
store.commit('setCategories', response.data.categories)
}
if (response.data.noteIds && response.data.notesData) {
store.dispatch('updateNotes', { noteIds: response.data.noteIds, notes: response.data.notesData })
}
if (response.data.errorMessage) {
showError(t('notes', 'Error from Nextcloud server: {msg}', { msg: response.data.errorMessage }))
} else {
store.commit('setSyncETag', response.headers.etag)
store.commit('setSyncLastModified', response.headers['last-modified'])
}
return response.data
})
.catch(err => {
if (err?.response?.status === 304) {
store.commit('setSyncLastModified', err.response.headers['last-modified'])
return null
} else {
console.error(err)
handleSyncError(t('notes', 'Fetching 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
// 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 })
})
.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 })
})
.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 findCategory = (categoryName) => {
return axios
.get(generateRemoteUrl(`dav/files/${getCurrentUser().uid}/${store.state.app.settings.notesPath}/${categoryName}`))
.then(response => {
return categoryName
})
.catch(err => {
if (err?.response?.status === 404) {
return false
} else {
console.error(err)
handleSyncError(t('notes', 'Fetching category {name} has failed.', { name: categoryName }), err)
throw err
}
})
}
export const createCategory = (categoryName) => {
// Axios MKCOL workaround: https://github.com/axios/axios/issues/2220
return axios
.request({
url: generateRemoteUrl(`dav/files/${getCurrentUser().uid}/${store.state.app.settings.notesPath}/${categoryName}`),
method: 'MKCOL',
})
.then(response => {
store.commit('addCategory', categoryName)
return categoryName
})
.catch(err => {
console.error(err)
handleSyncError(t('notes', 'Creating new category {name} has failed.', { name: categoryName }), 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
}
}