package net.pokeranalytics.android.api import android.content.Context import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import net.pokeranalytics.android.util.extensions.isNetworkAvailable import okhttp3.MediaType import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Call import retrofit2.Retrofit import retrofit2.http.Multipart import retrofit2.http.POST import retrofit2.http.Part import timber.log.Timber object RetrofitClient { private const val BASE_URL = "https://www.pokeranalytics.net/backup/" fun getClient(): Retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .build() } class BackupService { private val retrofit = RetrofitClient.getClient() val backupApi: MyBackupApi = retrofit.create(MyBackupApi::class.java) } interface MyBackupApi { @Multipart @POST("send") fun postFile(@Part mail: MultipartBody.Part, @Part fileBody: MultipartBody.Part): Call } object BackupApi { val service = BackupService() // curl -F recipient=laurent@staxriver.com -F file=@test.txt https://www.pokeranalytics.net/backup/send suspend fun backupFile(context: Context, mail: String, fileName: String, fileContent: String): Boolean { val filePart = MultipartBody.Part.createFormData( "file", fileName, RequestBody.create(MediaType.parse("text/csv"), fileContent) ) val mailPart = MultipartBody.Part.createFormData("recipient", mail) return if (context.isNetworkAvailable()) { var success = false val job = CoroutineScope(context = Dispatchers.IO).async { success = try { val response = service.backupApi.postFile(mailPart, filePart).execute() Timber.d("response code = ${response.code()}") Timber.d("success = ${response.isSuccessful}") true } catch (e: Exception) { Timber.d("!!! backup failed: ${e.message}") false } } job.await() return success } else { false } } }