trim down JSON parsing

hauntED
yova 3 months ago
parent 821ad615ee
commit 36b9d7bd0b

@ -40,6 +40,7 @@ import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import org.json.JSONObject
import org.wntr.mdeditor.databinding.ActivityMainBinding
import retrofit2.Response
import java.io.BufferedReader
import java.io.File
import java.io.FileOutputStream
@ -478,6 +479,13 @@ class MainActivity : AppCompatActivity() {
Log.d(javaClass.simpleName, "result: ${response.code()}")
}
if (response.isSuccessful) {
this@MainActivity.runOnUiThread({
Toast.makeText(
this@MainActivity,
"Post under ${metaData.metaData.get("url")} got deleted.",
Toast.LENGTH_LONG
).show()
})
Log.d(javaClass.simpleName, "Post under ${metaData.metaData.get("url")} got deleted.")
metaData.metaData.minusAssign("url")
metaData.ID=null
@ -585,76 +593,80 @@ class MainActivity : AppCompatActivity() {
val post = sendPost(title, updated_at = metaData.updatedAt!!, authors = listOf(author), html, feature_image = metaData.get("feature_image"))
val postings = sendPostList(listOf(post))
var response: retrofit2.Response<posts> = retrofit2.Response.error(
444,
"error".toResponseBody("text/plain".toMediaTypeOrNull())
)
try {
response = api.postApi.updatePost(id, postings).execute()
} catch (ex: Exception) {
Log.d(javaClass.simpleName, "Couldn't update posting. Exception: ${ex}")
}
val response = api.postApi.updatePost(id, postings).execute()
if (response.isSuccessful) {
Log.d(javaClass.simpleName, "Updated: ${response.body()!!.posts[0].url}")
metaData.updatedAt= response.body()!!.posts[0].updated_at
val intent = Intent(Intent.ACTION_VIEW).setData(parse(metaData.metaData.get("url")))
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
if (response.isSuccessful) {
val resp = JSONObject(response.body()!!.string())
metaData.updatedAt= resp.getJSONArray("posts").getJSONObject(0).getString("updated_at")
val intent = Intent(Intent.ACTION_VIEW).setData(parse(metaData.metaData.get("url")))
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
this.runOnUiThread({
Toast.makeText(this, "No eligble app installed.", Toast.LENGTH_LONG).show()
Log.i(javaClass.simpleName, e.toString())
})
}
Log.d(javaClass.simpleName, "Updated: ${resp.getJSONArray("posts").getJSONObject(0).getString("url")}")
} else {
this.runOnUiThread({
Toast.makeText(this, "No eligble app installed.", Toast.LENGTH_LONG).show()
Log.i(javaClass.simpleName, e.toString())
Toast.makeText(
this,
"error while updating post.\n${response.errorBody()}",
Toast.LENGTH_LONG
).show()
})
Log.i(javaClass.simpleName, response.code().toString())
}
} else {
this.runOnUiThread({
Toast.makeText(
this,
"error while updating post.\n${response.errorBody()}",
Toast.LENGTH_LONG
).show()
})
Log.i(javaClass.simpleName, response.code().toString())
return response as retrofit2.Response<Any>
} catch (ex: Exception) {
Log.d(javaClass.simpleName, "Couldn't update posting. Exception: ${ex}")
return retrofit2.Response.error(
444,
"error".toResponseBody("text/plain".toMediaTypeOrNull())
)
}
return response as retrofit2.Response<Any>
}
fun sendPosting(html: String, author: String): retrofit2.Response<Any> {
val title = metaData.get("title") ?: "test"
val post = sendPost(title, updated_at = Instant.now().toString(), authors = listOf(author), html, feature_image = metaData.get("feature_image"))
val postings = sendPostList(listOf(post))
var response: retrofit2.Response<posts> = retrofit2.Response.error(
444,
"error".toResponseBody("text/plain".toMediaTypeOrNull())
)
try {
response = api.postApi.pushPost(postings).execute()
} catch (ex: Exception) {
Log.d(javaClass.simpleName, "Couldn't send posting. Exception: ${ex}")
}
Log.d(javaClass.simpleName, "result: ${response.body()}")
if (response.isSuccessful) {
val post = response.body()!!.posts[0]
val uri = parse(post.url)
metaData.ID = post.id
metaData.updatedAt = post.updated_at
Log.d(javaClass.simpleName, "Uploaded to: $uri\nID: ${metaData.ID}")
metaData.put("url", uri.toString())
val response = api.postApi.pushPost(postings).execute()
Log.d(javaClass.simpleName, "result: ${response.code()}")
if (response.isSuccessful) {
val resp = JSONObject(response.body()!!.string())
val post = resp.getJSONArray("posts").getJSONObject(0)
val uri = parse(post.getString("url"))
metaData.ID = post.getString("id")
metaData.updatedAt = post.getString("updated_at")
Log.d(javaClass.simpleName, "Uploaded to: $uri\nID: ${metaData.ID}")
metaData.put("url", post.getString("url"))
saveFile()
val intent = Intent(Intent.ACTION_VIEW).setData(uri)
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this, "No eligble app installed.", Toast.LENGTH_LONG).show()
Log.i(javaClass.simpleName, e.toString())
saveFile()
val intent = Intent(Intent.ACTION_VIEW).setData(uri)
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this, "No eligble app installed.", Toast.LENGTH_LONG).show()
Log.i(javaClass.simpleName, e.toString())
}
} else if (response.code()==403){
this.runOnUiThread({
Toast.makeText(this, "You are not authorized to add posts", Toast.LENGTH_LONG).show()
})
}
return response as Response<Any>
} catch (ex: Exception) {
Log.d(javaClass.simpleName, "Couldn't send posting. Exception: ${ex}")
return retrofit2.Response.error(
444,
"error".toResponseBody("text/plain".toMediaTypeOrNull())
)
}
return response as retrofit2.Response<Any>
}
fun sendPost(username: String, text: String): retrofit2.Response<Any> {

@ -35,6 +35,7 @@ object RetrofitClient {
}
val cookieJar: ClearableCookieJar =
PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(applicationContext))
val okHttpClient = OkHttpClient()
.newBuilder()
/*
@ -122,7 +123,7 @@ class ghostAPI(applicationContext: Context, instance: String) {
interface PostApi {
@GET("posts")
fun getPosts(): Call<posts>
fun getPosts(): Call<ResponseBody>
/* fun getPosts(): Call<ResponseBody> <- for json string*/
@DELETE("posts/{id}")
@ -132,10 +133,10 @@ interface PostApi {
fun getCookie(@Body credentials: Credentials): Call<ResponseBody>
@POST("posts/?source=html")
fun pushPost(@Body postings: sendPostList): Call<posts>
fun pushPost(@Body postings: sendPostList): Call<ResponseBody>
@PUT("posts/{id}?source=html")
fun updatePost(@Path("id") id: String, @Body postings:sendPostList): Call<posts>
fun updatePost(@Path("id") id: String, @Body postings:sendPostList): Call<ResponseBody>
@Multipart
@POST("images/upload")

@ -5,7 +5,9 @@ import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.module.kotlin.KotlinModule
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import org.json.JSONObject
class mdMeta {
var metaData = mutableMapOf<String,String>()
@ -59,35 +61,38 @@ class mdMeta {
if (ID !== null)
return ID as String
if (metaData.get("url") == "") return null
var response: retrofit2.Response<posts> = retrofit2.Response.error(
444,
"error".toResponseBody("text/plain".toMediaTypeOrNull())
)
try {
response = MainActivity.api.postApi.getPosts().execute()
}
catch(e: Exception) {
Log.d(javaClass.simpleName, "Couldn't get post list: $e")
}
val response = MainActivity.api.postApi.getPosts().execute()
Log.d(javaClass.simpleName, "result: ${response.code()}")
if (response.isSuccessful) {
val remoteDoc = response.body()!!.posts.find { it.url == metaData.get("url")}
Log.d(javaClass.simpleName, "result: ${response.code()}")
if (response.isSuccessful) {
val resp = JSONObject(response.body()!!.string())
val posts = resp.getJSONArray("posts")
var remoteDoc : JSONObject? = null
if (remoteDoc == null ){
Log.d(javaClass.simpleName, "Could not find post ID ${metaData.get("url")}. Already deleted?")
metaData.put("url", "")
ID = null
for (i in 0 until posts.length()) {
remoteDoc = posts.getJSONObject(i)
if (remoteDoc.getString("url") == metaData.get("url")) break
}
if (remoteDoc == null ){
Log.d(javaClass.simpleName, "Could not find post ID ${metaData.get("url")}. Already deleted?")
metaData.put("url", "")
ID = null
return ID
}
ID = remoteDoc.getString("id")
updatedAt = remoteDoc.getString("updated_at")
Log.d(javaClass.simpleName, "Document is online at ${
metaData.get("url")}\nID: ${ID}")
return ID
} else {
return null
}
ID = remoteDoc.id
updatedAt = remoteDoc.updated_at
Log.d(javaClass.simpleName, "Document is online at ${
metaData.get("url")}\nID: ${ID}")
return ID
} else {
} catch(e: Exception) {
Log.d(javaClass.simpleName, "Couldn't get post list: $e")
return null
}
}
}

@ -21,209 +21,6 @@ data class sendPostList (
@JsonProperty("posts") val posts: List<sendPost>
)
data class posts(
@JsonProperty("meta") val meta: Meta?,
@JsonProperty("posts") val posts: List<PostX>
)
data class Author(
@JsonProperty("accessibility") val accessibility: String?,
@JsonProperty("bio") val bio: String?,
@JsonProperty("comment_notifications") val comment_notifications: Boolean?,
@JsonProperty("cover_image") val cover_image: String?,
@JsonProperty("created_at") val created_at: String?,
@JsonProperty("donation_notifications") val donation_notifications: Boolean?,
@JsonProperty("email") val email: String?,
@JsonProperty("facebook") val facebook: String?,
@JsonProperty("free_member_signup_notification") val free_member_signup_notification: Boolean?,
@JsonProperty("id") val id: String,
@JsonProperty("last_seen") val last_seen: String?,
@JsonProperty("location") val location: String?,
@JsonProperty("mention_notifications") val mention_notifications: Boolean?,
@JsonProperty("meta_description") val meta_description: String?,
@JsonProperty("meta_title") val meta_title: String?,
@JsonProperty("milestone_notifications") val milestone_notifications: Boolean?,
@JsonProperty("name") val name: String?,
@JsonProperty("paid_subscription_canceled_notification") val paid_subscription_canceled_notification: Boolean?,
@JsonProperty("paid_subscription_started_notification") val paid_subscription_started_notification: Boolean?,
@JsonProperty("profile_image") val profile_image: String?,
@JsonProperty("recommendation_notifications") val recommendation_notifications: Boolean?,
@JsonProperty("roles") val roles: List<Role>?,
@JsonProperty("slug") val slug: String?,
@JsonProperty("status") val status: String?,
@JsonProperty("tour") val tour: String?,
@JsonProperty("twitter") val twitter: String?,
@JsonProperty("updated_at") val updated_at: String?,
@JsonProperty("url") val url: String?,
@JsonProperty("website") val website: String?
)
data class Count(
@JsonProperty("clicks") val clicks: Int,
@JsonProperty("negative_feedback") val negative_feedback: Int,
@JsonProperty("positive_feedback") val positive_feedback: Int
)
data class Meta(
@JsonProperty("pagination") val pagination: Pagination
)
data class Pagination(
@JsonProperty("limit") val limit: Int,
@JsonProperty("next") val next: String?,
@JsonProperty("page") val page: Int,
@JsonProperty("pages") val pages: Int,
@JsonProperty("prev") val prev: String?,
@JsonProperty("total") val total: Int
)
data class PostX(
@JsonProperty("authors") val authors: List<Author>,
@JsonProperty("canonical_url") val canonical_url: String?,
@JsonProperty("codeinjection_foot") val codeinjection_foot: String?,
@JsonProperty("codeinjection_head") val codeinjection_head: String?,
@JsonProperty("comment_id") val comment_id: String?,
@JsonProperty("count") val count: Count,
@JsonProperty("created_at") val created_at: String?,
@JsonProperty("custom_excerpt") val custom_excerpt: String?,
@JsonProperty("custom_template") val custom_template: String?,
@JsonProperty("email") val email: String?,
@JsonProperty("email_only") val email_only: Boolean,
@JsonProperty("email_segment") val email_segment: String?,
@JsonProperty("email_subject") val email_subject: String?,
@JsonProperty("excerpt") val excerpt: String?,
@JsonProperty("feature_image") val feature_image: String?,
@JsonProperty("feature_image_alt") val feature_image_alt: String?,
@JsonProperty("feature_image_caption") val feature_image_caption: String?,
@JsonProperty("featured") val featured: Boolean,
@JsonProperty("frontmatter") val frontmatter: String?,
@JsonProperty("id") val id: String,
@JsonProperty("meta_description") val meta_description: String?,
@JsonProperty("meta_title") val meta_title: String?,
@JsonProperty("mobiledoc") val mobiledoc: String?,
@JsonProperty("newsletter") val newsletter: String?,
@JsonProperty("og_description") val og_description: String?,
@JsonProperty("og_image") val og_image: String?,
@JsonProperty("og_title") val og_title: String?,
@JsonProperty("post_revisions") val post_revisions: List<Any>,
@JsonProperty("primary_author") val primary_author: PrimaryAuthor,
@JsonProperty("primary_tag") val primary_tag: Tag?,
@JsonProperty("published_at") val published_at: String?,
@JsonProperty("reading_time") val reading_time: Int,
@JsonProperty("slug") val slug: String?,
@JsonProperty("status") val status: String?,
@JsonProperty("tags") val tags: List<Tag>,
@JsonProperty("tiers") val tiers: List<Tier>,
@JsonProperty("title") val title: String?,
@JsonProperty("twitter_description") val twitter_description: String?,
@JsonProperty("twitter_image") val twitter_image: String?,
@JsonProperty("twitter_title") val twitter_title: String?,
@JsonProperty("updated_at") val updated_at: String?,
@JsonProperty("url") val url: String?,
@JsonProperty("uuid") val uuid: String?,
@JsonProperty("visibility") val visibility: String?
)
data class PrimaryAuthor(
@JsonProperty("accessibility") val accessibility: String?,
@JsonProperty("bio") val bio: String?,
@JsonProperty("comment_notifications") val comment_notifications: Boolean,
@JsonProperty("cover_image") val cover_image: String?,
@JsonProperty("created_at") val created_at: String?,
@JsonProperty("donation_notifications") val donation_notifications: Boolean,
@JsonProperty("email") val email: String?,
@JsonProperty("facebook") val facebook: String?,
@JsonProperty("free_member_signup_notification") val free_member_signup_notification: Boolean,
@JsonProperty("id") val id: String?,
@JsonProperty("last_seen") val last_seen: String?,
@JsonProperty("location") val location: String?,
@JsonProperty("mention_notifications") val mention_notifications: Boolean,
@JsonProperty("meta_description") val meta_description: String?,
@JsonProperty("meta_title") val meta_title: String?,
@JsonProperty("milestone_notifications") val milestone_notifications: Boolean,
@JsonProperty("name") val name: String?,
@JsonProperty("paid_subscription_canceled_notification") val paid_subscription_canceled_notification: Boolean,
@JsonProperty("paid_subscription_started_notification") val paid_subscription_started_notification: Boolean,
@JsonProperty("profile_image") val profile_image: String?,
@JsonProperty("recommendation_notifications") val recommendation_notifications: Boolean,
@JsonProperty("roles") val roles: List<Role>,
@JsonProperty("slug") val slug: String?,
@JsonProperty("status") val status: String?,
@JsonProperty("tour") val tour: String?,
@JsonProperty("twitter") val twitter: String?,
@JsonProperty("updated_at") val updated_at: String?,
@JsonProperty("url") val url: String?,
@JsonProperty("website") val website: String?
)
data class Role(
@JsonProperty("created_at") val created_at: String?,
@JsonProperty("description") val description: String?,
@JsonProperty("id") val id: String,
@JsonProperty("name") val name: String?,
@JsonProperty("updated_at") val updated_at: String?
)
data class Tag(
@JsonProperty("accent_color") val accent_color: String?,
@JsonProperty("canonical_url") val canonical_url: String?,
@JsonProperty("codeinjection_foot") val codeinjection_foot: String?,
@JsonProperty("codeinjection_head") val codeinjection_head: String?,
@JsonProperty("created_at") val created_at: String?,
@JsonProperty("description") val description: String?,
@JsonProperty("feature_image") val feature_image: String?,
@JsonProperty("id") val id: String,
@JsonProperty("meta_description") val meta_description: String?,
@JsonProperty("meta_title") val meta_title: String?,
@JsonProperty("name") val name: String?,
@JsonProperty("og_description") val og_description: String?,
@JsonProperty("og_image") val og_image: String?,
@JsonProperty("og_title") val og_title: String?,
@JsonProperty("slug") val slug: String?,
@JsonProperty("twitter_description") val twitter_description: String?,
@JsonProperty("twitter_image") val twitter_image: String?,
@JsonProperty("twitter_title") val twitter_title: String?,
@JsonProperty("updated_at") val updated_at: String?,
@JsonProperty("url") val url: String?,
@JsonProperty("visibility") val visibility: String?
)
data class Tier(
@JsonProperty("active") val active: Boolean,
@JsonProperty("created_at") val created_at: String?,
@JsonProperty("currency") val currency: String?,
@JsonProperty("description") val description: String?,
@JsonProperty("id") val id: String,
@JsonProperty("monthly_price") val monthly_price: Int,
@JsonProperty("monthly_price_id") val monthly_price_id: String?,
@JsonProperty("name") val name: String?,
@JsonProperty("slug") val slug: String?,
@JsonProperty("trial_days") val trial_days: Int,
@JsonProperty("type") val type: String?,
@JsonProperty("updated_at") val updated_at: String?,
@JsonProperty("visibility") val visibility: String?,
@JsonProperty("welcome_page_url") val welcome_page_url: String?,
@JsonProperty("yearly_price") val yearly_price: Int,
@JsonProperty("yearly_price_id") val yearly_price_id: String?
)
data class Errors(
@JsonProperty("errors") val errors: List<Error>
)
data class Error(
@JsonProperty("code") val code: String,
@JsonProperty("context") val context: String,
@JsonProperty("details") val details: Any,
@JsonProperty("ghostErrorCode")val ghostErrorCode: Any,
@JsonProperty("help") val help: String,
@JsonProperty("id") val id: String,
@JsonProperty("message") val message: String,
@JsonProperty("property") val property: Any,
@JsonProperty("type") val type: String
)
data class imagesObj(
@JsonProperty("images") val images: List<imageObj>
)

Loading…
Cancel
Save