Skip to content

Commit

Permalink
optimized Api code
Browse files Browse the repository at this point in the history
  • Loading branch information
Yochyo committed Sep 30, 2019
1 parent d3d5aba commit 79f05d9
Show file tree
Hide file tree
Showing 9 changed files with 49 additions and 98 deletions.
Binary file modified .idea/caches/build_file_checksums.ser
Binary file not shown.
1 change: 1 addition & 0 deletions app/src/main/java/de/yochyo/yummybooru/api/Post.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ abstract class Post {
abstract val filePreviewURL: String

abstract suspend fun getTags(): List<Tag>
override fun toString() = "[$id] [${width}x$height]\n$fileURL\n$fileSampleURL\n$filePreviewURL"
}
90 changes: 23 additions & 67 deletions app/src/main/java/de/yochyo/yummybooru/api/api/Api.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import de.yochyo.yummybooru.api.entities.Server
import de.yochyo.yummybooru.api.entities.Tag
import de.yochyo.yummybooru.database.db
import de.yochyo.yummybooru.utils.Logger
import de.yochyo.yummybooru.utils.network.DownloadUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONArray
Expand All @@ -17,27 +18,27 @@ import java.net.URL
abstract class Api(var url: String) {

companion object {
const val searchTagLimit = 10

var instance: Api? = null

val apis = ArrayList<Api>()
fun addApi(api: Api) = apis.add(api)
fun initApi(name: String, url: String): Api? {

fun selectApi(name: String, url: String): Api? {
val api = apis.find { it.name.equals(name, true) }
if (api != null) api.url = url
instance = api
return api
}


const val searchTagLimit = 10
var instance: Api? = null
val name: String
get() = instance!!.name

suspend fun searchTags(beginSequence: String): List<Tag> {
suspend fun getTags(beginSequence: String): List<Tag> {
val array = ArrayList<Tag>(searchTagLimit)
val json = getJson(instance!!.urlGetTags(beginSequence))
val json = DownloadUtils.getJson(api.urlGetTags(beginSequence))
if (json != null) {
for (i in 0 until json.length()) {
val tag = instance!!.getTagFromJson(json.getJSONObject(i))
val tag = api.getTagFromJson(json.getJSONObject(i))
if (tag != null) array.add(tag)
}
}
Expand All @@ -46,85 +47,40 @@ abstract class Api(var url: String) {

suspend fun getTag(name: String): Tag {
if (name == "*") return Tag(name, Tag.SPECIAL, count = newestID())
val json = getJson(instance!!.urlGetTag(name))
val json = DownloadUtils.getJson(api.urlGetTag(name))
if (json != null && json.length() > 0) {
val tag = instance!!.getTagFromJson(json.getJSONObject(0))
val tag = api.getTagFromJson(json.getJSONObject(0))
if (tag != null) return tag
}
return Tag(name, if(Tag.isSpecialTag(name)) Tag.SPECIAL else Tag.UNKNOWN)
}

suspend fun getPosts(page: Int, tags: Array<String>, limit: Int = db.limit): List<Post> {
val array = ArrayList<Post>(limit)
var url = instance!!.urlGetPosts(page, tags, limit)

val posts = ArrayList<Post>(limit)
val urlBuilder = StringBuilder().append(api.urlGetPosts(page, tags, limit))
if (tags.isNotEmpty()) {
url += "&tags="
urlBuilder.append("&tags=")
for (tag in tags)
url += "$tag "
url = url.substring(0, url.length - 1)
urlBuilder.append("$tag ")
urlBuilder.deleteCharAt(urlBuilder.lastIndex)
}
val json = getJson(url)

val json = DownloadUtils.getJson(urlBuilder.toString())
if (json != null) {
for (i in 0 until json.length()) {
val post = instance!!.getPostFromJson(json.getJSONObject(i))
if (post != null) array += post
val post = api.getPostFromJson(json.getJSONObject(i))
if (post != null) posts += post
}
if (Server.currentServer.enableR18Filter) return array.filter { it.rating == "s" }
}
return array
return if (Server.currentServer.enableR18Filter) posts.filter { it.rating == "s" }
else posts
}

suspend fun newestID(): Int {
val json = getJson(instance!!.urlGetPosts(1, arrayOf("*"), 1))
val json = DownloadUtils.getJson(api.urlGetPosts(1, arrayOf("*"), 1))
return json?.getJSONObject(0)?.getInt("id") ?: 0
}

private suspend fun getJson(urlToRead: String): JSONArray? {
var array: JSONArray? = null
withContext(Dispatchers.IO) {
try {
val result = StringBuilder()
val url = URL(urlToRead)
val conn = url.openConnection() as HttpURLConnection
conn.addRequestProperty("User-Agent", "Mozilla/5.00")
conn.requestMethod = "GET"
val rd = BufferedReader(InputStreamReader(conn.inputStream))
var line: String? = rd.readLine()
while (line != null) {
result.append(line)
line = rd.readLine()
}
rd.close()
array = JSONArray(result.toString())
} catch (e: Exception) {
e.printStackTrace()
Logger.log(e, "URL: $urlToRead")
}
}
return array
}
}

protected suspend fun getURLSourceLines(url: String): ArrayList<String> {
return withContext(Dispatchers.IO) {
val urlObject = URL(url)
val urlConnection = urlObject.openConnection() as HttpURLConnection
urlConnection.addRequestProperty("User-Agent", "Mozilla/5.00")
val inputStream = urlConnection.inputStream
BufferedReader(InputStreamReader(inputStream, "UTF-8")).use { bufferedReader ->
var inputLine: String? = bufferedReader.readLine()
val array = ArrayList<String>()
while (inputLine != null) {
array += inputLine
inputLine = bufferedReader.readLine()
}
inputStream.close()

array
}
}
}

abstract val name: String
Expand Down
8 changes: 3 additions & 5 deletions app/src/main/java/de/yochyo/yummybooru/api/api/DanbooruApi.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package de.yochyo.yummybooru.api.api

import de.yochyo.yummybooru.api.Post
import de.yochyo.yummybooru.api.entities.Server
import de.yochyo.yummybooru.api.entities.Tag
import de.yochyo.yummybooru.utils.Logger
Expand All @@ -18,7 +19,7 @@ class DanbooruApi(url: String) : Api(url) {
return "${url}posts.json?limit=$limit&page=$page&login=${Server.currentServer.userName}&password_hash=${Server.currentServer.passwordHash}"
}

override fun getPostFromJson(json: JSONObject): de.yochyo.yummybooru.api.Post? {
override fun getPostFromJson(json: JSONObject): Post? {
try {
val tagsGeneral = json.getString("tag_string_general").split(" ").map { Tag(it, Tag.GENERAL) }.filter { it.name != "" }
val tagsCharacter = json.getString("tag_string_character").split(" ").map { Tag(it, Tag.CHARACTER) }.filter { it.name != "" }
Expand All @@ -31,7 +32,7 @@ class DanbooruApi(url: String) : Api(url) {
tags += tagsCharacter
tags += tagsGeneral
tags += tagsMeta
return object : de.yochyo.yummybooru.api.Post() {
return object :Post() {
override val id = json.getInt("id")
override val width = json.getInt("image_width")
override val height = json.getInt("image_height")
Expand All @@ -42,9 +43,6 @@ class DanbooruApi(url: String) : Api(url) {
override val fileSampleURL = json.getString("large_file_url")
override val filePreviewURL = json.getString("preview_file_url")
override suspend fun getTags() = tags
override fun toString(): String {
return "[$id] [${width}x$height]\nTags: $tags \n$fileURL\n$fileSampleURL\n$filePreviewURL"
}
}
} catch (e: Exception) {
Logger.log(e, json.toString())
Expand Down
40 changes: 18 additions & 22 deletions app/src/main/java/de/yochyo/yummybooru/api/api/MoebooruApi.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package de.yochyo.yummybooru.api.api

import de.yochyo.yummybooru.api.Post
import de.yochyo.yummybooru.api.entities.Server
import de.yochyo.yummybooru.api.entities.Tag
import de.yochyo.yummybooru.utils.Logger
import de.yochyo.yummybooru.utils.network.DownloadUtils
import org.json.JSONObject

class MoebooruApi(url: String) : Api(url) {
Expand All @@ -17,12 +19,12 @@ class MoebooruApi(url: String) : Api(url) {
return "${url}post.json?limit=$limit&page=$page&login=${Server.currentServer.userName}&password_hash=${Server.currentServer.passwordHash}"
}

override fun getPostFromJson(json: JSONObject): de.yochyo.yummybooru.api.Post? {
override fun getPostFromJson(json: JSONObject): Post? {
try {
val fileURL = json.getString("file_url")
val id = json.getInt("id")

return object : de.yochyo.yummybooru.api.Post() {
return object : Post() {
override val id = id
override val width = json.getInt("jpeg_width")
override val height = json.getInt("jpeg_height")
Expand All @@ -35,13 +37,9 @@ class MoebooruApi(url: String) : Api(url) {
private var tags: List<Tag>? = null
override suspend fun getTags(): List<Tag> {
if (tags == null)
tags = getTagsfromURL(getURLSourceLines("${Server.currentServer.url}post/show/$id"))
tags = parseTagsfromURL(DownloadUtils.getUrlLines("${Server.currentServer.url}post/show/$id"))
return tags!!
}

override fun toString(): String {
return "[$id] [${width}x$height]\nTags: $tags \n$fileURL\n$fileSampleURL\n$filePreviewURL"
}
}
} catch (e: Exception) {
e.printStackTrace()
Expand All @@ -50,7 +48,18 @@ class MoebooruApi(url: String) : Api(url) {
}
}

private fun getTagsfromURL(lines: ArrayList<String>): List<Tag> {
override fun getTagFromJson(json: JSONObject): Tag? {
return try {
val name = json.getString("name")
Tag(name, Tag.getCorrectTagType(name, json.getInt("type")), count = json.getInt("count"))
} catch (e: Exception) {
e.printStackTrace()
Logger.log(e, json.toString())
null
}
}

private fun parseTagsfromURL(lines: Collection<String>): List<Tag> {
val tags = ArrayList<Tag>()
fun getCurrentTagType(type: String): Int {
if (type.contains("tag-type-general")) return Tag.GENERAL
Expand All @@ -62,7 +71,7 @@ class MoebooruApi(url: String) : Api(url) {

fun String.startWithIgnoreSpace(start: String): Boolean {
val a = toCharArray()
for (i in 0 until a.size) {
for (i in a.indices) {
if (a[i] != ' ')
return startsWith(start, startIndex = i)
}
Expand Down Expand Up @@ -98,19 +107,6 @@ class MoebooruApi(url: String) : Api(url) {
Logger.log(e)
}
}

return tags
}

override fun getTagFromJson(json: JSONObject): Tag? {
return try {
val name = json.getString("name")
Tag(name, Tag.getCorrectTagType(name, json.getInt("type")), count = json.getInt("count"))
} catch (e: Exception) {
e.printStackTrace()
Logger.log(e, json.toString())
null
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ data class Server(var name: String, var api: String, var url: String, var userNa
if (_currentServer != null) SelectServerEvent.trigger(SelectServerEvent(context, _currentServer!!, this@Server))
db.currentServerID = id
_currentServer = this@Server
Api.initApi(api, url)
Api.selectApi(api, url)
db.loadServerWithMutex(context)
db.servers.notifyChange()
currentServer.updateMissingTypeTags(context)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import android.widget.*
import de.yochyo.yummybooru.R
import de.yochyo.yummybooru.api.api.Api
import de.yochyo.yummybooru.api.entities.Server
import de.yochyo.yummybooru.utils.ResponseCodes
import de.yochyo.yummybooru.utils.network.ResponseCodes
import de.yochyo.yummybooru.utils.parseURL
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class AddTagDialog(val runOnPositive: (editText: AutoCompleteTextView) -> Unit)
GlobalScope.launch {
val lastIndexOf = string.lastIndexOf(" ")
val a = if (lastIndexOf != -1) string.substring(0..lastIndexOf) else ""
val tags = Api.searchTags(name).map { it.copy(name = a + it.name) } //damit der filter funktioniert
val tags = Api.getTags(name).map { it.copy(name = a + it.name) } //damit der filter funktioniert
launch(Dispatchers.Main) {
if (!dialogIsDismissed) {
arrayAdapter.apply { clear(); addAll(tags); notifyDataSetChanged() }
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package de.yochyo.yummybooru.utils
package de.yochyo.yummybooru.utils.network

object ResponseCodes {
const val OK = 200
Expand Down

0 comments on commit 79f05d9

Please sign in to comment.