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 this.tags = tomap(post.tag_string.split(" "), def(k) = k, def(v) = 1) this.post = post } def isImage() { ext = this.post.file_ext return ext == "jpg" || ext == "png" } def getResolution() { w = int(this.post.image_width ?? 0) h = int(this.post.image_height ?? 0) if w == 0 || h == 0 return "" return "" + w + "x" + h } def getImageUrl() { fileSize = this.post.file_size ?? 0 if (fileSize >= 9500000) { return this.post.large_file_url } return this.post.file_url } def getSampleImageUrl() { return this.post.large_file_url } def containsTags(tags) = stream(tags) .anyMatch(def(t) = arrayKeyExists(t, this.tags)) def getScore() = int(this.post.score ?? 0) def getArtists() { return match int(this.post.tag_count_artist ?? 0) { case 0: [] case 1: [this.post.tag_string_artist] case _: this.post.tag_string_artist.split(" ") } } def getCharacters() { return match int(this.post.tag_count_character ?? 0) { case 0: [] case 1: [this.post.tag_string_character] case _: this.post.tag_string_character.split(" ") } } def getSource() { src = this.post.source if src.contains("twitter") { return src.replace("twitter", "x") } pixivId = this.post.pixiv_id ?? 0 if pixivId { return "https://www.pixiv.net/en/artworks/" + pixivId } return src } }