Skip to content

Commit

Permalink
support .env config file, add socks5 proxy support
Browse files Browse the repository at this point in the history
  • Loading branch information
TimothyYe committed Sep 8, 2017
1 parent caee558 commit f36d53e
Show file tree
Hide file tree
Showing 4 changed files with 148 additions and 77 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

[1]: https://travis-ci.org/TimothyYe/ydict.svg?branch=master
[2]: https://travis-ci.org/TimothyYe/ydict
[3]: https://img.shields.io/badge/release-v0.4-brightgreen.svg
[3]: https://img.shields.io/badge/release-v0.5-brightgreen.svg
[4]: https://github.com/TimothyYe/ydict/releases
[5]: https://img.shields.io/dub/l/vibe-d.svg
[6]: LICENSE
Expand Down
80 changes: 6 additions & 74 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,86 +1,18 @@
package main

import (
"fmt"
"log"
"os"
"strings"

"github.com/PuerkitoBio/goquery"
"github.com/fatih/color"
)

const ()

func query(word string) {
var url string
isChinese := IsChinese(word)

if isChinese {
url = "http://dict.youdao.com/w/eng/%s"
} else {
url = "http://dict.youdao.com/w/%s"
}

doc, err := goquery.NewDocument(fmt.Sprintf(url, word))
if err != nil {
log.Fatal(err)
os.Exit(1)
}

if isChinese {
// Find the result
fmt.Println()
doc.Find(".trans-container > ul > p > span.contentTitle").Each(func(i int, s *goquery.Selection) {
color.Green(" %s", s.Find(".search-js").Text())
})
} else {
// Find the result
result := doc.Find("div#phrsListTab > div.trans-container > ul").Text()
color.Green(result)
}

// Show examples
sentences := getSentences(doc, isChinese)
if len(sentences) > 0 {
fmt.Println()
for _, sentence := range sentences {
color.Green(" %s", sentence[0])
color.Magenta(" %s", sentence[1])
}
fmt.Println()
}
}

func getSentences(doc *goquery.Document, isChinese bool) [][]string {
result := [][]string{}
doc.Find("#bilingual ul li").Each(func(_ int, s *goquery.Selection) {
r := []string{}
s.Children().Each(func(ii int, ss *goquery.Selection) {
// Ignore source
if ii == 2 {
return
}
var sentence string
ss.Children().Each(func(iii int, sss *goquery.Selection) {
if text := strings.TrimSpace(sss.Text()); text != "" {
addSpace := (ii == 1 && isChinese) || (ii == 0 && !isChinese)
if addSpace && iii != 0 && text != "." {
text = " " + text
}
sentence += text
}
})
r = append(r, sentence)
})
if len(r) == 2 {
result = append(result, r)
}
})
return result
}
var (
proxy string
)

func main() {
//Check & load .env file
loadEnv()

if len(os.Args) == 1 {
displayUsage()
os.Exit(0)
Expand Down
108 changes: 108 additions & 0 deletions query.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package main

import (
"fmt"
"log"
"net/http"
"os"
"strings"

"github.com/PuerkitoBio/goquery"
"github.com/fatih/color"
proxier "golang.org/x/net/proxy"
)

func query(word string) {
var url string
var doc *goquery.Document
isChinese := isChinese(word)

if isChinese {
url = "http://dict.youdao.com/w/eng/%s"
} else {
url = "http://dict.youdao.com/w/%s"
}

//Check proxy
if proxy != "" {
client := &http.Client{}
dialer, err := proxier.SOCKS5("tcp", proxy, nil, proxier.Direct)

if err != nil {
color.Red("Can't connect to the proxy: %s", err)
os.Exit(1)
}

httpTransport := &http.Transport{}
client.Transport = httpTransport
httpTransport.Dial = dialer.Dial

resp, err := client.Get(fmt.Sprintf(url, word))

if err != nil {
color.Red("Query failed with err: %s", err.Error())
os.Exit(1)
}

doc, _ = goquery.NewDocumentFromResponse(resp)

} else {
var err error
doc, err = goquery.NewDocument(fmt.Sprintf(url, word))
if err != nil {
log.Fatal(err)
os.Exit(1)
}
}

if isChinese {
// Find the result
fmt.Println()
doc.Find(".trans-container > ul > p > span.contentTitle").Each(func(i int, s *goquery.Selection) {
color.Green(" %s", s.Find(".search-js").Text())
})
} else {
// Find the result
result := doc.Find("div#phrsListTab > div.trans-container > ul").Text()
color.Green(result)
}

// Show examples
sentences := getSentences(doc, isChinese)
if len(sentences) > 0 {
fmt.Println()
for _, sentence := range sentences {
color.Green(" %s", sentence[0])
color.Magenta(" %s", sentence[1])
}
fmt.Println()
}
}

func getSentences(doc *goquery.Document, isChinese bool) [][]string {
result := [][]string{}
doc.Find("#bilingual ul li").Each(func(_ int, s *goquery.Selection) {
r := []string{}
s.Children().Each(func(ii int, ss *goquery.Selection) {
// Ignore source
if ii == 2 {
return
}
var sentence string
ss.Children().Each(func(iii int, sss *goquery.Selection) {
if text := strings.TrimSpace(sss.Text()); text != "" {
addSpace := (ii == 1 && isChinese) || (ii == 0 && !isChinese)
if addSpace && iii != 0 && text != "." {
text = " " + text
}
sentence += text
}
})
r = append(r, sentence)
})
if len(r) == 2 {
result = append(result, r)
}
})
return result
}
35 changes: 33 additions & 2 deletions utils.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package main

import (
"fmt"
"log"
"os"
"path/filepath"
"unicode"

"github.com/fatih/color"
"github.com/joho/godotenv"
)

const (
Expand All @@ -15,7 +20,7 @@ const (
██║ ██████╔╝██║╚██████╗ ██║
╚═╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝
YDict V0.4
YDict V0.5
https://github.com/TimothyYe/ydict
`
Expand All @@ -26,11 +31,37 @@ func displayUsage() {
color.Cyan("Usage: ydict <word to query>")
}

func IsChinese(str string) bool {
func isChinese(str string) bool {
for _, r := range str {
if unicode.Is(unicode.Scripts["Han"], r) {
return true
}
}
return false
}

func getExecutePath() string {
ex, err := os.Executable()
if err != nil {
panic(err)
}

return filepath.Dir(ex)
}

func loadEnv() {
exPath := getExecutePath()

// if .env file doesn't exist, just return
if _, err := os.Stat(fmt.Sprintf("%s/.env", exPath)); os.IsNotExist(err) {
return
}

err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
return
}

proxy = os.Getenv("SOCKS5")
}

0 comments on commit f36d53e

Please sign in to comment.