Skip to content

Commit

Permalink
Merge pull request #4783 from vector-im/feature/adm/unable-to-change-…
Browse files Browse the repository at this point in the history
…avatar

Unable to change avatar due to `NetworkOnMainThread`
  • Loading branch information
bmarty authored Dec 30, 2021
2 parents 753d704 + a764e02 commit 5407c84
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 8 deletions.
1 change: 1 addition & 0 deletions changelog.d/4767.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixing unable to change change avatar in some scenarios
Original file line number Diff line number Diff line change
Expand Up @@ -109,18 +109,23 @@ internal class FileUploader @Inject constructor(
filename: String?,
mimeType: String?,
progressListener: ProgressRequestBody.Listener? = null): ContentUploadResponse {
val inputStream = withContext(Dispatchers.IO) {
context.contentResolver.openInputStream(uri)
} ?: throw FileNotFoundException()
val workingFile = temporaryFileCreator.create()
workingFile.outputStream().use {
inputStream.copyTo(it)
}
val workingFile = context.copyUriToTempFile(uri)
return uploadFile(workingFile, filename, mimeType, progressListener).also {
tryOrNull { workingFile.delete() }
}
}

private suspend fun Context.copyUriToTempFile(uri: Uri): File {
return withContext(Dispatchers.IO) {
val inputStream = contentResolver.openInputStream(uri) ?: throw FileNotFoundException()
val workingFile = temporaryFileCreator.create()
workingFile.outputStream().use {
inputStream.copyTo(it)
}
workingFile
}
}

private suspend fun upload(uploadBody: RequestBody,
filename: String?,
progressListener: ProgressRequestBody.Listener?): ContentUploadResponse {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ internal class DefaultProfileService @Inject constructor(private val taskExecuto
}

override suspend fun updateAvatar(userId: String, newAvatarUri: Uri, fileName: String) {
withContext(coroutineDispatchers.main) {
withContext(coroutineDispatchers.io) {
val response = fileUploader.uploadFromUri(newAvatarUri, fileName, MimeTypes.Jpeg)
setAvatarUrlTask.execute(SetAvatarUrlTask.Params(userId = userId, newAvatarUrl = response.contentUri))
userStore.updateAvatar(userId, response.contentUri)
Expand Down

0 comments on commit 5407c84

Please sign in to comment.