/
bing.go
78 lines (64 loc) · 1.55 KB
/
bing.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package picsource
import (
"../tools"
"encoding/json"
"fmt"
"os"
"path"
"strings"
)
const (
BING_API_URL = `http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=8`
)
type bingObj struct {
Images []bingImage `json:"images"`
}
type bingImage struct {
URL string `json:"url"`
Copyright string `json:"copyright"`
}
// Bing provide pictures
func Bing(fileDir string, quality int) (string, error) {
fmt.Println("[1/4]Checking directory...")
os.MkdirAll(fileDir, 0777)
fmt.Println("[2/4] Loadding API...")
jsonData, err := tools.Fetch(BING_API_URL)
if err != nil {
os.Exit(2)
}
var jsonObj bingObj
fmt.Println("Parse json string...")
if err := json.Unmarshal(jsonData, &jsonObj); err != nil {
fmt.Println("Parse json string failed.", err)
return "", err
}
currentItem := jsonObj.Images[0]
picURL := "http://www.bing.com"
switch quality {
case 0:
picURL += currentItem.URL
case 1:
picURL += currentItem.URL
default:
picURL += currentItem.URL
}
fileName := currentItem.Copyright[:strings.Index(currentItem.Copyright, ",")]
fileName += ".jpg"
filePath := path.Join(tools.GetCurrentDirectory(), fileDir, fileName)
if !tools.CheckPathExists(filePath) {
fmt.Println("[3/4] Downlouding picture...")
imageData, err := tools.Fetch(picURL)
if err != nil {
os.Exit(2)
}
fmt.Println("[4/4] Save file...")
if err := tools.WriteFile(filePath, imageData); err != nil {
fmt.Println(err)
os.Exit(2)
}
} else {
fmt.Println("[3/4] File already exists...")
fmt.Println("[4/4] Check file...")
}
return filePath, nil
}