/
flashcard.go
828 lines (714 loc) · 18 KB
/
flashcard.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
package core
import (
"bytes"
"database/sql"
"encoding/json"
"fmt"
"io"
"log"
"reflect"
"strings"
"time"
"github.com/julien-sobczak/the-notewriter/pkg/clock"
"github.com/julien-sobczak/the-notewriter/pkg/markdown"
"gopkg.in/yaml.v3"
)
const DefaultEaseFactor = 2.5 // Same as Anki
const MinEaseFactor = 1.3 // Same as Anki
const DefaultFirstInterval = 1 // day
type CardType int
const (
CardNew CardType = 0
CardLearning CardType = 1
CardReview CardType = 2
CardRelearning CardType = 3
)
type QueueType int
const (
QueueSuspend QueueType = -1 // leeches as manual suspension is not supported
QueueNew QueueType = 0 // new (never shown)
QueueLearn QueueType = 1 // learning/relearning
QueueReview QueueType = 2 // review (as for type)
QueueDayLearn QueueType = 3 // in learning, next review in at least a day after the previous review
)
type Flashcard struct {
OID string `yaml:"oid"`
// Short title of the note (denormalized field)
ShortTitle string `yaml:"short_title"`
// File
FileOID string `yaml:"file_oid"`
File *File `yaml:"-"` // Lazy-loaded
// Note representing the flashcard
NoteOID string `yaml:"note_oid"`
Note *Note `yaml:"-"` // Lazy-loaded
// The filepath of the file containing the note (denormalized field)
RelativePath string `yaml:"relative_path"`
// List of tags
Tags []string `yaml:"tags,omitempty"`
// Fields in Markdown (best for editing)
FrontMarkdown string `yaml:"front_markdown"`
BackMarkdown string `yaml:"back_markdown"`
// Fields in HTML (best for rendering)
FrontHTML string `yaml:"front_html"`
BackHTML string `yaml:"back_html"`
// Fields in raw text (best for indexing)
FrontText string `yaml:"front_text"`
BackText string `yaml:"back_text"`
// Timestamps to track changes
CreatedAt time.Time `yaml:"created_at"`
UpdatedAt time.Time `yaml:"updated_at"`
DeletedAt time.Time `yaml:"deleted_at,omitempty"`
LastCheckedAt time.Time `yaml:"-"`
// SRS
DueAt time.Time `yaml:"due_at,omitempty"`
StudiedAt time.Time `yaml:"studied_at,omitempty"`
Settings map[string]any `yaml:"settings,omitempty"`
new bool
stale bool
}
type Study struct {
OID string `yaml:"oid"` // Not persisted in database but can be useful to deduplicate, etc.
StartedAt time.Time `yaml:"started_at"` // Timestamp when the first card was revealed
EndedAt time.Time `yaml:"ended_at"` // Timestamp when the last card was completed
Reviews []*Review `yaml:"reviews"`
}
type Feedback string
const (
// Anki-inspired feedbacks
FeedbackEasy Feedback = "easy"
FeedbackGood Feedback = "good"
FeedbackAgain Feedback = "again"
FeedbackHard Feedback = "hard"
// Special feedbacks
FeedbackTooEasy Feedback = "too-easy" // Used to bury a card to max interval
FeedbackTooHard Feedback = "too-hard" // Used to relearn a card from scratch
)
type Review struct {
FlashcardOID string `yaml:"flashcard_oid"`
Feedback Feedback `yaml:"feedback"`
DurationInMs int `yaml:"duration_ms"`
CompletedAt time.Time `yaml:"completed_at"`
DueAt time.Time `yaml:"due_at"`
Settings map[string]any `yaml:"settings"` // Include algorithm-specific attributes (like the e-factor in SM-2)
}
func NewOrExistingFlashcard(file *File, note *Note) *Flashcard {
if note.new {
return NewFlashcard(file, note)
}
// Flashcard may already exists
flashcard, err := CurrentCollection().LoadFlashcardByNoteOID(note.OID)
if err != nil {
log.Fatal(err)
}
// or not if the note just have been saved now
if flashcard == nil {
return NewFlashcard(file, note)
}
if note.stale {
flashcard.update(file, note)
}
return flashcard
}
// NewFlashcard initializes a new flashcard.
func NewFlashcard(file *File, note *Note) *Flashcard {
frontMarkdown, backMarkdown := splitFrontBack(note.ContentMarkdown)
// FIXME if front => invalid flashcard (lint)
f := &Flashcard{
OID: NewOID(),
ShortTitle: note.ShortTitle,
FileOID: file.OID,
File: file,
NoteOID: note.OID,
Note: note,
RelativePath: note.RelativePath,
Tags: note.GetTags(),
// SRS
// Wait for first study to initialize SRS fields
// Timestamps
CreatedAt: clock.Now(),
UpdatedAt: clock.Now(),
new: true,
stale: true,
}
f.updateContent(frontMarkdown, backMarkdown)
return f
}
/* Object */
func (f *Flashcard) Kind() string {
return "flashcard"
}
func (f *Flashcard) UniqueOID() string {
return f.OID
}
func (f *Flashcard) ModificationTime() time.Time {
return f.UpdatedAt
}
func (f *Flashcard) Refresh() (bool, error) {
// Regenerate the flashcard content by rereading the associated note
file, err := CurrentCollection().LoadFileByOID(f.FileOID)
if err != nil {
return false, err
}
note, err := CurrentCollection().LoadNoteByOID(f.NoteOID)
if err != nil {
return false, err
}
f.update(file, note)
return f.stale, nil
}
func (f *Flashcard) State() State {
if !f.DeletedAt.IsZero() {
return Deleted
}
if f.new {
return Added
}
if f.stale {
return Modified
}
return None
}
func (f *Flashcard) ForceState(state State) {
switch state {
case Added:
f.new = true
case Deleted:
f.DeletedAt = clock.Now()
}
f.stale = true
}
func (f *Flashcard) Read(r io.Reader) error {
err := yaml.NewDecoder(r).Decode(f)
if err != nil {
return err
}
return nil
}
func (f *Flashcard) Write(w io.Writer) error {
data, err := yaml.Marshal(f)
if err != nil {
return err
}
_, err = w.Write(data)
return err
}
func (f *Flashcard) SubObjects() []StatefulObject {
return nil
}
func (f *Flashcard) Blobs() []*BlobRef {
// Use Media.Blobs() instead
return nil
}
func (f *Flashcard) Relations() []*Relation {
// We consider only relations related to notes
return nil
}
func (f Flashcard) String() string {
return fmt.Sprintf("flashcard %q [%s]", f.ShortTitle, f.OID)
}
/* Update */
func (f *Flashcard) updateContent(frontMarkdown, backMarkdown string) {
f.FrontMarkdown = frontMarkdown
f.BackMarkdown = backMarkdown
f.FrontHTML = markdown.ToHTML(frontMarkdown)
f.BackHTML = markdown.ToHTML(backMarkdown)
f.FrontText = markdown.ToText(frontMarkdown)
f.BackText = markdown.ToText(backMarkdown)
}
func (f *Flashcard) update(file *File, note *Note) {
if f.ShortTitle != note.ShortTitle {
f.ShortTitle = note.ShortTitle
f.stale = true
}
if f.FileOID != file.OID {
f.FileOID = file.OID
f.File = file
f.stale = true
}
if f.NoteOID != note.OID {
f.NoteOID = note.OID
f.Note = note
f.stale = true
}
if !reflect.DeepEqual(f.Tags, note.GetTags()) {
f.Tags = note.GetTags()
f.stale = true
}
frontMarkdown, backMarkdown := splitFrontBack(note.ContentMarkdown)
if f.FrontMarkdown != frontMarkdown || f.BackMarkdown != backMarkdown {
f.updateContent(frontMarkdown, backMarkdown)
f.stale = true
}
}
/* State Management */
func (f *Flashcard) New() bool {
return f.new
}
func (f *Flashcard) Updated() bool {
return f.stale
}
/* Parsing */
func splitFrontBack(content string) (string, string) {
front := true
var frontContent bytes.Buffer
var backContent bytes.Buffer
lines := strings.Split(content, "\n")
for _, line := range lines {
if line == "---" {
front = false
continue
}
if front {
frontContent.WriteString(line)
frontContent.WriteString("\n")
} else {
backContent.WriteString(line)
backContent.WriteString("\n")
}
}
return strings.TrimSpace(frontContent.String()), strings.TrimSpace(backContent.String())
}
func (f *Flashcard) Check() error {
CurrentLogger().Debugf("Checking flashcard %s...", f.ShortTitle)
f.LastCheckedAt = clock.Now()
query := `
UPDATE flashcard
SET last_checked_at = ?
WHERE oid = ?;`
_, err := CurrentDB().Client().Exec(query,
timeToSQL(f.LastCheckedAt),
f.OID,
)
return err
}
func (f *Flashcard) Save() error {
var err error
f.UpdatedAt = clock.Now()
f.LastCheckedAt = clock.Now()
switch f.State() {
case Added:
err = f.Insert()
case Modified:
err = f.Update()
case Deleted:
err = f.Delete()
default:
err = f.Check()
}
if err != nil {
return err
}
f.new = false
f.stale = false
return nil
}
func (f *Flashcard) Insert() error {
CurrentLogger().Debugf("Inserting flashcard %s...", f.ShortTitle)
query := `
INSERT INTO flashcard(
oid,
file_oid,
note_oid,
relative_path,
short_title,
tags,
front_markdown,
back_markdown,
front_html,
back_html,
front_text,
back_text,
created_at,
updated_at,
last_checked_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
`
_, err := CurrentDB().Client().Exec(query,
f.OID,
f.FileOID,
f.NoteOID,
f.RelativePath,
f.ShortTitle,
strings.Join(f.Tags, ","),
f.FrontMarkdown,
f.BackMarkdown,
f.FrontHTML,
f.BackHTML,
f.FrontText,
f.BackText,
timeToSQL(f.CreatedAt),
timeToSQL(f.UpdatedAt),
timeToSQL(f.LastCheckedAt))
if err != nil {
return err
}
return nil
}
func (f *Flashcard) Update() error {
CurrentLogger().Debugf("Updating flashcard %s...", f.ShortTitle)
query := `
UPDATE flashcard
SET
file_oid = ?,
note_oid = ?,
relative_path = ?,
short_title = ?,
tags = ?,
front_markdown = ?,
back_markdown = ?,
front_html = ?,
back_html = ?,
front_text = ?,
back_text = ?,
updated_at = ?,
last_checked_at = ?
WHERE oid = ?;
`
_, err := CurrentDB().Client().Exec(query,
f.FileOID,
f.NoteOID,
f.RelativePath,
f.ShortTitle,
strings.Join(f.Tags, ","),
f.FrontMarkdown,
f.BackMarkdown,
f.FrontHTML,
f.BackHTML,
f.FrontText,
f.BackText,
timeToSQL(f.UpdatedAt),
timeToSQL(f.LastCheckedAt),
f.OID)
return err
}
func (f *Flashcard) Delete() error {
CurrentLogger().Debugf("Deleting flashcard %s...", f.ShortTitle)
query := `DELETE FROM flashcard WHERE oid = ?;`
_, err := CurrentDB().Client().Exec(query, f.OID)
return err
}
func SettingsJSON(settings map[string]any) (string, error) {
var buf bytes.Buffer
bufEncoder := json.NewEncoder(&buf)
err := bufEncoder.Encode(settings)
if err != nil {
return "", err
}
return buf.String(), nil
}
// CountFlashcards returns the total number of flashcards.
func (c *Collection) CountFlashcards() (int, error) {
db := CurrentDB().Client()
var count int
if err := db.QueryRow(`SELECT count(*) FROM flashcard`).Scan(&count); err != nil {
return 0, err
}
return count, nil
}
func (c *Collection) LoadFlashcardByOID(oid string) (*Flashcard, error) {
return QueryFlashcard(CurrentDB().Client(), `WHERE oid = ?`, oid)
}
func (c *Collection) LoadFlashcardByNoteOID(noteID string) (*Flashcard, error) {
return QueryFlashcard(CurrentDB().Client(), `WHERE note_oid = ?`, noteID)
}
func (c *Collection) FindFlashcardByShortTitle(shortTitle string) (*Flashcard, error) {
return QueryFlashcard(CurrentDB().Client(), `WHERE short_title = ?`, shortTitle)
}
func (c *Collection) FindFlashcardByHash(hash string) (*Flashcard, error) {
return QueryFlashcard(CurrentDB().Client(), `WHERE hash = ?`, hash)
}
func (c *Collection) FindFlashcardsLastCheckedBefore(point time.Time, path string) ([]*Flashcard, error) {
if path == "." {
path = ""
}
return QueryFlashcards(CurrentDB().Client(), `WHERE last_checked_at < ? AND relative_path LIKE ?`, timeToSQL(point), path+"%")
}
/* SQL Helpers */
func QueryFlashcard(db SQLClient, whereClause string, args ...any) (*Flashcard, error) {
var f Flashcard
var tagsRaw string
var settingsRaw sql.NullString
var dueAt sql.NullString
var studiedAt sql.NullString
var createdAt string
var updatedAt string
var lastCheckedAt string
// Query for a value based on a single row.
if err := db.QueryRow(fmt.Sprintf(`
SELECT
oid,
file_oid,
note_oid,
relative_path,
short_title,
tags,
front_markdown,
back_markdown,
front_html,
back_html,
front_text,
back_text,
due_at,
studied_at,
settings,
created_at,
updated_at,
last_checked_at
FROM flashcard
%s;`, whereClause), args...).
Scan(
&f.OID,
&f.FileOID,
&f.NoteOID,
&f.RelativePath,
&f.ShortTitle,
&tagsRaw,
&f.FrontMarkdown,
&f.BackMarkdown,
&f.FrontHTML,
&f.BackHTML,
&f.FrontText,
&f.BackText,
&dueAt,
&studiedAt,
&settingsRaw,
&createdAt,
&updatedAt,
&lastCheckedAt,
); err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
var settings map[string]any
if settingsRaw.Valid {
err := yaml.Unmarshal([]byte(settingsRaw.String), &settings)
if err != nil {
return nil, err
}
}
f.Tags = strings.Split(tagsRaw, ",")
f.Settings = settings
f.DueAt = timeFromNullableSQL(dueAt)
f.StudiedAt = timeFromNullableSQL(studiedAt)
f.CreatedAt = timeFromSQL(createdAt)
f.UpdatedAt = timeFromSQL(updatedAt)
f.LastCheckedAt = timeFromSQL(lastCheckedAt)
return &f, nil
}
func QueryFlashcards(db SQLClient, whereClause string, args ...any) ([]*Flashcard, error) {
var flashcards []*Flashcard
rows, err := db.Query(fmt.Sprintf(`
SELECT
oid,
file_oid,
note_oid,
relative_path,
short_title,
tags,
front_markdown,
back_markdown,
front_html,
back_html,
front_text,
back_text,
due_at,
studied_at,
settings,
created_at,
updated_at,
last_checked_at
FROM flashcard
%s;`, whereClause), args...)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var f Flashcard
var tagsRaw string
var settingsRaw sql.NullString
var dueAt sql.NullString
var studiedAt sql.NullString
var createdAt string
var updatedAt string
var lastCheckedAt string
err = rows.Scan(
&f.OID,
&f.FileOID,
&f.NoteOID,
&f.RelativePath,
&f.ShortTitle,
&tagsRaw,
&f.FrontMarkdown,
&f.BackMarkdown,
&f.FrontHTML,
&f.BackHTML,
&f.FrontText,
&f.BackText,
&dueAt,
&studiedAt,
&settingsRaw,
&createdAt,
&updatedAt,
&lastCheckedAt,
)
if err != nil {
return nil, err
}
var settings map[string]any
if settingsRaw.Valid {
err := yaml.Unmarshal([]byte(settingsRaw.String), &settings)
if err != nil {
return nil, err
}
}
f.Tags = strings.Split(tagsRaw, ",")
f.Settings = settings
f.DueAt = timeFromNullableSQL(dueAt)
f.StudiedAt = timeFromNullableSQL(studiedAt)
f.CreatedAt = timeFromSQL(createdAt)
f.UpdatedAt = timeFromSQL(updatedAt)
f.LastCheckedAt = timeFromSQL(lastCheckedAt)
flashcards = append(flashcards, &f)
}
err = rows.Err()
if err != nil {
return nil, err
}
return flashcards, err
}
/*
* Study
*/
// NewStudy creates a new study.
func NewStudy(flashcardOID string) *Study {
return &Study{
OID: NewOID(),
}
}
/* Object */
func (s *Study) Kind() string {
return "study"
}
func (s *Study) UniqueOID() string {
return s.OID
}
func (s *Study) ModificationTime() time.Time {
return s.EndedAt
}
func (s *Study) Refresh() (bool, error) {
// Study are immutable
return false, nil
}
func (s *Study) State() State {
// Mark study as new to try to update the corresponding flashcard
// if the study is more recent that the last review.
return Added
}
func (s *Study) ForceState(state State) {
// Do nothing
}
func (s *Study) Read(r io.Reader) error {
err := yaml.NewDecoder(r).Decode(s)
if err != nil {
return err
}
return nil
}
func (s *Study) Write(w io.Writer) error {
data, err := yaml.Marshal(s)
if err != nil {
return err
}
_, err = w.Write(data)
return err
}
func (s *Study) SubObjects() []StatefulObject {
return nil
}
func (s *Study) Blobs() []*BlobRef {
return nil
}
func (s *Study) Relations() []*Relation {
return nil
}
func (s Study) String() string {
return fmt.Sprintf("study %q started on %v", s.OID, s.StartedAt)
}
func (s *Study) Save() error {
CurrentLogger().Debugf("Study %s has %d reviews", s.OID, len(s.Reviews))
for _, review := range s.Reviews {
CurrentLogger().Debugf("Saving review for flashcard %s...", review.FlashcardOID)
// Read the flashcard to determine if the study is more recent that the last study
flashcard, err := CurrentCollection().LoadFlashcardByOID(review.FlashcardOID)
if err != nil {
return err
}
if flashcard == nil {
CurrentLogger().Debugf("Flashcard %s not found", review.FlashcardOID)
continue
}
if flashcard.StudiedAt.After(review.CompletedAt) {
// The last known study is more recent. Ignore this study.
CurrentLogger().Debugf("Flashcard %s already studied since", review.FlashcardOID)
continue
}
// Record the study
CurrentLogger().Debugf("Updating flashcard %s following new study...", flashcard.ShortTitle)
settingsRaw, err := SettingsJSON(review.Settings)
if err != nil {
return err
}
query := `
UPDATE flashcard
SET
due_at = ?,
studied_at = ?,
settings = ?
WHERE oid = ?;
`
_, err = CurrentDB().Client().Exec(query,
timeToSQL(review.DueAt),
timeToSQL(review.CompletedAt),
settingsRaw,
review.FlashcardOID)
if err != nil {
return err
}
CurrentLogger().Debugf("Updated flashcard %s following new study", flashcard.ShortTitle)
}
return nil
}
/* Anki SM-2 settings */
/*
-- 0=new, 1=learning, 2=review, 3=relearning
"type" INTEGER NOT NULL DEFAULT 0,
-- Queue types:
-- -1=suspend => leeches as manual suspension is not supported
-- 0=new => new (never shown)
-- 1=(re)lrn => learning/relearning
-- 2=rev => review (as for type)
-- 3=day (re)lrn => in learning, next review in at least a day after the previous review
queue INTEGER NOT NULL DEFAULT 0,
-- Due is used differently for different card types:
-- new: note oid or random int
-- due: integer day, relative to the collection's creation time
-- learning: integer timestamp in second
due INTEGER NOT NULL DEFAULT 0,
-- The interval. Negative = seconds, positive = days
ivl INTEGER NOT NULL DEFAULT 0,
-- The ease factor in permille (ex: 2500 = the interval will be multiplied by 2.5 the next time you press "Good").
ease_factor INTEGER NOT NULL DEFAULT 0,
-- The number of reviews.
repetitions INTEGER NOT NULL DEFAULT 0,
-- The number of times the card went from a "was answered correctly" to "was answered incorrectly" state.
lapses INTEGER NOT NULL DEFAULT 0,
-- Of the form a*1000+b, with:
-- a the number of reps left today
-- b the number of reps left till graduation
-- for example: '2004' means 2 reps left today and 4 reps till graduation
left INTEGER NOT NULL DEFAULT 0,
*/