Skip to content

Commit

Permalink
improve: edit anki audio file can overwrite origin file
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinyay945 committed Sep 16, 2023
1 parent 68e368a commit 2ab1e4f
Show file tree
Hide file tree
Showing 7 changed files with 200 additions and 18 deletions.
8 changes: 0 additions & 8 deletions .idea/.gitignore

This file was deleted.

2 changes: 1 addition & 1 deletion .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

112 changes: 112 additions & 0 deletions .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion go.mod
Expand Up @@ -11,7 +11,7 @@ require (
github.com/sirupsen/logrus v1.9.3
github.com/spf13/cobra v1.7.0
github.com/spf13/viper v1.16.0
github.com/stretchr/testify v1.8.3
github.com/stretchr/testify v1.8.4
go.uber.org/mock v0.2.0
google.golang.org/api v0.126.0
gopkg.in/yaml.v3 v3.0.1
Expand Down Expand Up @@ -66,6 +66,7 @@ require (
github.com/spf13/cast v1.5.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/objx v0.5.1 // indirect
github.com/subosito/gotenv v1.4.2 // indirect
github.com/ugorji/go/codec v1.1.7 // indirect
go.opencensus.io v0.24.0 // indirect
Expand Down
5 changes: 5 additions & 0 deletions go.sum
Expand Up @@ -280,6 +280,8 @@ github.com/spf13/viper v1.16.0/go.mod h1:yg78JgCJcbrQOvV9YLXgkLaZqUidkY9K+Dd1Fof
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.1 h1:4VhoImhV/Bm0ToFkXFi8hXNXwpDRZ/ynw3amt82mzq0=
github.com/stretchr/objx v0.5.1/go.mod h1:/iHQpkQwBD6DLUmQ4pE+s1TXdob1mORJ4/UFdrifcy0=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
Expand All @@ -289,8 +291,11 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/subosito/gotenv v1.4.2 h1:X1TuBLAMDFbaTAChgCBLu3DU3UPyELpnF2jjJ2cz/S8=
github.com/subosito/gotenv v1.4.2/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0=
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
Expand Down
70 changes: 65 additions & 5 deletions infrastructure/anki/anki.go
Expand Up @@ -5,18 +5,29 @@ import (
"github.com/atselvan/ankiconnect"
"github.com/imroc/req/v3"
"github.com/privatesquare/bkst-go-utils/utils/errors"
"github.com/sirupsen/logrus"
"os"
"path/filepath"
)

type Client struct {
ankiConnect *ankiconnect.Client
httpClient *req.Client
ankiConnect *ankiconnect.Client
ankiMediaPath string
httpClient *req.Client
log *logrus.Entry
}

func NewClient() *Client {
c := &Client{}
func NewClient(log *logrus.Logger) *Client {
field := log.WithField("infrastructure", "anki")
c := &Client{log: field}
c.ankiConnect = ankiconnect.NewClient()
c.httpClient = req.C()
c.httpClient.SetBaseURL("http://127.0.0.1:8765")
if path, err := c.GetMediaFolderPath(); err != nil {
c.log.Warnf("Fail To Get Media Folder: %s", err.Error())
} else {
c.ankiMediaPath = path
}
return c
}

Expand Down Expand Up @@ -52,10 +63,36 @@ func (c *Client) EditNoteById(
for s, data := range note.Fields {
updateFields[s] = data.Value
}
var oldAudioList []ankiconnect.Audio
for _, audio := range audioList {
if audio.Path == "" {
oldAudioList = append(oldAudioList, audio)
continue
}
input, err := os.ReadFile(audio.Path)
if err != nil {
c.log.Warnf("Fail to read audio file: %s", err.Error())
oldAudioList = append(oldAudioList, audio)
continue
}

ankiAudioFile := fmt.Sprintf("anki-support-%s", audio.Filename)
destinationFile := filepath.Join(c.ankiMediaPath, ankiAudioFile)
err = os.WriteFile(destinationFile, input, 0644)
if err != nil {
c.log.Warnln("Error creating", destinationFile)
c.log.Warnln(err.Error())
oldAudioList = append(oldAudioList, audio)
continue
}
for _, field := range audio.Fields {
updateFields[field] = fmt.Sprintf("[sound:%s]", ankiAudioFile)
}
}
err := c.ankiConnect.Notes.Update(ankiconnect.UpdateNote{
Id: note.NoteId,
Fields: updateFields,
Audio: audioList,
Audio: oldAudioList,
Video: videoList,
Picture: pictureList,
})
Expand Down Expand Up @@ -170,6 +207,29 @@ func (c *Client) AddTagFromNote(id int64, tag string) error {
return nil
}

func (c *Client) GetMediaFolderPath() (string, error) {
result := struct {
Result string `json:"result"`
Error string `json:"error"`
}{}
post, err := c.httpClient.R().SetBodyJsonString(`
{
"action": "getMediaDirPath",
"version": 6
}
`).SetSuccessResult(&result).Post("")
if err != nil {
return "", fmt.Errorf("fail to add note tag")
}
if post.IsErrorState() {
return "", fmt.Errorf("fail to add note tag")
}
if result.Error != "" {
return "", fmt.Errorf("fail to add note tag")
}
return result.Result, nil
}

func NewAnkiError(err *errors.RestErr) error {
if err == nil {
return nil
Expand Down
18 changes: 15 additions & 3 deletions infrastructure/anki/anki_test.go
Expand Up @@ -2,8 +2,10 @@ package anki

import (
"github.com/atselvan/ankiconnect"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/suite"
"go.uber.org/mock/gomock"
"io"
"os"
"testing"
)
Expand All @@ -18,11 +20,14 @@ func TestSuiteInitAnki(t *testing.T) {
if os.Getenv("RUN_INFRASTRUCTURE") == "true" {
t.Skip("Skipping testing in production")
}
suite.Run(t, new(AnkiSuite))
}

func (t *AnkiSuite) SetupTest() {
logger := logrus.New()
logger.SetOutput(io.Discard)
t.mockCtrl = gomock.NewController(t.Suite.T())
client := NewClient()
client := NewClient(logger)
t.client = client
}

Expand Down Expand Up @@ -59,8 +64,15 @@ func (t *AnkiSuite) Test_get_todo_note_from_deck_name() {

func (t *AnkiSuite) Test_get_note_by_id() {
noteId := int64(1694305287189)
_, err := t.client.GetNoteById(noteId)
note, err := t.client.GetNoteById(noteId)
t.NoError(err)
t.NotEmpty(note)
}

func (t *AnkiSuite) Test_get_media_path() {
path, err := t.client.GetMediaFolderPath()
t.NoError(err)
t.Equal("test", path)
}

func (t *AnkiSuite) Test_edit_note_and_add_audio() {
Expand All @@ -75,7 +87,7 @@ func (t *AnkiSuite) Test_edit_note_and_add_audio() {
Path: outputPath,
Filename: "私の机は木製です。.mp3",
SkipHash: "",
Fields: []string{"JapaneseSound"},
Fields: []string{"Japanese-ToSound"},
},
}
err = t.client.EditNoteById(note, audioList, nil, nil)
Expand Down

0 comments on commit 2ab1e4f

Please sign in to comment.