Skip to content
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

fix: add data: image loader #367

Merged
merged 1 commit into from
Aug 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions app/src/main/kotlin/com/github/gotify/CoilInstance.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,23 @@ package com.github.gotify
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.util.Base64
import androidx.annotation.DrawableRes
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.graphics.drawable.toBitmap
import coil.ImageLoader
import coil.annotation.ExperimentalCoilApi
import coil.decode.DataSource
import coil.decode.SvgDecoder
import coil.disk.DiskCache
import coil.executeBlocking
import coil.fetch.DrawableResult
import coil.fetch.Fetcher
import coil.request.ErrorResult
import coil.request.ImageRequest
import coil.request.Options
import coil.request.SuccessResult
import com.github.gotify.api.CertUtils
import com.github.gotify.client.model.Application
Expand Down Expand Up @@ -96,6 +103,7 @@ object CoilInstance {
}
.components {
add(SvgDecoder.Factory())
add(DataDecoderFactory())
}
.build()
return sslSettings to loader
Expand All @@ -119,3 +127,31 @@ private class BasicAuthInterceptor : Interceptor {
return chain.proceed(request)
}
}

class DataDecoderFactory : Fetcher.Factory<Uri> {
override fun create(data: Uri, options: Options, imageLoader: ImageLoader): Fetcher? {
if (!data.scheme.equals("data", ignoreCase = true)) {
return null
}

val uri = data.toString()
val imageDataBytes = data.toString().substring(uri.indexOf(",") + 1)
val bytes = Base64.decode(imageDataBytes.toByteArray(), Base64.DEFAULT)
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)

if (bitmap == null) {
val show = if (uri.length > 50) uri.take(50) + "..." else uri
val malformed = RuntimeException("Malformed data uri: $show")
Logger.error(malformed) { "Could not load image" }
return null
}

return Fetcher {
DrawableResult(
drawable = BitmapDrawable(options.context.resources, bitmap),
isSampled = false,
dataSource = DataSource.MEMORY
)
}
}
}
Loading