Skip to content

Support Share to Zulip on Android #1774

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

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
10 changes: 10 additions & 0 deletions android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="zulip" android:host="login" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="*/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="*/*" />
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package com.zulip.flutter

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.OpenableColumns

class AndroidIntentEventListener : AndroidIntentEventsStreamHandler() {
private var eventSink: PigeonEventSink<AndroidIntentEvent>? = null
private val buffer = mutableListOf<AndroidIntentEvent>()

override fun onListen(p0: Any?, sink: PigeonEventSink<AndroidIntentEvent>) {
eventSink = sink
buffer.forEach { eventSink!!.success(it) }
}

private fun onEvent(event: AndroidIntentEvent) {
if (eventSink != null) {
eventSink?.success(event)
} else {
buffer.add(event)
}
}

fun handleSend(context: Context, intent: Intent) {
val intentAction = intent.action
assert(
intentAction == Intent.ACTION_SEND
|| intentAction == Intent.ACTION_SEND_MULTIPLE
)

// EXTRA_TEXT and EXTRA_STREAM are the text and file components of the
// content, respectively. The ACTION_SEND{,_MULTIPLE} docs say
// "either" / "or" will be present:
// https://developer.android.com/reference/android/content/Intent#ACTION_SEND
// But empirically both can be present, commonly, so we accept that form,
// interpreting it as an intent to share both kinds of data.
//
// Empirically, sometimes EXTRA_TEXT isn't something we think needs to be
// shared, like the URL of a file that's present in EXTRA_STREAM… but we
// shrug and include it anyway because we don't want to second-guess other
// apps' decisions about what to include; it's their responsibility.

val extraText = intent.getStringExtra(Intent.EXTRA_TEXT)
val extraStream = when (intentAction) {
Intent.ACTION_SEND -> {
var extraStream: List<IntentSharedFile>? = null
// TODO(android-sdk-33) Remove the use of deprecated API.
@Suppress("DEPRECATION") val url = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
if (url != null) {
extraStream = listOf(getIntentSharedFile(context, url))
}
extraStream
}

Intent.ACTION_SEND_MULTIPLE -> {
var extraStream: MutableList<IntentSharedFile>? = null
// TODO(android-sdk-33) Remove the use of deprecated API.
@Suppress("DEPRECATION") val urls =
intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)
if (urls != null) {
extraStream = mutableListOf()
for (url in urls) {
val sharedFile = getIntentSharedFile(context, url)
extraStream.add(sharedFile)
}
}
extraStream
}

else -> throw IllegalArgumentException("Unexpected value for intent.action: $intentAction")
}

if (extraText == null && extraStream == null) {
throw Exception("Got unexpected ACTION_SEND* intent, with neither EXTRA_TEXT nor EXTRA_STREAM")
}

onEvent(
AndroidIntentSendEvent(
action = intentAction,
extraText = extraText,
extraStream = extraStream,
)
)
}
}

// A helper function to retrieve the shared file from the `content://` URL
// from the ACTION_SEND{_MULTIPLE} intent.
fun getIntentSharedFile(context: Context, url: Uri): IntentSharedFile {
val contentResolver = context.contentResolver
val mimeType = contentResolver.getType(url)
val name = contentResolver.query(url, null, null, null, null)?.use { cursor ->
cursor.moveToFirst()
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
cursor.getString(nameIndex)
} ?: ("unknown." + (mimeType?.split('/')?.last() ?: "bin"))

class ResolverFailedException(msg: String) : RuntimeException(msg)

val bytes = (contentResolver.openInputStream(url)
?: throw ResolverFailedException("resolver.open… failed"))
.use { inputStream ->
inputStream.readBytes()
}

return IntentSharedFile(
name = name,
mimeType = mimeType,
bytes = bytes
)
}
203 changes: 203 additions & 0 deletions android/app/src/main/kotlin/com/zulip/flutter/AndroidIntents.g.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
// Autogenerated from Pigeon (v25.5.0), do not edit directly.
// See also: https://pub.dev/packages/pigeon
@file:Suppress("UNCHECKED_CAST", "ArrayInDataClass")

package com.zulip.flutter

import android.util.Log
import io.flutter.plugin.common.BasicMessageChannel
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MessageCodec
import io.flutter.plugin.common.StandardMethodCodec
import io.flutter.plugin.common.StandardMessageCodec
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
private object AndroidIntentsPigeonUtils {
fun deepEquals(a: Any?, b: Any?): Boolean {
if (a is ByteArray && b is ByteArray) {
return a.contentEquals(b)
}
if (a is IntArray && b is IntArray) {
return a.contentEquals(b)
}
if (a is LongArray && b is LongArray) {
return a.contentEquals(b)
}
if (a is DoubleArray && b is DoubleArray) {
return a.contentEquals(b)
}
if (a is Array<*> && b is Array<*>) {
return a.size == b.size &&
a.indices.all{ deepEquals(a[it], b[it]) }
}
if (a is List<*> && b is List<*>) {
return a.size == b.size &&
a.indices.all{ deepEquals(a[it], b[it]) }
}
if (a is Map<*, *> && b is Map<*, *>) {
return a.size == b.size && a.all {
(b as Map<Any?, Any?>).containsKey(it.key) &&
deepEquals(it.value, b[it.key])
}
}
return a == b
}

}

/** Generated class from Pigeon that represents data sent in messages. */
data class IntentSharedFile (
val name: String,
val mimeType: String? = null,
val bytes: ByteArray
)
{
companion object {
fun fromList(pigeonVar_list: List<Any?>): IntentSharedFile {
val name = pigeonVar_list[0] as String
val mimeType = pigeonVar_list[1] as String?
val bytes = pigeonVar_list[2] as ByteArray
return IntentSharedFile(name, mimeType, bytes)
}
}
fun toList(): List<Any?> {
return listOf(
name,
mimeType,
bytes,
)
}
override fun equals(other: Any?): Boolean {
if (other !is IntentSharedFile) {
return false
}
if (this === other) {
return true
}
return AndroidIntentsPigeonUtils.deepEquals(toList(), other.toList()) }

override fun hashCode(): Int = toList().hashCode()
}

