Skip to content

Commit ccda230

Browse files
committedMay 10, 2024·
Refactored adding tranlation methods
1 parent ce762bc commit ccda230

File tree

7 files changed

+42
-112
lines changed

7 files changed

+42
-112
lines changed
 

‎pkg/api/api.go

+3-52
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package api
22

33
import (
44
"bytes"
5-
"context"
65
"crypto/tls"
76
"encoding/json"
87
"fmt"
@@ -12,12 +11,9 @@ import (
1211
"net/http/cookiejar"
1312
"net/http/httputil"
1413
"strconv"
15-
"strings"
16-
"sync"
1714
"time"
1815

1916
"github.com/trezorg/lingualeo/internal/logger"
20-
"github.com/trezorg/lingualeo/pkg/channel"
2117

2218
"golang.org/x/net/publicsuffix"
2319
)
@@ -206,10 +202,10 @@ func (api *API) translateRequest(word string) ([]byte, error) {
206202
return request("POST", translateURL, api.client, jsonValue, "", api.Debug)
207203
}
208204

209-
func (api *API) addRequest(word string, translate []string) ([]byte, error) {
205+
func (api *API) addRequest(word string, translate string) ([]byte, error) {
210206
values := map[string]string{
211207
"word": word,
212-
"tword": strings.Join(translate, ", "),
208+
"tword": translate,
213209
"port": "1001",
214210
}
215211
jsonValue, _ := json.Marshal(values)
@@ -224,55 +220,10 @@ func (api *API) TranslateWord(word string) OperationResult {
224220
return opResultFromBody(word, body)
225221
}
226222

227-
func (api *API) AddWord(word string, translate []string) OperationResult {
223+
func (api *API) AddWord(word string, translate string) OperationResult {
228224
body, err := api.addRequest(word, translate)
229225
if err != nil {
230226
return OperationResult{Error: err}
231227
}
232228
return opResultFromBody(word, body)
233229
}
234-
235-
// TranslateWords transate words from string channel
236-
func (api *API) TranslateWords(ctx context.Context, results <-chan string) <-chan OperationResult {
237-
out := make(chan OperationResult)
238-
var wg sync.WaitGroup
239-
wg.Add(1)
240-
go func() {
241-
defer wg.Done()
242-
for word := range channel.OrDone(ctx, results) {
243-
wg.Add(1)
244-
go func(word string) {
245-
defer wg.Done()
246-
out <- api.TranslateWord(word)
247-
}(word)
248-
}
249-
}()
250-
go func() {
251-
defer close(out)
252-
wg.Wait()
253-
}()
254-
return out
255-
}
256-
257-
// AddWords add words
258-
func (api *API) AddWords(ctx context.Context, results <-chan Result) <-chan OperationResult {
259-
out := make(chan OperationResult)
260-
var wg sync.WaitGroup
261-
wg.Add(1)
262-
go func() {
263-
defer wg.Done()
264-
for res := range channel.OrDone(ctx, results) {
265-
wg.Add(1)
266-
result := res
267-
go func(result Result) {
268-
defer wg.Done()
269-
out <- api.AddWord(result.Word, result.Words)
270-
}(result)
271-
}
272-
}()
273-
go func() {
274-
defer close(out)
275-
wg.Wait()
276-
}()
277-
return out
278-
}

‎pkg/api/helpers.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"io"
77
"log/slog"
88
"net/http"
9+
"strings"
910

1011
"github.com/trezorg/lingualeo/pkg/messages"
1112
)
@@ -67,7 +68,8 @@ func printAddedTranslation(result *Result) {
6768
if err != nil {
6869
slog.Error("cannot show message", "error", err)
6970
}
70-
err = messages.Message(messages.GREEN, "['%s']\n", result.Word)
71+
72+
err = messages.Message(messages.GREEN, "['%s'] ['%s']\n", result.Word, strings.Join(result.AddWords, ", "))
7173
if err != nil {
7274
slog.Error("cannot show message", "error", err)
7375
}

‎pkg/api/items.go

+4-7
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ type Result struct {
6161
Transcription string `json:"transcription"`
6262
ErrorMsg string `json:"error_msg"`
6363
Words []string `json:"-"`
64+
AddWords []string `json:"-"`
6465
Translate []Word `json:"translate"`
6566
Exists convertibleBoolean `json:"is_user"`
6667
DirectionEnglish bool `json:"directionEnglish"`
@@ -91,13 +92,9 @@ func (result *Result) parse() {
9192
result.Words = slice.Unique(result.Words)
9293
}
9394

94-
// SetTranslate sets custom translation for a word
95-
func (result *Result) SetTranslate(translates []string, replace bool) {
96-
if replace {
97-
result.Words = slice.Unique(translates)
98-
} else {
99-
result.Words = slice.Unique(append(result.Words, translates...))
100-
}
95+
// SetTranslation sets custom translation for a word
96+
func (result *Result) SetTranslation(translates []string) {
97+
result.AddWords = slice.Unique(translates)
10198
}
10299

103100
// InDictionary checks either word is already has been added into the dictionary

‎pkg/translator/args.go

+10-30
Original file line numberDiff line numberDiff line change
@@ -16,22 +16,22 @@ import (
1616
"gopkg.in/yaml.v2"
1717
)
1818

19-
type configType int
20-
type decodeFunc func(data []byte, args *Lingualeo) error
19+
type (
20+
configType int
21+
decodeFunc func(data []byte, args *Lingualeo) error
22+
)
2123

2224
const (
2325
yamlType = configType(1)
2426
jsonType = configType(2)
2527
tomlType = configType(3)
2628
)
2729

28-
var (
29-
decodeMapping = map[configType]decodeFunc{
30-
yamlType: readYamlConfig,
31-
jsonType: readJSONConfig,
32-
tomlType: readTomlConfig,
33-
}
34-
)
30+
var decodeMapping = map[configType]decodeFunc{
31+
yamlType: readYamlConfig,
32+
jsonType: readJSONConfig,
33+
tomlType: readTomlConfig,
34+
}
3535

3636
type configFile struct {
3737
filename string
@@ -73,7 +73,6 @@ func newConfigFile(filename string) *configFile {
7373
}
7474

7575
func prepareArgs(version string) (Lingualeo, error) {
76-
7776
args := Lingualeo{}
7877

7978
var translate cli.StringSlice
@@ -87,7 +86,7 @@ func prepareArgs(version string) (Lingualeo, error) {
8786
return fmt.Errorf("there are no words to translate")
8887
}
8988
args.Words = slice.Unique(c.Args().Slice())
90-
args.Translation = translate.Value()
89+
args.Translation = slice.Unique(translate.Value())
9190
if args.Add && len(args.Translation) > 0 && len(args.Words) > 1 {
9291
return fmt.Errorf("you should add only one word with custom translation")
9392
}
@@ -212,18 +211,6 @@ func prepareArgs(version string) (Lingualeo, error) {
212211
Aliases: []string{"a"},
213212
Usage: "Add to lingualeo dictionary",
214213
Flags: []cli.Flag{
215-
&cli.BoolFlag{
216-
Name: "force",
217-
Aliases: []string{"f"},
218-
Usage: "Force add to lingualeo dictionary",
219-
Destination: &args.Force,
220-
},
221-
&cli.BoolFlag{
222-
Name: "replace",
223-
Aliases: []string{"r"},
224-
Usage: "Custom translation. Replace word instead of adding",
225-
Destination: &args.TranslateReplace,
226-
},
227214
&cli.StringSliceFlag{
228215
Name: "translate",
229216
Aliases: []string{"t"},
@@ -242,7 +229,6 @@ func prepareArgs(version string) (Lingualeo, error) {
242229
return args, err
243230
}
244231
return args, nil
245-
246232
}
247233

248234
func readTomlConfig(data []byte, args *Lingualeo) error {
@@ -343,9 +329,6 @@ func (args *Lingualeo) mergeConfigs(a *Lingualeo) {
343329
if len(args.Player) == 0 && len(a.Player) > 0 {
344330
args.Player = a.Player
345331
}
346-
if a.Force {
347-
args.Force = a.Force
348-
}
349332
if a.Add {
350333
args.Add = a.Add
351334
}
@@ -364,9 +347,6 @@ func (args *Lingualeo) mergeConfigs(a *Lingualeo) {
364347
if a.ReverseTranslate {
365348
args.ReverseTranslate = a.ReverseTranslate
366349
}
367-
if a.TranslateReplace {
368-
args.TranslateReplace = a.TranslateReplace
369-
}
370350
if len(args.LogLevel) == 0 && len(a.LogLevel) > 0 {
371351
args.LogLevel = a.LogLevel
372352
}

‎pkg/translator/get_word_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ func TestProcessTranslationResponseJson(t *testing.T) {
2929
downloader.EXPECT().Download(fakeapi.SoundURL).Return(testFile, nil).Times(count)
3030
translator.EXPECT().TranslateWord(fakeapi.SearchWord).Return(res).Times(count)
3131

32-
logger.Prepare(slog.LevelError + 1)
32+
logger.Prepare(slog.LevelError + 10)
3333
searchWords := make([]string, 0, count)
3434

3535
for i := 0; i < count; i++ {

‎pkg/translator/linguleo.go

+15-15
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ func (args *Lingualeo) checkMediaPlayer() {
4141
//go:generate mockery
4242
type Translator interface {
4343
TranslateWord(word string) api.OperationResult
44-
AddWord(word string, translate []string) api.OperationResult
44+
AddWord(word string, translate string) api.OperationResult
4545
}
4646

4747
type Lingualeo struct {
@@ -54,11 +54,9 @@ type Lingualeo struct {
5454
Words []string
5555
Translation []string
5656
Add bool `yaml:"add" json:"add" toml:"add"`
57-
TranslateReplace bool `yaml:"translate_replace" json:"translate_replace" toml:"translate_replace"`
5857
Sound bool `yaml:"sound" json:"sound" toml:"sound"`
5958
Debug bool `yaml:"debug" json:"debug" toml:"debug"`
6059
DownloadSoundFile bool `yaml:"download" json:"download" toml:"download"`
61-
Force bool `yaml:"force" json:"force" toml:"force"`
6260
LogPrettyPrint bool `yaml:"log_pretty_print" json:"log_pretty_print" toml:"log_pretty_print"`
6361
ReverseTranslate bool `yaml:"reverse_translate" json:"reverse_translate" toml:"reverse_translate"`
6462
}
@@ -129,12 +127,16 @@ func addWords(ctx context.Context, translator Translator, results <-chan api.Res
129127
go func() {
130128
defer wg.Done()
131129
for res := range channel.OrDone(ctx, results) {
132-
wg.Add(1)
133-
result := res
134-
go func(result api.Result) {
135-
defer wg.Done()
136-
out <- translator.AddWord(result.Word, result.Words)
137-
}(result)
130+
for _, translate := range res.AddWords {
131+
wg.Add(1)
132+
result := res
133+
go func(word, transate string) {
134+
defer wg.Done()
135+
added := translator.AddWord(word, transate)
136+
added.Result.AddWords = []string{transate}
137+
out <- added
138+
}(result.Word, translate)
139+
}
138140
}
139141
}()
140142
go func() {
@@ -177,11 +179,9 @@ func (args *Lingualeo) translateWords(ctx context.Context) <-chan api.OperationR
177179
}
178180

179181
func (args *Lingualeo) prepareResultToAdd(result *api.Result) bool {
180-
if !result.InDictionary() || args.Force {
181-
// Custom translation
182-
if len(args.Translation) > 0 {
183-
result.SetTranslate(args.Translation, args.TranslateReplace)
184-
}
182+
// Custom translation
183+
if len(args.Translation) > 0 {
184+
result.SetTranslation(args.Translation)
185185
return true
186186
}
187187
return false
@@ -244,7 +244,7 @@ func (args *Lingualeo) AddToDictionary(ctx context.Context, resultsToAdd <-chan
244244
// Process starts translation process
245245
func (args *Lingualeo) Process(ctx context.Context, wg *sync.WaitGroup) (<-chan string, <-chan api.Result, <-chan api.Result) {
246246
soundChan := make(chan string, len(args.Words))
247-
addWordChan := make(chan api.Result, len(args.Words))
247+
addWordChan := make(chan api.Result, len(args.Translation))
248248
resultsChan := make(chan api.Result, len(args.Words))
249249

250250
go func() {

‎pkg/translator/mock_Translator.go

+6-6
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)
Please sign in to comment.