aboutsummaryrefslogtreecommitdiff
path: root/util.go
blob: fb9a73da6a9f11f7bbcdc683e81e10a8353bc746 (plain) (blame)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package devianter

import (
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"strings"
)

// функция для высера ошибки в stderr
func try(txt error) {
	if txt != nil {
		println(txt.Error())
	}
}

// сокращение для вызова щенка и парсинга жсона
func ujson(data string, output any) {
	input, err := puppy(data)
	try(err)
	try(json.Unmarshal([]byte(input), output))
}

/* REQUEST SECTION */
// структура для ответа сервера
type reqrt struct {
	Body    string
	Status  int
	Cookies []*http.Cookie
	Headers http.Header
}

// функция для совершения запроса
var UserAgent string

func request(uri string, other ...string) reqrt {
	var r reqrt

	// создаём новый запрос
	cli := &http.Client{}
	req, e := http.NewRequest("GET", uri, nil)
	try(e)

	req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:123.0) Gecko/20100101 Firefox/123.0.0")

	// куки и UA-шник
	if UserAgent != "" {
		req.Header.Set("User-Agent", UserAgent)
	}
	if len(other) != 0 {
		req.Header.Set("Cookie", other[0])
	}

	resp, e := cli.Do(req)
	try(e)
	defer resp.Body.Close()

	body, e := io.ReadAll(resp.Body)
	try(e)

	// заполняем структуру
	r.Body = string(body)
	r.Cookies = resp.Cookies()
	r.Headers = resp.Header
	r.Status = resp.StatusCode

	return r
}

/* PUPPY aka DeviantArt API */
// получение или обновление токена
var cookie string
var token string

func UpdateCSRF() error {
	if cookie == "" {
		req := request("https://www.deviantart.com/_puppy")

		for _, content := range req.Cookies {
			cookie = content.Raw
		}
	}

	req := request("https://www.deviantart.com", cookie)
	if req.Status != 200 {
		return errors.New(req.Body)
	}
	token = req.Body[strings.Index(req.Body, "window.__CSRF_TOKEN__ = '")+25 : strings.Index(req.Body, "window.__XHR_LOCAL__")-3]

	return nil
}

func puppy(data string) (string, error) {
	var url strings.Builder
	url.WriteString("https://www.deviantart.com/_puppy/")
	url.WriteString(data)
	url.WriteString("&csrf_token=")
	url.WriteString(token)
	url.WriteString("&da_minor_version=20230710")

	body := request(url.String(), cookie)

	// если код ответа не 200, возвращается ошибка
	if body.Status != 200 {
		return "", errors.New(body.Body)
	}

	return body.Body, nil
}