-
-
Notifications
You must be signed in to change notification settings - Fork 25
feat: Add recipe image upload and camera capture support #190
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
20d6f08
fa5b036
c32f7e0
17f20e0
07dc8c6
cb64d4a
800d139
4871481
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,25 +4,37 @@ import coil3.ImageLoader | |
| import coil3.memory.MemoryCache | ||
| import com.haroldadmin.cnradapter.NetworkResponse | ||
| import de.lukasneugebauer.nextcloudcookbook.R | ||
| import de.lukasneugebauer.nextcloudcookbook.core.data.PreferencesManager | ||
| import de.lukasneugebauer.nextcloudcookbook.core.data.api.NcCookbookApiProvider | ||
| import de.lukasneugebauer.nextcloudcookbook.core.domain.model.NcAccount | ||
| import de.lukasneugebauer.nextcloudcookbook.core.domain.repository.BaseRepository | ||
| import de.lukasneugebauer.nextcloudcookbook.core.util.IoDispatcher | ||
| import de.lukasneugebauer.nextcloudcookbook.core.util.OkHttpClientProvider | ||
| import de.lukasneugebauer.nextcloudcookbook.core.util.Resource | ||
| import de.lukasneugebauer.nextcloudcookbook.core.util.SimpleResource | ||
| import de.lukasneugebauer.nextcloudcookbook.core.util.UiText | ||
| import de.lukasneugebauer.nextcloudcookbook.core.util.addSuffix | ||
| import de.lukasneugebauer.nextcloudcookbook.di.CategoriesStore | ||
| import de.lukasneugebauer.nextcloudcookbook.di.RecipePreviewsByCategoryStore | ||
| import de.lukasneugebauer.nextcloudcookbook.di.RecipePreviewsStore | ||
| import de.lukasneugebauer.nextcloudcookbook.di.RecipeStore | ||
| import de.lukasneugebauer.nextcloudcookbook.recipe.data.dto.ImportUrlDto | ||
| import de.lukasneugebauer.nextcloudcookbook.recipe.data.dto.RecipeDto | ||
| import de.lukasneugebauer.nextcloudcookbook.recipe.data.dto.RecipePreviewDto | ||
| import de.lukasneugebauer.nextcloudcookbook.recipe.domain.model.RecipeImageUpload | ||
| import de.lukasneugebauer.nextcloudcookbook.recipe.domain.repository.RecipeRepository | ||
| import de.lukasneugebauer.nextcloudcookbook.recipe.util.emptyRecipeDto | ||
| import kotlinx.coroutines.CoroutineDispatcher | ||
| import kotlinx.coroutines.flow.Flow | ||
| import kotlinx.coroutines.flow.first | ||
| import kotlinx.coroutines.withContext | ||
| import okhttp3.Credentials | ||
| import okhttp3.HttpUrl | ||
| import okhttp3.HttpUrl.Companion.toHttpUrl | ||
| import okhttp3.MediaType.Companion.toMediaType | ||
| import okhttp3.Request | ||
| import okhttp3.RequestBody.Companion.toRequestBody | ||
| import okhttp3.Response | ||
| import org.mobilenativefoundation.store.store5.ExperimentalStoreApi | ||
| import org.mobilenativefoundation.store.store5.StoreReadRequest | ||
| import org.mobilenativefoundation.store.store5.StoreReadResponse | ||
|
|
@@ -36,6 +48,8 @@ class RecipeRepositoryImpl | |
| private val apiProvider: NcCookbookApiProvider, | ||
| private val imageLoader: ImageLoader, | ||
| @IoDispatcher private val ioDispatcher: CoroutineDispatcher, | ||
| private val preferencesManager: PreferencesManager, | ||
| private val clientProvider: OkHttpClientProvider, | ||
| private val recipePreviewsByCategoryStore: RecipePreviewsByCategoryStore, | ||
| private val recipePreviewsStore: RecipePreviewsStore, | ||
| private val recipeStore: RecipeStore, | ||
|
|
@@ -60,6 +74,13 @@ class RecipeRepositoryImpl | |
|
|
||
| override suspend fun getRecipe(id: String): RecipeDto = recipeStore.get(id) | ||
|
|
||
| /** | ||
| * Creates a new recipe on the server. | ||
| * | ||
| * @param recipe The [RecipeDto] containing the recipe data. | ||
| * @return A [Resource] containing the new recipe ID on success, or an error message on failure. | ||
| * A 409 Conflict error usually indicates the recipe name already exists. | ||
| */ | ||
| override suspend fun createRecipe(recipe: RecipeDto): Resource<String> { | ||
| return withContext(ioDispatcher) { | ||
| val api = | ||
|
|
@@ -68,14 +89,78 @@ class RecipeRepositoryImpl | |
|
|
||
| try { | ||
| val id = api.createRecipe(recipe = recipe) | ||
| refreshCaches(id = recipe.id, categoryName = recipe.recipeCategory) | ||
| refreshCaches(id = id, categoryName = recipe.recipeCategory) | ||
| Resource.Success(data = id) | ||
| } catch (e: Exception) { | ||
| handleResponseError(e.fillInStackTrace()) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| override suspend fun uploadRecipeImage(image: RecipeImageUpload): Resource<String> { | ||
| return withContext(ioDispatcher) { | ||
| if (image.fileName.isBlank() || image.mimeType.isBlank() || image.bytes.isEmpty()) { | ||
| return@withContext Resource.Error(message = UiText.StringResource(R.string.error_invalid_image_payload)) | ||
| } | ||
|
|
||
| val ncAccount = preferencesManager.preferencesFlow.first().ncAccount | ||
| if (ncAccount.username.isBlank() || ncAccount.token.isBlank() || ncAccount.url.isBlank()) { | ||
| return@withContext Resource.Error(message = UiText.StringResource(R.string.error_no_account_data)) | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| try { | ||
| val client = clientProvider.getCurrentClient() | ||
| val authHeader = Credentials.basic(ncAccount.username, ncAccount.token) | ||
| val userId = getWebDavUserId(fallback = ncAccount.username) | ||
| val uploadFolderUrl = | ||
| ncAccount.toWebDavUrl( | ||
| userId = userId, | ||
| pathSegments = listOf(RECIPE_IMAGE_UPLOAD_FOLDER), | ||
| ) | ||
| val fileUrl = | ||
| ncAccount.toWebDavUrl( | ||
| userId = userId, | ||
| pathSegments = listOf(RECIPE_IMAGE_UPLOAD_FOLDER, image.fileName), | ||
| ) | ||
|
|
||
| client | ||
| .newCall( | ||
| Request | ||
| .Builder() | ||
| .url(uploadFolderUrl) | ||
| .header("Authorization", authHeader) | ||
| .method("MKCOL", null) | ||
| .build(), | ||
| ).execute() | ||
| .use { response -> | ||
| if (!response.isSuccessful && response.code != HTTP_METHOD_NOT_ALLOWED) { | ||
| return@withContext handleUploadError(response) | ||
| } | ||
| } | ||
|
|
||
| val body = image.bytes.toRequestBody(image.mimeType.toMediaType()) | ||
| client | ||
| .newCall( | ||
| Request | ||
| .Builder() | ||
| .url(fileUrl) | ||
| .header("Authorization", authHeader) | ||
| .put(body) | ||
| .build(), | ||
| ).execute() | ||
| .use { response -> | ||
| if (!response.isSuccessful) { | ||
| return@withContext handleUploadError(response) | ||
| } | ||
| } | ||
|
|
||
| Resource.Success(data = "/$RECIPE_IMAGE_UPLOAD_FOLDER/${image.fileName}") | ||
| } catch (e: Exception) { | ||
| handleResponseError(e.fillInStackTrace()) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| override suspend fun updateRecipe(recipe: RecipeDto): SimpleResource { | ||
| return withContext(ioDispatcher) { | ||
| val api = | ||
|
|
@@ -159,6 +244,33 @@ class RecipeRepositoryImpl | |
| imageLoader.diskCache?.remove(cacheKey) | ||
| } | ||
|
|
||
| private suspend fun getWebDavUserId(fallback: String): String = | ||
| when (val response = apiProvider.getApi()?.getCurrentUser()) { | ||
| is NetworkResponse.Success -> response.body.ocs.data.id | ||
| else -> fallback | ||
| } | ||
|
|
||
| private fun NcAccount.toWebDavUrl( | ||
| userId: String, | ||
| pathSegments: List<String>, | ||
| ): HttpUrl { | ||
| val builder = | ||
| url | ||
| .addSuffix("/") | ||
| .toHttpUrl() | ||
| .newBuilder() | ||
| .addPathSegments("remote.php/dav/files") | ||
| .addPathSegment(userId) | ||
|
|
||
| pathSegments.forEach { pathSegment -> | ||
| builder.addPathSegment(pathSegment) | ||
| } | ||
|
|
||
| return builder.build() | ||
| } | ||
|
|
||
| private fun <T> handleUploadError(response: Response): Resource.Error<T> = handleResponseError(t = null, code = response.code) | ||
|
|
||
| @OptIn(ExperimentalStoreApi::class) | ||
| private suspend fun refreshCaches( | ||
| id: String, | ||
|
|
@@ -176,4 +288,9 @@ class RecipeRepositoryImpl | |
| recipeStore.fresh(id) | ||
| } | ||
| } | ||
|
|
||
| private companion object { | ||
| const val HTTP_METHOD_NOT_ALLOWED = 405 | ||
| const val RECIPE_IMAGE_UPLOAD_FOLDER = "Cookbook uploads" | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not sure I like this hard coded folder name. Best case would be to mimic the same behaviour as in the webapp and only have a temporary file. |
||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| package de.lukasneugebauer.nextcloudcookbook.recipe.domain.model | ||
|
|
||
| data class RecipeImageUpload( | ||
| val fileName: String, | ||
| val mimeType: String, | ||
| val bytes: ByteArray, | ||
| ) { | ||
| override fun equals(other: Any?): Boolean { | ||
| if (this === other) return true | ||
| if (javaClass != other?.javaClass) return false | ||
|
|
||
| other as RecipeImageUpload | ||
|
|
||
| if (fileName != other.fileName) return false | ||
| if (mimeType != other.mimeType) return false | ||
| if (!bytes.contentEquals(other.bytes)) return false | ||
|
|
||
| return true | ||
| } | ||
|
|
||
| override fun hashCode(): Int { | ||
| var result = fileName.hashCode() | ||
| result = 31 * result + mimeType.hashCode() | ||
| result = 31 * result + bytes.contentHashCode() | ||
| return result | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'd prefer if we do not handle OkHttp directly and instead use retrofit like with the other requests in the app. Some stuff - like the auth header - is already handled that way and the repository class is cleaner.