krz/devianter
A DeviantArt guest API library for Go.
clone: git clone https://gitbay.org/krz/devianter.git
v0.2.5: misc.go · raw
1package devianter
2
3import (
4 "errors"
5 "log"
6 "math"
7 "net/url"
8 "strconv"
9 "strings"
10)
11
12/* AVATARS AND EMOJIS */
13func AEmedia(name string, t rune) (string, error) {
14 if len(name) < 2 {
15 return "", errors.New("name must be specified")
16 }
17 // список всех возможных расширений
18 var extensions = [3]string{
19 ".jpg",
20 ".png",
21 ".gif",
22 }
23 // надо
24 name = strings.ToLower(name)
25
26 // построение ссылок. билдер потому что он быстрее обычного сложения строк.
27 var b strings.Builder
28 switch t {
29 case 'a':
30 b.WriteString("https://a.deviantart.net/avatars-big/")
31 name_without_dashes := strings.ReplaceAll(name, "-", "_")
32 b.WriteString(name_without_dashes[:1])
33 b.WriteString("/")
34 b.WriteString(name_without_dashes[1:2])
35 b.WriteString("/")
36 case 'e':
37 b.WriteString("https://e.deviantart.net/emoticons/")
38 b.WriteString(name[:1])
39 b.WriteString("/")
40 default:
41 log.Fatalln("Invalid type.\n- 'a' -- avatar;\n- 'e' -- emoji.")
42 }
43 b.WriteString(name)
44
45 // проверка ссылки на доступность
46 for x := 0; x < len(extensions); x++ {
47 req := request(b.String() + extensions[x])
48 if req.Status == 200 {
49 return req.Body, nil
50 }
51 }
52
53 return "", errors.New("user not exists")
54}
55
56/* DAILY DEVIATIONS */
57type DailyDeviations struct {
58 HasMore bool
59 Strips []struct {
60 Codename, Title string
61 TitleType string
62 Deviations []Deviation
63 }
64 Deviations []Deviation
65}
66
67func GetDailyDeviations(page int) (dd DailyDeviations) {
68 ujson("dabrowse/networkbar/rfy/deviations?page="+strconv.Itoa(page), &dd)
69 return
70}
71
72/* SEARCH */
73type Search struct {
74 Total int `json:"estTotal"`
75 Pages int // only for 'a' and 'g' scope.
76 HasMore bool
77 Results []Deviation `json:"deviations"`
78 ResultsGalleryTemp []Deviation `json:"results"`
79}
80
81func PerformSearch(query string, page int, scope rune, user ...string) (ss Search, e error) {
82 var buildurl strings.Builder
83 e = nil
84
85 // о5 построение ссылок.
86 switch scope {
87 case 'a': // поиск артов по названию
88 buildurl.WriteString("dabrowse/search/all?q=")
89 case 't': // поиск артов по тегам
90 buildurl.WriteString("dabrowse/networkbar/tag/deviations?tag=")
91 case 'g': // поиск артов пользователя или группы
92 if user != nil {
93 buildurl.WriteString("dashared/gallection/search?username=")
94 buildurl.WriteString(user[0])
95 buildurl.WriteString("&type=gallery&order=most-recent&init=true&limit=50&q=")
96 } else {
97 e = errors.New("missing username (last argument)")
98 return
99 }
100 default:
101 log.Fatalln("Invalid type.\n- 'a' -- all;\n- 't' -- tag;\n- 'g' - gallery.")
102 }
103
104 buildurl.WriteString(url.QueryEscape(query))
105 if scope != 'g' { // если область поиска не равна поиску по группам, то активируется этот код
106 buildurl.WriteString("&page=")
107 } else { // иначе вместо страницы будет оффсет и страница умножится на 50
108 buildurl.WriteString("&offset=")
109 page = 50 * page
110 }
111 buildurl.WriteString(strconv.Itoa(page))
112
113 ujson(buildurl.String(), &ss)
114
115 if scope == 'g' {
116 ss.Results = ss.ResultsGalleryTemp
117 }
118
119 // расчёт, сколько всего страниц по запросу. без токена 417 страниц - максимум
120 totalfloat := int(math.Round(float64(ss.Total / 25)))
121 for x := 0; x < totalfloat; x++ {
122 if x <= 417 {
123 ss.Pages = x
124 }
125 }
126
127 return
128}