54 lines
2.2 KiB
Kotlin
54 lines
2.2 KiB
Kotlin
package com.abunchofknowitalls.otunes
|
|
|
|
import android.content.ClipData
|
|
import android.content.Intent
|
|
import androidx.core.content.FileProvider
|
|
import expo.modules.kotlin.modules.Module
|
|
import expo.modules.kotlin.modules.ModuleDefinition
|
|
import java.io.File
|
|
import java.net.URL
|
|
|
|
class MediaLinkShare : Module() {
|
|
override fun definition() = ModuleDefinition {
|
|
Name("MediaLinkShare")
|
|
AsyncFunction("share") { link: String, artwork: String, title: String ->
|
|
val context = requireNotNull(appContext.reactContext)
|
|
val intent = Intent(Intent.ACTION_SEND).apply {
|
|
type = "text/plain"
|
|
putExtra(Intent.EXTRA_TEXT, link)
|
|
putExtra(Intent.EXTRA_TITLE, title)
|
|
putExtra(Intent.EXTRA_SUBJECT, title)
|
|
}
|
|
// ClipData supplies the chooser thumbnail while the shared item stays a URL.
|
|
try {
|
|
val connection = URL(artwork).openConnection().apply {
|
|
connectTimeout = 8000
|
|
readTimeout = 8000
|
|
}
|
|
context.cacheDir.listFiles()?.filter {
|
|
it.name.startsWith("media-link-cover-") && it.lastModified() < System.currentTimeMillis() - 86400000
|
|
}?.forEach { it.delete() }
|
|
val extension = when (connection.contentType?.substringBefore(";")) {
|
|
"image/webp" -> "webp"
|
|
"image/png" -> "png"
|
|
"image/jpeg" -> "jpg"
|
|
"image/gif" -> "gif"
|
|
else -> error("Artwork format is not supported")
|
|
}
|
|
val file = File(context.cacheDir, "media-link-cover-${java.util.UUID.randomUUID()}.${extension}")
|
|
connection.getInputStream().use { input ->
|
|
file.outputStream().use { output -> input.copyTo(output) }
|
|
}
|
|
val uri = FileProvider.getUriForFile(context, context.packageName + ".SharingFileProvider", file)
|
|
intent.clipData = ClipData.newUri(context.contentResolver, "Artwork", uri)
|
|
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
|
} catch (_: Exception) {
|
|
// A failed artwork download must not prevent sharing the link.
|
|
}
|
|
appContext.throwingActivity.runOnUiThread {
|
|
appContext.throwingActivity.startActivity(Intent.createChooser(intent, "Share"))
|
|
}
|
|
}
|
|
}
|
|
}
|