-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathexporter.js
More file actions
153 lines (129 loc) · 4.77 KB
/
exporter.js
File metadata and controls
153 lines (129 loc) · 4.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import sha1 from 'sha1';
import Zip from 'jszip';
export default class {
constructor(deckName, { template, sql }) {
this.db = new sql.Database();
this.db.run(template);
const now = Date.now();
const topDeckId = this._getId('cards', 'did', now);
const topModelId = this._getId('notes', 'mid', now);
this.deckName = deckName;
this.zip = new Zip();
this.media = [];
this.topDeckId = topDeckId;
this.topModelId = topModelId;
this.separator = '\u001F';
const decks = this._getInitialRowValue('col', 'decks');
const deck = getLastItem(decks);
deck.name = this.deckName;
deck.id = topDeckId;
decks[topDeckId + ''] = deck;
this._update('update col set decks=:decks where id=1', { ':decks': JSON.stringify(decks) });
const models = this._getInitialRowValue('col', 'models');
const model = getLastItem(models);
model.name = this.deckName;
model.did = this.topDeckId;
model.id = topModelId;
models[`${topModelId}`] = model;
this._update('update col set models=:models where id=1', { ':models': JSON.stringify(models) });
}
save(options) {
const { zip, db, media } = this;
const binaryArray = db.export();
const mediaObj = media.reduce((prev, curr, idx) => {
prev[idx] = curr.filename;
return prev;
}, {});
zip.file('collection.anki2', new Buffer(binaryArray));
zip.file('media', JSON.stringify(mediaObj));
media.forEach((item, i) => zip.file(i, item.data));
const baseOptions =
process.env.APP_ENV === 'browser' || typeof window !== 'undefined'
? { type: 'blob' }
: {
type: 'nodebuffer',
base64: false,
compression: 'DEFLATE'
};
return zip.generateAsync(Object.assign(baseOptions, options));
}
addMedia(filename, data) {
this.media.push({ filename, data });
}
addCard(fields, { tags, sortField } = {}) {
const { topDeckId, topModelId, separator } = this;
const joinedFields = fields.join(separator);
const now = Date.now();
const note_id = this._getId('notes', 'id', now);
let strTags = '';
if (typeof tags === 'string') {
strTags = tags;
} else if (Array.isArray(tags)) {
strTags = this._tagsToStr(tags);
}
this._update('insert into notes values(:id,:guid,:mid,:mod,:usn,:tags,:flds,:sfld,:csum,:flags,:data)', {
':id': note_id, // integer primary key,
':guid': `${this._getId('notes', 'guid', now)}`, // text not null,
':mid': topModelId, // integer not null,
':mod': this._getId('notes', 'mod', now), // integer not null,
':usn': -1, // integer not null,
':tags': strTags, // text not null,
':flds': joinedFields, // text not null,
':sfld': sortField || fields[0], // integer not null,
':csum': this._checksum(joinedFields), //integer not null,
':flags': 0, // integer not null,
':data': '' // text not null,
});
return this._update(
'insert into cards values(:id,:nid,:did,:ord,:mod,:usn,:type,:queue,:due,:ivl,:factor,:reps,:lapses,:left,:odue,:odid,:flags,:data)',
{
':id': this._getId('cards', 'id', now), // integer primary key,
':nid': note_id, // integer not null,
':did': topDeckId, // integer not null,
':ord': 0, // integer not null,
':mod': this._getId('cards', 'mod', now), // integer not null,
':usn': -1, // integer not null,
':type': 0, // integer not null,
':queue': 0, // integer not null,
':due': 179, // integer not null,
':ivl': 0, // integer not null,
':factor': 0, // integer not null,
':reps': 0, // integer not null,
':lapses': 0, // integer not null,
':left': 0, // integer not null,
':odue': 0, // integer not null,
':odid': 0, // integer not null,
':flags': 0, // integer not null,
':data': '' // text not null
}
);
}
_update(query, obj) {
this.db.prepare(query).getAsObject(obj);
}
_getInitialRowValue(table, column = 'id') {
const query = `select ${column} from ${table}`;
return this._getFirstVal(query);
}
_checksum(str) {
return parseInt(sha1(str).substr(0, 8), 16);
}
_getFirstVal(query) {
return JSON.parse(this.db.exec(query)[0].values[0]);
}
_tagsToStr(tags = []) {
return ' ' + tags.map(tag => tag.replace(/ /g, '_')).join(' ') + ' ';
}
_getId(table, col, ts) {
const query = `SELECT ${col} from ${table} WHERE ${col} >= :ts ORDER BY ${col} DESC LIMIT 1`;
const rowObj = this.db.prepare(query).getAsObject({ ':ts': ts });
return rowObj[col] ? +rowObj[col] + 1 : ts;
}
}
export const getLastItem = obj => {
const keys = Object.keys(obj);
const lastKey = keys[keys.length - 1];
const item = obj[lastKey];
delete obj[lastKey];
return item;
};