Coverage for plugin/services.py: 89.4%
1002 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"""Native Anki domain services. No legacy action implementations live here."""
2import base64
3import copy
4import hashlib
5import json
6import os
7import re
8import fnmatch
9import time
10import unicodedata
11from datetime import datetime, timedelta
12from pathlib import Path
14from . import compat
15from .contract import SCHEMA
16from .protocol import ApiError, error_record, timestamp
19TYPES = {0: 'new', 1: 'learning', 2: 'review', 3: 'relearning'}
20QUEUES = {0: 'new', 1: 'learning', 2: 'review', 3: 'dayLearning', 4: 'preview',
21 -1: 'suspended', -2: 'buriedByScheduler', -3: 'buriedByUser'}
22RATINGS = ('again', 'hard', 'good', 'easy')
23FILTERED_POSITION_OFFSET = 100000
24KINDS = ('learning', 'review', 'relearning', 'filtered', 'manual', 'rescheduled')
25# Cards keep the user flag in the low three bits of their flags.
26FLAG_MASK = 7
27# Internal legacy note option. Public v1 schemas reject it, so only the legacy
28# adapter can attach it after schema validation.
29LEGACY_SKIP_CLOZE = 'x-legacySkipClozeChecks'
30# Preserve Anki's legacy filename filter without its deprecated stripIllegal API.
31MEDIA_ILLEGAL_CHARACTERS = re.compile(r'[][><:"/?*^\\|\0\r\n]')
32FIELD_KEYS = {'fontFamily': 'font', 'fontSize': 'size', 'description': 'description',
33 'sticky': 'sticky', 'rtl': 'rtl', 'plainText': 'plainText',
34 'collapsed': 'collapsed', 'excludeFromSearch': 'excludeFromSearch'}
35TEMPLATE_KEYS = {'questionHtml': 'qfmt', 'answerHtml': 'afmt', 'browserQuestionHtml': 'bqfmt',
36 'browserAnswerHtml': 'bafmt', 'browserFontFamily': 'bfont', 'browserFontSize': 'bsize'}
37PRESET_KEYS = {
38 'learnStepsMinutes': 'learn_steps', 'relearnStepsMinutes': 'relearn_steps',
39 'fsrsParameters4': 'fsrs_params_4', 'fsrsParameters5': 'fsrs_params_5', 'fsrsParameters6': 'fsrs_params_6',
40 'newPerDay': 'new_per_day', 'newPerDayMinimum': 'new_per_day_minimum',
41 'reviewsPerDay': 'reviews_per_day', 'initialEase': 'initial_ease',
42 'easyMultiplier': 'easy_multiplier', 'hardMultiplier': 'hard_multiplier', 'lapseMultiplier': 'lapse_multiplier',
43 'intervalMultiplier': 'interval_multiplier', 'maximumIntervalDays': 'maximum_review_interval',
44 'minimumLapseIntervalDays': 'minimum_lapse_interval', 'graduatingGoodDays': 'graduating_interval_good',
45 'graduatingEasyDays': 'graduating_interval_easy', 'leechThreshold': 'leech_threshold',
46 'answerTimeLimitSeconds': 'cap_answer_time_to_secs', 'desiredRetention': 'desired_retention',
47 'historicalRetention': 'historical_retention', 'easyDaysPercentages': 'easy_days_percentages',
48 'ignoreReviewsBefore': 'ignore_revlogs_before_date', 'parameterSearch': 'param_search',
49 'questionDisplaySeconds': 'seconds_to_show_question', 'answerDisplaySeconds': 'seconds_to_show_answer',
50 'disableAutoplay': 'disable_autoplay', 'showTimer': 'show_timer', 'stopTimerOnAnswer': 'stop_timer_on_answer',
51 'waitForAudio': 'wait_for_audio', 'skipQuestionOnAnswerReplay': 'skip_question_when_replaying_answer',
52 'buryNew': 'bury_new', 'buryReviews': 'bury_reviews', 'buryDayLearning': 'bury_interday_learning',
53}
55def enum_names(prefix, **names):
56 return {public: prefix + native for public, native in names.items()}
59# Values map to native enum names, not numbers: releases renumbered and renamed
60# some options (23.10 stored relative overdueness as 7, later retrievability).
61REVIEW_MIX = enum_names('REVIEW_MIX_', mixed='MIX_WITH_REVIEWS', afterReviews='AFTER_REVIEWS',
62 beforeReviews='BEFORE_REVIEWS')
63PRESET_ENUMS = {
64 'newInsertOrder': ('new_card_insert_order', enum_names('NEW_CARD_INSERT_ORDER_', due='DUE', random='RANDOM')),
65 'newGatherOrder': ('new_card_gather_priority', enum_names(
66 'NEW_CARD_GATHER_PRIORITY_', deck='DECK', lowestPosition='LOWEST_POSITION', highestPosition='HIGHEST_POSITION',
67 randomNotes='RANDOM_NOTES', randomCards='RANDOM_CARDS', deckThenRandomNotes='DECK_THEN_RANDOM_NOTES')),
68 'newSortOrder': ('new_card_sort_order', enum_names(
69 'NEW_CARD_SORT_ORDER_', template='TEMPLATE', none='NO_SORT', templateThenRandom='TEMPLATE_THEN_RANDOM',
70 randomNoteThenTemplate='RANDOM_NOTE_THEN_TEMPLATE', randomCard='RANDOM_CARD')),
71 'reviewOrder': ('review_order', enum_names(
72 'REVIEW_CARD_ORDER_', day='DAY', dayThenDeck='DAY_THEN_DECK', deckThenDay='DECK_THEN_DAY',
73 intervalAscending='INTERVALS_ASCENDING', intervalDescending='INTERVALS_DESCENDING',
74 easeAscending='EASE_ASCENDING', easeDescending='EASE_DESCENDING',
75 retrievabilityAscending='RETRIEVABILITY_ASCENDING', random='RANDOM', added='ADDED',
76 reverseAdded='REVERSE_ADDED', retrievabilityDescending='RETRIEVABILITY_DESCENDING',
77 relativeOverdueness='RELATIVE_OVERDUENESS')),
78 'newMix': ('new_mix', REVIEW_MIX),
79 'dayLearningMix': ('interday_learning_mix', REVIEW_MIX),
80 'leechAction': ('leech_action', enum_names('LEECH_ACTION_', suspend='SUSPEND', tagOnly='TAG_ONLY')),
81 'questionAction': ('question_action', enum_names('QUESTION_ACTION_', showAnswer='SHOW_ANSWER',
82 showReminder='SHOW_REMINDER')),
83 'answerAction': ('answer_action', enum_names(
84 'ANSWER_ACTION_', buryCard='BURY_CARD', again='ANSWER_AGAIN', good='ANSWER_GOOD', hard='ANSWER_HARD',
85 showReminder='SHOW_REMINDER')),
86}
87# Before 2.1.28 no descriptor exists; the JSON presets store only these enums.
88LEGACY_PRESET_ENUMS = {'leech_action': {0: 'LEECH_ACTION_SUSPEND', 1: 'LEECH_ACTION_TAG_ONLY'}}
91def native_preset_enum(native):
92 """This release's {number: name} values of a native preset enum, or None when it lacks the option."""
93 descriptor = compat.deck_config_descriptor()
94 if descriptor is None: 94 ↛ 95line 94 didn't jump to line 95 because the condition on line 94 was never true
95 return LEGACY_PRESET_ENUMS.get(native)
96 field = descriptor.fields_by_name.get(native)
97 return None if field is None else {value.number: value.name for value in field.enum_type.values}
100def preset_enum_value(public, number):
101 """The public value of a native preset enum number, or None when this release's option has no public name."""
102 native, names = PRESET_ENUMS[public]
103 value = (native_preset_enum(native) or {}).get(number)
104 return next((key for key, name in names.items() if value is not None and name == value), None)
107def preset_enum_number(public, value):
108 """The native number of a public preset enum value, rejecting options this release lacks."""
109 native, names = PRESET_ENUMS[public]
110 found = {name: number for number, name in (native_preset_enum(native) or {}).items()}.get(names[value])
111 if found is None: 111 ↛ 112line 111 didn't jump to line 112 because the condition on line 111 was never true
112 raise ApiError('unsupportedCapability', 'This Anki release has no ' + public + ' option ' + value + '.')
113 return found
116def entity_id(value):
117 if not isinstance(value, str) or not re.fullmatch(r'[1-9][0-9]{0,18}', value) or int(value) > 9223372036854775807:
118 raise ApiError('invalidParams', 'Expected a positive signed 64-bit decimal ID.')
119 return int(value)
122def interval(value):
123 return {'value': abs(value), 'unit': 'seconds' if value < 0 else 'days'}
126def normalized_field(value):
127 return unicodedata.normalize('NFC', compat.strip_html_media(value))
130def created_note(note):
131 return {'noteId': str(note.id), 'cardIds': [str(id) for id in note.card_ids()]}
134def review_total(counts):
135 """Reviews of every kind in one bucket of Anki's review graph."""
136 return counts.learn + counts.relearn + counts.young + counts.mature + counts.filtered
139def scheduler_day(cutoff):
140 """The date of the scheduler day that ends at cutoff."""
141 return datetime.fromtimestamp(cutoff - 86400).date()
144def template_fields(text, names):
145 """Mirror Anki's template tokens; its parsed tree is not exposed to Python."""
146 directive = '{{=<% %>=}}'
147 if text.lstrip().startswith(directive):
148 text = text.lstrip()
149 while text.startswith(directive):
150 text = text[len(directive):]
151 start, end = '<%', '%>'
152 else:
153 start, end = '{{', '}}'
154 pattern = re.compile(re.escape(start) + r'(.*?)' + re.escape(end) + r'|<!--.*?-->', re.S)
155 fields, stack = [], []
156 for match in pattern.finditer(text):
157 if match.group(1) is None:
158 continue
159 token = match.group(1).lstrip('{').strip()
160 if len(token) >= 2 and token[0] in '#^/':
161 name = token[1:].lstrip()
162 if token[0] == '/':
163 if not stack or stack.pop() != name: 163 ↛ 164line 163 didn't jump to line 164 because the condition on line 163 was never true
164 raise ApiError('validationFailed', 'Mismatched template conditional.')
165 continue
166 stack.append(name)
167 else:
168 name = token.rsplit(':', 1)[-1]
169 if name in names and name not in fields: 169 ↛ 156line 169 didn't jump to line 156 because the condition on line 169 was always true
170 fields.append(name)
171 if stack: 171 ↛ 172line 171 didn't jump to line 172 because the condition on line 171 was never true
172 raise ApiError('validationFailed', 'Unclosed template conditional.')
173 return fields
176def structure_name_key(name, is_field):
177 """Mirror the name identity Anki uses when it appends "+" to repeated field/template names."""
178 name = unicodedata.normalize('NFC', name)
179 if is_field:
180 removed, leading = compat.field_name_rules()
181 name = leading.sub('', removed.sub('', name)).rstrip()
182 return name.casefold()
185def require_unique_names(values, is_field):
186 seen = {}
187 for value in values:
188 key = structure_name_key(value['name'], is_field)
189 if key in seen:
190 kind = 'field' if is_field else 'template'
191 raise ApiError('validationFailed', f'Duplicate {kind} name: "{value["name"]}" is the same as "{seen[key]}" in Anki.')
192 seen[key] = value['name']
195class Services:
196 def __init__(self, runtime, collection, session):
197 self.runtime, self.col, self.session = runtime, collection, session
198 self.changes = []
199 self.undo_target = False
201 def change(self, result):
202 if result is None and not compat.reports_changes(): 202 ↛ 204line 202 didn't jump to line 204 because the condition on line 202 was never true
203 # Writes before 2.1.45 return nothing; treat each one as a change.
204 result = compat.LegacyChanges()
205 if result is not None: 205 ↛ 213line 205 didn't jump to line 213 because the condition on line 205 was always true
206 self.changes.append(result.changes if hasattr(result, 'changes') else result)
207 # Releases before 2.1.45 have no undo steps to group.
208 if self.undo_target is not False and compat.has(self.col, 'undo_status'):
209 if self.undo_target is None:
210 self.undo_target = self.col.undo_status().last_step
211 else:
212 self.col.merge_undo_entries(self.undo_target)
213 self.runtime.invalidate_predictions()
214 return result
216 def execute(self, method, params):
217 params = dict(params)
218 params.pop('session', None)
219 handler = getattr(self, method.replace('.', '_'), None)
220 if handler is None: 220 ↛ 221line 220 didn't jump to line 221 because the condition on line 220 was never true
221 raise ApiError('unsupportedCapability', 'No verified adapter for ' + method)
222 reason = self.runtime.capability_reason(method, self.col)
223 if reason:
224 raise ApiError('unsupportedCapability', reason)
225 previous_group = self.undo_target
226 if SCHEMA['x-methods'][method]['undo'] in ('single', 'grouped'):
227 self.undo_target = None
228 try:
229 return handler(**params)
230 except ApiError:
231 raise
232 except Exception as error:
233 if compat.is_not_found(error):
234 raise ApiError('notFound', compat.error_message(error)) from error
235 if method in ('packages.import', 'packages.export', 'media.get', 'media.delete') and isinstance(error, (OSError,) + compat.backend_errors()):
236 raise ApiError('ioError', str(error)) from error
237 raise
238 finally:
239 self.undo_target = previous_group
241 def many(self, values, function, deduplicate=False):
242 items, cache = [], {}
243 for index, value in enumerate(values):
244 key = json.dumps(value, sort_keys=True)
245 if deduplicate and key in cache:
246 items.append({'index': index, **copy.deepcopy(cache[key])})
247 continue
248 try:
249 entry = {'result': function(value)}
250 except Exception as error:
251 if compat.is_not_found(error):
252 error = ApiError('notFound', compat.error_message(error))
253 entry = {'error': error_record(error)}
254 cache[key] = entry
255 items.append({'index': index, **entry})
256 return {'items': items}
258 def note(self, id):
259 return self.col.get_note(entity_id(id))
261 def card(self, id):
262 return self.col.get_card(entity_id(id))
264 def resolve(self, reference, kind):
265 manager = self.col.decks if kind == 'deck' else self.col.models
266 if 'id' in reference:
267 id = entity_id(reference['id'])
268 value = manager.get(id, default=False) if kind == 'deck' else manager.get(id)
269 else:
270 value = manager.by_name(reference['name'])
271 if value is None:
272 raise ApiError('notFound', kind.title() + ' not found: ' + str(reference))
273 value = copy.deepcopy(value)
274 # 2.1.24-2.1.26 keep some deck and note type ids as strings.
275 value['id'] = int(value['id'])
276 return value
278 def summary(self, value):
279 return {'id': str(value['id']), 'name': value['name']}
281 def collection_get(self):
282 return {'profile': self.runtime.profile_name, 'session': self.session,
283 'scheduler': 'fsrs' if self.col.get_config('fsrs', False) else 'sm2'}
285 def note_record(self, note):
286 return {'id': str(note.id), 'noteType': self.summary(note.note_type()),
287 'fields': dict(note.items()), 'tags': list(note.tags),
288 'cardIds': [str(id) for id in note.card_ids()], 'modifiedAt': timestamp(note.mod)}
290 def notes_get(self, id):
291 return self.note_record(self.note(id))
293 def notes_getMany(self, ids):
294 return self.many(ids, self.notes_get)
296 def page(self, ids, method, params):
297 return self.runtime.page(ids, method, params, self.session)
299 def search(self, kind, query, limit=100, cursor=None, sort=None):
300 params = {'query': query, 'limit': limit, 'sort': sort}
301 if cursor:
302 return self.page(None, kind + '.search', {**params, 'cursor': cursor})
303 order = False
304 if sort:
305 if not compat.has(self.col, 'get_browser_column'): 305 ↛ 306line 305 didn't jump to line 306 because the condition on line 305 was never true
306 raise ApiError('unsupportedCapability', 'Sorting by browser column requires Anki 2.1.45 or later.')
307 from anki.collection import BrowserColumns
308 order = self.col.get_browser_column(sort['column'])
309 if order is None:
310 raise ApiError('invalidParams', 'Unknown browser sort column.')
311 sorting = compat.column_sorting(order, kind)
312 if sorting == BrowserColumns.SORTING_NONE: 312 ↛ 313line 312 didn't jump to line 313 because the condition on line 312 was never true
313 raise ApiError('invalidParams', 'Browser sort column does not support this search.')
314 try:
315 ids = list(compat.find_ids(self.col, kind, query, order,
316 reverse=bool(sort and sort['direction'] == 'descending')))
317 except Exception as error:
318 raise ApiError('invalidSearch', str(error)) from error
319 if sort is None:
320 ids.sort()
321 return self.page(ids, kind + '.search', params)
323 def notes_search(self, **params):
324 return self.search('notes', **params)
326 def cards_search(self, **params):
327 return self.search('cards', **params)
329 def prepare_note(self, data):
330 model = self.resolve(data['noteType'], 'noteType')
331 deck = self.resolve(data['deck'], 'deck')
332 if deck.get('dyn'): 332 ↛ 333line 332 didn't jump to line 333 because the condition on line 332 was never true
333 raise ApiError('validationFailed', 'Cannot add a note to a filtered deck.')
334 note = self.col.new_note(model)
335 for name, value in data['fields'].items():
336 if name not in note: 336 ↛ 337line 336 didn't jump to line 337 because the condition on line 336 was never true
337 raise ApiError('validationFailed', 'Unknown field: ' + name)
338 note[name] = value
339 note.tags = list(data.get('tags', []))
340 return note, deck
342 def empty_questions(self, note):
343 from anki.utils import to_json_bytes
344 if not compat.renders_uncommitted(self.col): 344 ↛ 346line 344 didn't jump to line 346 because the condition on line 344 was never true
345 # 2.1.24-2.1.26 add only templates whose required fields are filled.
346 return not self.col.findTemplates(note)
347 model = note.note_type()
348 templates = model['tmpls']
349 if model['type'] == 1:
350 # Native cloze ordinal enumeration, including fallback card 0.
351 ordinals = set(n - 1 for n in compat.cloze_numbers(self.col, note)) or {0}
352 templates = [{**templates[0], 'ord': index} for index in sorted(ordinals)]
353 return all(compat.rendered_empty(compat.render_uncommitted(
354 self.col, note._to_backend_note(), template['ord'], to_json_bytes(template), fill_empty=False))
355 for template in templates)
357 def duplicate_scope(self, policy, deck):
358 """Deck ids a deck-scoped duplicate policy covers, or None for the whole collection."""
359 if policy.get('scope', 'collection') != 'deck':
360 return None
361 target = self.resolve(policy.get('deck', self.summary(deck)), 'deck')['id']
362 ids = {target}
363 if policy.get('includeChildren', False):
364 ids.update(id for _, id in self.col.decks.children(target))
365 return ids
367 def validate_note_data(self, note, deck, data):
368 return self.validation(note, deck, data.get('duplicates'), data.get('rejectEmptyQuestions', True),
369 data.get(LEGACY_SKIP_CLOZE) is not True)
371 def validation(self, note, deck, policy, reject_empty, cloze_checks=True):
372 result = int(note.fields_check())
373 reasons = {1: 'emptyFirstField', 3: 'missingCloze', 4: 'notClozeNoteType', 5: 'notClozeField'}
374 # Legacy deck/all-model duplicate checks never ran Anki's cloze checks.
375 skipped = () if cloze_checks else (3, 4, 5)
376 issues = []
377 if result in reasons and result not in skipped:
378 issues.append({'type': reasons[result], 'message': 'Anki field validation: ' + reasons[result]})
379 elif result not in (0, 2) + skipped: 379 ↛ 380line 379 didn't jump to line 380 because the condition on line 379 was never true
380 raise ApiError('unsupportedCapability', 'Unknown native field validation result.')
381 duplicates = []
382 policy = policy or {}
383 source = normalized_field(note.fields[0])
384 if not policy.get('allow', False):
385 candidates = self.col.db.list('select id from notes where csum=? and id!=?', compat.field_checksum(note.fields[0]), note.id)
386 scope_decks = self.duplicate_scope(policy, deck)
387 for id in candidates:
388 other = self.col.get_note(id)
389 if not policy.get('acrossNoteTypes', False) and int(other.mid) != int(note.mid):
390 continue
391 if normalized_field(other.fields[0]) != source: 391 ↛ 392line 391 didn't jump to line 392 because the condition on line 391 was never true
392 continue
393 if scope_decks is not None and not any((card.odid or card.did) in scope_decks for card in other.cards()):
394 continue
395 duplicates.append(str(id))
396 if duplicates:
397 issues.append({'type': 'duplicate', 'message': 'A matching note exists.'})
398 if reject_empty and not issues and self.empty_questions(note):
399 issues.append({'type': 'emptyQuestions', 'message': 'All generated questions are empty.'})
400 return {'valid': not issues, 'issues': issues, 'duplicateNoteIds': duplicates}
402 def notes_validate(self, note):
403 native, deck = self.prepare_note(note)
404 return self.validate_note_data(native, deck, note)
406 def notes_validateMany(self, notes):
407 return self.many(notes, self.notes_validate)
409 def notes_create(self, **data):
410 note, deck = self.prepare_note(data)
411 validation = self.validate_note_data(note, deck, data)
412 if not validation['valid']:
413 raise ApiError('validationFailed', 'Note cannot be created.', validation)
414 self.change(self.col.add_note(note, deck['id']))
415 return created_note(note)
417 def notes_createMany(self, notes, atomic=False):
418 if not atomic:
419 return self.many(notes, lambda data: self.notes_create(**data))
420 prepared, errors = self.prepare_notes(notes)
421 if errors:
422 raise ApiError('validationFailed', 'Atomic batch validation failed.', {'items': errors})
423 if prepared:
424 self.add_notes(prepared)
425 return {'items': [{'index': index, 'result': created_note(request.note)} for index, request in enumerate(prepared)]}
427 def add_notes(self, requests):
428 if compat.has(self.col, 'add_notes'):
429 return self.change(self.col.add_notes(requests))
430 # Before 23.10, add one at a time in a single undo step and remove partial
431 # batches within that step, so undoing a failed batch restores nothing.
432 added, previous_group = [], self.undo_target
433 if previous_group is False: 433 ↛ 435line 433 didn't jump to line 435 because the condition on line 433 was always true
434 self.undo_target = None
435 try:
436 for request in requests:
437 self.change(self.col.add_note(request.note, request.deck_id))
438 added.append(request.note.id)
439 except BaseException:
440 if added: 440 ↛ 442line 440 didn't jump to line 442 because the condition on line 440 was always true
441 self.change(self.col.remove_notes(added))
442 raise
443 finally:
444 if previous_group is False: 444 ↛ exitline 444 didn't return from function 'add_notes' because the condition on line 444 was always true
445 self.undo_target = False
447 def prepare_notes(self, notes):
448 """Validate an ordered batch without writing it, including duplicates."""
449 prepared, errors, seen = [], [], []
450 for index, data in enumerate(notes):
451 try:
452 note, deck = self.prepare_note(data)
453 validation = self.validate_note_data(note, deck, data)
454 policy = data.get('duplicates', {})
455 if not policy.get('allow', False):
456 source = normalized_field(note.fields[0])
457 scope_decks = self.duplicate_scope(policy, deck)
458 for old_note, old_deck in seen:
459 if source != normalized_field(old_note.fields[0]):
460 continue
461 if not policy.get('acrossNoteTypes', False) and int(old_note.mid) != int(note.mid): 461 ↛ 462line 461 didn't jump to line 462 because the condition on line 461 was never true
462 continue
463 if scope_decks is not None and old_deck['id'] not in scope_decks: 463 ↛ 464line 463 didn't jump to line 464 because the condition on line 463 was never true
464 continue
465 validation['valid'] = False
466 validation['issues'].append({'type': 'duplicate', 'message': 'Duplicate within batch.'})
467 if not validation['valid']:
468 raise ApiError('validationFailed', 'Invalid note.', validation)
469 prepared.append(compat.AddNoteRequest(note=note, deck_id=deck['id']))
470 seen.append((note, deck))
471 except Exception as error:
472 errors.append({'index': index, 'error': error_record(error)})
473 return prepared, errors
475 def notes_update(self, id, patch):
476 note = self.note(id)
477 for name, value in patch.get('fields', {}).items():
478 if name not in note: 478 ↛ 479line 478 didn't jump to line 479 because the condition on line 478 was never true
479 raise ApiError('validationFailed', 'Unknown field: ' + name)
480 note[name] = value
481 if 'tags' in patch:
482 note.tags = patch['tags']
483 self.change(self.col.update_note(note))
484 return self.note_record(self.note(id))
486 def notes_delete(self, ids):
487 def delete(id):
488 self.note(id)
489 self.change(self.col.remove_notes([entity_id(id)]))
490 return {'changed': True}
491 return self.many(ids, delete, True)
493 def notes_planConversion(self, source, target):
494 old, new = self.resolve(source, 'noteType'), self.resolve(target, 'noteType')
495 info = compat.change_notetype_info(self.col, old['id'], new['id'])
496 def maps(key, indices):
497 return [{'target': item['name'], 'source': old[key][index]['name'] if index >= 0 else None}
498 for item, index in zip(new[key], indices)]
499 return {'source': self.summary(old), 'target': self.summary(new),
500 'fields': maps('flds', info.input.new_fields), 'templates': maps('tmpls', info.input.new_templates),
501 'token': self.runtime.token('conversion', [old, new])}
503 def notes_convert(self, ids, target, fields, templates, planToken):
504 if not ids: 504 ↛ 505line 504 didn't jump to line 505 because the condition on line 504 was never true
505 return {'changedCount': 0}
506 notes = [self.note(id) for id in ids]
507 old = self.resolve({'id': str(notes[0].mid)}, 'noteType')
508 new = self.resolve(target, 'noteType')
509 if any(int(note.mid) != old['id'] for note in notes): 509 ↛ 510line 509 didn't jump to line 510 because the condition on line 509 was never true
510 raise ApiError('validationFailed', 'Conversion requires one source note type.')
511 self.runtime.check_token(planToken, 'conversion', [old, new])
512 info = compat.change_notetype_info(self.col, old['id'], new['id'])
513 def indices(mapping, key):
514 if key == 'tmpls' and compat.field(info.input, 'is_cloze', old['type'] == 1 or new['type'] == 1):
515 if mapping: 515 ↛ 516line 515 didn't jump to line 516 because the condition on line 515 was never true
516 raise ApiError('invalidParams', 'Native cloze conversion requires an empty template map.')
517 return []
518 by_name = {entry['target']: entry['source'] for entry in mapping}
519 if len(by_name) != len(mapping) or set(by_name) != {item['name'] for item in new[key]}: 519 ↛ 520line 519 didn't jump to line 520 because the condition on line 519 was never true
520 raise ApiError('invalidParams', 'Mappings must cover every target once.')
521 source_names = [item['name'] for item in old[key]]
522 chosen = [by_name[item['name']] for item in new[key]]
523 used = [name for name in chosen if name is not None]
524 if len(used) != len(set(used)) or any(name not in source_names for name in used): 524 ↛ 525line 524 didn't jump to line 525 because the condition on line 524 was never true
525 raise ApiError('invalidParams', 'Invalid/duplicate source mapping.')
526 return [source_names.index(name) if name is not None else -1 for name in chosen]
527 request = info.input
528 request.note_ids.extend(entity_id(id) for id in ids)
529 request.new_fields[:] = indices(fields, 'flds')
530 request.new_templates[:] = indices(templates, 'tmpls')
531 self.change(compat.change_notetype_of_notes(self.col, request))
532 return {'changedCount': len(set(ids))}
534 def notes_findEmpty(self, criterion, query='', limit=100, cursor=None):
535 params = {'criterion': criterion, 'query': query, 'limit': limit}
536 if cursor: 536 ↛ 537line 536 didn't jump to line 537 because the condition on line 536 was never true
537 return self.page(None, 'notes.findEmpty', {**params, 'cursor': cursor})
538 matches = []
539 try:
540 ids = self.col.find_notes(query)
541 except Exception as error:
542 raise ApiError('invalidSearch', str(error)) from error
543 for id in ids:
544 note = self.col.get_note(id)
545 if ((criterion == 'noCards' and not note.card_ids()) or
546 (criterion == 'allFieldsEmpty' and all(not normalized_field(value).strip() for value in note.fields)) or
547 (criterion == 'allQuestionsEmpty' and self.empty_questions(note))):
548 matches.append(id)
549 return self.page(sorted(matches), 'notes.findEmpty', params)
551 def tags_list(self):
552 return list(self.col.tags.all())
554 def mutate_tags(self, noteIds, tags, remove):
555 def mutate(id):
556 note = self.note(id)
557 before = list(note.tags)
558 for tag in tags:
559 note.remove_tag(tag) if remove else note.has_tag(tag) or note.add_tag(tag)
560 if before != note.tags:
561 self.change(self.col.update_note(note))
562 return {'changed': before != note.tags}
563 return self.many(noteIds, mutate, True)
565 def tags_add(self, noteIds, tags):
566 return self.mutate_tags(noteIds, tags, False)
568 def tags_remove(self, noteIds, tags):
569 return self.mutate_tags(noteIds, tags, True)
571 def tags_replace(self, **params):
572 ids = params.get('noteIds') if 'noteIds' in params else [str(id) for id in self.col.find_notes('')]
573 changed = []
574 for id in set(ids):
575 note = self.note(id)
576 if note.has_tag(params['from']):
577 note.remove_tag(params['from'])
578 note.add_tag(params['to'])
579 changed.append(note)
580 if not hasattr(self.col, 'update_notes'): 580 ↛ 582line 580 didn't jump to line 582 because the condition on line 580 was never true
581 # 2.1.45 updates one note at a time; change() merges them into one undo step.
582 for note in changed:
583 self.change(self.col.update_note(note))
584 elif changed:
585 self.change(self.col.update_notes(changed))
586 return {'changedCount': len(changed)}
588 def tags_deleteUnused(self):
589 out = self.change(compat.clear_unused_tags(self.col))
590 return {'changedCount': out.count}
592 def state_record(self, card):
593 queue = QUEUES.get(card.queue)
594 if queue is None or card.type not in TYPES: 594 ↛ 595line 594 didn't jump to line 595 because the condition on line 594 was never true
595 raise ApiError('unsupportedCapability', 'Unknown card scheduling state.')
596 underlying = card.queue if card.queue >= 0 else card.type
597 if card.odid and card.due < 0:
598 # Filtered builds replace due with -100000 + build order; the home due moves to odue.
599 due = {'kind': 'position', 'position': max(0, card.due + FILTERED_POSITION_OFFSET)}
600 elif underlying == 0:
601 due = {'kind': 'position', 'position': max(0, card.due)}
602 elif card.queue in (1, 4) or (card.queue < 0 and card.type in (1, 3) and card.due > 1000000000):
603 due = {'kind': 'timestamp', 'at': timestamp(card.due)}
604 else:
605 due = {'kind': 'day', 'day': card.due}
606 seconds = None
607 if card.type in (1, 3):
608 seconds = compat.learning_seconds(self.col, card)
609 # FSRS card state arrived in 23.10.
610 memory = getattr(card, 'memory_state', None)
611 return {'type': TYPES[card.type], 'queue': queue, 'due': due, 'intervalDays': card.ivl,
612 'learningIntervalSeconds': seconds, 'remainingSteps': card.left, 'repetitions': card.reps,
613 'lapses': card.lapses, 'sm2EasePermille': card.factor,
614 'fsrsMemory': {'difficulty': memory.difficulty, 'stabilityDays': memory.stability} if memory else None,
615 'desiredRetention': getattr(card, 'desired_retention', None)}
617 def card_record(self, card):
618 return {'id': str(card.id), 'noteId': str(card.nid), 'deck': self.summary(self.resolve({'id': str(card.did)}, 'deck')),
619 'homeDeck': self.summary(self.resolve({'id': str(card.odid)}, 'deck')) if card.odid else None,
620 'templateIndex': card.ord, 'flags': card.flags & FLAG_MASK, 'modifiedAt': timestamp(card.mod),
621 'scheduling': self.state_record(card)}
623 def cards_get(self, id):
624 return self.card_record(self.card(id))
626 def cards_getMany(self, ids):
627 return self.many(ids, self.cards_get)
629 def cards_render(self, id):
630 card = self.card(id)
631 return {'cardId': id, 'questionHtml': card.question(), 'answerHtml': card.answer(), 'css': card.note_type()['css']}
633 def cards_move(self, ids, deck):
634 target = self.resolve(deck, 'deck')
635 if target.get('dyn'):
636 raise ApiError('invalidState', 'Filtered decks cannot be move destinations.')
637 def move(id):
638 card = self.card(id)
639 changed = bool(card.odid or card.did != target['id'])
640 if changed: 640 ↛ 642line 640 didn't jump to line 642 because the condition on line 640 was always true
641 self.change(self.col.set_deck([card.id], target['id']))
642 return {'changed': changed}
643 return self.many(ids, move, True)
645 def cards_setSuspended(self, ids, suspended):
646 def mutate(id):
647 card = self.card(id)
648 changed = (card.queue == -1) != suspended
649 if changed:
650 operation = self.col.sched.suspend_cards if suspended else self.col.sched.unsuspend_cards
651 self.change(operation([card.id]))
652 return {'changed': changed}
653 return self.many(ids, mutate, True)
655 def cards_setFlags(self, ids, flag):
656 def mutate(id):
657 card = self.card(id)
658 changed = card.flags & FLAG_MASK != flag
659 if changed: 659 ↛ 661line 659 didn't jump to line 661 because the condition on line 659 was always true
660 self.change(self.col.set_user_flag_for_cards(flag, [card.id]))
661 return {'changed': changed}
662 return self.many(ids, mutate, True)
664 def scheduling_get(self, cardId):
665 return self.state_record(self.card(cardId))
667 def scheduling_getQueue(self, fetchLimit=1):
668 queued = self.col.sched.get_queued_cards(fetch_limit=fetchLimit)
669 cards = [{'cardId': str(item.card.id), 'queue': QUEUES[item.queue]}
670 for item in queued.cards]
671 return {'cards': cards, 'newCount': queued.new_count,
672 'learningCount': queued.learning_count, 'reviewCount': queued.review_count}
674 def scheduling_predict(self, cardId):
675 card = self.card(cardId)
676 states = compat.scheduling_states(self.col, card.id)
677 labels = self.col._backend.describe_next_states(states)
678 answers = []
679 for rating, label in zip(RATINGS, labels):
680 state = getattr(states, rating)
681 native = state.normal
682 if compat.which(state) == 'filtered': 682 ↛ 683line 682 didn't jump to line 683 because the condition on line 682 was never true
683 if compat.which(state.filtered) == 'preview':
684 amount = {'value': state.filtered.preview.scheduled_secs, 'unit': 'seconds'}
685 answers.append({'rating': rating, 'label': label, 'interval': amount})
686 continue
687 native = state.filtered.rescheduling.original_state
688 kind = compat.which(native)
689 if kind == 'review':
690 amount = {'value': native.review.scheduled_days, 'unit': 'days'}
691 elif kind == 'learning':
692 amount = {'value': native.learning.scheduled_secs, 'unit': 'seconds'}
693 elif kind == 'relearning': 693 ↛ 696line 693 didn't jump to line 696 because the condition on line 693 was always true
694 amount = {'value': native.relearning.learning.scheduled_secs, 'unit': 'seconds'}
695 else:
696 amount = None
697 answers.append({'rating': rating, 'label': label, 'interval': amount})
698 token = self.runtime.token('scheduler', self.scheduler_state(card, states))
699 return {'cardId': cardId, 'source': 'scheduler', 'stateToken': token, 'answers': answers}
701 def scheduler_state(self, card, states):
702 """What a state token binds: an answer must see the card and states its prediction described."""
703 return [card._to_backend_card().SerializeToString().hex(), states.SerializeToString().hex(), self.col.sched.today]
705 def scheduling_getDue(self, cardId, includeLearnAhead=False):
706 card = self.card(cardId)
707 now = time.time()
708 due = False
709 ahead = False
710 if card.queue in (1, 4): 710 ↛ 711line 710 didn't jump to line 711 because the condition on line 710 was never true
711 due = card.due <= now
712 ahead = not due and card.due <= now + self.col.get_config('collapseTime', 1200)
713 elif card.queue in (2, 3): 713 ↛ 715line 713 didn't jump to line 715 because the condition on line 713 was always true
714 due = card.due <= self.col.sched.today
715 return {'cardId': cardId, 'dueNow': due, 'available': due or card.queue == 0 or (includeLearnAhead and ahead), 'learnAhead': ahead}
717 def scheduling_answer(self, cardId, rating, stateToken, elapsedMs=0):
718 from anki.scheduler.v3 import CardAnswer
719 card = self.card(cardId)
720 if card.queue < 0 or card.queue == 4:
721 raise ApiError('invalidState', 'This card cannot be answered outside the reviewer.')
722 if self.runtime.active_reviewer_card == card.id:
723 raise ApiError('invalidState', 'Use reviewer.answer for the active GUI card.')
724 states = compat.scheduling_states(self.col, card.id)
725 self.runtime.check_token(stateToken, 'scheduler', self.scheduler_state(card, states))
726 card.start_timer()
727 native_rating = {'again': CardAnswer.AGAIN, 'hard': CardAnswer.HARD,
728 'good': CardAnswer.GOOD, 'easy': CardAnswer.EASY}[rating]
729 answer = self.col.sched.build_answer(card=card, states=states, rating=native_rating)
730 maximum = card.time_limit()
731 answer.milliseconds_taken = min(elapsedMs, maximum)
732 self.change(self.col.sched.answer_card(answer))
733 review_id = self.col.db.scalar('select max(id) from revlog where cid=?', card.id)
734 return {'cardId': cardId, 'reviewId': str(review_id) if review_id else None, 'scheduling': self.state_record(self.card(cardId))}
736 def scheduling_answerMany(self, answers):
737 return self.many(answers, lambda data: self.scheduling_answer(**data))
739 def scheduling_repositionNewCards(self, cardIds, startingFrom, stepSize=1, randomize=False, shiftExisting=False):
740 cards = [self.card(id) for id in dict.fromkeys(cardIds)]
741 if any(card.type != 0 or card.queue != 0 or card.odid for card in cards):
742 raise ApiError('invalidState', 'Repositioning requires active new cards outside filtered decks.')
743 if startingFrom + (len({card.nid for card in cards}) - 1) * stepSize > 2147483647:
744 raise ApiError('invalidParams', 'New card positions exceed the supported range.')
745 if shiftExisting:
746 # Native shifting uses the card count (including siblings), and
747 # includes suspended, buried and filtered new cards across decks.
748 shift = len(cards) * stepSize
749 highest = self.col.db.scalar('select max(due) from cards where type=0 and due>=?', startingFrom)
750 if shift > 4294967295 or (highest is not None and highest + shift > 2147483647):
751 raise ApiError('invalidParams', 'Shifted new card positions exceed the supported range.')
752 out = self.change(self.col.sched.reposition_new_cards(
753 card_ids=[card.id for card in cards], starting_from=startingFrom,
754 step_size=stepSize, randomize=randomize, shift_existing=shiftExisting))
755 return {'changedCount': out.count}
757 def scheduling_reset(self, cardIds, restorePosition=True, resetCounts=False, log=True):
758 if resetCounts and not compat.resets_counts(): 758 ↛ 759line 758 didn't jump to line 759 because the condition on line 758 was never true
759 raise ApiError('unsupportedCapability', 'Resetting review counts requires Anki 2.1.50.')
760 def reset(id):
761 card = self.card(id)
762 self.change(compat.schedule_cards_as_new(self.col, [card.id], restorePosition, resetCounts, log))
763 return {'changed': True}
764 return self.many(cardIds, reset, True)
766 def scheduling_setDueDate(self, cardIds, days):
767 def set_due(id):
768 from anki.errors import InvalidInput
769 card = self.card(id)
770 try:
771 self.change(compat.set_due_date(self.col, [card.id], days))
772 except InvalidInput as error:
773 raise ApiError('invalidParams', compat.error_message(error)) from error
774 return {'changed': True}
775 return self.many(cardIds, set_due, True)
777 def deck_record(self, deck):
778 return {**self.summary(deck), 'kind': 'filtered' if deck.get('dyn') else 'normal',
779 'presetId': str(deck['conf']) if not deck.get('dyn') else None}
781 def decks_list(self):
782 return [self.decks_get({'id': str(deck.id)}) for deck in self.col.decks.all_names_and_ids()]
784 def decks_get(self, deck):
785 return self.deck_record(self.resolve(deck, 'deck'))
787 def decks_create(self, name):
788 out = self.change(self.col.decks.add_normal_deck_with_name(name))
789 return self.decks_get({'id': str(out.id)})
791 def decks_update(self, deck, name):
792 value = self.resolve(deck, 'deck')
793 other = self.col.decks.id_for_name(name)
794 if other and other != value['id']:
795 raise ApiError('conflict', 'A deck with this name exists.')
796 # Before 2.1.45 rename takes the deck dictionary.
797 # Before 2.1.28 renaming changes only the dict it is given, so pass the registered one.
798 self.change(self.col.decks.rename(value['id'] if compat.reports_changes() else self.col.decks.get(value['id']), name))
799 return self.decks_get({'id': str(value['id'])})
801 def decks_delete(self, decks, deleteCards):
802 def delete(reference):
803 value = self.resolve(reference, 'deck')
804 self.change(self.col.decks.remove([value['id']]))
805 return {'changed': True}
806 return self.many(decks, delete, True)
808 def decks_getCounts(self, deck, includeChildren=True):
809 value = self.resolve(deck, 'deck')
810 def find(node):
811 if node.deck_id == value['id']:
812 return node
813 for child in node.children: 813 ↛ exitline 813 didn't return from function 'find' because the loop on line 813 didn't complete
814 match = find(child)
815 if match: 815 ↛ 813line 815 didn't jump to line 813 because the condition on line 815 was always true
816 return match
817 node = find(self.col.sched.deck_due_tree())
818 if not node: 818 ↛ 819line 818 didn't jump to line 819 because the condition on line 818 was never true
819 raise ApiError('notFound', 'Deck counts unavailable.')
820 counts = [node.new_count, node.learn_count, node.review_count]
821 if not includeChildren: 821 ↛ 822line 821 didn't jump to line 822 because the condition on line 821 was never true
822 for child in node.children:
823 counts = [max(0, a - b) for a, b in zip(counts, [child.new_count, child.learn_count, child.review_count])]
824 dids = [value['id']] + ([id for _, id in self.col.decks.children(value['id'])] if includeChildren else [])
825 total = sum(self.col.db.scalar('select count(*) from cards where did=?', id) for id in dids)
826 return {'deckId': str(value['id']), **dict(zip(['new', 'learning', 'review'], counts)), 'total': total}
828 def noteTypes_list(self):
829 return [{'id': str(value.id), 'name': value.name} for value in self.col.models.all_names_and_ids()]
831 def type_record(self, model):
832 fields = []
833 for field in model['flds']:
834 fields.append({'name': field['name'], **{public: field.get(native, '' if public == 'description' else False)
835 for public, native in FIELD_KEYS.items()}})
836 templates = []
837 for template in model['tmpls']:
838 templates.append({'name': template['name'], **{public: (template.get(native) or (20 if public == 'browserFontSize' else 'Arial' if public == 'browserFontFamily' else ''))
839 for public, native in TEMPLATE_KEYS.items()},
840 'deck': {'id': str(template['did'])} if template.get('did') else None})
841 return {**self.summary(model), 'kind': 'cloze' if model['type'] else 'normal', 'fields': fields,
842 'templates': templates, 'css': model['css'], 'sortField': model['flds'][model['sortf']]['name'],
843 'latexHeader': model.get('latexPre', ''), 'latexFooter': model.get('latexPost', ''),
844 'latexSvg': bool(model.get('latexsvg', False)), 'modifiedAt': timestamp(model['mod'])}
846 def noteTypes_get(self, noteType):
847 return self.type_record(self.resolve(noteType, 'noteType'))
849 def fill_field(self, target, source):
850 target['name'] = source.get('name', target['name'])
851 for public, native in FIELD_KEYS.items():
852 if public in source:
853 target[native] = source[public]
855 def fill_template(self, target, source):
856 target['name'] = source.get('name', target['name'])
857 for public, native in TEMPLATE_KEYS.items():
858 if public in source:
859 target[native] = source[public]
860 if 'deck' in source: 860 ↛ 861line 860 didn't jump to line 861 because the condition on line 860 was never true
861 target['did'] = self.resolve(source['deck'], 'deck')['id'] if source['deck'] else None
863 def noteTypes_create(self, name, fields, templates, kind='normal', css='', sortField=None, latexHeader='', latexFooter='', latexSvg=False):
864 if self.col.models.by_name(name): 864 ↛ 865line 864 didn't jump to line 865 because the condition on line 864 was never true
865 raise ApiError('conflict', 'Note type already exists.')
866 model = self.col.models.new(name)
867 model.update(type=int(kind == 'cloze'), css=css, latexPre=latexHeader, latexPost=latexFooter, latexsvg=latexSvg)
868 for data in fields:
869 field = self.col.models.new_field(data['name'])
870 self.fill_field(field, data)
871 self.col.models.add_field(model, field)
872 for data in templates:
873 template = self.col.models.new_template(data['name'])
874 self.fill_template(template, data)
875 self.col.models.add_template(model, template)
876 require_unique_names(model['flds'], True)
877 require_unique_names(model['tmpls'], False)
878 names = [field['name'] for field in model['flds']]
879 model['sortf'] = names.index(sortField) if sortField else 0
880 out = self.change(self.col.models.add_dict(model))
881 return self.noteTypes_get({'id': str(out.id)})
883 def noteTypes_update(self, noteType, patch):
884 model = self.resolve(noteType, 'noteType')
885 mapping = {'name': 'name', 'css': 'css', 'latexHeader': 'latexPre', 'latexFooter': 'latexPost', 'latexSvg': 'latexsvg'}
886 if 'name' in patch:
887 other = self.col.models.by_name(patch['name'])
888 if other and int(other['id']) != model['id']: 888 ↛ 889line 888 didn't jump to line 889 because the condition on line 888 was never true
889 raise ApiError('conflict', 'Note type name exists.')
890 for key, value in patch.items():
891 if key == 'sortField':
892 names = [field['name'] for field in model['flds']]
893 if value not in names: 893 ↛ 894line 893 didn't jump to line 894 because the condition on line 893 was never true
894 raise ApiError('validationFailed', 'Sort field not found.')
895 model['sortf'] = names.index(value)
896 else:
897 model[mapping[key]] = value
898 self.change(self.col.models.update_dict(model))
899 return self.noteTypes_get({'id': str(model['id'])})
901 def noteTypes_editStructure(self, noteType, edits):
902 model = self.resolve(noteType, 'noteType')
903 for edit in edits:
904 is_field = edit['op'].endswith('Field')
905 key = 'flds' if is_field else 'tmpls'
906 values = model[key]
907 verb = edit['op'].replace('Field' if is_field else 'Template', '')
908 if verb == 'add':
909 data = edit['field' if is_field else 'template']
910 value = self.col.models.new_field(data['name']) if is_field else self.col.models.new_template(data['name'])
911 (self.fill_field if is_field else self.fill_template)(value, data)
912 index = edit.get('index', len(values))
913 if index > len(values): 913 ↛ 914line 913 didn't jump to line 914 because the condition on line 913 was never true
914 raise ApiError('validationFailed', 'Insertion index out of range.')
915 values.insert(index, value)
916 else:
917 value = next((value for value in values if value['name'] == edit['name']), None)
918 if value is None: 918 ↛ 919line 918 didn't jump to line 919 because the condition on line 918 was never true
919 raise ApiError('notFound', 'Field/template not found.')
920 if verb == 'update':
921 patch = edit['patch']
922 if is_field and 'name' in patch:
923 self.col.models.rename_field(model, value, patch['name'])
924 (self.fill_field if is_field else self.fill_template)(value, patch)
925 elif verb == 'remove':
926 values.remove(value)
927 elif verb == 'move': 927 ↛ 932line 927 didn't jump to line 932 because the condition on line 927 was always true
928 if edit['index'] >= len(values): 928 ↛ 929line 928 didn't jump to line 929 because the condition on line 928 was never true
929 raise ApiError('validationFailed', 'Move index out of range.')
930 values.remove(value)
931 values.insert(edit['index'], value)
932 if not values:
933 raise ApiError('validationFailed', 'A note type must keep at least one ' + ('field.' if is_field else 'template.'))
934 require_unique_names(values, is_field)
935 self.change(self.col.models.update_dict(model))
936 return self.noteTypes_get({'id': str(model['id'])})
938 def noteTypes_getTemplateUsage(self, noteType):
939 model = self.resolve(noteType, 'noteType')
940 names = {field['name'] for field in model['flds']}
941 result = []
942 for template in model['tmpls']:
943 fields = [template_fields(template[key], names) for key in ('qfmt', 'afmt')]
944 result.append({'templateName': template['name'], 'questionFields': fields[0], 'answerFields': fields[1]})
945 return result
947 def noteTypes_replaceText(self, find, replace, noteTypes=None, allNoteTypes=False, targets=('question', 'answer', 'css')):
948 references = noteTypes if noteTypes is not None else self.noteTypes_list()
949 changed = 0
950 for reference in references:
951 model = self.resolve(reference, 'noteType')
952 before = copy.deepcopy(model)
953 if 'css' in targets: 953 ↛ 955line 953 didn't jump to line 955 because the condition on line 953 was always true
954 model['css'] = model['css'].replace(find, replace)
955 for template in model['tmpls']:
956 for target, key in [('question', 'qfmt'), ('answer', 'afmt')]:
957 if target in targets: 957 ↛ 956line 957 didn't jump to line 956 because the condition on line 957 was always true
958 template[key] = template[key].replace(find, replace)
959 if model != before: 959 ↛ 950line 959 didn't jump to line 950 because the condition on line 959 was always true
960 self.change(self.col.models.update_dict(model))
961 changed += 1
962 return {'changedCount': changed}
964 def noteTypes_deleteUnused(self, noteTypes):
965 def delete(reference):
966 model = self.resolve(reference, 'noteType')
967 if self.col.models.use_count(model):
968 raise ApiError('conflict', 'Note type is in use.')
969 self.change(self.col.models.remove(model['id']))
970 return {'changed': True}
971 return self.many(noteTypes, delete, True)
973 def preset(self, reference):
974 values = self.col.decks.all_config()
975 value = next((value for value in values if str(value['id']) == reference.get('id') or value['name'] == reference.get('name')), None)
976 if value is None:
977 raise ApiError('notFound', 'Preset not found.')
978 return self.col._backend.get_deck_config(value['id'])
980 def preset_record(self, config):
981 settings = {}
982 # Settings this Anki release does not define are omitted.
983 native_fields = config.config.DESCRIPTOR.fields_by_name
984 for public, native in PRESET_KEYS.items():
985 if native in native_fields: 985 ↛ 984line 985 didn't jump to line 984 because the condition on line 985 was always true
986 value = getattr(config.config, native)
987 settings[public] = list(value) if compat.repeated(native_fields[native]) else value
988 for public, (native, names) in PRESET_ENUMS.items():
989 if native in native_fields: 989 ↛ 988line 989 didn't jump to line 988 because the condition on line 989 was always true
990 value = preset_enum_value(public, getattr(config.config, native))
991 if value is not None: 991 ↛ 988line 991 didn't jump to line 988 because the condition on line 991 was always true
992 settings[public] = value
993 return {'id': str(config.id), 'name': config.name, 'settings': settings, 'modifiedAt': timestamp(config.mtime_secs)}
995 def deckPresets_list(self):
996 return [self.summary(value) for value in self.col.decks.all_config()]
998 def deckPresets_get(self, preset):
999 return self.preset_record(self.preset(preset))
1001 def preset_update_request(self, deck_id, configs=(), remove=(), reschedule=False):
1002 from anki.decks import UpdateDeckConfigs
1003 if reschedule and 'fsrs_reschedule' not in UpdateDeckConfigs.DESCRIPTOR.fields_by_name: 1003 ↛ 1004line 1003 didn't jump to line 1004 because the condition on line 1003 was never true
1004 raise ApiError('unsupportedCapability', 'This Anki release cannot reschedule cards with FSRS.')
1005 current = self.col.decks.get_deck_configs_for_update(deck_id)
1006 # Retain the current values of options this API does not expose.
1007 retained = {name: compat.field(current, name) for name in (
1008 'card_state_customizer', 'new_cards_ignore_review_limit', 'fsrs',
1009 'apply_all_parent_limits', 'fsrs_health_check')}
1010 return compat.message(UpdateDeckConfigs, target_deck_id=deck_id, configs=configs, removed_config_ids=remove,
1011 mode=0, limits=compat.field(current.current_deck, 'limits'),
1012 fsrs_reschedule=reschedule, **retained)
1014 def deckPresets_create(self, name, cloneFrom=None):
1015 if any(value['name'] == name for value in self.col.decks.all_config()): 1015 ↛ 1016line 1015 didn't jump to line 1016 because the condition on line 1015 was never true
1016 raise ApiError('conflict', 'Preset already exists.')
1017 current = self.col.decks.get_deck_configs_for_update(1)
1018 config = copy.deepcopy(self.preset(cloneFrom) if cloneFrom else current.defaults)
1019 config.id, config.name = 0, name
1020 # Updating configs selects the last one: include the previously selected
1021 # preset last so cloning does not change the Default deck's assignment.
1022 selected = self.preset({'id': str(current.current_deck.config_id)})
1023 self.change(self.col.decks.update_deck_configs(self.preset_update_request(1, [config, selected])))
1024 return self.deckPresets_get({'name': name})
1026 def deckPresets_update(self, preset, name=None, settings=None, rescheduleFsrs=False):
1027 config = copy.deepcopy(self.preset(preset))
1028 if name:
1029 config.name = name
1030 native_fields = config.config.DESCRIPTOR.fields_by_name
1031 for public, value in (settings or {}).items():
1032 native = PRESET_ENUMS[public][0] if public in PRESET_ENUMS else PRESET_KEYS[public]
1033 if native not in native_fields: 1033 ↛ 1034line 1033 didn't jump to line 1034 because the condition on line 1033 was never true
1034 raise ApiError('unsupportedCapability', 'This Anki release has no preset setting ' + public + '.')
1035 if public in PRESET_ENUMS:
1036 setattr(config.config, native, preset_enum_number(public, value))
1037 else:
1038 destination = getattr(config.config, native)
1039 if isinstance(value, list): 1039 ↛ 1040line 1039 didn't jump to line 1040 because the condition on line 1039 was never true
1040 destination[:] = value
1041 else:
1042 setattr(config.config, native, value)
1043 current = self.col.decks.get_deck_configs_for_update(1)
1044 selected = self.preset({'id': str(current.current_deck.config_id)})
1045 configs = [config] if selected.id == config.id else [config, selected]
1046 self.change(self.col.decks.update_deck_configs(self.preset_update_request(1, configs, reschedule=rescheduleFsrs)))
1047 return self.deckPresets_get({'id': str(config.id)})
1049 def deckPresets_assign(self, decks, preset, rescheduleFsrs=False):
1050 config = self.preset(preset)
1051 def assign(reference):
1052 deck = self.resolve(reference, 'deck')
1053 if deck.get('dyn'): 1053 ↛ 1054line 1053 didn't jump to line 1054 because the condition on line 1053 was never true
1054 raise ApiError('invalidState', 'Filtered decks have no preset.')
1055 changed = deck['conf'] != config.id
1056 if changed: 1056 ↛ 1058line 1056 didn't jump to line 1058 because the condition on line 1056 was always true
1057 self.change(self.col.decks.update_deck_configs(self.preset_update_request(deck['id'], [config], reschedule=rescheduleFsrs)))
1058 return {'changed': changed}
1059 return self.many(decks, assign, True)
1061 def deckPresets_delete(self, preset, replacement=None):
1062 config = self.preset(preset)
1063 if config.id == 1: 1063 ↛ 1064line 1063 didn't jump to line 1064 because the condition on line 1063 was never true
1064 raise ApiError('conflict', 'Cannot delete the Default preset.')
1065 dependent = [deck for deck in self.decks_list() if deck['presetId'] == str(config.id)]
1066 if dependent and replacement is None: 1066 ↛ 1067line 1066 didn't jump to line 1067 because the condition on line 1066 was never true
1067 raise ApiError('conflict', 'An in-use preset needs a replacement.')
1068 if replacement: 1068 ↛ 1074line 1068 didn't jump to line 1074 because the condition on line 1068 was always true
1069 chosen = self.preset(replacement)
1070 if chosen.id == config.id: 1070 ↛ 1071line 1070 didn't jump to line 1071 because the condition on line 1070 was never true
1071 raise ApiError('conflict', 'Replacement is the preset being deleted.')
1072 for deck in dependent:
1073 self.change(self.col.decks.update_deck_configs(self.preset_update_request(int(deck['id']), [chosen])))
1074 selected = self.preset({'id': str(self.resolve({'id': '1'}, 'deck')['conf'])})
1075 self.change(self.col.decks.update_deck_configs(self.preset_update_request(1, [selected], [config.id])))
1076 return {'changed': True}
1078 def media_filename(self, filename):
1079 if filename in ('.', '..') or any(char in filename for char in ('/', '\\', '\0')):
1080 raise ApiError('invalidParams', 'Expected a media basename.')
1081 return MEDIA_ILLEGAL_CHARACTERS.sub('', unicodedata.normalize('NFC', filename))
1083 def media_list(self, pattern='*'):
1084 self.media_filename(pattern)
1085 return sorted(name for name in os.listdir(self.col.media.dir()) if fnmatch.fnmatchcase(name, pattern))
1087 def media_get(self, filename):
1088 filename = self.media_filename(filename)
1089 path = Path(self.col.media.dir()) / filename
1090 if not path.is_file():
1091 raise ApiError('notFound', 'Media file not found.')
1092 return {'filename': filename, 'data': base64.b64encode(path.read_bytes()).decode('ascii')}
1094 def media_delete(self, filename):
1095 filename = self.media_filename(filename)
1096 if not (Path(self.col.media.dir()) / filename).is_file():
1097 raise ApiError('notFound', 'Media file not found.')
1098 self.col.media.trash_files([filename])
1099 return {'changed': True}
1101 def media_getDirectory(self):
1102 return {'path': os.path.abspath(self.col.media.dir())}
1104 def store_bytes(self, filename, data, collision='rename', skipIfHash=None):
1105 if collision != 'replace':
1106 try:
1107 return self._store_bytes(filename, data, collision, skipIfHash)
1108 except (OSError,) + compat.backend_errors() as error:
1109 raise ApiError('ioError', str(error)) from error
1110 from .media import MediaTransaction
1111 transaction = MediaTransaction(self)
1112 try:
1113 actual = transaction.install(filename, data, skipIfHash, collision)
1114 transaction.commit()
1115 return {'filename': actual, 'status': 'skipped' if actual is None else 'stored',
1116 'sha256': hashlib.sha256(data).hexdigest()}
1117 except Exception as error:
1118 failures = transaction.rollback()
1119 if isinstance(error, ApiError) and not failures: 1119 ↛ 1120line 1119 didn't jump to line 1120 because the condition on line 1119 was never true
1120 raise
1121 raise ApiError('ioError', 'Media replacement failed.', {'rollbackFailures': failures}) from error
1123 def _store_bytes(self, filename, data, collision='rename', skipIfHash=None):
1124 filename = self.media_filename(filename)
1125 sha = hashlib.sha256(data).hexdigest()
1126 if skipIfHash and hashlib.new(skipIfHash['algorithm'], data).hexdigest() == skipIfHash['digest']: 1126 ↛ 1127line 1126 didn't jump to line 1127 because the condition on line 1126 was never true
1127 return {'filename': None, 'status': 'skipped', 'sha256': sha}
1128 path = Path(self.col.media.dir()) / filename
1129 if path.exists():
1130 if collision == 'error':
1131 raise ApiError('conflict', 'Media filename already exists.')
1132 if collision == 'replace' and path.read_bytes() != data:
1133 # Replacement callers journal the original before this native write.
1134 self.col.media.trash_files([filename])
1135 actual = self.col.media.write_data(filename, data)
1136 return {'filename': actual, 'status': 'stored', 'sha256': sha}
1138 def review_ids(self, cardIds=None, deck=None, includeChildren=False, membership='current', afterId=None, includeManual=True):
1139 clauses, args = [], []
1140 if cardIds is not None:
1141 for id in cardIds:
1142 self.card(id)
1143 # Inline validated integers; SQLite before 3.32 allows only 999 parameters.
1144 clauses.append('cid in (' + ','.join(str(entity_id(id)) for id in cardIds) + ')')
1145 if deck:
1146 value = self.resolve(deck, 'deck')
1147 dids = [value['id']]
1148 if includeChildren: 1148 ↛ 1149line 1148 didn't jump to line 1149 because the condition on line 1148 was never true
1149 dids.extend(id for _, id in self.col.decks.children(value['id']))
1150 column = '(case when odid!=0 then odid else did end)' if membership == 'home' else 'did'
1151 clauses.append('cid in (select id from cards where ' + column + ' in (' + ','.join(str(int(id)) for id in dids) + '))')
1152 if afterId: 1152 ↛ 1153line 1152 didn't jump to line 1153 because the condition on line 1152 was never true
1153 clauses.append('id>?')
1154 args.append(entity_id(afterId))
1155 if not includeManual: 1155 ↛ 1156line 1155 didn't jump to line 1156 because the condition on line 1155 was never true
1156 clauses.append('type not in (4,5)')
1157 sql = 'select id from revlog' + (' where ' + ' and '.join(clauses) if clauses else '') + ' order by id'
1158 return self.col.db.list(sql, *args)
1160 def review_record(self, id):
1161 row = self.col.db.first('select id,cid,usn,ease,ivl,lastIvl,factor,time,type from revlog where id=?', id)
1162 if not row: 1162 ↛ 1163line 1162 didn't jump to line 1163 because the condition on line 1162 was never true
1163 return None
1164 id, cid, usn, ease, ivl, last, factor, elapsed, kind = row
1165 return {'id': str(id), 'cardId': str(cid), 'answeredAt': timestamp(id / 1000),
1166 'rating': RATINGS[ease - 1] if 1 <= ease <= 4 else None, 'interval': interval(ivl),
1167 'previousInterval': interval(last), 'factor': {'encoding': 'unknown', 'value': factor},
1168 'elapsedMs': elapsed, 'kind': KINDS[kind], 'syncSequence': usn}
1170 def reviews_list(self, limit=100, cursor=None, **params):
1171 ids = None if cursor else self.review_ids(**params)
1172 page = self.page(ids, 'reviews.list', {**params, 'limit': limit, 'cursor': cursor})
1173 records = (self.review_record(int(id)) for id in page['ids'])
1174 return {'items': [value for value in records if value], 'nextCursor': page['nextCursor']}
1176 def reviews_getLatestId(self, **params):
1177 ids = self.review_ids(**params)
1178 return {'id': str(ids[-1]) if ids else None}
1180 def statistics_getToday(self):
1181 graphs = compat.graphs(self.col, '')
1182 cutoff = compat.day_cutoff(self.col)
1183 return {'count': graphs.today.answer_count, 'day': scheduler_day(cutoff).isoformat(), 'nextDayAt': timestamp(cutoff)}
1185 def statistics_getReviewDays(self):
1186 graphs = compat.graphs(self.col, '')
1187 today = scheduler_day(compat.day_cutoff(self.col))
1188 return [{'day': (today + timedelta(days=offset)).isoformat(), 'count': review_total(counts)}
1189 for offset, counts in sorted(graphs.reviews.count.items(), reverse=True)]
1191 def statistics_getSummary(self, deck=None):
1192 query = compat.deck_search(self.col, self.resolve(deck, 'deck')['name']) if deck else ''
1193 graphs = compat.graphs(self.col, query)
1194 counts = graphs.card_counts.excluding_inactive
1195 card_ids = self.col.find_cards(query)
1196 note_ids = {self.col.get_card(id).nid for id in card_ids}
1197 review_count = sum(review_total(value) for value in graphs.reviews.count.values())
1198 times = sum(review_total(value) for value in graphs.reviews.time.values())
1199 return {'cardCount': len(card_ids), 'noteCount': len(note_ids), 'reviewCount': review_count,
1200 'reviewTimeMs': times * 1000, 'newCount': counts.newCards, 'learningCount': counts.learn + counts.relearn,
1201 'reviewCardCount': counts.young + counts.mature, 'suspendedCount': counts.suspended}
1203 def statistics_getHtml(self, deck=None):
1204 stats = self.col.stats()
1205 stats.wholeCollection = deck is None
1206 if deck:
1207 # Legacy HTML stats binds its deck explicitly; never change selected deck as a read.
1208 stats.did = self.resolve(deck, 'deck')['id']
1209 return {'html': stats.report(), 'format': 'legacyReport'}
1211 def packages_import(self, path):
1212 if not os.path.isfile(path): 1212 ↛ 1213line 1212 didn't jump to line 1213 because the condition on line 1212 was never true
1213 raise ApiError('notFound', 'Package not found.')
1214 self.change(compat.import_package(self.col, path))
1215 return {'completed': True}
1217 def packages_export(self, deck, path, includeScheduling=False):
1218 compat.export_package(self.col, path, self.resolve(deck, 'deck')['id'], includeScheduling)
1219 return {'path': os.path.abspath(path)}
1221 def advanced_cards_update(self, cardId, patch):
1222 card = self.card(cardId)
1223 if any(key in patch for key in ('remainingSteps', 'fsrsMemory')):
1224 raise ApiError('unsupportedCapability', 'Coupled scheduler state must use native scheduling transitions.')
1225 if 'customData' in patch and not hasattr(card, 'custom_data'): 1225 ↛ 1226line 1225 didn't jump to line 1226 because the condition on line 1225 was never true
1226 raise ApiError('unsupportedCapability', 'Card custom data requires Anki 2.1.55.')
1227 mapping = {'intervalDays': 'ivl', 'sm2EasePermille': 'factor', 'repetitions': 'reps', 'lapses': 'lapses', 'customData': 'custom_data'}
1228 for key, value in patch.items():
1229 if key == 'customData':
1230 try:
1231 if not isinstance(json.loads(value or '{}'), dict):
1232 raise ValueError('Expected object')
1233 except ValueError as error:
1234 raise ApiError('validationFailed', 'Custom data must encode a JSON object.') from error
1235 if key == 'sm2EasePermille' and not 1300 <= value <= 65535:
1236 raise ApiError('validationFailed', 'SM-2 ease must be between 1300 and 65535 permille.')
1237 setattr(card, mapping[key], value)
1238 self.change(compat.update_card(self.col, card))
1239 return self.card_record(self.card(cardId))
1241 def advanced_reviews_import(self, reviews):
1242 rows, ids = [], set()
1243 for review in reviews:
1244 id = entity_id(review['id'])
1245 cid = self.card(review['cardId']).id
1246 if id in ids or self.col.db.scalar('select 1 from revlog where id=?', id):
1247 raise ApiError('conflict', 'Review ID already exists.')
1248 ids.add(id)
1249 def encoded(value):
1250 amount = value['value']
1251 if amount > 2147483647: 1251 ↛ 1252line 1251 didn't jump to line 1252 because the condition on line 1251 was never true
1252 raise ApiError('validationFailed', 'Interval exceeds native limits.')
1253 return -amount if value['unit'] == 'seconds' else amount
1254 ease = RATINGS.index(review['rating']) + 1 if review['rating'] else 0
1255 factor, elapsed = review['factor']['value'], review['elapsedMs']
1256 if factor > 65535 or elapsed > 2147483647: 1256 ↛ 1257line 1256 didn't jump to line 1257 because the condition on line 1256 was never true
1257 raise ApiError('validationFailed', 'Review metadata exceeds native limits.')
1258 rows.append((id, cid, -1, ease, encoded(review['interval']), encoded(review['previousInterval']),
1259 factor, elapsed, KINDS.index(review['kind'])))
1260 if rows: 1260 ↛ 1265line 1260 didn't jump to line 1265 because the condition on line 1260 was always true
1261 compat.transact(self.col, lambda: self.col.db.executemany(
1262 'insert into revlog (id,cid,usn,ease,ivl,lastIvl,factor,time,type) values (?,?,?,?,?,?,?,?,?)', rows))
1263 self.runtime.full_reset_required = True
1264 self.runtime.invalidate_predictions()
1265 return {'changedCount': len(rows)}
1267 def collection_undo(self):
1268 status = self.col.undo_status()
1269 if not status.undo: 1269 ↛ 1270line 1269 didn't jump to line 1270 because the condition on line 1269 was never true
1270 raise ApiError('invalidState', 'Nothing to undo.')
1271 self.change(self.col.undo())
1272 return {'label': status.undo, 'changed': True}
1274 def collection_checkIntegrity(self):
1275 report, ok = self.col.fix_integrity()
1276 self.runtime.full_reset_required = True
1277 return {'problems': [] if ok else [report], 'repaired': bool(ok)}