Coverage for plugin/legacy.py: 90.8%
1234 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-28 02:31 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-28 02:31 +0000
1"""Legacy argument translation and result projection over shared domain services."""
2import base64
3import binascii
4import copy
5import html
6import os
7import re
8import time
10from . import compat, util
11from .media import MediaTransaction
12from .protocol import ApiError, Deferred, epoch_seconds
13from .services import (RATINGS, KINDS, MEDIA_ILLEGAL_CHARACTERS, LEGACY_SKIP_CLOZE, PRESET_ENUMS,
14 entity_id, interval, native_preset_enum, preset_enum_value)
16EMPTY_NOTE = 'cannot create note because it is empty'
17MEDIA_KINDS = ('audio', 'video', 'picture')
18MEDIA_SIZE_LIMIT = 64 * 1024 * 1024
21def integer(value):
22 """Accept decimal strings without rounding numbers or interpreting truthiness."""
23 if isinstance(value, str) and re.fullmatch(r'[+-]?[0-9]{1,19}', value.strip()):
24 return int(value)
25 if type(value) is float and value.is_integer() and abs(value) <= 9007199254740991:
26 return int(value)
27 return value
30def decode_base64(value):
31 """Decode like the historical server, also accepting omitted '=' padding."""
32 try:
33 return base64.b64decode(value)
34 except binascii.Error:
35 if not isinstance(value, str): 35 ↛ 36line 35 didn't jump to line 36 because the condition on line 35 was never true
36 raise
37 # b64decode discards non-alphabet characters, so pad by the kept count.
38 missing = -len(re.sub(r'[^A-Za-z0-9+/]', '', value)) % 4
39 if missing not in (1, 2):
40 raise
41 return base64.b64decode(value + '=' * missing)
44def review_ease(rating):
45 """The legacy 1-4 ease of a review rating; 0 for reviews without one."""
46 return RATINGS.index(rating) + 1 if rating else 0
49def is_missing(error):
50 """Whether a native or API error reports a missing entity."""
51 return compat.is_not_found(error) or isinstance(error, ApiError) and error.kind == 'notFound'
54def legacy_request(request):
55 """Normalize only the legacy envelope, shared by HTTP and nested dispatch."""
56 if not isinstance(request, dict): 56 ↛ 57line 56 didn't jump to line 57 because the condition on line 56 was never true
57 raise ApiError('invalidParams', 'Legacy requests must be objects.')
58 request = dict(request)
59 version = integer(request.get('version')) if request.get('version') is not None else 4
60 if type(version) is not int: 60 ↛ 61line 60 didn't jump to line 61 because the condition on line 60 was never true
61 raise ApiError('invalidParams', 'version must be an integer.')
62 request['version'] = version
63 params = request.get('params')
64 if params is None or params == []:
65 params = {}
66 if not isinstance(params, dict):
67 raise ApiError('invalidParams', 'params must be an object.')
68 request['params'] = dict(params)
69 return request
72class Accepted:
73 def __init__(self, value, pending, project=lambda value: value):
74 self.value, self.pending, self.project = value, pending, project
77class Legacy:
78 def __init__(self, owner, service=None):
79 self.owner, self.runtime = owner, owner.runtime
80 self.service = service
81 self.media_transaction = None
83 def ensure_service(self):
84 """The shared services, bound to the active collection on first use."""
85 if self.service is None:
86 self.service = self.runtime.service()
87 return self.service
89 @staticmethod
90 def boolean(value, default, label):
91 if value is None:
92 return default
93 if isinstance(value, str):
94 value = {'true': True, 'false': False, '1': True, '0': False}.get(value.strip().lower(), value)
95 if type(value) is int and value in (0, 1):
96 value = bool(value)
97 if type(value) is not bool:
98 raise ApiError('invalidParams', label + ' must be boolean')
99 return value
101 @staticmethod
102 def array(value):
103 return [] if value is None else value if isinstance(value, list) else [value]
105 @staticmethod
106 def identifier(value):
107 value = integer(value)
108 # Queries and direct native calls also consume legacy IDs, so validate
109 # before constructing a search or allowing Qt guards to inspect them.
110 if type(value) is not int:
111 raise ApiError('invalidParams', 'Expected a positive signed 64-bit decimal ID.')
112 entity_id(str(value))
113 return value
115 @classmethod
116 def normalize_params(cls, name, params):
117 """Keep coercion at the compatibility boundary, before guards and services."""
118 p = dict(params)
119 note_lists = name in ('addNotes', 'canAddNotes', 'canAddNotesWithErrorDetail')
120 for key in ('cards', 'notes', 'decks', 'modelIds', 'modelNames', 'easeFactors',
121 'keys', 'newValues', 'answers', 'inOrderFields', 'cardTemplates'):
122 if key in p and not (name == 'notesInfo' and key == 'notes' and p[key] is None):
123 p[key] = cls.array(p[key])
124 for key in ('cards', 'modelIds', 'notes'):
125 if key in p and p[key] is not None and not (key == 'notes' and note_lists):
126 p[key] = [cls.identifier(value) for value in p[key]]
127 for key in ('card', 'note', 'deckId', 'modelId', 'configId', 'cloneFrom', 'ease', 'index', 'fontSize', 'startID'):
128 if key in p:
129 p[key] = integer(p[key])
130 if 'easeFactors' in p:
131 p['easeFactors'] = [integer(value) for value in p['easeFactors']]
132 if name == 'setDueDate' and type(p.get('days')) is int:
133 p['days'] = str(p['days'])
134 defaults = {'cardsToo': False, 'deleteExisting': True, 'add': True, 'warning_check': False,
135 'suspend': True, 'complete': False, 'isCloze': False, 'front': True, 'back': True,
136 'append': False, 'includeSched': False, 'wholeCollection': True}
137 if name == 'findAndReplaceInModels':
138 defaults['css'] = True
139 for key, default in defaults.items():
140 if key in p:
141 p[key] = cls.boolean(p[key], default, key)
142 if name == 'cardsInfo' and p.get('fields') is not None:
143 p['fields'] = cls.array(p['fields'])
144 if name == 'apiReflect':
145 if p.get('scopes') is None:
146 p['scopes'] = []
147 for key in ('scopes', 'actions'):
148 if isinstance(p.get(key), str):
149 p[key] = cls.array(p[key])
150 if isinstance(p.get('note'), dict):
151 p['note'] = cls.normalize_note(p['note'])
152 if note_lists and 'notes' in p:
153 p['notes'] = [cls.normalize_note(note) if isinstance(note, dict) else note for note in p['notes']]
154 if name == 'answerCards':
155 p['answers'] = [{**answer, **{key: integer(answer[key]) for key in ('cardId', 'ease') if key in answer}}
156 if isinstance(answer, dict) else answer for answer in p['answers']]
157 return p
159 @classmethod
160 def normalize_note(cls, note):
161 note = dict(note)
162 if 'id' in note:
163 note['id'] = integer(note['id'])
164 # Null optional settings mean the same thing as omitted settings.
165 if note.get('options') is None:
166 note['options'] = {}
167 options = note['options']
168 if isinstance(options, dict): 168 ↛ 176line 168 didn't jump to line 176 because the condition on line 168 was always true
169 options = note['options'] = dict(options)
170 scoped = options.get('duplicateScopeOptions')
171 if scoped is None:
172 scoped = {}
173 if isinstance(scoped, dict): 173 ↛ 175line 173 didn't jump to line 175 because the condition on line 173 was always true
174 scoped = dict(scoped)
175 options['duplicateScopeOptions'] = scoped
176 for kind in MEDIA_KINDS:
177 if note.get(kind):
178 entries = []
179 for entry in cls.array(note[kind]):
180 if isinstance(entry, dict): 180 ↛ 184line 180 didn't jump to line 184 because the condition on line 180 was always true
181 entry = dict(entry)
182 # Historical attachments passed a missing flag through as falsy and renamed on collision.
183 entry['deleteExisting'] = cls.boolean(entry.get('deleteExisting'), False, 'deleteExisting')
184 entries.append(entry)
185 note[kind] = entries
186 return note
188 @staticmethod
189 def field_name(name, names):
190 if name in names:
191 return name
192 matches = [value for value in names if isinstance(name, str) and value.lower() == name.strip().lower()]
193 if len(matches) > 1: 193 ↛ 194line 193 didn't jump to line 194 because the condition on line 193 was never true
194 raise ApiError('compatibilityError', 'Ambiguous field name.')
195 return matches[0] if matches else None
197 @classmethod
198 def fields(cls, values, names):
199 if values is None:
200 values = {}
201 if not isinstance(values, dict): 201 ↛ 202line 201 didn't jump to line 202 because the condition on line 201 was never true
202 raise ApiError('invalidParams', 'Fields must be provided as a dictionary')
203 result = {}
204 for key, value in values.items():
205 actual = cls.field_name(key, names)
206 if actual is not None:
207 if actual in values and key != actual:
208 continue
209 value = '' if value is None else value
210 # JSON scalars become their text, as Gson-based clients send them.
211 if type(value) is bool:
212 value = 'true' if value else 'false'
213 elif type(value) in (int, float):
214 value = str(value)
215 elif not isinstance(value, str):
216 raise ApiError('invalidParams', 'Field values must be strings: ' + actual)
217 if actual in result and result[actual] != value:
218 raise ApiError('compatibilityError', 'Ambiguous field name.')
219 result[actual] = value
220 return result
222 @classmethod
223 def media_targets(cls, entry, fields):
224 actual = (cls.field_name(field, fields) for field in cls.array(entry.get('fields')))
225 return list(dict.fromkeys(name for name in actual if name is not None))
227 def era_scheduler(self):
228 """The v1/v2 scheduler, when this release or collection has no v3 scheduler.
230 Legacy actions predate v3, so they answer and describe cards the way
231 Anki-Connect did on those schedulers.
232 """
233 col = self.ensure_service().col
234 if self.runtime.capability_reason('scheduling.answer', col) is None: 234 ↛ 236line 234 didn't jump to line 236 because the condition on line 234 was always true
235 return None
236 return col.sched if callable(getattr(col.sched, 'answerCard', None)) else None
238 def next_reviews(self, card_id):
239 sched = self.era_scheduler()
240 if sched is None: 240 ↛ 243line 240 didn't jump to line 243 because the condition on line 240 was always true
241 prediction = self.s('scheduling.predict', cardId=str(card_id))
242 return [item['label'] for item in prediction['answers']]
243 card = self.service.card(str(card_id))
244 return [sched.nextIvlStr(card, ease, True) for ease in range(1, sched.answerButtons(card) + 1)]
246 def answer_card(self, card_id, ease):
247 sched = self.era_scheduler()
248 if sched is None: 248 ↛ 252line 248 didn't jump to line 252 because the condition on line 248 was always true
249 prediction = self.s('scheduling.predict', cardId=str(card_id))
250 self.s('scheduling.answer', cardId=str(card_id), rating=RATINGS[ease - 1], stateToken=prediction['stateToken'])
251 return
252 card = self.service.card(str(card_id))
253 if card.queue < 0 or card.queue == 4 or ease > sched.answerButtons(card):
254 raise ApiError('invalidState', 'This card cannot be answered outside the reviewer.')
255 if self.runtime.active_reviewer_card == card.id:
256 raise ApiError('invalidState', 'Use reviewer.answer for the active GUI card.')
257 # These schedulers answer from queues that reset() builds.
258 sched.reset()
259 card.start_timer()
260 sched.answerCard(card, ease)
261 # These schedulers report no changes; refresh every screen afterwards.
262 self.runtime.full_reset_required = True
263 self.runtime.invalidate_predictions()
265 def era_preset_action(self, name, p):
266 """Releases before 2.1.45 edit presets through their JSON dictionaries."""
267 decks = self.service.col.decks
268 # Missing ids return the Default preset from get_config.
269 known = {config['id']: config for config in decks.all_config()}
270 try:
271 if name == 'setDeckConfigId':
272 config = known.get(int(p['configId']))
273 targets = [decks.get(int(self.s('decks.get', deck=self.ref(deck))['id'])) for deck in p['decks']]
274 if config is None or any(deck.get('dyn') for deck in targets):
275 return False
276 for deck in targets:
277 decks.setConf(deck, config['id'])
278 elif name == 'cloneDeckConfigId':
279 source = known.get(int(p['cloneFrom']))
280 return False if source is None else int(decks.confId(p['name'], source))
281 elif name == 'removeDeckConfigId':
282 if int(p['configId']) == 1 or int(p['configId']) not in known:
283 return False
284 decks.remConf(int(p['configId']))
285 else:
286 config = p['config']
287 if not isinstance(config, dict) or int(config['id']) not in known:
288 return False
289 self.preset_patch(config, raw=True)
290 # Clients round-trip configs without mod/usn, which 2.1.24-2.1.44 backends require.
291 stored = known[int(config['id'])]
292 decks.updateConf({**{key: stored[key] for key in ('mod', 'usn') if key in stored}, **copy.deepcopy(config)})
293 except Exception:
294 return False
295 self.service.change(None)
296 return True
298 def s(self, method, **params):
299 self.ensure_service()
300 notes = [params['note']] if isinstance(params.get('note'), dict) else params.get('notes', [])
301 flags = [isinstance(note, dict) and note.get(LEGACY_SKIP_CLOZE) for note in notes]
302 if any(flags):
303 params = dict(params)
304 stripped = [{key: value for key, value in note.items() if key != LEGACY_SKIP_CLOZE} for note in notes]
305 params.update({'note': stripped[0]} if 'note' in params else {'notes': stripped})
306 try:
307 validated = self.runtime.dispatcher.params(method, params)
308 # Reattach legacy-only options after public schema validation.
309 for note, flag in zip([validated['note']] if 'note' in validated and any(flags) else validated.get('notes', []), flags):
310 if flag:
311 note[LEGACY_SKIP_CLOZE] = True
312 return self.service.execute(method, validated)
313 except ApiError as error:
314 if error.kind == 'notFound':
315 # Resolve only on failure, so a missing entity keeps its legacy
316 # wording without disguising unrelated service failures.
317 source = params.get('note', params)
318 for key, kind in (('noteType', 'noteType'), ('deck', 'deck')):
319 if key in source:
320 self.resolve(source[key], kind)
321 if method in ('notes.get', 'notes.update'):
322 raise ApiError(error.kind, 'Note was not found: ' + params['id'], error.details) from error
323 if method == 'cards.get':
324 raise ApiError(error.kind, 'Card was not found: ' + params['id'], error.details) from error
325 if error.kind == 'validationFailed' and error.details: 325 ↛ 326line 325 didn't jump to line 326 because the condition on line 325 was never true
326 message = self.validation_error(error.details)
327 if message:
328 raise ApiError(error.kind, message, error.details) from error
329 if method == 'noteTypes.create' and error.kind == 'conflict': 329 ↛ 330line 329 didn't jump to line 330 because the condition on line 329 was never true
330 raise ApiError(error.kind, 'Model name already exists', error.details) from error
331 raise
333 def resolve(self, reference, kind):
334 try:
335 return self.service.resolve(reference, kind)
336 except ApiError as error:
337 if error.kind == 'notFound': 337 ↛ 341line 337 didn't jump to line 341 because the condition on line 337 was always true
338 label = 'model' if kind == 'noteType' else 'deck'
339 value = reference.get('name', reference.get('id'))
340 raise ApiError(error.kind, label + ' was not found: ' + str(value), error.details) from error
341 raise
343 @staticmethod
344 def validation_error(validation):
345 messages = {
346 'emptyFirstField': EMPTY_NOTE,
347 'duplicate': 'cannot create note because it is a duplicate',
348 'emptyQuestions': 'The field values you have provided would make an empty question on all cards.',
349 'missingCloze': 'cannot create note for unknown reason',
350 'notClozeNoteType': 'cannot create note for unknown reason',
351 'notClozeField': 'cannot create note for unknown reason',
352 }
353 # Legacy note creation reported the first failure. In particular, an
354 # empty first field must not be mistaken for a duplicate by clients.
355 issues = validation.get('issues', [])
356 if issues:
357 return messages.get(issues[0]['type'], issues[0]['message'])
358 for item in validation.get('items', []): 358 ↛ 363line 358 didn't jump to line 363 because the loop on line 358 didn't complete
359 details = item.get('error', {}).get('data', {}).get('details', item)
360 message = Legacy.validation_error(details)
361 if message: 361 ↛ 358line 361 didn't jump to line 358 because the condition on line 361 was always true
362 return message
363 return None
365 def ids(self, values):
366 return [str(value) for value in values]
368 def ref(self, name):
369 return {'name': name}
371 def unwrap(self, value, missing=False):
372 values = []
373 for item in value['items']:
374 if 'error' in item:
375 if missing and item['error'].get('data', {}).get('type') == 'notFound':
376 values.append(None)
377 else:
378 error = item['error']
379 raise ApiError(error.get('data', {}).get('type', 'internalError'), error['message'],
380 error.get('data', {}).get('details'))
381 else:
382 values.append(item['result'])
383 return values
385 def all_pages(self, method, **params):
386 result, cursor = [], None
387 while True:
388 page = self.s(method, **params, **({'cursor': cursor} if cursor else {}))
389 result.extend(page.get('ids', page.get('items', [])))
390 cursor = page['nextCursor']
391 if not cursor:
392 return result
394 def native_search(self, kind, query):
395 # Unlike paginated v1 searches, legacy results keep Anki's native order.
396 col = self.ensure_service().col
397 try:
398 return [int(id) for id in (col.find_notes if kind == 'notes' else col.find_cards)(query)]
399 except Exception as error:
400 raise ApiError('invalidSearch', str(error)) from error
402 def model(self, name=None, id=None):
403 # Compatibility projections are snapshots, never a writable alternate service.
404 self.ensure_service()
405 return self.resolve({'id': str(id)} if id is not None else self.ref(name), 'noteType')
407 @staticmethod
408 def normalize_tags(tags):
409 if tags is None:
410 return []
411 entries = [tags] if isinstance(tags, str) else tags
412 if not isinstance(entries, list) or any(tag is not None and not isinstance(tag, str) for tag in entries):
413 raise ApiError('invalidParams', 'Must provide tags as a list of strings')
414 # Use Anki's whitespace-separated tag convention for both input forms.
415 return list(dict.fromkeys(tag for entry in entries if entry is not None for tag in entry.split()))
417 @staticmethod
418 def require_note_names(source):
419 for key, label in (('modelName', 'Model'), ('deckName', 'Deck')):
420 if isinstance(source, dict) and key not in source:
421 raise ApiError('invalidParams', label + ' name is required')
423 def note_error(self, validation, source):
424 message = self.validation_error(validation)
425 if message != EMPTY_NOTE or not isinstance(source.get('fields'), dict):
426 return message
427 # Unmatched field names are dropped, which usually leaves the note empty.
428 try:
429 model = self.model(source['modelName'])
430 except ApiError:
431 return message
432 names = [field['name'] for field in model['flds']]
433 unknown = [key for key in source['fields'] if self.field_name(key, names) is None]
434 if not unknown:
435 return message
436 return '{} (unknown fields for model "{}": {})'.format(
437 message, model['name'], ', '.join('"{}"'.format(key) for key in unknown))
439 def created_note(self, source, pure=False):
440 self.require_note_names(source)
441 source = self.normalize_note(source)
442 model = self.model(source['modelName'])
443 self.resolve(self.ref(source['deckName']), 'deck')
444 # Native notes have every model field, including omitted media targets.
445 fields = {field['name']: '' for field in model['flds']}
446 fields.update(self.fields(source.get('fields'), fields))
447 options = source.get('options', {})
448 scoped = options.get('duplicateScopeOptions', {})
449 for key, values, label in (('allowDuplicate', options, 'allowDuplicate'),
450 ('checkChildren', scoped, 'duplicateScopeOptions.checkChildren'),
451 ('checkAllModels', scoped, 'duplicateScopeOptions.checkAllModels')):
452 if key in values:
453 values[key] = self.boolean(values[key], False, 'option parameter "' + label + '"')
454 scope = 'deck' if options.get('duplicateScope') == 'deck' else 'collection'
455 duplicates = {'allow': options.get('allowDuplicate', False), 'scope': scope,
456 'includeChildren': scoped.get('checkChildren', False),
457 'acrossNoteTypes': scoped.get('checkAllModels', False)}
458 # The historical deck/all-model duplicate path checked only the first
459 # field, while the default path used Anki's full field check.
460 skip_cloze = scope == 'deck' or duplicates['acrossNoteTypes']
461 if scope == 'deck':
462 deck_name = scoped.get('deckName')
463 duplicates['deck'] = self.ref(source['deckName'] if deck_name is None else deck_name)
464 if deck_name is not None:
465 try:
466 self.service.resolve(duplicates['deck'], 'deck')
467 except ApiError as error:
468 if error.kind != 'notFound': 468 ↛ 469line 468 didn't jump to line 469 because the condition on line 468 was never true
469 raise
470 # Historically, a missing scope deck cannot contain duplicates.
471 duplicates = {'allow': True}
472 data = {'noteType': self.ref(source['modelName']), 'deck': self.ref(source['deckName']),
473 'fields': fields, 'tags': self.normalize_tags(source.get('tags')), 'duplicates': duplicates,
474 # Legacy creation lets Anki generate its fallback card. Rendering
475 # a blank template is not the same as a native add returning 0.
476 'rejectEmptyQuestions': False}
477 if skip_cloze:
478 data[LEGACY_SKIP_CLOZE] = True
479 if pure:
480 self.attachments(data['fields'], source, pure=True)
481 return data
483 def acquire(self, params):
484 sources = [key for key in ('data', 'path', 'url') if params.get(key)]
485 if not sources:
486 raise ApiError('invalidParams', 'You must provide a "data", "path", or "url" field.')
487 key = sources[0]
488 if key == 'data':
489 data = decode_base64(params[key])
490 elif key == 'path':
491 with open(params[key], 'rb') as file:
492 data = file.read(MEDIA_SIZE_LIMIT + 1)
493 else:
494 data = util.download(params[key], MEDIA_SIZE_LIMIT)
495 if len(data) > MEDIA_SIZE_LIMIT: 495 ↛ 496line 495 didn't jump to line 496 because the condition on line 495 was never true
496 raise ApiError('invalidParams', 'Media exceeds the size limit.')
497 return data
499 def install(self, entry, data, transaction=None):
500 if transaction is None:
501 if self.media_transaction is None: 501 ↛ 503line 501 didn't jump to line 503 because the condition on line 501 was always true
502 self.media_transaction = MediaTransaction(self.ensure_service())
503 transaction = self.media_transaction
504 skip = {'algorithm': 'md5', 'digest': entry['skipHash']} if entry.get('skipHash') else None
505 return transaction.install(self.media_name(entry['filename']), data, skip,
506 'replace' if entry.get('deleteExisting', True) else 'rename')
508 def media_name(self, filename):
509 # Anki's old writeData wrapper took the host-platform basename, then
510 # the native writer stripped illegal characters. GSM passes full paths.
511 # Sanitize before journaling; every destination is still a basename.
512 return self.service.media_filename(MEDIA_ILLEGAL_CHARACTERS.sub('', os.path.basename(filename)))
514 def stage_media(self, source, pure=False):
515 """Acquire every attachment before any install; failures become field text."""
516 staged = []
517 for kind in MEDIA_KINDS:
518 for entry in self.array(source.get(kind)):
519 if not entry: 519 ↛ 520line 519 didn't jump to line 520 because the condition on line 519 was never true
520 continue
521 try:
522 staged.append((kind, entry, None if pure else self.acquire(entry), None))
523 except Exception as error:
524 if isinstance(error, ApiError) and str(error) == 'Media exceeds the size limit.': 524 ↛ 525line 524 didn't jump to line 525 because the condition on line 524 was never true
525 raise
526 staged.append((kind, entry, None, error))
527 return staged
529 def apply_media(self, fields, staged, filename):
530 # Historical attachments append references and errors in entry order.
531 for kind, entry, data, error in staged:
532 if error is None:
533 name = filename(entry, data)
534 if name is None: 534 ↛ 535line 534 didn't jump to line 535 because the condition on line 534 was never true
535 continue
536 escaped = html.escape(name, quote=True)
537 content = '<img src="' + escaped + '">' if kind == 'picture' else '[sound:' + escaped + ']'
538 else:
539 content = html.escape(str(error), quote=False)
540 for field in self.media_targets(entry, fields):
541 fields[field] += content
543 def attachments(self, fields, source, pure=False):
544 self.apply_media(fields, self.stage_media(source, pure),
545 lambda entry, data: entry['filename'] if pure else self.install(entry, data))
547 def store_media(self, params):
548 return self.install(params, self.acquire(params))
550 def prepare_gui_media(self, fields, source):
551 session = self.runtime.session
552 def prepare(service):
553 self.service = service
554 self.attachments(fields, source)
555 return self.runtime.background(prepare, expected=session)
557 def validate(self, source):
558 try:
559 result = self.s('notes.validate', note=self.created_note(source, pure=True))
560 if not result['valid']:
561 return {'canAdd': False, 'error': self.note_error(result, source)}
562 return {'canAdd': True}
563 except Exception as error:
564 return {'canAdd': False, 'error': str(error)}
566 def add_notes(self, sources, atomic):
567 prepared = [self.created_note(source, pure=True) for source in sources]
568 validation = self.unwrap(self.s('notes.validateMany', notes=prepared))
569 invalid = [index for index, value in enumerate(validation) if not value['valid']]
570 if invalid:
571 raise ApiError('validationFailed', self.note_error(validation[invalid[0]], sources[invalid[0]]),
572 {'items': validation})
573 # Acquire every attachment before installing any file. Back up only
574 # destinations this request owns; never scan or restore unrelated media.
575 staged = [self.stage_media(source) for source in sources]
576 transaction = MediaTransaction(self.service)
577 try:
578 filenames = {id(entry): self.install(entry, data, transaction)
579 for items in staged for _, entry, data, error in items if error is None}
580 for source, data, items in zip(sources, prepared, staged):
581 data['fields'] = self.created_note(source)['fields']
582 self.apply_media(data['fields'], items, lambda entry, _: filenames[id(entry)])
583 values = self.unwrap(self.s('notes.createMany', notes=prepared, atomic=atomic))
584 transaction.commit()
585 return [int(value['noteId']) for value in values]
586 except Exception as error:
587 if transaction.committed: 587 ↛ 588line 587 didn't jump to line 588 because the condition on line 587 was never true
588 raise
589 failures = transaction.rollback()
590 if failures: 590 ↛ 591line 590 didn't jump to line 591 because the condition on line 590 was never true
591 raise ApiError('ioError', 'Media restoration failed.', {'failures': failures, 'cause': str(error)}) from error
592 raise
594 def record(self, kind, id, fields=None):
595 if kind == 'cards':
596 return self.card_info(id, fields)
597 value = self.s(kind + '.get', id=str(id))
598 model = self.model(id=value['noteType']['id'])
599 return {'noteId': int(id), 'profile': self.runtime.profile_name, 'tags': value['tags'],
600 'fields': {field['name']: {'value': value['fields'][field['name']], 'order': index} for index, field in enumerate(model['flds'])},
601 'modelName': model['name'], 'mod': int(epoch_seconds(value['modifiedAt'])),
602 'cards': [int(id) for id in value['cardIds']]}
604 def card_info(self, id, fields=None):
605 card = self.ensure_service().card(str(id))
606 result = {'cardId': card.id, 'fieldOrder': card.ord, 'ord': card.ord,
607 'factor': card.factor, 'interval': card.ivl, 'note': card.nid, 'type': card.type, 'queue': card.queue,
608 'due': card.due, 'reps': card.reps, 'lapses': card.lapses, 'left': card.left, 'mod': card.mod,
609 'flags': card.flags}
610 requested = None if fields is None else set(fields)
611 if requested is None or requested & {'fields', 'modelName', 'css'}:
612 note = card.note()
613 model = self.model(id=note.mid)
614 if requested is None or 'fields' in requested:
615 result['fields'] = {field['name']: {'value': note.fields[index], 'order': index} for index, field in enumerate(model['flds'])}
616 if requested is None or 'modelName' in requested:
617 result['modelName'] = model['name']
618 if requested is None or 'css' in requested:
619 result['css'] = model['css']
620 if requested is None or 'deckName' in requested:
621 result['deckName'] = self.resolve({'id': str(card.did)}, 'deck')['name']
622 if requested is None or requested & {'question', 'answer'}:
623 rendered = self.s('cards.render', id=str(id))
624 result.update(question=rendered['questionHtml'], answer=rendered['answerHtml'])
625 if requested is None or 'nextReviews' in requested:
626 result['nextReviews'] = self.next_reviews(id)
627 return result if requested is None else {key: value for key, value in result.items() if key in requested}
629 def gui_call(self, name, p, draft_fields=None):
630 runtime = self.runtime
631 gui = runtime.gui
632 def call(method, **params):
633 return gui.execute(method, params)
634 def accepted(method, value, final=lambda value: value, **params):
635 pending = runtime.await_value(runtime.invoke(method, runtime.dispatcher.params(method, params)))
636 return Accepted(value, pending, final)
637 if name == 'getProfiles':
638 return [value['name'] for value in gui.profiles_list()]
639 if name == 'getActiveProfile':
640 value = gui.profiles_getActive()
641 return value['name'] if value else None
642 if name == 'loadProfile':
643 if p['name'] not in self.owner.window().pm.profiles():
644 return False
645 return accepted('profiles.switch', True, lambda value: True, name=p['name'])
646 if name == 'sync':
647 runtime.require_capability('collection.sync')
648 if not self.owner.window().pm.sync_auth():
649 raise ApiError('authenticationRequired', 'sync: auth not configured')
650 return accepted('collection.sync', None, lambda value: None)
651 if name == 'reloadCollection':
652 call('collection.refresh', target='cachesAndWindows')
653 return None
654 if name == 'guiBrowse':
655 sort = p['reorderCards']
656 if sort is not None:
657 if not isinstance(sort, dict):
658 raise ApiError('invalidParams', 'reorderCards should be a dict: ' + str(sort))
659 if 'columnId' not in sort or 'order' not in sort:
660 raise ApiError('invalidParams', 'Must provide a "columnId" and a "order" property"')
661 if sort['order'] not in ('ascending', 'descending'):
662 raise ApiError('invalidParams', 'invalid card order: ' + str(sort['order']))
663 if not compat.browser_column_exists(self.ensure_service().col, sort['columnId']): 663 ↛ 665line 663 didn't jump to line 665 because the condition on line 663 was always true
664 raise ApiError('invalidParams', 'invalid columnId: ' + str(sort['columnId']))
665 sort = {'column': sort['columnId'], 'direction': sort['order']}
666 value = call('browser.open', query=p['query'], sort=sort)
667 if isinstance(value, Deferred):
668 pending = Deferred()
669 def translate(source):
670 error = source.error
671 if isinstance(error, ApiError) and str(error) == 'Browser sort column is not active.': 671 ↛ 672line 671 didn't jump to line 672 because the condition on line 671 was never true
672 error = ApiError('invalidParams', 'invalid columnId: ' + str(p['reorderCards']['columnId']))
673 pending.resolve(source.value, error)
674 value.then(translate)
675 value = pending
676 def project(_):
677 return [] if p['query'] is None else self.native_search('cards', p['query'])
678 return value.map(project) if isinstance(value, Deferred) else project(value)
679 if name in ('guiSelectNote', 'guiSelectCard'):
680 if not gui.browser():
681 return False
682 try:
683 call('browser.select', cardIds=[str(p.get('card', p.get('note')))])
684 except Exception as error:
685 if not is_missing(error): 685 ↛ 686line 685 didn't jump to line 686 because the condition on line 685 was never true
686 raise
687 # Historically a missing card only cleared the selection.
688 call('browser.select', cardIds=[])
689 return True
690 if name == 'guiSelectedNotes':
691 return [int(id) for id in call('browser.getSelection')['selectedNoteIds']]
692 if name == 'guiEditNote':
693 return accepted('editors.openNote', None, lambda value: None, noteId=str(p['note']))
694 if name == 'guiAddCards':
695 if p['note']:
696 self.require_note_names(p['note'])
697 self.s('decks.get', deck=self.ref(p['note']['deckName']))
698 note = self.created_note(p['note']) if p['note'] else None
699 session = runtime.session
700 def open_add(_=None):
701 runtime.capture(session)
702 if note:
703 note.pop('duplicates', None)
704 note.pop('rejectEmptyQuestions', None)
705 note.pop(LEGACY_SKIP_CLOZE, None)
706 return accepted('editors.openAdd', 0, lambda value: int(value['noteId'] or 0), **({'note': note} if note else {}))
707 if note and any(p['note'].get(kind) for kind in MEDIA_KINDS):
708 return self.prepare_gui_media(note['fields'], p['note']).map(open_add)
709 return open_add()
710 if name == 'guiAddNoteSetData':
711 dialog = gui.add_dialog()
712 if dialog is None:
713 return {'error': 'Add Note dialog is not open', 'code': 1}
714 source = copy.deepcopy(p['note'])
715 self.ensure_service()
716 for key, kind, label in [('deckName', 'deck', 'Deck'), ('modelName', 'noteType', 'Model')]:
717 if key in source:
718 try:
719 self.resolve(self.ref(source[key]), kind)
720 except ApiError as error:
721 if error.kind == 'notFound': 721 ↛ 723line 721 didn't jump to line 723 because the condition on line 721 was always true
722 raise ApiError(error.kind, '{} "{}" not found'.format(label, source[key])) from error
723 raise
724 if 'fields' in source: 724 ↛ 739line 724 didn't jump to line 739 because the condition on line 724 was always true
725 names = draft_fields
726 if names is None:
727 if 'modelName' in source or hasattr(dialog.editor, 'note'):
728 model = self.model(source['modelName']) if 'modelName' in source else dialog.editor.note.note_type()
729 names = [value['name'] for value in model['flds']]
730 else:
731 # Svelte keeps the selected note type in the webview.
732 # Read its draft asynchronously before matching field keys.
733 return gui.editor_record(dialog, 'add').map(
734 lambda record: self.gui_call(name, p, list(record['fields'])))
735 for field in source['fields'] or {}:
736 if self.field_name(field, names) is None:
737 raise ApiError('notFound', 'Field "' + field + '" not found in current note')
738 source['fields'] = self.fields(source['fields'], names)
739 patch = {key: value for key, value in source.items() if key in ('fields', 'tags')}
740 if 'tags' in patch:
741 patch['tags'] = self.normalize_tags(patch['tags'])
742 for old, new in [('deckName', 'deck'), ('modelName', 'noteType')]:
743 if old in source:
744 patch[new] = self.ref(source[old])
745 editor_id = gui.register(dialog, 'add')
746 session = runtime.session
747 def update(_=None):
748 runtime.capture(session)
749 return call('editors.updateDraft', editorId=editor_id, patch=patch,
750 mode='append' if p['append'] else 'replace')
751 value = (self.prepare_gui_media(patch['fields'], source).map(update)
752 if 'fields' in patch and any(source.get(kind) for kind in MEDIA_KINDS)
753 else update())
754 if isinstance(value, Deferred): 754 ↛ 763line 754 didn't jump to line 763 because the condition on line 754 was always true
755 pending = Deferred()
756 def finished(source):
757 error = source.error
758 if isinstance(error, ApiError) and str(error).startswith('Unknown field: '): 758 ↛ 759line 758 didn't jump to line 759 because the condition on line 758 was never true
759 error = ApiError(error.kind, 'Field "' + str(error)[len('Unknown field: '):] + '" not found in current note')
760 pending.resolve(True if error is None else None, error)
761 value.then(finished)
762 return pending
763 return True
764 if name in ('guiReviewActive', 'guiCurrentCard', 'guiStartCardTimer', 'guiShowQuestion',
765 'guiShowAnswer', 'guiPlayAudio', 'guiAnswerCard') and self.owner.reviewer() is None:
766 raise ApiError('invalidState', 'reviewer is not available')
767 if name == 'guiReviewActive':
768 return call('reviewer.get')['active']
769 if name == 'guiCurrentCard':
770 value = call('reviewer.get')
771 if not value['active']:
772 raise ApiError('invalidState', 'Gui review is not currently active.')
773 record = self.record('cards', value['card']['id'])
774 keep = ('cardId', 'fields', 'fieldOrder', 'question', 'answer', 'modelName', 'deckName', 'css')
775 return {**{key: record[key] for key in keep}, 'buttons': [ease for ease, _ in enumerate(value['answers'], 1)],
776 'nextReviews': [item['label'] for item in value['answers']], 'template': gui.reviewer().card.template()['name']}
777 if name in ('guiStartCardTimer', 'guiShowQuestion', 'guiShowAnswer', 'guiPlayAudio', 'guiAnswerCard'):
778 value = call('reviewer.get')
779 if not value['active']: 779 ↛ 780line 779 didn't jump to line 780 because the condition on line 779 was never true
780 return False
781 method = {'guiStartCardTimer': 'reviewer.startTimer', 'guiShowQuestion': 'reviewer.showQuestion',
782 'guiShowAnswer': 'reviewer.showAnswer', 'guiPlayAudio': 'reviewer.playAudio', 'guiAnswerCard': 'reviewer.answer'}[name]
783 if name == 'guiAnswerCard':
784 ease = p['ease']
785 # Eases number the offered buttons, which v1 learning cards limit to three.
786 if value['side'] != 'answer' or type(ease) is not int or not 1 <= ease <= len(value['answers']): 786 ↛ 787line 786 didn't jump to line 787 because the condition on line 786 was never true
787 return False
788 return accepted(method, True, lambda value: True, stateToken=value['stateToken'],
789 rating=value['answers'][ease - 1]['rating'])
790 call(method, stateToken=value['stateToken'])
791 return True
792 if name in ('guiUndo', 'guiCheckDatabase'):
793 return accepted('collection.undo' if name == 'guiUndo' else 'collection.checkIntegrity', True, lambda value: True)
794 if name == 'guiImportFile':
795 return accepted('application.importFile', None, lambda value: None, **({'path': p['path']} if p['path'] else {}))
796 if name == 'guiExitAnki':
797 call('application.exit')
798 return None
799 if name in ('guiDeckOverview', 'guiDeckReview', 'guiDeckBrowser'): 799 ↛ 808line 799 didn't jump to line 808 because the condition on line 799 was always true
800 if name != 'guiDeckBrowser':
801 try:
802 self.s('decks.get', deck=self.ref(p['name']))
803 except ApiError:
804 return False
805 call('application.navigate', view={'guiDeckOverview': 'deckOverview', 'guiDeckReview': 'review', 'guiDeckBrowser': 'deckBrowser'}[name],
806 **({'deck': self.ref(p['name'])} if name != 'guiDeckBrowser' else {}))
807 return None if name == 'guiDeckBrowser' else True
808 raise ApiError('methodNotFound', 'Unknown GUI action.')
810 def call(self, name, p):
811 """Run one action with parameters already bound by AnkiConnect.resolve_action."""
812 def success(value):
813 if self.media_transaction:
814 self.media_transaction.commit()
815 self.media_transaction = None
816 return value
817 def failure(error):
818 if self.media_transaction and not self.media_transaction.committed:
819 failures = self.media_transaction.rollback()
820 self.media_transaction = None
821 if failures: 821 ↛ 822line 821 didn't jump to line 822 because the condition on line 821 was never true
822 raise ApiError('ioError', 'Media restoration failed.', {'failures': failures}) from error
823 raise error
824 def cleanup(value=None, error=None):
825 if self.media_transaction and name.startswith('gui'):
826 try:
827 return self.runtime.background(lambda service: failure(error) if error else success(value),
828 expected=self.service.session)
829 except Exception:
830 # A profile switch can close the pinned collection before
831 # cleanup admission. Retain its journal for recovery there.
832 self.media_transaction._active.discard(self.media_transaction.path)
833 self.media_transaction = None
834 raise
835 return failure(error) if error else success(value)
836 def wrapped(value):
837 if isinstance(value, Accepted):
838 return Accepted(value.value, wrapped(value.pending), value.project)
839 if isinstance(value, Deferred):
840 pending = Deferred()
841 def finish(source):
842 try:
843 output = cleanup(error=source.error) if source.error else wrapped(source.value)
844 if isinstance(output, Deferred):
845 output.then(lambda final: pending.resolve(final.value, final.error))
846 else:
847 pending.resolve(output)
848 except Exception as error:
849 pending.resolve(error=error)
850 value.then(finish)
851 return pending
852 return cleanup(value)
853 try:
854 return wrapped(self.dispatch(name, p))
855 except Exception as error:
856 return cleanup(error=error)
858 def dispatch(self, name, p):
859 if name == 'version':
860 return util.setting('apiVersion')
861 if name == 'requestPermission':
862 return self.owner.permission(p['origin'], p['allowed'])
863 if name == 'apiReflect':
864 if not isinstance(p['scopes'], list):
865 raise ApiError('invalidParams', 'scopes has invalid value')
866 if not (p['actions'] is None or isinstance(p['actions'], list)):
867 raise ApiError('invalidParams', 'actions has invalid value')
868 if 'actions' not in p['scopes']:
869 return {'scopes': []}
870 names = p['actions'] if p['actions'] is not None else self.owner.legacy_actions()
871 return {'scopes': ['actions'], 'actions': [name for name in names if name in self.owner.legacy_actions()]}
872 if name.startswith('gui') or name in ('getProfiles', 'getActiveProfile', 'loadProfile', 'sync', 'reloadCollection'):
873 return self.gui_call(name, p)
874 if name in ('deckNames', 'deckNamesAndIds', 'modelNames', 'modelNamesAndIds'):
875 values = self.s('decks.list' if name.startswith('deck') else 'noteTypes.list')
876 return {value['name']: int(value['id']) for value in values} if name.endswith('AndIds') else [value['name'] for value in values]
877 if name in ('deckNameFromId', 'modelNameFromId'):
878 return self.s('decks.get' if name == 'deckNameFromId' else 'noteTypes.get',
879 **({'deck': {'id': str(p['deckId'])}} if name == 'deckNameFromId' else {'noteType': {'id': str(p['modelId'])}}))['name']
880 if name == 'createDeck':
881 return int(self.s('decks.create', name=p['deck'])['id'])
882 if name == 'getDecks':
883 result = {}
884 for id in p['cards']:
885 card = self.s('cards.get', id=str(id))
886 result.setdefault(card['deck']['name'], []).append(id)
887 return result
888 if name == 'changeDeck':
889 target = self.s('decks.create', name=p['deck'])
890 # Historical bulk writes ignored card IDs that do not exist.
891 self.unwrap(self.s('cards.move', ids=self.ids(p['cards']), deck={'id': target['id']}), missing=True)
892 return None
893 if name == 'deleteDecks':
894 if not p['cardsToo']:
895 raise ApiError('invalidParams', "Since Anki 2.1.28 it's not possible to delete decks without deleting cards as well")
896 existing = {value['name'] for value in self.s('decks.list')}
897 self.unwrap(self.s('decks.delete', decks=[self.ref(name) for name in p['decks'] if name in existing], deleteCards=True))
898 return None
899 if name == 'getDeckStats':
900 # Native due-tree nodes: leaf names and each deck's own card total.
901 wanted = {int(self.s('decks.create', name=deck)['id']) for deck in p['decks']}
902 result = {}
903 def collect(node):
904 if node.deck_id in wanted:
905 result[str(node.deck_id)] = {'deck_id': node.deck_id, 'name': node.name, 'new_count': node.new_count,
906 'learn_count': node.learn_count, 'review_count': node.review_count,
907 'total_in_deck': compat.deck_total(self.service.col, node)}
908 for child in node.children:
909 collect(child)
910 collect(self.service.col.sched.deck_due_tree())
911 return result
912 if name == 'getDeckConfig':
913 try:
914 deck = self.s('decks.get', deck=self.ref(p['deck']))
915 return copy.deepcopy(self.service.col.decks.get_config(int(deck['presetId'])))
916 except ApiError as error:
917 if error.kind == 'notFound': 917 ↛ 919line 917 didn't jump to line 919 because the condition on line 917 was always true
918 return False
919 raise
920 if name in ('saveDeckConfig', 'setDeckConfigId', 'cloneDeckConfigId', 'removeDeckConfigId'):
921 if self.runtime.capability_reason('deckPresets.update', self.service.col): 921 ↛ 922line 921 didn't jump to line 922 because the condition on line 921 was never true
922 return self.era_preset_action(name, p)
923 try:
924 if name == 'setDeckConfigId':
925 refs = [self.ref(deck) for deck in p['decks']]
926 for ref in refs:
927 self.s('decks.get', deck=ref)
928 self.unwrap(self.s('deckPresets.assign', decks=refs, preset={'id': str(p['configId'])}))
929 return True
930 if name == 'cloneDeckConfigId':
931 return int(self.s('deckPresets.create', name=p['name'], cloneFrom={'id': str(p['cloneFrom'])})['id'])
932 if name == 'removeDeckConfigId':
933 self.s('deckPresets.delete', preset={'id': str(p['configId'])}, replacement={'id': '1'})
934 return True
935 settings = self.preset_patch(p['config'])
936 self.s('deckPresets.update', preset={'id': str(p['config']['id'])}, name=p['config']['name'], settings=settings)
937 return True
938 except Exception:
939 return False
940 if name == 'storeMediaFile':
941 return self.store_media(p)
942 if name == 'retrieveMediaFile':
943 try:
944 return self.s('media.get', filename=os.path.basename(p['filename']))['data']
945 except ApiError as error:
946 if error.kind == 'notFound': 946 ↛ 948line 946 didn't jump to line 948 because the condition on line 946 was always true
947 return False
948 raise
949 if name == 'getMediaFilesNames':
950 return self.s('media.list', pattern=p['pattern'])
951 if name == 'deleteMediaFile':
952 try:
953 self.s('media.delete', filename=p['filename'])
954 except ApiError as error:
955 if error.kind != 'notFound': 955 ↛ 956line 955 didn't jump to line 956 because the condition on line 955 was never true
956 raise
957 return None
958 if name == 'getMediaDirPath':
959 return self.s('media.getDirectory')['path']
960 if name in ('canAddNote', 'canAddNoteWithErrorDetail', 'canAddNotes', 'canAddNotesWithErrorDetail'):
961 sources = p.get('notes', [p.get('note')])
962 result = [self.validate(source) for source in sources]
963 if not name.endswith('WithErrorDetail'):
964 result = [item['canAdd'] for item in result]
965 return result if name.startswith('canAddNotes') else result[0]
966 if name in ('addNote', 'addNotes'):
967 if name == 'addNotes':
968 prepared, indices, errors = [], [], {}
969 for index, source in enumerate(p['notes']):
970 try:
971 prepared.append(self.created_note(source, pure=True))
972 indices.append(index)
973 except Exception as error:
974 errors[index] = str(error)
975 _, failures = self.service.prepare_notes(prepared)
976 for failure in failures:
977 index = indices[failure['index']]
978 errors[index] = (self.note_error({'items': [failure]}, p['notes'][index])
979 or failure['error']['message'])
980 if errors:
981 raise ApiError('validationFailed', str([errors[index] for index in sorted(errors)]), {'items': failures})
982 try:
983 values = self.add_notes(p.get('notes', [p.get('note')]), True)
984 except Exception as error:
985 if name == 'addNotes': 985 ↛ 986line 985 didn't jump to line 986 because the condition on line 985 was never true
986 items = error.details.get('items', []) if isinstance(error, ApiError) and error.details else []
987 errors = [self.validation_error({'items': [item]}) or item.get('error', {}).get('message', str(error))
988 for item in items]
989 raise ApiError(getattr(error, 'kind', 'internalError'), str(errors or [str(error)]),
990 getattr(error, 'details', None)) from error
991 raise
992 return values if name == 'addNotes' else values[0]
993 if name in ('updateNote', 'updateNoteFields', 'updateNoteTags'):
994 source = p['note']
995 source = {'id': source, 'tags': p['tags']} if name == 'updateNoteTags' else copy.deepcopy(source)
996 patch = {}
997 if 'fields' in source or any(source.get(kind) for kind in MEDIA_KINDS):
998 current = self.s('notes.get', id=str(source['id']))
999 patch['fields'] = self.fields(source.get('fields'), current['fields'])
1000 # Attachments may target a field omitted from the text patch.
1001 for kind in MEDIA_KINDS:
1002 for entry in self.array(source.get(kind)):
1003 if entry: 1003 ↛ 1002line 1003 didn't jump to line 1002 because the condition on line 1003 was always true
1004 for field in self.media_targets(entry, current['fields']):
1005 patch['fields'].setdefault(field, current['fields'][field])
1006 if name != 'updateNoteFields' and 'tags' in source:
1007 patch['tags'] = self.normalize_tags(source['tags'])
1008 if not patch:
1009 raise ApiError('invalidParams', 'Must provide a "fields" or "tags" property.')
1010 self.runtime.dispatcher.params('notes.update', {'id': str(source['id']), 'patch': patch})
1011 if 'fields' in patch:
1012 self.attachments(patch['fields'], source)
1013 self.s('notes.update', id=str(source['id']), patch=patch)
1014 return None
1015 if name == 'updateNoteModel':
1016 source = p['note']
1017 if not source.get('id'):
1018 raise ApiError('invalidParams', 'Note ID is required')
1019 if not source.get('modelName'):
1020 raise ApiError('invalidParams', 'Model name is required')
1021 if not source.get('fields') or not isinstance(source['fields'], dict):
1022 raise ApiError('invalidParams', 'Fields must be provided as a dictionary')
1023 original = self.s('notes.get', id=str(source['id']))
1024 try:
1025 target = self.s('noteTypes.get', noteType=self.ref(source['modelName']))
1026 except ApiError as error:
1027 if error.kind == 'notFound': 1027 ↛ 1029line 1027 didn't jump to line 1029 because the condition on line 1027 was always true
1028 raise ApiError(error.kind, "Model '" + source['modelName'] + "' not found", error.details) from error
1029 raise
1030 plan = self.s('notes.planConversion', source={'id': original['noteType']['id']}, target={'id': target['id']})
1031 fields = {item['name']: '' for item in target['fields']}
1032 fields.update(self.fields(source['fields'], fields))
1033 # Historical conversion replaced tags; omitted or null tags clear them.
1034 patch = {'fields': fields, 'tags': self.normalize_tags(source.get('tags'))}
1035 # Validate content before conversion can change cards or review history.
1036 self.runtime.dispatcher.params('notes.update', {'id': str(source['id']), 'patch': patch})
1037 old = self.model(id=original['noteType']['id'])
1038 for key, mapping in [('flds', plan['fields']), ('tmpls', plan['templates'])]:
1039 names = [[item['name'] for item in old[key] if item['name'].lower() == entry['target'].lower()]
1040 for entry in mapping]
1041 for matches in names:
1042 if len(matches) > 1 or (key == 'tmpls' and not matches and len(old[key]) > 1):
1043 raise ApiError('compatibilityError', 'Explicit conversion mappings are required.')
1044 # Raw mid assignment kept cards by ordinal. A lone source template without a
1045 # namesake keeps Anki's positional mapping instead of losing its cards.
1046 if key == 'tmpls' and not any(names):
1047 continue
1048 for entry, matches in zip(mapping, names):
1049 entry['source'] = matches[0] if matches else None
1050 self.s('notes.convert', ids=[str(source['id'])], target={'id': target['id']}, fields=plan['fields'], templates=plan['templates'], planToken=plan['token'])
1051 self.s('notes.update', id=str(source['id']), patch=patch)
1052 return None
1053 if name == 'getNoteTags':
1054 return self.s('notes.get', id=str(p['note']))['tags']
1055 if name in ('addTags', 'removeTags'):
1056 tags = self.normalize_tags(p['tags'])
1057 method = 'tags.remove' if name == 'removeTags' or not p.get('add', True) else 'tags.add'
1058 self.unwrap(self.s(method, noteIds=self.ids(p['notes']), tags=tags), missing=True)
1059 return None
1060 if name == 'getTags':
1061 return self.s('tags.list')
1062 if name == 'clearUnusedTags':
1063 self.s('tags.deleteUnused')
1064 return None
1065 if name in ('replaceTags', 'replaceTagsInAllNotes'):
1066 ids = self.ids(p['notes']) if name == 'replaceTags' else None
1067 if ids is not None:
1068 ids = [value['id'] for value in self.unwrap(self.s('notes.getMany', ids=ids), missing=True) if value]
1069 self.s('tags.replace', **{'from': p['tag_to_replace'], 'to': p['replace_with_tag']},
1070 **({'noteIds': ids} if name == 'replaceTags' else {'allNotes': True}))
1071 return None
1072 if name in ('findNotes', 'findCards'):
1073 return [] if p['query'] is None else self.native_search('notes' if name == 'findNotes' else 'cards', p['query'])
1074 if name in ('notesInfo', 'cardsInfo', 'notesModTime', 'cardsModTime'):
1075 fields = p.get('fields') if name == 'cardsInfo' else None
1076 if fields is not None and (not isinstance(fields, list) or not all(isinstance(field, str) for field in fields)):
1077 raise ApiError('invalidParams', 'fields must be a list of card record field names.')
1078 kind = 'notes' if name.startswith('notes') else 'cards'
1079 ids = p.get(kind)
1080 if name == 'notesInfo' and p['query'] is not None:
1081 ids = self.native_search('notes', p['query'])
1082 if ids is None:
1083 raise ApiError('invalidParams', 'Must provide either "notes" or a "query"')
1084 result = []
1085 for id in ids:
1086 try:
1087 if name.endswith('ModTime'):
1088 native = self.service.note(str(id)) if kind == 'notes' else self.service.card(str(id))
1089 result.append({'noteId' if kind == 'notes' else 'cardId': int(id), 'mod': native.mod})
1090 else:
1091 result.append(self.record(kind, id, fields))
1092 except Exception as error:
1093 if is_missing(error): 1093 ↛ 1096line 1093 didn't jump to line 1096 because the condition on line 1093 was always true
1094 result.append({})
1095 else:
1096 raise
1097 return result
1098 if name == 'deleteNotes':
1099 self.unwrap(self.s('notes.delete', ids=self.ids(p['notes'])), missing=True)
1100 return None
1101 if name == 'removeEmptyNotes':
1102 # Historically this silently deleted every unused note type. Sync
1103 # clients call it routinely, so it now succeeds without deleting.
1104 return None
1105 if name == 'cardsToNotes':
1106 values = self.unwrap(self.s('cards.getMany', ids=self.ids(p['cards'])), missing=True)
1107 return list(dict.fromkeys(int(value['noteId']) for value in values if value))
1108 if name in ('suspend', 'unsuspend'):
1109 for id in p['cards']:
1110 self.s('cards.get', id=str(id))
1111 values = self.unwrap(self.s('cards.setSuspended', ids=self.ids(p['cards']), suspended=False if name == 'unsuspend' else p['suspend']))
1112 return None if name == 'unsuspend' else any(value['changed'] for value in values)
1113 if name in ('suspended', 'areSuspended'):
1114 if name == 'suspended':
1115 return self.s('cards.get', id=str(p['card']))['scheduling']['queue'] == 'suspended'
1116 ids = [p['card']] if name == 'suspended' else p['cards']
1117 values = self.unwrap(self.s('cards.getMany', ids=self.ids(ids)), missing=name != 'suspended')
1118 result = [value['scheduling']['queue'] == 'suspended' if value else None for value in values]
1119 return result[0] if name == 'suspended' else result
1120 if name == 'areDue':
1121 result = []
1122 cards = self.unwrap(self.s('cards.getMany', ids=self.ids(p['cards'])), missing=True)
1123 for id, card in zip(p['cards'], cards):
1124 # Anki does not show suspended or buried cards, even new ones.
1125 if card and card['scheduling']['queue'] in ('suspended', 'buriedByScheduler', 'buriedByUser'):
1126 result.append(False)
1127 elif self.all_pages('cards.search', query='cid:{} is:new'.format(id)):
1128 result.append(True)
1129 else:
1130 # Historical queries depend on the latest review, including
1131 # their IndexError when the card has no review history.
1132 date, ivl = self.service.col.db.all('select id/1000.0, ivl from revlog where cid = ?', id)[-1]
1133 result.append(bool(self.all_pages('cards.search', query='cid:{} is:due'.format(id)))
1134 if ivl >= -1200 else date - ivl <= time.time())
1135 return result
1136 if name == 'getIntervals':
1137 result = []
1138 for id in p['cards']:
1139 if self.all_pages('cards.search', query='cid:{} is:new'.format(id)):
1140 result.append(0)
1141 else:
1142 intervals = self.service.col.db.list('select ivl from revlog where cid = ?', id)
1143 result.append(intervals if p['complete'] else intervals[-1])
1144 return result
1145 if name in ('getEaseFactors', 'setEaseFactors'):
1146 if name == 'getEaseFactors':
1147 return [value['scheduling']['sm2EasePermille'] if value else None
1148 for value in self.unwrap(self.s('cards.getMany', ids=self.ids(p['cards'])), missing=True)]
1149 result = []
1150 for index, id in enumerate(p['cards']):
1151 try:
1152 self.s('cards.get', id=str(id))
1153 except ApiError as error:
1154 if error.kind != 'notFound': 1154 ↛ 1155line 1154 didn't jump to line 1155 because the condition on line 1154 was never true
1155 raise
1156 result.append(False)
1157 continue
1158 self.s('advanced.cards.update', cardId=str(id), patch={'sm2EasePermille': p['easeFactors'][index]})
1159 result.append(True)
1160 return result
1161 if name == 'setSpecificValueOfCard':
1162 return self.expert_card(p)
1163 if name in ('forgetCards', 'setDueDate', 'relearnCards', 'answerCards'):
1164 if name == 'forgetCards':
1165 self.unwrap(self.s('scheduling.reset', cardIds=self.ids(p['cards'])), missing=True)
1166 return None
1167 if name == 'setDueDate':
1168 self.unwrap(self.s('scheduling.setDueDate', cardIds=self.ids(p['cards']), days=p['days']), missing=True)
1169 return True
1170 if name == 'relearnCards':
1171 for id in p['cards']:
1172 card = self.s('cards.get', id=str(id))
1173 if card['scheduling']['queue'] != 'review' or card['homeDeck']: 1173 ↛ 1174line 1173 didn't jump to line 1174 because the condition on line 1173 was never true
1174 raise ApiError('invalidState', 'Relearning requires an unfiltered active review card.')
1175 answers = [{'cardId': id, 'ease': 1} for id in p['cards']]
1176 else:
1177 answers = p['answers']
1178 if any(answer['ease'] not in (1, 2, 3, 4) for answer in answers):
1179 raise ApiError('invalidParams', 'Invalid ease.')
1180 result = []
1181 for answer in answers:
1182 try:
1183 self.answer_card(answer['cardId'], answer['ease'])
1184 result.append(True)
1185 except Exception as error:
1186 # Missing and unanswerable cards fail individually, so one
1187 # suspended or on-screen card cannot abort a partial batch.
1188 if is_missing(error) or name == 'answerCards' and isinstance(error, ApiError) and error.kind == 'invalidState': 1188 ↛ 1191line 1188 didn't jump to line 1191 because the condition on line 1188 was always true
1189 result.append(False)
1190 else:
1191 raise
1192 return result if name == 'answerCards' else None
1193 if name.startswith('model') or name in ('createModel', 'findModelsById', 'findModelsByName', 'updateModelTemplates', 'updateModelStyling', 'findAndReplaceInModels'):
1194 return self.model_action(name, p)
1195 if name in ('getNumCardsReviewedToday', 'getNumCardsReviewedByDay', 'getCollectionStatsHTML'):
1196 if name == 'getNumCardsReviewedToday':
1197 return self.s('statistics.getToday')['count']
1198 if name == 'getNumCardsReviewedByDay':
1199 return [[value['day'], value['count']] for value in self.s('statistics.getReviewDays')]
1200 deck = None if p['wholeCollection'] else {'id': str(self.service.col.decks.selected())}
1201 return self.s('statistics.getHtml', **({'deck': deck} if deck else {}))['html']
1202 if name == 'getLatestReviewID':
1203 self.s('decks.create', name=p['deck'])
1204 return int(self.s('reviews.getLatestId', deck=self.ref(p['deck']))['id'] or 0)
1205 if name in ('cardReviews', 'getReviewsOfCards'):
1206 if name == 'cardReviews':
1207 self.s('decks.create', name=p['deck'])
1208 params = {'deck': self.ref(p['deck']), **({'afterId': str(p['startID'])} if p['startID'] else {})}
1209 else:
1210 values = self.unwrap(self.s('cards.getMany', ids=self.ids(p['cards'])), missing=True)
1211 params = {'cardIds': [value['id'] for value in values if value]}
1212 reviews = self.all_pages('reviews.list', **params)
1213 if name == 'cardReviews':
1214 return [[int(row['id']), int(row['cardId']), row['syncSequence'], review_ease(row['rating']),
1215 self.signed(row['interval']), self.signed(row['previousInterval']), row['factor']['value'], row['elapsedMs'], KINDS.index(row['kind'])] for row in reviews]
1216 result = {str(id): [] for id in p['cards']}
1217 for row in reviews:
1218 result[row['cardId']].append({'id': int(row['id']), 'usn': row['syncSequence'], 'ease': review_ease(row['rating']),
1219 'ivl': self.signed(row['interval']), 'lastIvl': self.signed(row['previousInterval']), 'factor': row['factor']['value'], 'time': row['elapsedMs'], 'type': KINDS.index(row['kind'])})
1220 return result
1221 if name == 'insertReviews':
1222 values = []
1223 for row in p['reviews']:
1224 if not isinstance(row, (list, tuple)) or len(row) != 9 or not all(type(value) is int for value in row): 1224 ↛ 1225line 1224 didn't jump to line 1225 because the condition on line 1224 was never true
1225 raise ApiError('invalidParams', 'Review rows require nine integers.')
1226 id, cid, usn, ease, ivl, last, factor, elapsed, kind = row
1227 if not 0 <= ease <= 4 or not 0 <= kind <= 5: 1227 ↛ 1228line 1227 didn't jump to line 1228 because the condition on line 1227 was never true
1228 raise ApiError('invalidParams', 'Invalid review rating/kind.')
1229 values.append({'id': str(id), 'cardId': str(cid), 'rating': RATINGS[ease - 1] if ease else None,
1230 'interval': interval(ivl), 'previousInterval': interval(last), 'factor': {'encoding': 'unknown', 'value': factor},
1231 'elapsedMs': elapsed, 'kind': KINDS[kind]})
1232 if values: 1232 ↛ 1234line 1232 didn't jump to line 1234 because the condition on line 1232 was always true
1233 self.s('advanced.reviews.import', reviews=values)
1234 return None
1235 if name == 'importPackage':
1236 with open(p['path'], 'rb'):
1237 pass
1238 self.s('packages.import', path=p['path'])
1239 return True
1240 if name == 'exportPackage': 1240 ↛ 1248line 1240 didn't jump to line 1248 because the condition on line 1240 was always true
1241 try:
1242 self.s('packages.export', deck=self.ref(p['deck']), path=p['path'], includeScheduling=p['includeSched'])
1243 return True
1244 except ApiError as error:
1245 if error.kind == 'notFound': 1245 ↛ 1247line 1245 didn't jump to line 1247 because the condition on line 1245 was always true
1246 return False
1247 raise
1248 raise ApiError('methodNotFound', 'Unsupported legacy action: ' + name)
1250 def signed(self, value):
1251 return -value['value'] if value['unit'] == 'seconds' else value['value']
1253 def expert_card(self, p):
1254 protected = {'did', 'id', 'ivl', 'lapses', 'left', 'mod', 'nid', 'odid', 'odue', 'ord', 'queue', 'reps', 'type', 'usn'}
1255 if type(p['card']) is not int or not isinstance(p['keys'], list) or not isinstance(p['newValues'], list) or len(p['keys']) != len(p['newValues']):
1256 return False
1257 if not p['warning_check'] and protected.intersection(p['keys']):
1258 return False
1259 if len(set(p['keys'])) != len(p['keys']):
1260 raise ApiError('compatibilityError', 'Duplicate card keys.')
1261 mapping = {'factor': 'sm2EasePermille', 'ivl': 'intervalDays', 'reps': 'repetitions', 'lapses': 'lapses', 'custom_data': 'customData'}
1262 if any(key not in {*mapping, 'did', 'flags', 'due'} for key in p['keys']):
1263 raise ApiError('compatibilityError', 'Use native scheduling commands for protected state.')
1264 if any(key in p['keys'] for key in ('did', 'flags', 'due')) and len(p['keys']) != 1:
1265 raise ApiError('compatibilityError', 'Separate deck/flag/due edits from metadata edits.')
1266 values = dict(zip(p['keys'], p['newValues']))
1267 try:
1268 record = self.s('cards.get', id=str(p['card']))
1269 except Exception as error:
1270 return [[False, str(error)]]
1271 # A new card's due is its queue position, also while suspended or buried;
1272 # other types store days or timestamps.
1273 if 'due' in values and (record['scheduling']['type'] != 'new' or record['homeDeck']):
1274 raise ApiError('compatibilityError', 'Raw due writes only set new card positions outside filtered decks; use setDueDate.')
1275 try:
1276 if 'due' in values:
1277 # Write only this position, as historically: native repositioning
1278 # would also overwrite the Browser's remembered reposition options.
1279 if type(values['due']) is not int or not 0 <= values['due'] <= 2147483647:
1280 raise ApiError('invalidParams', 'New card positions must be integers from 0 to 2147483647.')
1281 card = self.service.card(str(p['card']))
1282 card.due = values['due']
1283 self.service.change(compat.update_card(self.service.col, card))
1284 elif 'did' in values:
1285 self.unwrap(self.s('cards.move', ids=[str(p['card'])], deck={'id': str(values['did'])}))
1286 elif 'flags' in values:
1287 self.unwrap(self.s('cards.setFlags', ids=[str(p['card'])], flag=values['flags']))
1288 else:
1289 self.s('advanced.cards.update', cardId=str(p['card']), patch={mapping[key]: value for key, value in values.items()})
1290 return [True]
1291 except Exception as error:
1292 return [[False, str(error)]]
1294 @staticmethod
1295 def preset_enum(public, number, raw=False):
1296 # Releases before 2.1.45 store the raw JSON, so any number they define is valid.
1297 if raw and number in (native_preset_enum(PRESET_ENUMS[public][0]) or {}): 1297 ↛ 1298line 1297 didn't jump to line 1298 because the condition on line 1297 was never true
1298 return number
1299 value = preset_enum_value(public, number)
1300 if value is None: 1300 ↛ 1301line 1300 didn't jump to line 1301 because the condition on line 1300 was never true
1301 raise ApiError('compatibilityError', 'Unsupported ' + public + ' value ' + str(number) + '.')
1302 return value
1304 def preset_patch(self, data, raw=False):
1305 baseline = self.service.col.decks.get_config(int(data['id']))
1306 settings = {}
1307 paths = {'newPerDay': ('new', 'perDay'), 'reviewsPerDay': ('rev', 'perDay'), 'learnStepsMinutes': ('new', 'delays'),
1308 'relearnStepsMinutes': ('lapse', 'delays'), 'initialEase': ('new', 'initialFactor'),
1309 'easyMultiplier': ('rev', 'ease4'), 'hardMultiplier': ('rev', 'hardFactor'),
1310 'lapseMultiplier': ('lapse', 'mult'), 'intervalMultiplier': ('rev', 'ivlFct'),
1311 'maximumIntervalDays': ('rev', 'maxIvl'), 'minimumLapseIntervalDays': ('lapse', 'minInt'),
1312 'leechThreshold': ('lapse', 'leechFails'), 'buryNew': ('new', 'bury'), 'buryReviews': ('rev', 'bury')}
1313 handled = {'id', 'name', 'mod', 'usn'}
1314 groups = {}
1315 for public, (group, key) in paths.items():
1316 groups.setdefault(group, set()).add(key)
1317 if key in data.get(group, {}) and data[group][key] != baseline[group][key]:
1318 value = data[group][key]
1319 settings[public] = value / 1000 if public == 'initialEase' else value
1320 enums = {'newMix': 'newMix', 'interdayLearningMix': 'dayLearningMix', 'reviewOrder': 'reviewOrder',
1321 'newSortOrder': 'newSortOrder', 'newGatherPriority': 'newGatherOrder',
1322 'questionAction': 'questionAction', 'answerAction': 'answerAction'}
1323 for old, public in enums.items():
1324 handled.add(old)
1325 if old in data and data[old] != baseline.get(old):
1326 settings[public] = self.preset_enum(public, data[old], raw)
1327 # Anki ignores these obsolete keys and the unused third graduating interval;
1328 # historical README configs still send them.
1329 groups['new'].update(('ints', 'order', 'separate'))
1330 groups['rev'].update(('fuzz', 'minSpace'))
1331 groups['lapse'].add('leechAction')
1332 if 'ints' in data.get('new', {}) and data['new']['ints'][:2] != baseline['new']['ints'][:2]:
1333 if len(data['new']['ints']) not in (2, 3): 1333 ↛ 1334line 1333 didn't jump to line 1334 because the condition on line 1333 was never true
1334 raise ApiError('compatibilityError', 'Unsupported graduating interval metadata.')
1335 settings['graduatingGoodDays'], settings['graduatingEasyDays'] = data['new']['ints'][:2]
1336 if 'order' in data.get('new', {}) and data['new']['order'] != baseline['new']['order']:
1337 settings['newInsertOrder'] = {0: 'random', 1: 'due'}[data['new']['order']]
1338 if 'leechAction' in data.get('lapse', {}) and data['lapse']['leechAction'] != baseline['lapse']['leechAction']:
1339 settings['leechAction'] = self.preset_enum('leechAction', data['lapse']['leechAction'], raw)
1340 mapping = {'newPerDayMinimum': 'newPerDayMinimum',
1341 'maxTaken': 'answerTimeLimitSeconds', 'timer': 'showTimer', 'autoplay': 'disableAutoplay',
1342 'desiredRetention': 'desiredRetention', 'ignoreRevlogsBeforeDate': 'ignoreReviewsBefore',
1343 'buryInterdayLearning': 'buryDayLearning', 'fsrsWeights': 'fsrsParameters4',
1344 'fsrsParams5': 'fsrsParameters5', 'fsrsParams6': 'fsrsParameters6',
1345 'easyDaysPercentages': 'easyDaysPercentages', 'stopTimerOnAnswer': 'stopTimerOnAnswer',
1346 'secondsToShowQuestion': 'questionDisplaySeconds', 'secondsToShowAnswer': 'answerDisplaySeconds',
1347 'waitForAudio': 'waitForAudio', 'sm2Retention': 'historicalRetention', 'weightSearch': 'parameterSearch',
1348 'replayq': 'skipQuestionOnAnswerReplay'}
1349 for old, public in mapping.items():
1350 handled.add(old)
1351 if old in data and data[old] != baseline.get(old):
1352 settings[public] = not data[old] if old in ('autoplay', 'replayq') else bool(data[old]) if old == 'timer' else data[old]
1353 for group, keys in groups.items():
1354 handled.add(group)
1355 for key, value in data.get(group, {}).items():
1356 if key not in keys and value != baseline.get(group, {}).get(key): 1356 ↛ 1357line 1356 didn't jump to line 1357 because the condition on line 1356 was never true
1357 raise ApiError('compatibilityError', 'Unsupported preset setting: ' + group + '.' + key)
1358 for key, value in data.items():
1359 if key not in handled and value != baseline.get(key):
1360 raise ApiError('compatibilityError', 'Unsupported preset setting: ' + key)
1361 return settings
1363 def model_action(self, name, p):
1364 ref = self.ref(p.get('modelName', ''))
1365 if name in ('findModelsById', 'findModelsByName'):
1366 return [self.model(id=id) for id in p['modelIds']] if name == 'findModelsById' else [self.model(name=value) for value in p['modelNames']]
1367 if name == 'createModel':
1368 if not p['inOrderFields']:
1369 raise ApiError('invalidParams', 'Must provide at least one field for inOrderFields')
1370 if not p['cardTemplates']:
1371 raise ApiError('invalidParams', 'Must provide at least one card for cardTemplates')
1372 if self.service.col.models.by_name(p['modelName']) is not None:
1373 raise ApiError('conflict', 'Model name already exists')
1374 templates = [{'name': template.get('Name', 'Card ' + str(index + 1)), 'questionHtml': template['Front'], 'answerHtml': template['Back']}
1375 for index, template in enumerate(p['cardTemplates'])]
1376 # Historical createModel kept Anki's new-model CSS and LaTeX defaults.
1377 defaults = self.service.col.models.new(p['modelName'])
1378 css = p['css'] if p['css'] is not None else defaults['css']
1379 value = self.s('noteTypes.create', name=p['modelName'], fields=[{'name': value} for value in p['inOrderFields']],
1380 templates=templates, kind='cloze' if p['isCloze'] else 'normal', css=css,
1381 latexHeader=defaults['latexPre'], latexFooter=defaults['latexPost'])
1382 return self.model(id=value['id'])
1383 if name in ('modelFieldNames', 'modelFieldDescriptions', 'modelFieldFonts', 'modelTemplates', 'modelStyling', 'modelFieldsOnTemplates'):
1384 # Names v1 cannot represent are missing models, as in historical lookups.
1385 if not isinstance(p['modelName'], str) or not p['modelName']:
1386 raise ApiError('notFound', 'model was not found: ' + str(p['modelName']))
1387 model = self.s('noteTypes.get', noteType=ref)
1388 if name == 'modelFieldNames':
1389 return [value['name'] for value in model['fields']]
1390 if name == 'modelFieldDescriptions':
1391 return [value['description'] for value in model['fields']]
1392 if name == 'modelFieldFonts':
1393 return {value['name']: {'font': value['fontFamily'], 'size': value['fontSize']} for value in model['fields']}
1394 if name == 'modelTemplates':
1395 return {value['name']: {'Front': value['questionHtml'], 'Back': value['answerHtml']} for value in model['templates']}
1396 if name == 'modelStyling':
1397 return {'css': model['css']}
1398 return {value['templateName']: [value['questionFields'], [field for field in value['answerFields'] if field not in value['questionFields']]]
1399 for value in self.s('noteTypes.getTemplateUsage', noteType=ref)}
1400 if name == 'updateModelStyling':
1401 self.s('noteTypes.update', noteType=self.ref(p['model']['name']), patch={'css': p['model']['css']})
1402 return None
1403 if name == 'findAndReplaceInModels':
1404 targets = [new for old, new in [('front', 'question'), ('back', 'answer'), ('css', 'css')] if p[old]]
1405 if not targets: 1405 ↛ 1406line 1405 didn't jump to line 1406 because the condition on line 1405 was never true
1406 return 0
1407 return self.s('noteTypes.replaceText', find=p['findText'], replace=p['replaceText'], targets=targets,
1408 **({'noteTypes': [ref]} if p['modelName'] else {'allNoteTypes': True}))['changedCount']
1409 edits = []
1410 if name == 'updateModelTemplates':
1411 ref = self.ref(p['model']['name'])
1412 model = self.s('noteTypes.get', noteType=ref)
1413 for template in model['templates']:
1414 value = p['model']['templates'].get(template['name'], {})
1415 patch = {new: value[old] for old, new in [('Front', 'questionHtml'), ('Back', 'answerHtml')] if value.get(old)}
1416 if patch: 1416 ↛ 1413line 1416 didn't jump to line 1413 because the condition on line 1416 was always true
1417 edits.append({'op': 'updateTemplate', 'name': template['name'], 'patch': patch})
1418 elif name in ('modelTemplateRename', 'modelFieldRename'):
1419 kind = 'Template' if 'Template' in name else 'Field'
1420 edits = [{'op': 'update' + kind, 'name': p['old' + kind + 'Name'], 'patch': {'name': p['new' + kind + 'Name']}}]
1421 elif name in ('modelTemplateReposition', 'modelFieldReposition'):
1422 kind = 'Template' if 'Template' in name else 'Field'
1423 edits = [{'op': 'move' + kind, 'name': p[kind.lower() + 'Name'], 'index': p['index']}]
1424 elif name in ('modelTemplateRemove', 'modelFieldRemove'):
1425 kind = 'Template' if 'Template' in name else 'Field'
1426 edits = [{'op': 'remove' + kind, 'name': p[kind.lower() + 'Name']}]
1427 elif name == 'modelTemplateAdd':
1428 value = p['template']
1429 data = {'name': value['Name'], 'questionHtml': value['Front'], 'answerHtml': value['Back']}
1430 model = self.s('noteTypes.get', noteType=ref)
1431 if value['Name'] in [template['name'] for template in model['templates']]: 1431 ↛ 1432line 1431 didn't jump to line 1432 because the condition on line 1431 was never true
1432 edits = [{'op': 'updateTemplate', 'name': value['Name'], 'patch': data}]
1433 else:
1434 edits = [{'op': 'addTemplate', 'template': data}]
1435 elif name == 'modelFieldAdd':
1436 model = self.s('noteTypes.get', noteType=ref)
1437 if p['fieldName'] not in [field['name'] for field in model['fields']]: 1437 ↛ 1439line 1437 didn't jump to line 1439 because the condition on line 1437 was always true
1438 edits.append({'op': 'addField', 'field': {'name': p['fieldName']}})
1439 if p['index'] is not None:
1440 edits.append({'op': 'moveField', 'name': p['fieldName'], 'index': p['index']})
1441 elif name in ('modelFieldSetFont', 'modelFieldSetFontSize', 'modelFieldSetDescription'): 1441 ↛ 1446line 1441 didn't jump to line 1446 because the condition on line 1441 was always true
1442 key, source = {'modelFieldSetFont': ('fontFamily', 'font'), 'modelFieldSetFontSize': ('fontSize', 'fontSize'),
1443 'modelFieldSetDescription': ('description', 'description')}[name]
1444 edits = [{'op': 'updateField', 'name': p['fieldName'], 'patch': {key: p[source]}}]
1445 else:
1446 raise ApiError('methodNotFound', 'Unknown note type action.')
1447 if edits: 1447 ↛ 1468line 1447 didn't jump to line 1468 because the condition on line 1447 was always true
1448 model = self.model(p.get('modelName', p.get('model', {}).get('name')))
1449 names = {'field': {value['name'] for value in model['flds']},
1450 'template': {value['name'] for value in model['tmpls']}}
1451 for edit in edits:
1452 kind = 'field' if edit['op'].endswith('Field') else 'template'
1453 if edit['op'].startswith('add'):
1454 names[kind].add(edit[kind]['name'])
1455 continue
1456 if edit['name'] not in names[kind]:
1457 raise ApiError('notFound', kind + ' was not found in ' + model['name'] + ': ' + edit['name'])
1458 if edit['op'].startswith('move'):
1459 # Anki's historical list insertion placed large indexes last.
1460 edit['index'] = min(edit['index'], len(names[kind]) - 1)
1461 if name in ('modelFieldSetFont', 'modelFieldSetFontSize', 'modelFieldSetDescription'):
1462 key, expected, label = {'modelFieldSetFont': ('font', str, 'a string'),
1463 'modelFieldSetFontSize': ('fontSize', int, 'an integer'),
1464 'modelFieldSetDescription': ('description', str, 'a string')}[name]
1465 if not isinstance(p[key], expected):
1466 raise ApiError('invalidParams', key + ' should be ' + label + ': ' + str(p[key]))
1467 self.s('noteTypes.editStructure', noteType=ref, edits=edits)
1468 return True if name == 'modelFieldSetDescription' else None