SkunkyArt/app/util.go

328 lines
6.6 KiB
Go
Raw Normal View History

2024-06-27 11:51:46 +00:00
package app
import (
2024-09-23 06:38:32 +00:00
"encoding/json"
2024-07-05 21:46:25 +00:00
"io"
"net/http"
"net/url"
2024-07-05 21:46:25 +00:00
"os"
"skunkyart/static"
"strconv"
2024-06-27 11:51:46 +00:00
"strings"
"text/template"
2024-07-05 21:46:25 +00:00
"time"
2024-06-27 11:51:46 +00:00
"git.macaw.me/skunky/devianter"
"golang.org/x/net/html"
2024-06-27 11:51:46 +00:00
)
2024-07-13 18:32:04 +00:00
/* INTERNAL */
2024-08-14 16:18:06 +00:00
var wr = io.WriteString
2024-07-13 18:32:04 +00:00
func exit(msg string, code int) {
println(msg)
os.Exit(code)
}
func try(e error) {
if e != nil {
println(e.Error())
}
}
func tryWithExitStatus(err error, code int) {
2024-07-13 18:32:04 +00:00
if err != nil {
exit(err.Error(), code)
}
}
func restore() {
if r := recover(); r != nil {
recover()
}
}
var instances []byte
2024-09-23 06:38:32 +00:00
var About instanceAbout
2024-08-01 19:48:05 +00:00
func RefreshInstances() {
for {
func() {
defer restore()
instances = Download("https://git.macaw.me/skunky/SkunkyArt/raw/branch/master/instances.json").Body
2024-09-23 06:38:32 +00:00
try(json.Unmarshal(instances, &About))
2024-08-01 19:48:05 +00:00
}()
time.Sleep(1 * time.Hour)
}
}
2024-07-13 18:32:04 +00:00
// some crap for frontend
2024-09-23 06:38:32 +00:00
type instanceAbout struct {
Proxy bool
Nsfw bool
Instances []settings
}
2024-08-14 16:18:06 +00:00
type skunkyart struct {
Writer http.ResponseWriter
2024-11-15 19:43:27 +00:00
_pth string
2024-08-14 16:18:06 +00:00
Args url.Values
Page int
Type rune
Atom bool
BasePath, Endpoint string
Query, QueryRaw string
2024-09-23 06:38:32 +00:00
API API
Version string
2024-09-02 08:16:54 +00:00
2024-08-14 16:18:06 +00:00
Templates struct {
2024-09-23 06:38:32 +00:00
About instanceAbout
2024-08-14 16:18:06 +00:00
SomeList string
DDStrips string
Deviation struct {
Post devianter.Post
Related string
StringTime string
Tags string
Comments string
}
GroupUser struct {
GR devianter.GRuser
Admins string
Group bool
CreationDate string
About struct {
A devianter.About
DescriptionFormatted string
Interests, Social string
Comments string
BG string
BGMeta devianter.Deviation
}
Gallery struct {
Folders string
Pages int
List string
}
}
Search struct {
Content devianter.Search
List string
}
}
}
func (s skunkyart) ExecuteTemplate(file, dir string, data any) {
var buf strings.Builder
tmp := template.New(file)
tmp, err := tmp.ParseFS(static.Templates, dir+"/*")
if err != nil {
s.Writer.WriteHeader(500)
wr(s.Writer, err.Error())
return
}
2024-07-13 18:32:04 +00:00
try(tmp.Execute(&buf, &data))
wr(s.Writer, buf.String())
}
2024-07-05 21:46:25 +00:00
func UrlBuilder(strs ...string) string {
var str strings.Builder
2024-07-05 21:46:25 +00:00
l := len(strs)
2024-07-13 18:32:04 +00:00
str.WriteString(Host)
2024-08-01 19:48:05 +00:00
str.WriteString(CFG.URI)
2024-07-05 21:46:25 +00:00
for n, x := range strs {
str.WriteString(x)
2024-09-23 06:38:32 +00:00
if n := n + 1; n < l && len(strs[n]) != 0 && !(strs[n][0] == '?' || strs[n][0] == '&') && !(x[0] == '?' || x[0] == '&') {
2024-07-05 21:46:25 +00:00
str.WriteString("/")
}
}
return str.String()
}
2024-09-04 17:22:58 +00:00
func (s skunkyart) Error(dAerr devianter.Error) {
s.Writer.WriteHeader(502)
var msg strings.Builder
msg.WriteString(`<html><link rel="stylesheet" href="`)
msg.WriteString(UrlBuilder("stylesheet"))
msg.WriteString(`" /><h3>DeviantArt error — '`)
msg.WriteString(dAerr.Error)
msg.WriteString("'</h3></html>")
wr(s.Writer, msg.String())
}
func (s skunkyart) ReturnHTTPError(status int) {
s.Writer.WriteHeader(status)
var msg strings.Builder
2024-07-05 21:46:25 +00:00
msg.WriteString(`<html><link rel="stylesheet" href="`)
2024-07-13 18:32:04 +00:00
msg.WriteString(UrlBuilder("stylesheet"))
2024-07-05 21:46:25 +00:00
msg.WriteString(`" /><h1>`)
msg.WriteString(strconv.Itoa(status))
msg.WriteString(" - ")
msg.WriteString(http.StatusText(status))
msg.WriteString("</h1></html>")
wr(s.Writer, msg.String())
}
2024-09-03 12:36:19 +00:00
func (s skunkyart) SetFilename(name string) {
var filename strings.Builder
filename.WriteString(`filename="`)
filename.WriteString(name)
filename.WriteString(`"`)
s.Writer.Header().Add("Content-Disposition", filename.String())
}
2024-07-13 18:32:04 +00:00
type Downloaded struct {
Headers http.Header
Status int
Body []byte
}
func Download(urlString string) (d Downloaded) {
2024-07-13 18:32:04 +00:00
cli := &http.Client{}
if CFG.DownloadProxy != "" {
u, e := url.Parse(CFG.DownloadProxy)
2024-07-13 18:32:04 +00:00
try(e)
cli.Transport = &http.Transport{Proxy: http.ProxyURL(u)}
}
req, e := http.NewRequest("GET", urlString, nil)
2024-07-13 18:32:04 +00:00
try(e)
req.Header.Set("User-Agent", CFG.UserAgent)
2024-07-13 18:32:04 +00:00
resp, e := cli.Do(req)
try(e)
defer resp.Body.Close()
b, e := io.ReadAll(resp.Body)
try(e)
d.Body = b
d.Status = resp.StatusCode
d.Headers = resp.Header
return
}
/* PARSING HELPERS */
2024-09-02 08:16:54 +00:00
func ParseMedia(media devianter.Media, thumb ...int) string {
mediaUrl, filename := devianter.UrlFromMedia(media, thumb...)
if len(mediaUrl) != 0 && CFG.Proxy {
mediaUrl = mediaUrl[21:]
dot := strings.Index(mediaUrl, ".")
2024-09-03 12:36:19 +00:00
if filename == "" {
filename = "image.gif"
}
2024-09-02 08:16:54 +00:00
return UrlBuilder("media", "file", mediaUrl[:dot], mediaUrl[dot+11:], "&filename=", filename)
2024-09-23 06:38:32 +00:00
} else if !CFG.Proxy {
return mediaUrl
2024-07-13 18:32:04 +00:00
}
2024-09-04 17:22:58 +00:00
return ""
2024-07-13 18:32:04 +00:00
}
func ConvertDeviantArtUrlToSkunkyArt(url string) (output string) {
2024-07-05 21:46:25 +00:00
if len(url) > 32 && url[27:32] != "stash" {
url = url[27:]
firstshash := strings.Index(url, "/")
lastshash := firstshash + strings.Index(url[firstshash+1:], "/")
if lastshash != -1 {
output = UrlBuilder("post", url[:firstshash], url[lastshash+2:])
}
2024-07-05 21:46:25 +00:00
}
return
}
2024-07-09 09:54:15 +00:00
func BuildUserPlate(name string) string {
var htm strings.Builder
htm.WriteString(`<div class="user-plate"><img src="`)
htm.WriteString(UrlBuilder("media", "emojitar", name, "?type=a"))
htm.WriteString(`"><a href="`)
htm.WriteString(UrlBuilder("group_user", "?type=about&q=", name))
htm.WriteString(`">`)
htm.WriteString(name)
htm.WriteString(`</a></div>`)
return htm.String()
}
2024-07-13 18:32:04 +00:00
func GetValueOfTag(t *html.Tokenizer) string {
2024-07-09 09:54:15 +00:00
for tt := t.Next(); ; {
2024-08-01 19:48:05 +00:00
if tt == html.TextToken {
2024-07-09 09:54:15 +00:00
return string(t.Text())
2024-08-01 19:48:05 +00:00
} else {
return ""
2024-07-09 09:54:15 +00:00
}
}
}
// навигация по страницам
2024-07-13 18:32:04 +00:00
type DeviationList struct {
Pages int
More bool
}
// FIXME: на некоротрых артах первая страница может вызывать полное отсутствие панели навигации.
2024-07-13 18:32:04 +00:00
func (s skunkyart) NavBase(c DeviationList) string {
var list strings.Builder
list.WriteString("<br>")
prevrev := func(msg string, page int, onpage bool) {
if !onpage {
list.WriteString(`<a href="`)
2024-11-15 19:43:27 +00:00
list.WriteString(s._pth)
list.WriteString(`?p=`)
list.WriteString(strconv.Itoa(page))
if s.Type != 0 {
list.WriteString("&type=")
list.WriteRune(s.Type)
}
if s.Query != "" {
list.WriteString("&q=")
list.WriteString(s.Query)
}
if f := s.Args.Get("folder"); f != "" {
list.WriteString("&folder=")
list.WriteString(f)
}
list.WriteString(`">`)
list.WriteString(msg)
list.WriteString("</a> ")
} else {
list.WriteString(strconv.Itoa(page))
list.WriteString(" ")
}
}
p := s.Page
if p > 1 {
prevrev("<= Prev |", p-1, false)
} else {
p = 1
}
for i, x := p-6, 0; (i <= c.Pages && i <= p+6) && x < 12; i++ {
if i > 0 {
var onPage bool
if i == p {
onPage = true
}
prevrev(strconv.Itoa(i), i, onPage)
x++
}
}
2024-07-13 18:32:04 +00:00
if c.More {
prevrev("| Next =>", p+1, false)
}
return list.String()
}