package anki import ( "archive/zip" "database/sql" "encoding/json" "fmt" "io" "os" "path/filepath" "strings" "time" _ "github.com/mattn/go-sqlite3" ) // APKGGenerator creates Anki package files (.apkg) type APKGGenerator struct { deckName string deckID int64 modelID int64 cards []Card mediaFiles map[string]int // maps original filename to media number mediaCounter int } // NewAPKGGenerator creates a new APKG generator func NewAPKGGenerator(deckName string) *APKGGenerator { // Generate IDs based on timestamp to ensure uniqueness now := time.Now().UnixMilli() return &APKGGenerator{ deckName: deckName, deckID: now, modelID: now + 1, cards: make([]Card, 0), mediaFiles: make(map[string]int), mediaCounter: 0, } } // AddCard adds a card to the generator func (g *APKGGenerator) AddCard(card Card) { g.cards = append(g.cards, card) } // GenerateAPKG creates an .apkg file func (g *APKGGenerator) GenerateAPKG(outputPath string) error { // Create temporary directory for building the package tempDir, err := os.MkdirTemp("", "anki_export_*") if err != nil { return fmt.Errorf("failed to create temp directory: %w", err) } defer os.RemoveAll(tempDir) // Copy media files FIRST (this populates g.mediaFiles map) if err := g.copyMediaFiles(tempDir); err != nil { return fmt.Errorf("failed to copy media files: %w", err) } // Create media mapping file if err := g.createMediaMapping(tempDir); err != nil { return fmt.Errorf("failed to create media mapping: %w", err) } // Create SQLite database (this uses g.mediaFiles map) dbPath := filepath.Join(tempDir, "collection.anki2") if err := g.createDatabase(dbPath); err != nil { return fmt.Errorf("failed to create database: %w", err) } // Create the .apkg zip file if err := g.createZipPackage(tempDir, outputPath); err != nil { return fmt.Errorf("failed to create zip package: %w", err) } return nil } // createDatabase creates the Anki SQLite database func (g *APKGGenerator) createDatabase(dbPath string) error { db, err := sql.Open("sqlite3", dbPath) if err != nil { return err } defer db.Close() // Create tables if err := g.createTables(db); err != nil { return fmt.Errorf("failed to create tables: %w", err) } // Insert collection metadata if err := g.insertCollection(db); err != nil { return fmt.Errorf("failed to insert collection: %w", err) } // Insert notes and cards if err := g.insertNotesAndCards(db); err != nil { return fmt.Errorf("failed to insert notes and cards: %w", err) } return nil } // createTables creates the required Anki database tables func (g *APKGGenerator) createTables(db *sql.DB) error { queries := []string{ `CREATE TABLE col ( id integer PRIMARY KEY, crt integer NOT NULL, mod integer NOT NULL, scm integer NOT NULL, ver integer NOT NULL, dty integer NOT NULL, usn integer NOT NULL, ls integer NOT NULL, conf text NOT NULL, models text NOT NULL, decks text NOT NULL, dconf text NOT NULL, tags text NOT NULL )`, `CREATE TABLE notes ( id integer PRIMARY KEY, guid text NOT NULL, mid integer NOT NULL, mod integer NOT NULL, usn integer NOT NULL, tags text NOT NULL, flds text NOT NULL, sfld text NOT NULL, csum integer NOT NULL, flags integer NOT NULL, data text NOT NULL )`, `CREATE TABLE cards ( id integer PRIMARY KEY, nid integer NOT NULL, did integer NOT NULL, ord integer NOT NULL, mod integer NOT NULL, usn integer NOT NULL, type integer NOT NULL, queue integer NOT NULL, due integer NOT NULL, ivl integer NOT NULL, factor integer NOT NULL, reps integer NOT NULL, lapses integer NOT NULL, left integer NOT NULL, odue integer NOT NULL, odid integer NOT NULL, flags integer NOT NULL, data text NOT NULL )`, `CREATE TABLE revlog ( id integer PRIMARY KEY, cid integer NOT NULL, usn integer NOT NULL, ease integer NOT NULL, ivl integer NOT NULL, lastIvl integer NOT NULL, factor integer NOT NULL, time integer NOT NULL, type integer NOT NULL )`, `CREATE TABLE graves ( usn integer NOT NULL, oid integer NOT NULL, type integer NOT NULL )`, // Create indexes `CREATE INDEX ix_notes_csum ON notes (csum)`, `CREATE INDEX ix_notes_usn ON notes (usn)`, `CREATE INDEX ix_cards_usn ON cards (usn)`, `CREATE INDEX ix_cards_nid ON cards (nid)`, `CREATE INDEX ix_cards_sched ON cards (did, queue, due)`, `CREATE INDEX ix_revlog_usn ON revlog (usn)`, `CREATE INDEX ix_revlog_cid ON revlog (cid)`, } for _, query := range queries { if _, err := db.Exec(query); err != nil { return fmt.Errorf("failed to execute query: %w", err) } } return nil } // insertCollection inserts the collection metadata func (g *APKGGenerator) insertCollection(db *sql.DB) error { now := time.Now().Unix() // Create deck configuration // The arrays are [learningCount, reviewCount] for today's stats decks := map[string]interface{}{ "1": map[string]interface{}{ "id": 1, "name": "Default", "mod": now, "desc": "", "collapsed": false, "dyn": 0, "conf": 1, "usn": 0, "newToday": []int{0, 0}, "revToday": []int{0, 0}, "lrnToday": []int{0, 0}, "timeToday": []int{0, 0}, "browserCollapsed": false, "extendNew": 10, "extendRev": 50, }, fmt.Sprintf("%d", g.deckID): map[string]interface{}{ "id": g.deckID, "name": g.deckName, "mod": now, "desc": "Bulgarian vocabulary cards created by TotalRecall", "collapsed": false, "dyn": 0, "conf": 1, "usn": 0, "newToday": []int{0, 0}, "revToday": []int{0, 0}, "lrnToday": []int{0, 0}, "timeToday": []int{0, 0}, "browserCollapsed": false, "extendNew": 10, "extendRev": 50, }, } decksJSON, _ := json.Marshal(decks) // Create model (note type) configuration models := map[string]interface{}{ fmt.Sprintf("%d", g.modelID): g.createNoteTypeConfig(), } modelsJSON, _ := json.Marshal(models) // Default configuration conf := map[string]interface{}{ "nextPos": 1, "estTimes": true, "activeDecks": []int64{1}, "sortType": "noteFld", "sortBackwards": false, "addToCur": true, "curDeck": 1, "newSpread": 0, "dueCounts": true, "collapseTime": 1200, "timeLim": 0, "schedVer": 1, "curModel": fmt.Sprintf("%d", g.modelID), "dayLearnFirst": false, } confJSON, _ := json.Marshal(conf) // Deck options dconf := map[string]interface{}{ "1": map[string]interface{}{ "id": 1, "name": "Default", "dyn": 0, "new": map[string]interface{}{ "delays": []int{1, 10}, "ints": []int{1, 4, 7}, "initialFactor": 2500, "perDay": 20, "order": 1, "bury": true, "separate": true, }, "lapse": map[string]interface{}{ "delays": []int{10}, "mult": 0, "minInt": 1, "leechFails": 8, "leechAction": 0, }, "rev": map[string]interface{}{ "perDay": 100, "ease4": 1.3, "fuzz": 0.05, "maxIvl": 36500, "ivlFct": 1, "bury": true, "minSpace": 1, }, "timer": 0, "maxTaken": 60, "usn": 0, "mod": now, "autoplay": true, "replayq": true, }, } dconfJSON, _ := json.Marshal(dconf) query := `INSERT INTO col VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` _, err := db.Exec(query, 1, // id now, // crt now*1000, // mod now*1000, // scm 11, // ver (schema version) 0, // dty 0, // usn 0, // ls string(confJSON), string(modelsJSON), string(decksJSON), string(dconfJSON), "{}", // tags ) return err } // createNoteTypeConfig creates the note type configuration func (g *APKGGenerator) createNoteTypeConfig() map[string]interface{} { return map[string]interface{}{ "id": g.modelID, "name": "Bulgarian Vocabulary", "type": 0, "mod": time.Now().Unix(), "usn": -1, "sortf": 0, "did": g.deckID, "req": [][]interface{}{[]interface{}{0, "all", []int{0}}}, "vers": []int{}, "tags": []string{}, "latexPre": `\documentclass[12pt]{article} \special{papersize=3in,5in} \usepackage[utf8]{inputenc} \usepackage{amssymb,amsmath} \pagestyle{empty} \setlength{\parindent}{0in} \begin{document}`, "latexPost": `\end{document}`, "flds": []map[string]interface{}{ { "name": "English", "ord": 0, "sticky": false, "rtl": false, "font": "Arial", "size": 20, "media": []string{}, }, { "name": "Bulgarian", "ord": 1, "sticky": false, "rtl": false, "font": "Arial", "size": 20, "media": []string{}, }, { "name": "Image", "ord": 2, "sticky": false, "rtl": false, "font": "Arial", "size": 20, "media": []string{}, }, { "name": "Audio", "ord": 3, "sticky": false, "rtl": false, "font": "Arial", "size": 20, "media": []string{}, }, { "name": "Notes", "ord": 4, "sticky": false, "rtl": false, "font": "Arial", "size": 16, "media": []string{}, }, }, "tmpls": []map[string]interface{}{ { "name": "Card 1", "ord": 0, "qfmt": g.getFrontTemplate(), "afmt": g.getBackTemplate(), "did": nil, "bqfmt": "", "bafmt": "", }, }, "css": g.getCSS(), } } // getFrontTemplate returns the question template func (g *APKGGenerator) getFrontTemplate() string { return `