Skip to content

Commit

Permalink
OkHttp/Retrofit -> Ktor/Ktorfit
Browse files Browse the repository at this point in the history
  • Loading branch information
terrakok committed Feb 3, 2025
1 parent dd3299c commit 339729b
Show file tree
Hide file tree
Showing 20 changed files with 261 additions and 256 deletions.
2 changes: 1 addition & 1 deletion .idea/kotlinc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 9 additions & 3 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ plugins {
id("org.jetbrains.kotlin.plugin.serialization")
id("com.google.devtools.ksp")
alias(libs.plugins.compose.compiler)
alias(libs.plugins.ktorfit)
}


Expand Down Expand Up @@ -73,9 +74,14 @@ dependencies {

implementation(libs.volley)

implementation(libs.retrofit)
implementation(libs.retrofit.json)
implementation(libs.logging.interceptor)
implementation(libs.ktor.client.core)
implementation(libs.ktor.client.content.negotiation)
implementation(libs.ktor.client.serialization)
implementation(libs.ktor.serialization.json)
implementation(libs.ktor.client.logging)
implementation(libs.ktor.client.okhttp)
implementation(libs.ktorfit)
implementation(libs.ktorfit.call)

implementation(libs.androidx.runtime.livedata)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,18 @@ import com.daniebeler.pfpixelix.data.remote.dto.WellKnownDomainsDto
import com.daniebeler.pfpixelix.data.remote.dto.nodeinfo.FediSoftwareDto
import com.daniebeler.pfpixelix.data.remote.dto.nodeinfo.NodeInfoDto
import com.daniebeler.pfpixelix.data.remote.dto.nodeinfo.WrapperDto
import okhttp3.RequestBody
import retrofit2.Call
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.PUT
import retrofit2.http.Path
import retrofit2.http.Query
import retrofit2.http.Url
import de.jensklingenberg.ktorfit.Call
import de.jensklingenberg.ktorfit.http.Body
import de.jensklingenberg.ktorfit.http.DELETE
import de.jensklingenberg.ktorfit.http.Field
import de.jensklingenberg.ktorfit.http.FormUrlEncoded
import de.jensklingenberg.ktorfit.http.GET
import de.jensklingenberg.ktorfit.http.POST
import de.jensklingenberg.ktorfit.http.PUT
import de.jensklingenberg.ktorfit.http.Path
import de.jensklingenberg.ktorfit.http.Query
import de.jensklingenberg.ktorfit.http.Url
import io.ktor.client.request.forms.MultiPartFormDataContent

interface PixelfedApi {

Expand Down Expand Up @@ -143,7 +142,7 @@ interface PixelfedApi {

@POST("api/v1/accounts/update_credentials?_pe=1")
fun updateAccount(
@Body body: RequestBody
@Body body: MultiPartFormDataContent
): Call<AccountDto>

@GET("api/v1/accounts/{accountid}/statuses?pe=1")
Expand Down Expand Up @@ -363,7 +362,7 @@ interface PixelfedApi {

@POST("/api/v2/media")
fun uploadMedia(
@Body body: RequestBody
@Body body: MultiPartFormDataContent
): Call<MediaAttachmentDto>

@FormUrlEncoded
Expand All @@ -376,7 +375,7 @@ interface PixelfedApi {
@POST("/api/v1/statuses")
suspend fun createPost(
@Body createPostDto: CreatePostDto
): Response<PostDto>
): Call<PostDto>

@POST("/api/v1/statuses")
fun createReply(
Expand All @@ -386,7 +385,7 @@ interface PixelfedApi {
@PUT("/api/v1/statuses/{id}")
suspend fun updatePost(
@Path("id") postId: String, @Body updatePostDto: UpdatePostDto
): Response<Unit>
): Call<Unit>

@DELETE("/api/v1/statuses/{id}")
fun deletePost(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import com.daniebeler.pfpixelix.domain.model.Relationship
import com.daniebeler.pfpixelix.domain.model.Settings
import com.daniebeler.pfpixelix.domain.repository.AccountRepository
import com.daniebeler.pfpixelix.utils.NetworkCall
import com.daniebeler.pfpixelix.utils.execute
import io.ktor.client.request.forms.MultiPartFormDataContent
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import okhttp3.RequestBody
import retrofit2.awaitResponse
import javax.inject.Inject

class AccountRepositoryImpl @Inject constructor(
Expand Down Expand Up @@ -44,7 +44,7 @@ class AccountRepositoryImpl @Inject constructor(
)
}

override fun updateAccount(body: RequestBody): Flow<Resource<Account>> {
override fun updateAccount(body: MultiPartFormDataContent): Flow<Resource<Account>> {
return NetworkCall<Account, AccountDto>().makeCall(
pixelfedApi.updateAccount(
body
Expand Down Expand Up @@ -142,16 +142,12 @@ class AccountRepositoryImpl @Inject constructor(
try {
emit(Resource.Loading())
val response = if (maxId.isNotEmpty()) {
pixelfedApi.getAccountsFollowing(accountId, maxId).awaitResponse()
pixelfedApi.getAccountsFollowing(accountId, maxId).execute()
} else {
pixelfedApi.getAccountsFollowing(accountId).awaitResponse()
pixelfedApi.getAccountsFollowing(accountId).execute()
}
if (response.isSuccessful) {
val res = response.body()?.map { it.toModel() } ?: emptyList()
val res = response.map { it.toModel() }
emit(Resource.Success(res))
} else {
emit(Resource.Error("Unknown Error"))
}
} catch (exception: Exception) {
emit(Resource.Error("Unknown Error"))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import com.daniebeler.pfpixelix.domain.model.Collection
import com.daniebeler.pfpixelix.domain.model.Post
import com.daniebeler.pfpixelix.domain.repository.CollectionRepository
import com.daniebeler.pfpixelix.utils.NetworkCall
import com.daniebeler.pfpixelix.utils.execute
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import retrofit2.awaitResponse
import javax.inject.Inject

class CollectionRepositoryImpl @Inject constructor(
Expand Down Expand Up @@ -48,13 +48,8 @@ class CollectionRepositoryImpl @Inject constructor(
emit(Resource.Loading())
val response = pixelfedApi.removePostOfCollection(
collectionId, postId
).awaitResponse()
if (response.isSuccessful) {
val res = response.body()
emit(Resource.Success(res!!))
} else {
emit(Resource.Error("Unknown Error"))
}
).execute()
emit(Resource.Success(response))
} catch (exception: Exception) {
emit(Resource.Error(exception.message ?: "Unknown Error"))
}
Expand All @@ -67,13 +62,8 @@ class CollectionRepositoryImpl @Inject constructor(
emit(Resource.Loading())
val response = pixelfedApi.addPostOfCollection(
collectionId, postId
).awaitResponse()
if (response.isSuccessful) {
val res = response.body()
emit(Resource.Success(res!!))
} else {
emit(Resource.Error("Unknown Error"))
}
).execute()
emit(Resource.Success(response))
} catch (exception: Exception) {
emit(Resource.Error(exception.message ?: "Unknown Error"))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ import com.daniebeler.pfpixelix.domain.model.nodeinfo.FediSoftware
import com.daniebeler.pfpixelix.domain.model.nodeinfo.NodeInfo
import com.daniebeler.pfpixelix.domain.repository.CountryRepository
import com.daniebeler.pfpixelix.utils.NetworkCall
import com.daniebeler.pfpixelix.utils.execute
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import retrofit2.awaitResponse
import javax.inject.Inject


Expand Down Expand Up @@ -81,17 +81,13 @@ class CountryRepositoryImpl @Inject constructor(
try {
emit(Resource.Loading())
val response = if (maxNotificationId.isNotEmpty()) {
pixelfedApi.getNotifications(maxNotificationId).awaitResponse()
pixelfedApi.getNotifications(maxNotificationId).execute()
} else {
pixelfedApi.getNotifications().awaitResponse()
pixelfedApi.getNotifications().execute()
}

if (response.isSuccessful) {
val res = response.body()?.map { it.toModel() } ?: emptyList()
emit(Resource.Success(res))
} else {
emit(Resource.Error("Unknown Error"))
}
val res = response.map { it.toModel() }
emit(Resource.Success(res))
} catch (exception: Exception) {
emit(Resource.Error(exception.message ?: "Unknown Error"))
}
Expand All @@ -110,13 +106,8 @@ class CountryRepositoryImpl @Inject constructor(
override fun search(searchText: String, type: String?, limit: Int): Flow<Resource<Search>> = flow {
try {
emit(Resource.Loading())
val response = pixelfedApi.getSearch(searchText, type, limit).awaitResponse()
if (response.isSuccessful) {
val res = response.body()!!.toModel()
emit(Resource.Success(res))
} else {
emit(Resource.Error("Unknown Error"))
}
val response = pixelfedApi.getSearch(searchText, type, limit).execute().toModel()
emit(Resource.Success(response))
} catch (exception: Exception) {
emit(Resource.Error("Unknown Error"))
}
Expand Down Expand Up @@ -144,12 +135,7 @@ class CountryRepositoryImpl @Inject constructor(

override suspend fun createApplication(): Application? {
return try {
val response = pixelfedApi.createApplication().awaitResponse()
if (response.isSuccessful) {
response.body()?.toModel()
} else {
null
}
pixelfedApi.createApplication().execute().toModel()
} catch (exception: Exception) {
null
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,14 @@ import com.daniebeler.pfpixelix.data.remote.dto.ChatDto
import com.daniebeler.pfpixelix.data.remote.dto.ConversationDto
import com.daniebeler.pfpixelix.data.remote.dto.CreateMessageDto
import com.daniebeler.pfpixelix.data.remote.dto.MessageDto
import com.daniebeler.pfpixelix.data.remote.dto.TagDto
import com.daniebeler.pfpixelix.domain.model.Chat
import com.daniebeler.pfpixelix.domain.model.Conversation
import com.daniebeler.pfpixelix.domain.model.Message
import com.daniebeler.pfpixelix.domain.model.Tag
import com.daniebeler.pfpixelix.domain.repository.DirectMessagesRepository
import com.daniebeler.pfpixelix.domain.repository.HashtagRepository
import com.daniebeler.pfpixelix.utils.NetworkCall
import com.daniebeler.pfpixelix.utils.execute
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import retrofit2.awaitResponse
import javax.inject.Inject

class DirectMessagesRepositoryImpl @Inject constructor(
Expand All @@ -42,13 +39,8 @@ class DirectMessagesRepositoryImpl @Inject constructor(
override fun deleteMessage(id: String): Flow<Resource<List<Int>>> = flow {
try {
emit(Resource.Loading())
val response = pixelfedApi.deleteMessage(id).awaitResponse()
if (response.isSuccessful) {
val res = response.body()
emit(Resource.Success(res!!))
} else {
emit(Resource.Error("Unknown Error"))
}
val response = pixelfedApi.deleteMessage(id).execute()
emit(Resource.Success(response))
} catch (exception: Exception) {
emit(Resource.Error(exception.message ?: "Unknown Error"))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,20 @@ import com.daniebeler.pfpixelix.data.remote.dto.MediaAttachmentDto
import com.daniebeler.pfpixelix.data.remote.dto.PostDto
import com.daniebeler.pfpixelix.data.remote.dto.UpdatePostDto
import com.daniebeler.pfpixelix.domain.model.MediaAttachment
import com.daniebeler.pfpixelix.domain.model.MediaAttachmentConfiguration
import com.daniebeler.pfpixelix.domain.model.Post
import com.daniebeler.pfpixelix.domain.repository.PostEditorRepository
import com.daniebeler.pfpixelix.utils.GetFile
import com.daniebeler.pfpixelix.utils.MimeType
import com.daniebeler.pfpixelix.utils.NetworkCall
import com.daniebeler.pfpixelix.utils.execute
import io.ktor.client.request.forms.MultiPartFormDataContent
import io.ktor.client.request.forms.formData
import io.ktor.http.Headers
import io.ktor.http.HttpHeaders
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import retrofit2.awaitResponse
import java.io.ByteArrayOutputStream
import javax.inject.Inject

Expand All @@ -48,35 +47,31 @@ class PostEditorRepositoryImpl @Inject constructor(
//val pixelfedApi = buildPixelFedApi(true)

val fileType = MimeType.getMimeType(uri, context.contentResolver) ?: "image/*"

val inputStream = context.contentResolver.openInputStream(uri)
val fileRequestBody =
inputStream?.readBytes()?.toRequestBody(fileType.toMediaTypeOrNull())

val bytes = context.contentResolver.openInputStream(uri)?.readBytes()
val file = GetFile.getFile(uri, context) ?: return@flow

val builder: MultipartBody.Builder = MultipartBody.Builder().setType(MultipartBody.FORM)
builder.addFormDataPart("description", description)
.addFormDataPart("file", file.name, fileRequestBody!!)
val thumbnailBitmap = if (fileType.take(5) != "image" || fileType == "image/gif") {
getThumbnail(uri, context)
} else null

if (fileType.take(5) != "image" || fileType == "image/gif") {
val thumbnailBitmap = getThumbnail(uri, context)
val data = MultiPartFormDataContent(formData {
append("file", bytes!!, Headers.build {
append(HttpHeaders.ContentType, fileType)
append(HttpHeaders.ContentDisposition, file.name)
})
if (thumbnailBitmap != null) {
bitmapToBytes(thumbnailBitmap)?.let {
builder.addFormDataPart(
"thumbnail", "thumbnail", it.toRequestBody()
)
append("thumbnail", it, Headers.build {
append(HttpHeaders.ContentDisposition, "thumbnail")
})
}
}
}
})

val requestBody: RequestBody = builder.build()
val response = pixelfedApi.uploadMedia(requestBody
).awaitResponse()
if (response.isSuccessful) {
val res = response.body()!!.toModel()
try {
val res = pixelfedApi.uploadMedia(data).execute().toModel()
emit(Resource.Success(res))
} else {
} catch (e: Exception) {
emit(Resource.Error("Unknown Error"))
}
} catch (exception: Exception) {
Expand Down Expand Up @@ -113,13 +108,8 @@ class PostEditorRepositoryImpl @Inject constructor(
override fun createPost(createPostDto: CreatePostDto): Flow<Resource<Post>> = flow {
try {
emit(Resource.Loading())
val response = pixelfedApi.createPost(createPostDto)
if (response != null) {
val res = response.body()!!.toModel()
emit(Resource.Success(res))
} else {
emit(Resource.Error("Unknown Error"))
}
val res = pixelfedApi.createPost(createPostDto).execute().toModel()
emit(Resource.Success(res))
} catch (exception: Exception) {
if (exception.message != null) {
emit(Resource.Error(exception.message!!))
Expand All @@ -132,12 +122,8 @@ class PostEditorRepositoryImpl @Inject constructor(
override fun updatePost(postId: String, updatePostDto: UpdatePostDto): Flow<Resource<Post?>> = flow {
try {
emit(Resource.Loading())
val response = pixelfedApi.updatePost(postId, updatePostDto)
if (response.code() == 200) {
emit(Resource.Success(null))
} else {
emit(Resource.Error("Unknown Error"))
}
pixelfedApi.updatePost(postId, updatePostDto).execute()
emit(Resource.Success(null))
} catch (exception: Exception) {
if (exception.message != null) {
emit(Resource.Error(exception.message!!))
Expand Down
Loading

0 comments on commit 339729b

Please sign in to comment.