0
Fork 0
mirror of https://codeberg.org/SafeTwitch/safetwitch-backend.git synced 2024-12-22 13:13:00 -05:00
safetwitch-backend/extractor/parser.go
2023-05-26 10:17:55 -04:00

77 lines
2.1 KiB
Go

package extractor
import (
"errors"
"safetwitch-backend/extractor/structs"
"time"
"github.com/tidwall/gjson"
)
func ParseSocials(data string) ([]structs.Social, error) {
var parsedSocials []structs.Social
result := gjson.Get(data, "user.channel.socialMedias")
for _, social := range result.Array() {
parsedSocials = append(parsedSocials, structs.Social{
Title: social.Get("title").String(),
Type: social.Get("name").String(),
Url: social.Get("url").String(),
})
}
if !result.Exists() {
return parsedSocials, errors.New("error while parsing socials, path does not exist")
}
return parsedSocials, nil
}
func ParseStream(data string) (*structs.Stream, error) {
// check if live
stream := gjson.Get(data, "1.data.user.stream")
if !stream.IsObject() {
return nil, errors.New("streamer is not live")
}
var tags []string
tagArea := gjson.Get(data, "2.data.user.stream.freeformTags").Array()
for _, tag := range tagArea {
tags = append(tags, tag.Get("name").String())
}
time, err := time.Parse(time.RFC3339, stream.Get("createdAt").String())
if err != nil {
return &structs.Stream{}, err
}
parsedStream := structs.Stream{
Title: gjson.Get(data, "1.data.user.lastBroadcast.title").String(),
Topic: stream.Get("game.name").String(),
StartedAt: time,
Tags: tags,
Viewers: int(gjson.Get(data, "4.data.user.stream.viewersCount").Int()),
Preview: ProxyUrl(gjson.Get(data, "3.data.user.stream.previewImageURL").String()),
}
return &parsedStream, nil
}
// discover
func ParseCategory(data gjson.Result) (structs.Category, error) {
tags := data.Get("node.tags").Array()
var parsedTags []string
for _, tag := range tags {
parsedTags = append(parsedTags, tag.Get("localizedName").String())
}
return structs.Category{
Name: data.Get("node.name").String(),
DisplayName: data.Get("node.displayName").String(),
Viewers: data.Get("node.viewersCount").String(),
CreatedAt: data.Get("node.originalReleaseDate").Time(),
Tags: parsedTags,
Cursor: data.Get("node.cursor").String(),
Image: ProxyUrl(data.Get("node.avatarURL").String()),
}, nil
}