/**
* Generated class from Pigeon that represents data sent in messages.
* This class should not be extended by any user class outside of the generated file.
*/
sealed class AndroidIntentEvent
/** Generated class from Pigeon that represents data sent in messages. */
data class AndroidIntentSendEvent (
val action: String,
val extraText: String? = null,
val extraStream: List<IntentSharedFile>? = null
) : AndroidIntentEvent()
{
companion object {
fun fromList(pigeonVar_list: List<Any?>): AndroidIntentSendEvent {
val action = pigeonVar_list[0] as String
val extraText = pigeonVar_list[1] as String?
val extraStream = pigeonVar_list[2] as List<IntentSharedFile>?
return AndroidIntentSendEvent(action, extraText, extraStream)
}
}
fun toList(): List<Any?> {
return listOf(
action,
extraText,
extraStream,
)
}
override fun equals(other: Any?): Boolean {
if (other !is AndroidIntentSendEvent) {
return false
}
if (this === other) {
return true
}
return AndroidIntentsPigeonUtils.deepEquals(toList(), other.toList()) }

override fun hashCode(): Int = toList().hashCode()
}
private open class AndroidIntentsPigeonCodec : StandardMessageCodec() {
override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? {
return when (type) {
129.toByte() -> {
return (readValue(buffer) as? List<Any?>)?.let {
IntentSharedFile.fromList(it)
}
}
130.toByte() -> {
return (readValue(buffer) as? List<Any?>)?.let {
AndroidIntentSendEvent.fromList(it)
}
}
else -> super.readValueOfType(type, buffer)
}
}
override fun writeValue(stream: ByteArrayOutputStream, value: Any?) {
when (value) {
is IntentSharedFile -> {
stream.write(129)
writeValue(stream, value.toList())
}
is AndroidIntentSendEvent -> {
stream.write(130)
writeValue(stream, value.toList())
}
else -> super.writeValue(stream, value)
}
}
}

val AndroidIntentsPigeonMethodCodec = StandardMethodCodec(AndroidIntentsPigeonCodec())


private class AndroidIntentsPigeonStreamHandler<T>(
val wrapper: AndroidIntentsPigeonEventChannelWrapper<T>
) : EventChannel.StreamHandler {
var pigeonSink: PigeonEventSink<T>? = null

override fun onListen(p0: Any?, sink: EventChannel.EventSink) {
pigeonSink = PigeonEventSink<T>(sink)
wrapper.onListen(p0, pigeonSink!!)
}

override fun onCancel(p0: Any?) {
pigeonSink = null
wrapper.onCancel(p0)
}
}

interface AndroidIntentsPigeonEventChannelWrapper<T> {
open fun onListen(p0: Any?, sink: PigeonEventSink<T>) {}

open fun onCancel(p0: Any?) {}
}

class PigeonEventSink<T>(private val sink: EventChannel.EventSink) {
fun success(value: T) {
sink.success(value)
}

fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
sink.error(errorCode, errorMessage, errorDetails)
}

fun endOfStream() {
sink.endOfStream()
}
}

abstract class AndroidIntentEventsStreamHandler : AndroidIntentsPigeonEventChannelWrapper<AndroidIntentEvent> {
companion object {
fun register(messenger: BinaryMessenger, streamHandler: AndroidIntentEventsStreamHandler, instanceName: String = "") {
var channelName: String = "dev.flutter.pigeon.zulip.AndroidIntentsEventChannelApi.androidIntentEvents"
if (instanceName.isNotEmpty()) {
channelName += ".$instanceName"
}
val internalStreamHandler = AndroidIntentsPigeonStreamHandler<AndroidIntentEvent>(streamHandler)
EventChannel(messenger, channelName, AndroidIntentsPigeonMethodCodec).setStreamHandler(internalStreamHandler)
}
}
}

38 changes: 37 additions & 1 deletion android/app/src/main/kotlin/com/zulip/flutter/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,42 @@
package com.zulip.flutter

import android.content.Intent
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine

class MainActivity: FlutterActivity() {
class MainActivity : FlutterActivity() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a fair amount of code added here. Was there a particular place (or handful of places) you looked for working out what this code should look like? That'll be helpful to point to in commit messages.

For example, specific files in the legacy app; or places in the Flutter tree; or Android documentation; or other sources.

private var androidIntentEventListener: AndroidIntentEventListener? = null

override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)

androidIntentEventListener = AndroidIntentEventListener()
AndroidIntentEventsStreamHandler.register(
flutterEngine.dartExecutor.binaryMessenger,
androidIntentEventListener!!
)
maybeHandleIntent(intent)
}

override fun onNewIntent(intent: Intent) {
if (maybeHandleIntent(intent)) {
return
}
super.onNewIntent(intent)
}

/** Returns true just if we did handle the intent. */
private fun maybeHandleIntent(intent: Intent?): Boolean {
intent ?: return false
when (intent.action) {
// Share-to-Zulip
Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE -> {
androidIntentEventListener!!.handleSend(this, intent)
return true
}

// For other intents, let Flutter handle it.
else -> return false
}
}
}
Loading