From f41b98df2f2c6b7ebebf4dbe1396e9b32d20efeb Mon Sep 17 00:00:00 2001 From: Ihar Niamilentsau Date: Mon, 13 Jul 2020 01:31:51 +0300 Subject: [PATCH] Updated for API changed. Same format english->russian and russian->english translate response --- internal/fakeapi/api.go | 7 +- pkg/api/api.go | 24 +++--- pkg/api/constants.go | 19 +---- pkg/api/items.go | 163 +++++++--------------------------------- pkg/api/parsing.go | 30 -------- 5 files changed, 51 insertions(+), 192 deletions(-) delete mode 100644 pkg/api/parsing.go diff --git a/internal/fakeapi/api.go b/internal/fakeapi/api.go index 7f76ab3..edfd199 100644 --- a/internal/fakeapi/api.go +++ b/internal/fakeapi/api.go @@ -14,7 +14,6 @@ var ( "word_forms":[{"word":"accommodation","type":"прил."}], "pic_url":"http:\/\/contentcdn.lingualeo.com\/uploads\/picture\/3589594.png", "translate":[ - {"id":33404925,"value":"размещение; жильё","votes":6261,"is_user":0,"pic_url":"http:\/\/contentcdn.lingualeo.com\/uploads\/picture\/3589594.png"}, {"id":2569250,"value":"жильё","votes":5703,"is_user":0,"pic_url":"http:\/\/contentcdn.lingualeo.com\/uploads\/picture\/31064.png"}, {"id":2718711,"value":"проживание","votes":1589,"is_user":0,"pic_url":"http:\/\/contentcdn.lingualeo.com\/uploads\/picture\/335521.png"}, {"id":185932,"value":"размещение","votes":880,"is_user":0,"pic_url":"http:\/\/contentcdn.lingualeo.com\/uploads\/picture\/374830.png"}, @@ -22,7 +21,7 @@ var ( ], "transcription":"əkəədˈeɪːʃən","word_id":102085,"word_top":0, "sound_url":"http:\/\/audiocdn.lingualeo.com\/v2\/3\/102085-631152000.mp3"}` - Expected = []string{"размещение", "жильё", "проживание", "помещение"} + Expected = []string{"жильё", "проживание", "размещение", "помещение"} SearchWord = "accommodation" ) @@ -31,13 +30,13 @@ type FakeAPI struct { } func (f *FakeAPI) TranslateWord(word string) api.OpResult { - res := api.EnglishResult{Word: word} + res := api.TranslationResult{Word: word} err := res.FromResponse(responseData) return api.OpResult{Result: &res, Error: err} } func (f *FakeAPI) AddWord(word string, _ []string) api.OpResult { - res := api.EnglishResult{Word: word} + res := api.TranslationResult{Word: word} err := res.FromResponse(responseData) return api.OpResult{Result: &res, Error: err} } diff --git a/pkg/api/api.go b/pkg/api/api.go index fe9b7aa..2eb0216 100644 --- a/pkg/api/api.go +++ b/pkg/api/api.go @@ -38,6 +38,20 @@ type API struct { client *http.Client } +func checkAuthError(body *string) error { + if body == nil || *body == "" { + return nil + } + res := apiError{} + if err := getJSONFromString(*body, &res); err != nil { + return err + } + if res.ErrorCode != 0 { + return fmt.Errorf("%s: Status code: %d", res.ErrorMsg, res.ErrorCode) + } + return nil +} + func NewAPI(email string, password string, debug bool) (*API, error) { client, err := prepareClient() if err != nil { @@ -103,15 +117,7 @@ func (api *API) auth() error { if err != nil { return err } - res := apiError{} - err = getJSONFromString(*responseBody, &res) - if err != nil { - return err - } - if res.ErrorCode != 0 { - return fmt.Errorf("%s: Status code: %d", res.ErrorMsg, res.ErrorCode) - } - return nil + return checkAuthError(responseBody) } func debugRequest(request *http.Request) { diff --git a/pkg/api/constants.go b/pkg/api/constants.go index 2d382b4..f88ba39 100644 --- a/pkg/api/constants.go +++ b/pkg/api/constants.go @@ -2,16 +2,13 @@ package api import ( "net/http" - "regexp" - "strings" ) const ( - authURL = "https://lingualeo.com/api/login" - translateURL = "https://api.lingualeo.com/gettranslates?port=1001" - addWordURL = "https://api.lingualeo.com/addword?port=1001" - bigRussianAlphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ" - apiVersion = "1.0.1" + authURL = "https://lingualeo.com/api/login" + translateURL = "https://api.lingualeo.com/gettranslates?port=1001" + addWordURL = "https://api.lingualeo.com/addword?port=1001" + apiVersion = "1.0.1" ) var ( @@ -19,12 +16,4 @@ var ( "User-Agent": []string{"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36"}, "Accept": []string{"application/json"}, } - splitRegex = regexp.MustCompile(`\s*?[:,;]+\s*?`) - blankSymbolsRegex = regexp.MustCompile(`\s+`) - blankSymbolsWithPointRegex = regexp.MustCompile(`\s+\.\s*`) - alphabet = strings.Join( - []string{symbols, bigRussianAlphabet, strings.ToLower(bigRussianAlphabet)}, - "", - ) - symbols = "-. " ) diff --git a/pkg/api/items.go b/pkg/api/items.go index 6cfccad..6754a11 100644 --- a/pkg/api/items.go +++ b/pkg/api/items.go @@ -35,6 +35,7 @@ type Result interface { PrintTranslation() PrintAddedTranslation() InDictionary() bool + IsRussian() bool } type apiError struct { @@ -56,28 +57,7 @@ type OpResult struct { } func opResultFromBody(word string, body string) OpResult { - engOp := opEnglishResultFromBody(word, body) - if engOp.Error != nil { - rusOp := opRussianResultFromBody(word, body) - if rusOp.Error != nil { - return engOp - } - return rusOp - } - return engOp -} - -func opEnglishResultFromBody(word string, body string) OpResult { - res := EnglishResult{Word: word} - err := res.FromResponse(body) - return OpResult{ - Error: err, - Result: &res, - } -} - -func opRussianResultFromBody(word string, body string) OpResult { - res := RussianResult{Word: word} + res := TranslationResult{Word: word} err := res.FromResponse(body) return OpResult{ Error: err, @@ -85,69 +65,56 @@ func opRussianResultFromBody(word string, body string) OpResult { } } -type WordForm struct { - PictureURL string `json:"pic_url"` - SoundURL string `json:"sound_url"` - Transcription string `json:"transcription"` - Votes int `json:"votes"` - Word string `json:"word"` -} - -type EnglishResult struct { - Word string `json:"-"` - Words []string `json:"-"` - Exists bool `json:"-"` - SoundURL string `json:"sound_url"` - Transcription string `json:"transcription"` - Translate []Word `json:"translate"` - ErrorMsg string `json:"error_msg"` - DirectionEnglish bool `json:"directionEnglish"` +type TranslationResult struct { + Word string `json:"-"` + Words []string `json:"-"` + Exists convertibleBoolean `json:"is_user"` + SoundURL string `json:"sound_url"` + Transcription string `json:"transcription"` + Translate []Word `json:"translate"` + ErrorMsg string `json:"error_msg"` + DirectionEnglish bool `json:"directionEnglish"` } -func (result *EnglishResult) FromResponse(body string) error { +func (result *TranslationResult) FromResponse(body string) error { return fromResponse(result, body) } -func (result *EnglishResult) GetTranscription() []string { +func (result *TranslationResult) GetTranscription() []string { return []string{result.Transcription} } -func (result *EnglishResult) PrintTranslation() { +func (result *TranslationResult) PrintTranslation() { printTranslation(result) } -func (result *EnglishResult) PrintAddedTranslation() { +func (result *TranslationResult) PrintAddedTranslation() { printAddedTranslation(result) } -func (result *EnglishResult) parse() { - isUsed := false +func (result *TranslationResult) parse() { sort.Slice(result.Translate, func(i, j int) bool { return result.Translate[i].Votes > result.Translate[j].Votes }) for _, translate := range result.Translate { - if !isUsed { - isUsed = bool(translate.Exists) - } - result.Words = append(result.Words, sanitizeWords(translate.Value)...) + result.Words = append(result.Words, translate.Value) } - result.Exists = isUsed result.Words = utils.Unique(result.Words) } -func (result *EnglishResult) GetWord() string { +func (result *TranslationResult) GetWord() string { return result.Word } -func (result *EnglishResult) SetWord(word string) { +func (result *TranslationResult) SetWord(word string) { result.Word = word } -func (result *EnglishResult) GetTranslate() []string { +func (result *TranslationResult) GetTranslate() []string { return result.Words } -func (result *EnglishResult) SetTranslate(translates []string, replace bool) { +func (result *TranslationResult) SetTranslate(translates []string, replace bool) { if replace { result.Words = utils.Unique(translates) } else { @@ -155,95 +122,23 @@ func (result *EnglishResult) SetTranslate(translates []string, replace bool) { } } -func (result *EnglishResult) GetSoundURLs() []string { +func (result *TranslationResult) GetSoundURLs() []string { return []string{result.SoundURL} } -func (result *EnglishResult) InDictionary() bool { - return result.Exists +func (result *TranslationResult) InDictionary() bool { + return bool(result.Exists) } -func (result *EnglishResult) Error() string { +func (result *TranslationResult) Error() string { return result.ErrorMsg } +func (result *TranslationResult) IsRussian() bool { + return result.Transcription == "" +} + type NoResult struct { Translate []string `json:"translate"` ErrorMsg string `json:"error_msg"` } - -type RussianResult struct { - Word string `json:"-"` - Words []string `json:"-"` - Exists convertibleBoolean `json:"is_user"` - Translate []string `json:"translate"` - ErrorMsg string `json:"error_msg"` - DirectionEnglish bool `json:"directionEnglish"` - WordForms []WordForm `json:"word_forms"` -} - -func (result *RussianResult) FromResponse(body string) error { - return fromResponse(result, body) -} - -func (result *RussianResult) parse() { - sort.Slice(result.WordForms, func(i, j int) bool { - return result.WordForms[i].Votes > result.WordForms[j].Votes - }) - for _, form := range result.WordForms { - result.Words = append(result.Words, form.Word) - } - result.Words = utils.Unique(result.Words) -} - -func (result *RussianResult) Error() string { - return result.ErrorMsg -} - -func (result *RussianResult) InDictionary() bool { - return bool(result.Exists) -} - -func (result *RussianResult) GetSoundURLs() []string { - urls := make([]string, 0) - for _, form := range result.WordForms { - urls = append(urls, form.SoundURL) - } - return urls -} - -func (result *RussianResult) GetWord() string { - return result.Word -} - -func (result *RussianResult) SetWord(word string) { - result.Word = word -} - -func (result *RussianResult) GetTranslate() []string { - return result.Words -} - -func (result *RussianResult) GetTranscription() []string { - transcriptions := make([]string, 0) - for _, form := range result.WordForms { - transcriptions = append(transcriptions, form.Transcription) - } - return transcriptions -} - -func (result *RussianResult) SetTranslate(translates []string, replace bool) { - if replace { - result.Words = utils.Unique(translates) - } else { - result.Words = utils.Unique(append(result.Words, translates...)) - } -} - -func (result *RussianResult) PrintTranslation() { - printTranslation(result) -} - -func (result *RussianResult) PrintAddedTranslation() { - printAddedTranslation(result) -} diff --git a/pkg/api/parsing.go b/pkg/api/parsing.go deleted file mode 100644 index e6118e4..0000000 --- a/pkg/api/parsing.go +++ /dev/null @@ -1,30 +0,0 @@ -package api - -import ( - "fmt" - "regexp" - "strings" -) - -func fixTranslateString(word string) string { - word = blankSymbolsRegex.ReplaceAllString(word, " ") - word = blankSymbolsWithPointRegex.ReplaceAllString(word, ". ") - return strings.ToLower(word) -} - -func removeSymbols(word string) string { - nonAlphaBet := regexp.MustCompile(fmt.Sprintf(`[^%s]`, alphabet)) - return nonAlphaBet.ReplaceAllString(word, "") -} - -func sanitizeWords(word string) []string { - var results []string - words := splitRegex.Split(strings.TrimSpace(word), -1) - for _, word := range words { - word = fixTranslateString(strings.TrimSpace(removeSymbols(word))) - if len(word) > 1 { - results = append(results, word) - } - } - return results -}