use persistent cookiejar

hauntED
yova 7 months ago
parent 4884967244
commit b759ce94f3

@ -63,6 +63,7 @@ dependencies {
implementation 'androidx.webkit:webkit:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.github.franmontiel:PersistentCookieJar:v1.0.1'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'

@ -5,7 +5,6 @@ import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.net.Uri.parse
import android.os.Bundle
@ -41,6 +40,7 @@ import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import kotlin.reflect.typeOf
class MainActivity : ComponentActivity() {
@ -50,12 +50,13 @@ class MainActivity : ComponentActivity() {
const val CONTEXT_MENU_CUT = 456
var mdeValue : String = ""
var mdToAppend : String = ""
lateinit var thisFileUri : Uri
var thisFileUri : Uri? = null
lateinit var tempFile: File
var emptyFile = false
lateinit var credentials : Credentials
lateinit var pickMultipleVisualMedia: ActivityResultLauncher<PickVisualMediaRequest>
lateinit var webView:WebView
lateinit var api:ghostAPI
}
override fun onCreate(savedInstanceState: Bundle?) {
@ -94,7 +95,7 @@ class MainActivity : ComponentActivity() {
}
@JavascriptInterface
fun triggerOpenFile() {
openFile(thisFileUri)
openFile(thisFileUri!!)
}
@JavascriptInterface
fun triggerSaveFile(value:String) {
@ -111,7 +112,7 @@ class MainActivity : ComponentActivity() {
}
@JavascriptInterface
fun refresh() {
readFile(thisFileUri)
readFile(thisFileUri!!)
}
@JavascriptInterface
fun triggerDisplayName() : String {
@ -242,7 +243,7 @@ class MainActivity : ComponentActivity() {
}
fun pushImageFile(credentials:Credentials, file: File): retrofit2.Response<Any> {
val response = ghostAPI.postApi.pushImage(
val response = api.postApi.pushMyImage(
MultipartBody.Part.createFormData(
"file",
file.name,
@ -274,7 +275,7 @@ class MainActivity : ComponentActivity() {
)
try {
response = ghostAPI.postApi.pushPost(postings).execute()
response = api.postApi.pushPost(postings).execute()
} catch (ex: Exception) {
Log.d(javaClass.simpleName, "Couldn't send posting in. Exception: ${ex}")
}
@ -318,11 +319,12 @@ class MainActivity : ComponentActivity() {
)
finishAffinity()
}
api = ghostAPI(applicationContext)
CoroutineScope(Dispatchers.Main).launch {
withContext(Dispatchers.IO) {
var result =""
try {
result = ghostAPI.register(credentials)
result = api.register(credentials)
} catch (e: ExceptionInInitializerError) {
this@MainActivity.runOnUiThread(Runnable() {
Toast.makeText(
@ -526,10 +528,11 @@ class MainActivity : ComponentActivity() {
@SuppressLint("Range")
fun getDisplayName() : String {
// via: https://stackoverflow.com/questions/5568874/how-to-extract-the-file-name-from-uri-returned-from-intent-action-get-content
var result: String? = null;
if (thisFileUri.getScheme().equals("content")) {
val cursor = getContentResolver().query(thisFileUri, null, null, null, null);
if (thisFileUri == null) return "hauntED.md"
if (thisFileUri!!.getScheme().equals("content")) {
val cursor = getContentResolver().query(thisFileUri!!, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
@ -539,7 +542,7 @@ class MainActivity : ComponentActivity() {
}
}
if (result == null) {
result = thisFileUri.getPath();
result = thisFileUri!!.getPath();
val cut = result!!.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
@ -613,7 +616,7 @@ class MainActivity : ComponentActivity() {
lateinit var textFile: ParcelFileDescriptor
try {
textFile = contentResolver.openFileDescriptor(thisFileUri, "w")!!
textFile = contentResolver.openFileDescriptor(thisFileUri!!, "w")!!
textFile.checkError()
} catch (e: Exception) {
Log.d(javaClass.simpleName,"Problem with accessing file\n${e.stackTraceToString()}")
@ -630,7 +633,7 @@ class MainActivity : ComponentActivity() {
return false
}
try {
contentResolver.openFileDescriptor(thisFileUri, "wt")?.use {
contentResolver.openFileDescriptor(thisFileUri!!, "wt")?.use {
FileOutputStream(it.fileDescriptor).use {
it.write(mdeValue.toByteArray())
}
@ -653,7 +656,7 @@ class MainActivity : ComponentActivity() {
private fun saveAs(): Boolean {
lateinit var textFile: ParcelFileDescriptor
try {
textFile = contentResolver.openFileDescriptor(thisFileUri, "w")!!
textFile = contentResolver.openFileDescriptor(thisFileUri!!, "w")!!
textFile.checkError()
} catch (e: Exception) {
Toast.makeText(this,

@ -1,6 +1,11 @@
package org.wntr.mdeditor
import android.content.Context
import android.util.Log
import com.franmontiel.persistentcookiejar.ClearableCookieJar
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
@ -15,111 +20,109 @@ import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.Part
class ghostAPI() {
companion object {
object RetrofitClient {
private val BASE_URL = credentials.instance + "/ghost/api/admin/"
fun getClient(applicationContext: Context): Retrofit {
/* Detailed logging
val loggingInterceptor = HttpLoggingInterceptor().apply {
this.setLevel(HttpLoggingInterceptor.Level.BASIC)
}*/
Log.i(javaClass.simpleName, "Retrofitclient baseurl: $BASE_URL")
val cookieJar: ClearableCookieJar =
PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(applicationContext))
val okHttpClient = OkHttpClient()
.newBuilder()
/*
.addInterceptor(RequestInterceptor)
*/
/*
.addInterceptor(loggingInterceptor)
*/
.cookieJar(cookieJar)
.build()
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl(BASE_URL)
.addConverterFactory(JacksonConverterFactory.create())
.build()
private val retrofit = RetrofitClient.getClient()
val postApi = retrofit.create(PostApi::class.java)
}
}
fun register(credentials: Credentials): String {
return try {
val response = postApi.getCookie(credentials).execute()
if (!response.isSuccessful) {
Log.d(javaClass.simpleName, "Response code ${response.code()}")
when (response.code()) {
404 -> {
return "404"
}
class ghostAPI(applicationContext: Context) {
val retrofit = RetrofitClient.getClient(applicationContext)
val postApi = retrofit.create(PostApi::class.java)
fun register(credentials: Credentials): String {
return try {
val response = postApi.getCookie(credentials).execute()
if (!response.isSuccessful) {
Log.d(javaClass.simpleName, "Response code ${response.code()}")
when (response.code()) {
404 -> {
return "404"
}
429 -> {
Log.d(javaClass.simpleName, "Too many failures")
return "TOO_MANY_FAILURES"
}
429 -> {
Log.d(javaClass.simpleName, "Too many failures")
return "TOO_MANY_FAILURES"
}
else -> {
val errors = JSONObject(response.errorBody()!!.string())
val code =
errors.getJSONArray("errors").getJSONObject(0).getString("code")
Log.d(javaClass.simpleName, "Error code $code")
if (code.equals("PASSWORD_INCORRECT")) {
Log.d(javaClass.simpleName, "Password incorrect")
}
if (code !== null) return code
else return response.code().toString()
else -> {
val errors = JSONObject(response.errorBody()!!.string())
val code =
errors.getJSONArray("errors").getJSONObject(0).getString("code")
Log.d(javaClass.simpleName, "Error code $code")
if (code.equals("PASSWORD_INCORRECT")) {
Log.d(javaClass.simpleName, "Password incorrect")
}
if (code !== null) return code
else return response.code().toString()
}
}
return "SUCCESS"
} catch (ex: Exception) {
Log.d(javaClass.simpleName, "Couldn't log in. Exception: ${ex}")
return "EXCEPTION"
}
return "SUCCESS"
} catch (ex: Exception) {
Log.d(javaClass.simpleName, "Couldn't log in. Exception: ${ex}")
return "EXCEPTION"
}
}
/* Detailed logging
/* object RequestInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val newRequest = request.newBuilder()
*//*.header("Authorization", "Ghost "+ API_KEY)*//*
object RequestInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val newRequest = request.newBuilder()
*//*.header("Authorization", "Ghost "+ API_KEY)*//*
.header("Origin", "https://mary.joefix.it")
.build()
Log.i(javaClass.simpleName, "Outgoing request to ${newRequest.url}")
//Log.i(javaClass.simpleName, newRequest.body.toString())
//Log.i(javaClass.simpleName, newRequest.body.toString())
return chain.proceed(newRequest)
}
}*/
object RetrofitClient {
private val BASE_URL = credentials.instance + "/ghost/api/admin/"
//"https://mary.joefix.it/ghost/api/admin/"
fun getClient(): Retrofit {
/*val loggingInterceptor = HttpLoggingInterceptor().apply {
this.setLevel(HttpLoggingInterceptor.Level.BASIC)
}*/
Log.i(javaClass.simpleName, "Retrofitclient baseurl: $BASE_URL")
val okHttpClient = OkHttpClient()
.newBuilder()
/*
.addInterceptor(RequestInterceptor)
*/
/*
.addInterceptor(loggingInterceptor)
*/
.cookieJar(MyCookieJar())
.build()
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl(BASE_URL)
.addConverterFactory(JacksonConverterFactory.create())
.build()
}
}
}
*/
}
interface PostApi {
@GET("posts")
fun getPosts(): Call<posts>
/* fun getPosts(): Call<ResponseBody> <- for json string*/
interface PostApi {
@GET("posts")
fun getPosts(): Call<posts>
/* fun getPosts(): Call<ResponseBody> <- for json string*/
@POST("session")
fun getCookie(@Body credentials: Credentials): Call<ResponseBody>
@POST("session")
fun getCookie(@Body credentials: Credentials): Call<ResponseBody>
@POST("posts/?source=html")
fun pushPost(@Body postings: sendPostList): Call<posts>
@POST("posts/?source=html")
fun pushPost(@Body postings: sendPostList): Call<posts>
@Multipart
@POST("images/upload")
fun pushImage(@Part file: MultipartBody.Part): Call<imagesObj>
}
}
@Multipart
@POST("images/upload")
fun pushMyImage(@Part file: MultipartBody.Part): Call<imagesObj>
}

@ -1,21 +0,0 @@
package org.wntr.mdeditor
import android.util.Log
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
class MyCookieJar : CookieJar {
companion object {
var myCookies: List<Cookie>? = null
}
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
Log.i(javaClass.simpleName,"getting cookies: " +cookies.toString())
myCookies = cookies
}
override fun loadForRequest(url: HttpUrl): List<Cookie> {
Log.i(javaClass.simpleName,"giving cookies: " + myCookies.toString())
return myCookies ?: ArrayList()
}
}

@ -10,6 +10,7 @@ dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven { url 'https://jitpack.io' }
}
}
rootProject.name = "MDEditor"

Loading…
Cancel
Save