66 lines
2.5 KiB
Kotlin
66 lines
2.5 KiB
Kotlin
package profiles.data.repository
|
|
|
|
import android.content.Context
|
|
import android.net.Uri
|
|
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
|
import okhttp3.MultipartBody
|
|
import okhttp3.RequestBody.Companion.asRequestBody
|
|
import profiles.data.remote.api.ProfileApi
|
|
import profiles.data.remote.dto.ProfileDto
|
|
import profiles.data.remote.dto.UpdateProfileRequest
|
|
import profiles.domain.repository.ProfileRepository
|
|
import java.io.File
|
|
import java.io.FileOutputStream
|
|
import javax.inject.Inject
|
|
|
|
class ProfileRepositoryImpl @Inject constructor(
|
|
private val api: ProfileApi,
|
|
private val context: Context,
|
|
private val serverConfig: core.network.ServerConfig
|
|
) : ProfileRepository {
|
|
|
|
private fun ProfileDto.fixAvatarUrl(): ProfileDto {
|
|
if (avatarUrl == null || avatarUrl.startsWith("http")) return this
|
|
val baseUrl = serverConfig.getBaseUrl().removeSuffix("/api/")
|
|
return copy(avatarUrl = baseUrl + avatarUrl)
|
|
}
|
|
|
|
override suspend fun getProfile(id: String): Result<ProfileDto> = runCatching {
|
|
api.getProfile(id).fixAvatarUrl()
|
|
}
|
|
|
|
override suspend fun getMyProfile(): Result<ProfileDto> = runCatching {
|
|
// Сначала получаем ID пользователя из /auth/me
|
|
val me = api.getMyProfile()
|
|
// Затем загружаем полный профиль из /profiles/{id}
|
|
api.getProfile(me.id).fixAvatarUrl()
|
|
}
|
|
|
|
override suspend fun updateProfile(displayName: String?, bio: String?, birthday: String?): Result<ProfileDto> = runCatching {
|
|
api.updateProfile(UpdateProfileRequest(displayName, bio, birthday)).fixAvatarUrl()
|
|
}
|
|
|
|
override suspend fun uploadAvatar(uri: Uri): Result<ProfileDto> = runCatching {
|
|
val file = uriToFile(uri)
|
|
val requestFile = file.asRequestBody("image/jpeg".toMediaTypeOrNull())
|
|
val body = MultipartBody.Part.createFormData("avatar", file.name, requestFile)
|
|
api.uploadAvatar(body).fixAvatarUrl()
|
|
}
|
|
|
|
override suspend fun removeAvatar(): Result<ProfileDto> = runCatching {
|
|
api.removeAvatar().fixAvatarUrl()
|
|
}
|
|
|
|
private fun uriToFile(uri: Uri): File {
|
|
val inputStream = context.contentResolver.openInputStream(uri)
|
|
val file = File(context.cacheDir, "temp_avatar_${System.currentTimeMillis()}.jpg")
|
|
val outputStream = FileOutputStream(file)
|
|
inputStream?.use { input ->
|
|
outputStream.use { output ->
|
|
input.copyTo(output)
|
|
}
|
|
}
|
|
return file
|
|
}
|
|
}
|