danboo/DanbooruApi.own

91 lines
2.0 KiB
Scala
Raw Normal View History

2024-08-10 19:12:42 +03:00
use okhttp, types, json, functional
class DanbooruApi {
def DanbooruApi(auth) {
this.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:129.0) Gecko/20100101 Firefox/129.0"
}
if auth != "" {
this.headers["Authorization"] = auth
}
}
def getPosts(params) {
url = "https://danbooru.donmai.us/posts.json" + params
response = okhttp.request()
.headers(this.headers)
.url(url)
.get()
.newCall(okhttp.client)
.execute()
.body()
.string()
if (!length(response)) return []
posts = jsondecode(response)
if (typeof(posts) != ARRAY) return []
return map(posts, def(p) = new Post(p))
}
}
class Post {
def Post(post) {
this.id = int(post.id) ?? 0
post.tags = tomap(post.tag_string.split(" "), def(k) = k, def(v) = 1)
this.post = post
}
def isImage(post) {
ext = post.file_ext
return ext == "jpg" || ext == "png"
}
def getResolution(post) {
w = int(post.image_width ?? 0)
h = int(post.image_height ?? 0)
if w == 0 || h == 0 return ""
return "" + w + "x" + h
}
def getImageUrl(post) {
fileSize = post.file_size ?? 0
if (fileSize >= 9500000) {
return post.large_file_url
}
return post.file_url
}
def getSampleImageUrl(post) {
return post.large_file_url
}
def getScore(post) = int(post.score ?? 0)
def getArtists(post) {
return match int(post.tag_count_artist ?? 0) {
case 0: []
case 1: [post.tag_string_artist]
case _: post.tag_string_artist.split(" ")
}
}
def getCharacters(post) {
return match int(post.tag_count_character ?? 0) {
case 0: []
case 1: [post.tag_string_character]
case _: post.tag_string_character.split(" ")
}
}
def getSource(post) {
src = post.source
if src.contains("twitter") {
return src.replace("twitter", "x")
}
pixivId = post.pixiv_id ?? 0
if pixivId {
return "https://www.pixiv.net/en/artworks/" + pixivId
}
return src
}
}