krz/devianter

A DeviantArt guest API library for Go.

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

8f645d7ccb01c15650958f2f9dd14f15f9afd72b

unsigned

author: lost+skunk <skunky@macaw.me> · 2024-06-13T21:05:21Z

небольшие улучшения
 comments.go   |  8 ++++----
 deviantion.go | 53 +++++++++++++++++++++++++++++++++--------------------
 misc.go       | 13 +++++++------
 user-group.go | 20 +++++++++++++-------
 4 files changed, 57 insertions(+), 37 deletions(-)

diff --git a/comments.go b/comments.go
index 7b3bb3d..a78ab1a 100644
--- a/comments.go
+++ b/comments.go
@@ -6,7 +6,7 @@ import (
 	"strings"
 )
 
-type comments struct {
+type Comments struct {
 	Cursor           string
 	PrevOffset       int
 	HasMore, HasLess bool
@@ -33,12 +33,12 @@ type comments struct {
 }
 
 // функция для обработки комментариев поста, пользователя, группы и многого другого
-func Comments(
+func CommentsFunc(
 	postid string,
 	cursor string,
 	page int,
 	typ int, // 1 - комментарии поста; 4 - комментарии на стене группы или пользователя
-) (cmmts comments) {
+) (cmmts Comments) {
 	for x := 0; x <= page; x++ {
 		ujson(
 			"dashared/comments/thread?typeid="+strconv.Itoa(typ)+
@@ -55,7 +55,7 @@ func Comments(
 			cmmts.Thread[i].Comment = m
 
 			// если начало строки {, а конец }, то срабатывает этот иф
-			if m[0] == 123 && m[l-1] == 125 {
+			if m[0] == '{' && m[l-1] == '}' {
 				var content struct {
 					Blocks []struct {
 						Text string
diff --git a/deviantion.go b/deviantion.go
index 9803855..9e17da2 100644
--- a/deviantion.go
+++ b/deviantion.go
@@ -3,6 +3,7 @@ package devianter
 import (
 	"encoding/json"
 	"strconv"
+	"strings"
 	timelib "time"
 )
 
@@ -20,7 +21,7 @@ func (t *time) UnmarshalJSON(b []byte) (err error) {
 }
 
 // самая главная структура для поста
-type deviantion struct {
+type Deviation struct {
 	Title, Url, License string
 	PublishedTime       time
 
@@ -41,7 +42,7 @@ type deviantion struct {
 		}
 		DescriptionText text
 		RelatedContent  []struct {
-			Deviations []deviantion
+			Deviations []Deviation
 		}
 	}
 	TextContent text
@@ -65,8 +66,8 @@ type text struct {
 }
 
 // структура поста
-type Deviantion struct {
-	Deviation deviantion
+type Post struct {
+	Deviation Deviation
 	Comments  struct {
 		Total  int
 		Cursor string
@@ -78,32 +79,44 @@ type Deviantion struct {
 		Replies, Likes int
 	}
 
-	IMG, Desctiption string
+	IMG, Description string
+}
+
+// преобразование урла в правильный
+func UrlFromMedia(m media) string {
+	var url strings.Builder
+	for _, t := range m.Types {
+		if t.T == "fullview" {
+			url.WriteString(m.BaseUri)
+			if m.BaseUri[len(m.BaseUri)-3:] != "gif" && t.W*t.H < 33177600 {
+				url.WriteString("/v1/fill/w_")
+				url.WriteString(strconv.Itoa(t.W))
+				url.WriteString(",h_")
+				url.WriteString(strconv.Itoa(t.H))
+				url.WriteString("/")
+				url.WriteString("image")
+				url.WriteString(".gif")
+			}
+			url.WriteString("?token=")
+			url.WriteString(m.Token[0])
+		}
+	}
+	return url.String()
 }
 
 // для работы функции нужно ID поста и имя пользователя.
-func Deviation(id string, user string) Deviantion {
-	var st Deviantion
+func DeviationFunc(id string, user string) Post {
+	var st Post
 	ujson(
 		"dadeviation/init?deviationid="+id+"&username="+user+"&type=art&include_session=false&expand=deviation.related&preload=true",
 		&st,
 	)
 
-	// преобразование урла в правильный
-	for _, t := range st.Deviation.Media.Types {
-		if m := st.Deviation.Media; t.T == "fullview" {
-			if len(m.Token) > 0 {
-				st.IMG = m.BaseUri + "?token="
-			} else {
-				st.IMG = m.BaseUri + "/v1/fill/w_" + strconv.Itoa(t.W) + ",h_" + strconv.Itoa(t.H) + "/" + id + "_" + user + ".gif" + "?token="
-			}
-			st.IMG += m.Token[0]
-		}
-	}
+	st.IMG = UrlFromMedia(st.Deviation.Media)
 
 	// базовая обработка описания
 	txt := st.Deviation.TextContent.Html.Markup
-	if len(txt) > 0 && txt[1] == 125 {
+	if len(txt) > 0 && txt[1] == '{' {
 		var description struct {
 			Blocks []struct {
 				Text string
@@ -116,7 +129,7 @@ func Deviation(id string, user string) Deviantion {
 		}
 	}
 
-	st.Desctiption = txt
+	st.Description = txt
 
 	return st
 }
diff --git a/misc.go b/misc.go
index d5f6793..5976e80 100644
--- a/misc.go
+++ b/misc.go
@@ -116,13 +116,13 @@ func AEmedia(name string, t rune) (string, error) {
 }
 
 /* SEARCH */
-type search struct {
-	Total   int          `json:"estTotal"`
-	Pages   int          // only for 'a' and 'g' scope.
-	Results []deviantion `json:"deviations,results"`
+type Search struct {
+	Total   int         `json:"estTotal"`
+	Pages   int         // only for 'a' and 'g' scope.
+	Results []Deviation `json:"deviations,results"`
 }
 
-func Search(query string, page int, scope rune, user ...string) (ss search, e error) {
+func SearchFunc(query string, page int, scope rune, user ...string) (ss Search, e error) {
 	var url strings.Builder
 	e = nil
 
@@ -159,7 +159,8 @@ func Search(query string, page int, scope rune, user ...string) (ss search, e er
 	ujson(url.String(), &ss)
 
 	// расчёт, сколько всего страниц по запросу. без токена 417 страниц - максимум
-	for x := 0; x < int(math.Round(float64(ss.Total/25))); x++ {
+	totalfloat := int(math.Round(float64(ss.Total / 25)))
+	for x := 0; x < totalfloat; x++ {
 		if x <= 417 {
 			ss.Pages = x
 		}
diff --git a/user-group.go b/user-group.go
index 32342fb..c9a1f2b 100644
--- a/user-group.go
+++ b/user-group.go
@@ -6,7 +6,7 @@ import (
 )
 
 // структура группы или пользователя
-type Group struct {
+type GRuser struct {
 	ErrorDescription string
 	Owner            struct {
 		Group    bool `json:"isGroup"`
@@ -30,7 +30,7 @@ type Group struct {
 						}
 					}
 					CoverDeviation struct {
-						Deviation deviantion `json:"coverDeviation"`
+						Deviation Deviation `json:"coverDeviation"`
 					}
 
 					// группы
@@ -56,7 +56,7 @@ type Group struct {
 						Folder struct {
 							Username   string
 							Pages      int `json:"totalPageCount"`
-							Deviations []deviantion
+							Deviations []Deviation
 						} `json:"folderDeviations"`
 					}
 				}
@@ -72,17 +72,23 @@ type Group struct {
 	}
 }
 
-func UGroup(name string) (g Group) {
-	ujson("dauserprofile/init/about?username="+name, &g)
+type Group struct {
+	Name    string // обязательно заполнить
+	Content GRuser
+}
+
+// подходит как группа, так и пользователь
+func (s Group) GroupFunc() (g Group) {
+	ujson("dauserprofile/init/about?username="+s.Name, &g)
 
 	return
 }
 
 // гарелея пользователя или группы
-func Gallery(name string, page int) (g Group) {
+func (s Group) Gallery(page int) (g Group) {
 	var url strings.Builder
 	url.WriteString("dauserprofile/init/gallery?username=")
-	url.WriteString(name)
+	url.WriteString(s.Name)
 	url.WriteString("&page=")
 	url.WriteString(strconv.Itoa(page))
 	url.WriteString("&deviations_limit=50&with_subfolders=false")