-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
102 lines (89 loc) · 3.32 KB
/
main.js
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
async function collection(source, target, options = {}) {
const { config, utils } = options;
const { http } = utils;
const { fetch, Boxy } = http;
const { port = 8765 } = config;
async function ankiConnect(action, version, params = {}) {
let res = await fetch(`http://127.0.0.1:${port}`, {
method: 'POST',
body: Body.json({ action, version, params }),
});
return res.data;
}
function ankiText(target) {
let result = '';
if (typeof target === 'object') {
for (let explanation of target.explanations) {
result += explanation.trait + '. ';
let index = 0;
for (let explain of explanation.explains) {
index++;
if (index !== explanation.explains.length) {
result += explain + '; ';
} else {
result += explain + '<br>';
}
}
}
} else {
return target;
}
return result;
}
function ankiPronunciation(target) {
let results = [];
if (typeof target !== 'object' || target.pronunciations === undefined) {
return results;
}
for (let i = 0; i < target.pronunciations.length; i++) {
let pronunciation = target.pronunciations[i];
let region = pronunciation.region;
let symbol = pronunciation.symbol;
// make pronunciation symbol readable
region = region ? `[${region}]` : '';
symbol = symbol[0] === '/' ? symbol : `/${symbol}/`;
let regionSymbol = `${region} ${symbol}`;
let audio;
if (pronunciation.voice) {
// step1: convert number array to Char String
// step2: convert Char String to base64
let voiceString = String.fromCharCode(...pronunciation.voice);
let voice = btoa(voiceString);
let filename = `${region}_${source}.mp3`;
let fields = [`Voice${i + 1}`];
audio = { data: voice, filename, fields };
}
results.push({ regionSymbol, audio });
}
return results;
}
await ankiConnect('createDeck', 6, { deck: 'Pot' });
await ankiConnect('createModel', 6, {
modelName: 'Pot Card 2',
inOrderFields: ['Front', 'Back', 'Symbol1', 'Voice1', 'Symbol2', 'Voice2'],
isCloze: false,
cardTemplates: [
{
Name: 'Pot Card 2',
Front: '{{Front}}',
Back: '{{FrontSide}}<br>{{Symbol1}} {{Voice1}}<br>{{Symbol2}} {{Voice2}}<hr id=answer>{{Back}}',
},
],
});
let pronunciations = ankiPronunciation(target);
await ankiConnect('addNote', 6, {
note: {
deckName: 'Pot',
modelName: 'Pot Card 2',
fields: {
Front: source,
Back: ankiText(target),
Symbol1: pronunciations[0] && pronunciations[0].regionSymbol,
Symbol2: pronunciations[1] && pronunciations[1].regionSymbol,
},
audio: pronunciations.map((pronunciation) => {
return pronunciation.audio;
}),
},
});
}