Skip to content

Commit

Permalink
Merge pull request #70 from xyaman/extensionless
Browse files Browse the repository at this point in the history
Mine without using the extension
  • Loading branch information
Natsume-197 authored Sep 9, 2024
2 parents ccdc6f1 + f0c36b9 commit 79c65a6
Show file tree
Hide file tree
Showing 5 changed files with 152 additions and 39 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const openAnkiModal = () => {
<SearchDropdownContent>
<!-- Anki by last added -->
<SearchDropdownItem text="Añadir a Anki (Ultima carta añadida)" :iconPath="mdiStarShootingOutline"
@click="addSentenceToAnki(content)" />
@click="ankiStore().addSentenceToAnki(content)" />

<!-- Anki by ID -->
<SearchDropdownItem text="Añadir a Anki (Busca en tu colección)" @click="openAnkiModal()"
Expand Down
2 changes: 1 addition & 1 deletion frontend_v2/components/search/segment/SegmentContainer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ const openAnkiModal = (sentence: Sentence) => {
<SearchModalContext :sentence="selectedSentence" />
<SearchModalAnkiNotes :sentence="searchNoteSentence"
:onClick="(sentence: Sentence, id: number) => addSentenceToAnki(sentence, id)" />
:onClick="(sentence: Sentence, id: number) => ankiStore().addSentenceToAnki(sentence, id)" />
<GeneralLazy v-for="(sentence, index) in searchData.sentences" :key="sentence.segment_info.position"
:id="sentence.segment_info.position" :unrender="true" :min-height="300"
Expand Down
150 changes: 149 additions & 1 deletion frontend_v2/stores/anki.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export const ankiStore = defineStore("anki", {
serverAddress: "http://127.0.0.1:8765",
availableDecks: [],
availableModels: [],
// TODO: define structure type
settings: {
current: {
deck: null,
Expand All @@ -20,7 +21,7 @@ export const ankiStore = defineStore("anki", {
paths: ["ankiPreferences"],
},
actions: {
async executeAction(action, params = {}) {
async executeAction(action: string, params = {}) {
try {
const response = await fetch(this.ankiPreferences.serverAddress, {
method: "POST",
Expand Down Expand Up @@ -87,5 +88,152 @@ export const ankiStore = defineStore("anki", {
});
return response;
},

async addSentenceToAnki(sentence: Sentence, id?: number) {
// TODO: use local store
// como solucion temporal funciona bien.
const localSettings = localStorage.getItem('settings');

if (!localSettings) {
const message = 'No se han encontrado ajustes. Por favor, vaya a la página de ajustes y configure la extensión.'
useToastError(message);
return;
}

try {
useToastInfo("Minando la carta...");

let cardID = id;

// Si no hay ID, significa que actualizaremos la ultima carta
if (!id) {
// Buscamos las cartas mas recientes
let queryParts = []
let queryString = ''
queryParts.push(`"deck:${this.ankiPreferences.settings.current.deck}"`)
queryParts.push(`"note:${this.ankiPreferences.settings.current.model}"`)
queryParts.push("added:2 is:new")
queryString = queryParts.join(' ')

let response = await this.executeAction('findNotes', { query: queryString })
const noteIDs = response.result

// Seleccionamos la ultima carta

// @ts-ignore:ignore-next-line
const latestCard = noteIDs.reduce((a, b) => Math.max(a, b), -1)

if (!latestCard || latestCard === -1) {
useToastError('No anki card to export to. Please add a card first.');
return;
}

cardID = latestCard;
}

// Extrae la información de la nota a actualizar
let infoResponse = await this.executeAction('notesInfo', { notes: [cardID] })
const infoCard = infoResponse.result
console.log(infoCard)

// Almacena el contenido multimedia en Anki
let imageRequest = this.executeAction('storeMediaFile', {
filename: sentence.segment_info.uuid + '.webp',
url: sentence.media_info.path_image,
})

let audioRequest = this.executeAction('storeMediaFile', {
filename: sentence.segment_info.uuid + '.mp3',
url: sentence.media_info.path_audio,
})

let [imageResult, audioResult] = await Promise.all([imageRequest, audioRequest]);

// Realiza una busqueda en la interfaz de Anki para cambiar a una tarjeta generica
// Y evitar problemas al actualizar
await this.guiBrowse('nid:1 nid:2')

let allowedFields = [
'sentence-jp',
'content_jp_highlight',
'sentence-es',
'sentence-en',
'image',
'sentence-audio',
'empty',
]
let fieldsNew = {}

this.ankiPreferences.settings.current.fields.forEach((field) => {
if (field.value) {
const regex = new RegExp(`\\{(${allowedFields.join('|')})\\}`)
const match = field.value.match(regex)

if (match) {
const key = match[1]

switch (key) {
case 'empty':
fieldsNew[field.key] = field.value.replace(`{${key}}`, '')
break
case 'sentence-jp':
fieldsNew[field.key] = field.value.replace(
`{${key}}`,
'<div>' + sentence.segment_info.content_jp + '</div>'
)
break
case 'sentence-es':
fieldsNew[field.key] = field.value.replace(
`{${key}}`,
'<div>' + sentence.segment_info.content_es + '</div>'
)
break
case 'sentence-en':
fieldsNew[field.key] = field.value.replace(
`{${key}}`,
'<div>' + sentence.segment_info.content_en + '</div>'
)
break
case 'image':
fieldsNew[field.key] = field.value.replace(
`{${key}}`,
`<img src="${imageResult.result}">`
)
break
case 'sentence-audio':
fieldsNew[field.key] = field.value.replace(
`{${key}}`,
`[sound:${audioResult.result}]`
)
break
}
}
}
})

await this.executeAction('updateNoteFields', {
note: {
fields: fieldsNew,
id: infoCard[0].noteId,
},
})

// Busca la ultima tarjeta insertada
await this.guiBrowse(`nid:${infoCard[0].noteId}`)

const message = 'La tarjeta ha sido añadida en Anki exitosamente.'
useToastSuccess(message);

} catch (error) {
console.log(error);
const message = 'No se ha podido añadir la tarjeta en Anki. Error: ' + error;
useToastError(message);
}
},

async guiBrowse(query: string) {
let response = await this.executeAction('guiBrowse', { query: query });
return response.result
}
},
});
2 changes: 1 addition & 1 deletion frontend_v2/stores/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export type MediaInfo = {

export type SegmentInfo = {
status: number;
uid: string;
uuid: string;
position: number;
start_time: string;
end_time: string;
Expand Down
35 changes: 0 additions & 35 deletions frontend_v2/utils/anki.ts

This file was deleted.

0 comments on commit 79c65a6

Please sign in to comment.