krz/devianter

A DeviantArt guest API library for Go.

clone: git clone https://gitbay.org/krz/devianter.git

v0.1.0: deviantion.go · raw

  1package devianter
  2
  3import (
  4	"encoding/json"
  5	"strconv"
  6	timelib "time"
  7)
  8
  9// хрень для парсинга времени публикации
 10type time struct {
 11	timelib.Time
 12}
 13
 14func (t *time) UnmarshalJSON(b []byte) (err error) {
 15	if b[0] == '"' && b[len(b)-1] == '"' {
 16		b = b[1 : len(b)-1]
 17	}
 18	t.Time, err = timelib.Parse("2006-01-02T15:04:05-0700", string(b))
 19	return
 20}
 21
 22// самая главная структура для поста
 23type deviantion struct {
 24	Title, Url, License string
 25	PublishedTime       time
 26
 27	NSFW bool `json:"isMature"`
 28	AI   bool `json:"isAiGenerated"`
 29	DD   bool `json:"isDailyDeviation"`
 30
 31	Author struct {
 32		Username string
 33	}
 34	Stats struct {
 35		Favourites, Views, Downloads int
 36	}
 37	Media    media
 38	Extended struct {
 39		Tags []struct {
 40			Name string
 41		}
 42		DescriptionText text
 43		RelatedContent  []struct {
 44			Deviations []deviantion
 45		}
 46	}
 47	TextContent text
 48}
 49
 50// её выпердыши
 51type media struct {
 52	BaseUri string
 53	Token   []string
 54	Types   []struct {
 55		T    string
 56		H, W int
 57	}
 58}
 59
 60type text struct {
 61	Excerpt string
 62	Html    struct {
 63		Markup, Type string
 64	}
 65}
 66
 67// структура поста
 68type Deviantion struct {
 69	Deviation deviantion
 70	Comments  struct {
 71		Total  int
 72		Cursor string
 73	}
 74
 75	ParsedComments []struct {
 76		Author         string
 77		Posted         time
 78		Replies, Likes int
 79	}
 80
 81	IMG, Desctiption string
 82}
 83
 84// для работы функции нужно ID поста и имя пользователя.
 85func Deviation(id string, user string) Deviantion {
 86	var st Deviantion
 87	ujson(
 88		"dadeviation/init?deviationid="+id+"&username="+user+"&type=art&include_session=false&expand=deviation.related&preload=true",
 89		&st,
 90	)
 91
 92	// преобразование урла в правильный
 93	for _, t := range st.Deviation.Media.Types {
 94		if m := st.Deviation.Media; t.T == "fullview" {
 95			if len(m.Token) > 0 {
 96				st.IMG = m.BaseUri + "?token="
 97			} else {
 98				st.IMG = m.BaseUri + "/v1/fill/w_" + strconv.Itoa(t.W) + ",h_" + strconv.Itoa(t.H) + "/" + id + "_" + user + ".gif" + "?token="
 99			}
100			st.IMG += m.Token[0]
101		}
102	}
103
104	// базовая обработка описания
105	txt := st.Deviation.TextContent.Html.Markup
106	if len(txt) > 0 && txt[1] == 125 {
107		var description struct {
108			Blocks []struct {
109				Text string
110			}
111		}
112
113		json.Unmarshal([]byte(txt), &description)
114		for _, a := range description.Blocks {
115			txt = a.Text
116		}
117	}
118
119	st.Desctiption = txt
120
121	return st
122}