diff --git a/.github/workflows/release-android.yml b/.github/workflows/release-android.yml new file mode 100644 index 00000000..881ee215 --- /dev/null +++ b/.github/workflows/release-android.yml @@ -0,0 +1,80 @@ +name: Release Android APK + +on: + release: + types: [published] + workflow_dispatch: + inputs: + attach_to_release_tag: + description: "Optional release tag to attach the APK to (leave empty to skip upload)" + required: false + default: "" + +jobs: + build: + runs-on: ubuntu-latest + timeout-minutes: 45 + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: npm + + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 17 + + - uses: android-actions/setup-android@v3 + + - name: Install JS dependencies + run: npm ci + + - name: Decode release keystore + id: keystore + env: + KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} + run: | + if [ -n "$KEYSTORE_BASE64" ]; then + echo "$KEYSTORE_BASE64" | base64 -d > "$RUNNER_TEMP/release.keystore" + echo "path=$RUNNER_TEMP/release.keystore" >> "$GITHUB_OUTPUT" + echo "present=true" >> "$GITHUB_OUTPUT" + else + echo "present=false" >> "$GITHUB_OUTPUT" + fi + + - name: Build release APK + working-directory: android + env: + ORG_GRADLE_PROJECT_BULWARK_RELEASE_STORE_FILE: ${{ steps.keystore.outputs.path }} + ORG_GRADLE_PROJECT_BULWARK_RELEASE_STORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + ORG_GRADLE_PROJECT_BULWARK_RELEASE_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }} + ORG_GRADLE_PROJECT_BULWARK_RELEASE_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }} + run: ./gradlew assembleRelease --no-daemon + + - name: Rename APK with version + id: artifact + run: | + VERSION=$(node -p "require('./app.json').expo.version") + SRC=android/app/build/outputs/apk/release/app-release.apk + DEST="bulwark-mobile-${VERSION}-${GITHUB_SHA::7}.apk" + cp "$SRC" "$DEST" + echo "path=$DEST" >> "$GITHUB_OUTPUT" + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + + - uses: actions/upload-artifact@v4 + with: + name: ${{ steps.artifact.outputs.path }} + path: ${{ steps.artifact.outputs.path }} + if-no-files-found: error + + - name: Attach APK to release + if: github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.attach_to_release_tag != '') + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ github.event.release.tag_name || github.event.inputs.attach_to_release_tag }} + files: ${{ steps.artifact.outputs.path }} diff --git a/.gitignore b/.gitignore index d914c328..400e3a61 100644 --- a/.gitignore +++ b/.gitignore @@ -18,8 +18,15 @@ expo-env.d.ts *.key *.mobileprovision -# Metro +# Metro / Expo dev-server logs .metro-health-check* +metro.log +expo.log +expo-run.log +scripts/*.log + +# Scratch +tmp-* # debug npm-debug.* @@ -38,4 +45,18 @@ yarn-error.* # generated native folders /ios -/android + +# Android build outputs (track the project itself, not its build artifacts) +/android/.gradle/ +/android/.idea/ +/android/.kotlin/ +/android/build/ +/android/app/build/ +/android/app/.cxx/ +/android/local.properties +/android/captures/ +/android/*.iml +/android/app/*.iml +/android/build-release.log +/android/expo*.log +/android/metro.log diff --git a/App.tsx b/App.tsx index 8bb4dac9..808fd873 100644 --- a/App.tsx +++ b/App.tsx @@ -1,12 +1,21 @@ import React from 'react'; import { ActivityIndicator, StyleSheet, Text, View } from 'react-native'; import { StatusBar } from 'expo-status-bar'; -import { NavigationContainer } from '@react-navigation/native'; +import { NavigationContainer, createNavigationContainerRef } from '@react-navigation/native'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import { createNativeStackNavigator, type NativeStackScreenProps } from '@react-navigation/native-stack'; import { Mail, Calendar, BookUser, HardDrive, Settings } from 'lucide-react-native'; import { startPushUpdates } from './src/api/push'; +import { + addMessageListener, + addNotificationTapListener, + addTokenRefreshListener, + getInitialNotificationTap, + getStoredRelayBaseUrl, + setupPushNotifications, + type NotificationTapPayload, +} from './src/lib/push-notifications'; import type { MainTabsParamList, RootStackParamList } from './src/navigation/types'; import ComposeScreen from './src/screens/ComposeScreen'; import EmailThreadScreen from './src/screens/EmailThreadScreen'; @@ -19,6 +28,7 @@ import ContactDetailScreen from './src/screens/ContactDetailScreen'; import ContactFormScreen from './src/screens/ContactFormScreen'; import GroupDetailScreen from './src/screens/GroupDetailScreen'; import SettingsScreen from './src/screens/SettingsScreenNew2'; +import { useAccountStore } from './src/stores/account-store'; import { useAuthStore } from './src/stores/auth-store'; import { useCalendarStore } from './src/stores/calendar-store'; import { useContactsStore } from './src/stores/contacts-store'; @@ -28,6 +38,16 @@ import { colors, spacing, typography } from './src/theme/tokens'; const Stack = createNativeStackNavigator(); const Tab = createBottomTabNavigator(); +const navigationRef = createNavigationContainerRef(); + +function navigateToNotificationTap(payload: NotificationTapPayload): void { + if (!navigationRef.isReady()) return; + navigationRef.navigate('EmailThread', { + emailId: payload.emailId, + threadId: payload.threadId, + subject: payload.subject, + }); +} function LoadingScreen({ message }: { message: string }) { return ( @@ -135,6 +155,11 @@ export default function App() { const isAuthenticated = useAuthStore((state) => state.isAuthenticated); const client = useAuthStore((state) => state.client); const restoreSession = useAuthStore((state) => state.restoreSession); + // Persisted active account is the signal that the user was already signed + // in on the previous launch. When present we render the main UI with the + // cached mail list instead of the "Restoring session" spinner; the real + // JMAP session comes up in the background. + const hasPersistedAccount = useAccountStore((state) => state.activeAccountId != null); React.useEffect(() => { if (!hasRestoredSession) { @@ -146,6 +171,74 @@ export default function App() { void useSettingsStore.getState().hydrate(); }, []); + // Listen for FCM messages so the app can refresh state even when woken + // from the background — the FirebaseMessagingService also posts the system + // notification so the user sees it regardless of RN runtime state. + React.useEffect(() => { + const unsubscribe = addMessageListener((payload) => { + console.log('[push] fcm message', payload.title); + }); + return unsubscribe; + }, []); + + // When the user taps a notification the app lands here with an email id + // either stashed on the cold-start intent or delivered as a live event. + // Wait until auth is restored so the navigation target has credentials to + // load the thread. + React.useEffect(() => { + if (!isAuthenticated) return; + + let cancelled = false; + void (async () => { + const initial = await getInitialNotificationTap(); + if (cancelled || !initial) return; + navigateToNotificationTap(initial); + })(); + + const unsubscribe = addNotificationTapListener((payload) => { + navigateToNotificationTap(payload); + }); + + return () => { + cancelled = true; + unsubscribe(); + }; + }, [isAuthenticated]); + + // Re-register the device with the configured relay once authenticated, + // and whenever the FCM token rotates. + React.useEffect(() => { + if (!isAuthenticated || !client) return; + + let cancelled = false; + const doSetup = async () => { + const relayBaseUrl = await getStoredRelayBaseUrl(); + if (!relayBaseUrl) return; + try { + await setupPushNotifications({ + relayBaseUrl, + accountLabel: client.username ?? undefined, + }); + if (cancelled) return; + } catch (error) { + console.warn( + '[push] relay setup failed:', + error instanceof Error ? error.message : error, + ); + } + }; + + void doSetup(); + const unsubscribe = addTokenRefreshListener(() => { + void doSetup(); + }); + + return () => { + cancelled = true; + unsubscribe(); + }; + }, [client, isAuthenticated]); + React.useEffect(() => { if (!isAuthenticated || !client) { return; @@ -186,16 +279,20 @@ export default function App() { }; }, [client, isAuthenticated]); - if (!hasRestoredSession) { + // Skip the "Restoring session" flash for returning users: if we already + // have a persisted active account, render the main UI immediately with + // whatever the email-store hydrated from cache. restoreSession still runs + // in the background and swaps in fresh data once it completes. + if (!hasRestoredSession && !hasPersistedAccount) { return ( <> - + ); } - if (!isAuthenticated) { + if (hasRestoredSession && !isAuthenticated) { return ( <> @@ -205,7 +302,7 @@ export default function App() { } return ( - + @@ -261,3 +358,4 @@ const styles = StyleSheet.create({ color: colors.textSecondary, }, }); + diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 00000000..8a6be077 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,16 @@ +# OSX +# +.DS_Store + +# Android/IntelliJ +# +build/ +.idea +.gradle +local.properties +*.iml +*.hprof +.cxx/ + +# Bundle artifacts +*.jsbundle diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 00000000..a81980d3 --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,195 @@ +apply plugin: "com.android.application" +apply plugin: "org.jetbrains.kotlin.android" +apply plugin: "com.facebook.react" +apply plugin: "com.google.gms.google-services" + +def projectRoot = rootDir.getAbsoluteFile().getParentFile().getAbsolutePath() + +/** + * This is the configuration block to customize your React Native Android app. + * By default you don't need to apply any configuration, just uncomment the lines you need. + */ +react { + entryFile = file(["node", "-e", "require('expo/scripts/resolveAppEntry')", projectRoot, "android", "absolute"].execute(null, rootDir).text.trim()) + reactNativeDir = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsoluteFile() + hermesCommand = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/sdks/hermesc/%OS-BIN%/hermesc" + codegenDir = new File(["node", "--print", "require.resolve('@react-native/codegen/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim()).getParentFile().getAbsoluteFile() + + enableBundleCompression = (findProperty('android.enableBundleCompression') ?: false).toBoolean() + // Use Expo CLI to bundle the app, this ensures the Metro config + // works correctly with Expo projects. + cliFile = new File(["node", "--print", "require.resolve('@expo/cli', { paths: [require.resolve('expo/package.json')] })"].execute(null, rootDir).text.trim()) + bundleCommand = "export:embed" + + /* Folders */ + // The root of your project, i.e. where "package.json" lives. Default is '../..' + // root = file("../../") + // The folder where the react-native NPM package is. Default is ../../node_modules/react-native + // reactNativeDir = file("../../node_modules/react-native") + // The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen + // codegenDir = file("../../node_modules/@react-native/codegen") + + /* Variants */ + // The list of variants to that are debuggable. For those we're going to + // skip the bundling of the JS bundle and the assets. By default is just 'debug'. + // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. + // debuggableVariants = ["liteDebug", "prodDebug"] + + /* Bundling */ + // A list containing the node command and its flags. Default is just 'node'. + // nodeExecutableAndArgs = ["node"] + + // + // The path to the CLI configuration file. Default is empty. + // bundleConfig = file(../rn-cli.config.js) + // + // The name of the generated asset file containing your JS bundle + // bundleAssetName = "MyApplication.android.bundle" + // + // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' + // entryFile = file("../js/MyApplication.android.js") + // + // A list of extra flags to pass to the 'bundle' commands. + // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle + // extraPackagerArgs = [] + + /* Hermes Commands */ + // The hermes compiler command to run. By default it is 'hermesc' + // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" + // + // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" + // hermesFlags = ["-O", "-output-source-map"] + + /* Autolinking */ + autolinkLibrariesWithApp() +} + +/** + * Set this to true in release builds to optimize the app using [R8](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization). + */ +def enableMinifyInReleaseBuilds = (findProperty('android.enableMinifyInReleaseBuilds') ?: false).toBoolean() + +/** + * The preferred build flavor of JavaScriptCore (JSC) + * + * For example, to use the international variant, you can use: + * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` + * + * The international variant includes ICU i18n library and necessary data + * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that + * give correct results when using with locales other than en-US. Note that + * this variant is about 6MiB larger per architecture than default. + */ +def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+' + +android { + ndkVersion rootProject.ext.ndkVersion + + buildToolsVersion rootProject.ext.buildToolsVersion + compileSdk rootProject.ext.compileSdkVersion + + namespace 'com.anonymous.bulwarkmobile' + defaultConfig { + applicationId 'com.anonymous.bulwarkmobile' + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + versionCode 1 + versionName "1.0.0" + + buildConfigField "String", "REACT_NATIVE_RELEASE_LEVEL", "\"${findProperty('reactNativeReleaseLevel') ?: 'stable'}\"" + } + signingConfigs { + debug { + storeFile file('debug.keystore') + storePassword 'android' + keyAlias 'androiddebugkey' + keyPassword 'android' + } + if (project.hasProperty('BULWARK_RELEASE_STORE_FILE') + && project.property('BULWARK_RELEASE_STORE_FILE')?.trim()) { + release { + storeFile file(project.property('BULWARK_RELEASE_STORE_FILE')) + storePassword project.property('BULWARK_RELEASE_STORE_PASSWORD') + keyAlias project.property('BULWARK_RELEASE_KEY_ALIAS') + keyPassword project.property('BULWARK_RELEASE_KEY_PASSWORD') + } + } + } + buildTypes { + debug { + signingConfig signingConfigs.debug + } + release { + signingConfig signingConfigs.findByName('release') ?: signingConfigs.debug + def enableShrinkResources = findProperty('android.enableShrinkResourcesInReleaseBuilds') ?: 'false' + shrinkResources enableShrinkResources.toBoolean() + minifyEnabled enableMinifyInReleaseBuilds + proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" + def enablePngCrunchInRelease = findProperty('android.enablePngCrunchInReleaseBuilds') ?: 'true' + crunchPngs enablePngCrunchInRelease.toBoolean() + } + } + packagingOptions { + jniLibs { + def enableLegacyPackaging = findProperty('expo.useLegacyPackaging') ?: 'false' + useLegacyPackaging enableLegacyPackaging.toBoolean() + } + } + androidResources { + ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:!CVS:!thumbs.db:!picasa.ini:!*~' + } +} + +// Apply static values from `gradle.properties` to the `android.packagingOptions` +// Accepts values in comma delimited lists, example: +// android.packagingOptions.pickFirsts=/LICENSE,**/picasa.ini +["pickFirsts", "excludes", "merges", "doNotStrip"].each { prop -> + // Split option: 'foo,bar' -> ['foo', 'bar'] + def options = (findProperty("android.packagingOptions.$prop") ?: "").split(","); + // Trim all elements in place. + for (i in 0.. 0) { + println "android.packagingOptions.$prop += $options ($options.length)" + // Ex: android.packagingOptions.pickFirsts += '**/SCCS/**' + options.each { + android.packagingOptions[prop] += it + } + } +} + +dependencies { + // The version of react-native is set by the React Native Gradle Plugin + implementation("com.facebook.react:react-android") + + // Firebase Cloud Messaging — delivers pushes via Google Play services. + // Requires android/app/google-services.json at build time. + implementation(platform("com.google.firebase:firebase-bom:33.7.0")) + implementation("com.google.firebase:firebase-messaging") + + def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true"; + def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true"; + def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true"; + + if (isGifEnabled) { + // For animated gif support + implementation("com.facebook.fresco:animated-gif:${expoLibs.versions.fresco.get()}") + } + + if (isWebpEnabled) { + // For webp support + implementation("com.facebook.fresco:webpsupport:${expoLibs.versions.fresco.get()}") + if (isWebpAnimatedEnabled) { + // Animated webp support + implementation("com.facebook.fresco:animated-webp:${expoLibs.versions.fresco.get()}") + } + } + + if (hermesEnabled.toBoolean()) { + implementation("com.facebook.react:hermes-android") + } else { + implementation jscFlavor + } +} diff --git a/android/app/debug.keystore b/android/app/debug.keystore new file mode 100644 index 00000000..364e105e Binary files /dev/null and b/android/app/debug.keystore differ diff --git a/android/app/google-services.json b/android/app/google-services.json new file mode 100644 index 00000000..4517c7e1 --- /dev/null +++ b/android/app/google-services.json @@ -0,0 +1,48 @@ +{ + "project_info": { + "project_number": "504486613721", + "project_id": "bulwark-mobile", + "storage_bucket": "bulwark-mobile.firebasestorage.app" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:504486613721:android:69a5d7ba9148fb14cb24c8", + "android_client_info": { + "package_name": "com.anonymous.bulwarkmobile" + } + }, + "oauth_client": [], + "api_key": [ + { + "current_key": "AIzaSyD4Zyu1BU4YNYy4SOK5te3EhSRHRGoMZno" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:504486613721:android:14c6a69aa49cac3ecb24c8", + "android_client_info": { + "package_name": "com.bulwark.bulwarkmobile" + } + }, + "oauth_client": [], + "api_key": [ + { + "current_key": "AIzaSyD4Zyu1BU4YNYy4SOK5te3EhSRHRGoMZno" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [] + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 00000000..551eb41d --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,14 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# react-native-reanimated +-keep class com.swmansion.reanimated.** { *; } +-keep class com.facebook.react.turbomodule.** { *; } + +# Add any project specific keep options here: diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 00000000..3ec2507b --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/android/app/src/debugOptimized/AndroidManifest.xml b/android/app/src/debugOptimized/AndroidManifest.xml new file mode 100644 index 00000000..3ec2507b --- /dev/null +++ b/android/app/src/debugOptimized/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..29294f8c --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/android/app/src/main/java/com/anonymous/bulwarkmobile/BulwarkFcmModule.kt b/android/app/src/main/java/com/anonymous/bulwarkmobile/BulwarkFcmModule.kt new file mode 100644 index 00000000..210b3a08 --- /dev/null +++ b/android/app/src/main/java/com/anonymous/bulwarkmobile/BulwarkFcmModule.kt @@ -0,0 +1,179 @@ +package com.anonymous.bulwarkmobile + +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Typeface +import androidx.core.app.NotificationCompat +import com.facebook.react.bridge.Promise +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.bridge.ReactContextBaseJavaModule +import com.facebook.react.bridge.ReactMethod +import com.facebook.react.bridge.ReadableMap +import com.facebook.react.bridge.WritableMap +import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter +import com.google.firebase.messaging.FirebaseMessaging +import java.net.HttpURLConnection +import java.net.URL +import kotlin.concurrent.thread + +class BulwarkFcmModule(reactContext: ReactApplicationContext) + : ReactContextBaseJavaModule(reactContext) { + + init { + synchronized(BulwarkFcmModule::class.java) { + currentInstance = this + } + BulwarkMessagingService.ensureChannel(reactContext) + } + + override fun getName(): String = "BulwarkFcm" + + @ReactMethod + fun getToken(promise: Promise) { + FirebaseMessaging.getInstance().token + .addOnSuccessListener { token -> promise.resolve(token) } + .addOnFailureListener { err -> promise.reject("fcm_token_failed", err) } + } + + @ReactMethod + fun deleteToken(promise: Promise) { + FirebaseMessaging.getInstance().deleteToken() + .addOnSuccessListener { promise.resolve(null) } + .addOnFailureListener { err -> promise.reject("fcm_delete_failed", err) } + } + + @ReactMethod + fun showNotification(options: ReadableMap, promise: Promise) { + val notificationId = options.getString("notificationId") + if (notificationId.isNullOrBlank()) { + promise.reject("bad_args", "notificationId is required") + return + } + val title = options.getString("title") ?: "New mail" + val body = options.getString("body") ?: "" + val initials = options.getString("initials") ?: "?" + val bgColorHex = options.getString("bgColorHex") ?: "#2563eb" + val iconUrl = options.takeIf { it.hasKey("iconUrl") }?.getString("iconUrl") + val emailId = options.getString("emailId") + val threadId = options.getString("threadId") + val subject = options.takeIf { it.hasKey("subject") }?.getString("subject") + + // Bitmap fetch + draw off the bridge thread so the caller doesn't + // block waiting for the favicon request. + thread(name = "bulwark-notification") { + val largeIcon = iconUrl?.let { fetchBitmap(it) } + ?: makeLetterAvatar(initials, bgColorHex) + postNotification( + notificationId, title, body, largeIcon, bgColorHex, + emailId, threadId, subject, + ) + promise.resolve(null) + } + } + + @ReactMethod + fun getInitialNotification(promise: Promise) { + val payload = NotificationTapStore.consume() + promise.resolve(payload?.toMap()) + } + + private fun postNotification( + notificationId: String, + title: String, + body: String, + largeIcon: Bitmap, + colorHex: String, + emailId: String?, + threadId: String?, + subject: String?, + ) { + val ctx = reactApplicationContext + val intent = Intent(ctx, MainActivity::class.java).apply { + flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP + if (emailId != null) putExtra(NotificationTapStore.EXTRA_EMAIL_ID, emailId) + if (threadId != null) putExtra(NotificationTapStore.EXTRA_THREAD_ID, threadId) + if (subject != null) putExtra(NotificationTapStore.EXTRA_SUBJECT, subject) + } + val pending = PendingIntent.getActivity( + ctx, + notificationId.hashCode(), + intent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + + val builder = NotificationCompat.Builder(ctx, BulwarkMessagingService.CHANNEL_ID) + .setSmallIcon(android.R.drawable.ic_dialog_email) + .setLargeIcon(largeIcon) + .setContentTitle(title) + .setContentText(body) + .setStyle(NotificationCompat.BigTextStyle().bigText(body)) + .setColor(parseColor(colorHex, fallback = Color.parseColor("#2563eb"))) + .setAutoCancel(true) + .setPriority(NotificationCompat.PRIORITY_HIGH) + .setContentIntent(pending) + + val manager = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + manager.notify(notificationId, notificationId.hashCode(), builder.build()) + } + + private fun makeLetterAvatar(initials: String, bgHex: String): Bitmap { + val size = 192 + val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) + val canvas = Canvas(bitmap) + val bgPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = parseColor(bgHex, fallback = Color.parseColor("#2563eb")) + } + canvas.drawCircle(size / 2f, size / 2f, size / 2f, bgPaint) + val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.WHITE + textSize = size * 0.44f + textAlign = Paint.Align.CENTER + typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) + } + val baseline = size / 2f - (textPaint.descent() + textPaint.ascent()) / 2f + canvas.drawText(initials.take(2).uppercase(), size / 2f, baseline, textPaint) + return bitmap + } + + private fun fetchBitmap(url: String): Bitmap? = try { + val conn = URL(url).openConnection() as HttpURLConnection + conn.connectTimeout = 3000 + conn.readTimeout = 3000 + conn.instanceFollowRedirects = true + conn.setRequestProperty("User-Agent", "bulwark-mobile") + conn.inputStream.use { BitmapFactory.decodeStream(it) } + } catch (_: Exception) { + null + } + + private fun parseColor(hex: String, fallback: Int): Int = try { + Color.parseColor(hex) + } catch (_: IllegalArgumentException) { + fallback + } + + // NativeEventEmitter required no-ops. + @ReactMethod + fun addListener(eventName: String) {} + + @ReactMethod + fun removeListeners(count: Int) {} + + companion object { + @Volatile private var currentInstance: BulwarkFcmModule? = null + + fun emit(eventName: String, params: WritableMap?) { + val module = currentInstance ?: return + val ctx = module.reactApplicationContext + if (!ctx.hasActiveReactInstance()) return + ctx.getJSModule(RCTDeviceEventEmitter::class.java).emit(eventName, params) + } + } +} diff --git a/android/app/src/main/java/com/anonymous/bulwarkmobile/BulwarkFcmPackage.kt b/android/app/src/main/java/com/anonymous/bulwarkmobile/BulwarkFcmPackage.kt new file mode 100644 index 00000000..4f6dba03 --- /dev/null +++ b/android/app/src/main/java/com/anonymous/bulwarkmobile/BulwarkFcmPackage.kt @@ -0,0 +1,14 @@ +package com.anonymous.bulwarkmobile + +import com.facebook.react.ReactPackage +import com.facebook.react.bridge.NativeModule +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.uimanager.ViewManager + +class BulwarkFcmPackage : ReactPackage { + override fun createNativeModules(reactContext: ReactApplicationContext): List = + listOf(BulwarkFcmModule(reactContext)) + + override fun createViewManagers(reactContext: ReactApplicationContext): List> = + emptyList() +} diff --git a/android/app/src/main/java/com/anonymous/bulwarkmobile/BulwarkMessagingService.kt b/android/app/src/main/java/com/anonymous/bulwarkmobile/BulwarkMessagingService.kt new file mode 100644 index 00000000..c05d0cf4 --- /dev/null +++ b/android/app/src/main/java/com/anonymous/bulwarkmobile/BulwarkMessagingService.kt @@ -0,0 +1,80 @@ +package com.anonymous.bulwarkmobile + +import android.app.ActivityManager +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.Bundle +import androidx.core.app.NotificationCompat +import com.facebook.react.HeadlessJsTaskService +import com.facebook.react.bridge.Arguments +import com.google.firebase.messaging.FirebaseMessagingService +import com.google.firebase.messaging.RemoteMessage + +class BulwarkMessagingService : FirebaseMessagingService() { + override fun onNewToken(token: String) { + val params = Arguments.createMap().apply { putString("token", token) } + BulwarkFcmModule.emit("fcm:newToken", params) + } + + override fun onMessageReceived(message: RemoteMessage) { + ensureChannel(this) + + val data = message.data + + // Hand off to JS via a headless task only when the app isn't already + // running in the foreground — HeadlessJsTaskContext throws if started + // while foreground. When the app is open, the main JS instance already + // receives JMAP push directly, so the fcm:message event below is + // sufficient for it to refresh state. + if (!isAppInForeground()) { + startHeadlessTask(data) + } + + val params = Arguments.createMap().apply { + val dataMap = Arguments.createMap() + for ((k, v) in data) dataMap.putString(k, v) + putMap("data", dataMap) + } + BulwarkFcmModule.emit("fcm:message", params) + } + + private fun isAppInForeground(): Boolean { + val info = ActivityManager.RunningAppProcessInfo() + ActivityManager.getMyMemoryState(info) + return info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND || + info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE + } + + private fun startHeadlessTask(data: Map) { + val intent = Intent(applicationContext, BulwarkPushTaskService::class.java) + val bundle = Bundle().apply { + for ((k, v) in data) putString(k, v) + } + intent.putExtras(bundle) + applicationContext.startService(intent) + HeadlessJsTaskService.acquireWakeLockNow(applicationContext) + } + + companion object { + const val CHANNEL_ID = "bulwark_mail" + + fun ensureChannel(context: Context) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return + val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + if (manager.getNotificationChannel(CHANNEL_ID) != null) return + val channel = NotificationChannel( + CHANNEL_ID, + "Mail notifications", + NotificationManager.IMPORTANCE_HIGH, + ).apply { + description = "Incoming email alerts" + enableVibration(true) + } + manager.createNotificationChannel(channel) + } + } +} diff --git a/android/app/src/main/java/com/anonymous/bulwarkmobile/BulwarkPushTaskService.kt b/android/app/src/main/java/com/anonymous/bulwarkmobile/BulwarkPushTaskService.kt new file mode 100644 index 00000000..c4b118e9 --- /dev/null +++ b/android/app/src/main/java/com/anonymous/bulwarkmobile/BulwarkPushTaskService.kt @@ -0,0 +1,18 @@ +package com.anonymous.bulwarkmobile + +import android.content.Intent +import com.facebook.react.bridge.Arguments +import com.facebook.react.jstasks.HeadlessJsTaskConfig +import com.facebook.react.HeadlessJsTaskService + +class BulwarkPushTaskService : HeadlessJsTaskService() { + override fun getTaskConfig(intent: Intent?): HeadlessJsTaskConfig? { + val extras = intent?.extras ?: return null + return HeadlessJsTaskConfig( + "BulwarkPushTask", + Arguments.fromBundle(extras), + 30000L, + false, + ) + } +} diff --git a/android/app/src/main/java/com/anonymous/bulwarkmobile/MainActivity.kt b/android/app/src/main/java/com/anonymous/bulwarkmobile/MainActivity.kt new file mode 100644 index 00000000..96f77647 --- /dev/null +++ b/android/app/src/main/java/com/anonymous/bulwarkmobile/MainActivity.kt @@ -0,0 +1,70 @@ +package com.anonymous.bulwarkmobile + +import android.content.Intent +import android.os.Build +import android.os.Bundle + +import com.facebook.react.ReactActivity +import com.facebook.react.ReactActivityDelegate +import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled +import com.facebook.react.defaults.DefaultReactActivityDelegate + +import expo.modules.ReactActivityDelegateWrapper + +class MainActivity : ReactActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + // Set the theme to AppTheme BEFORE onCreate to support + // coloring the background, status bar, and navigation bar. + // This is required for expo-splash-screen. + setTheme(R.style.AppTheme); + super.onCreate(null) + NotificationTapStore.captureFromIntent(intent) + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + val payload = NotificationTapStore.captureFromIntent(intent) ?: return + BulwarkFcmModule.emit("fcm:notificationTap", payload.toMap()) + } + + /** + * Returns the name of the main component registered from JavaScript. This is used to schedule + * rendering of the component. + */ + override fun getMainComponentName(): String = "main" + + /** + * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] + * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] + */ + override fun createReactActivityDelegate(): ReactActivityDelegate { + return ReactActivityDelegateWrapper( + this, + BuildConfig.IS_NEW_ARCHITECTURE_ENABLED, + object : DefaultReactActivityDelegate( + this, + mainComponentName, + fabricEnabled + ){}) + } + + /** + * Align the back button behavior with Android S + * where moving root activities to background instead of finishing activities. + * @see onBackPressed + */ + override fun invokeDefaultOnBackPressed() { + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) { + if (!moveTaskToBack(false)) { + // For non-root activities, use the default implementation to finish them. + super.invokeDefaultOnBackPressed() + } + return + } + + // Use the default back button implementation on Android S + // because it's doing more than [Activity.moveTaskToBack] in fact. + super.invokeDefaultOnBackPressed() + } +} diff --git a/android/app/src/main/java/com/anonymous/bulwarkmobile/MainApplication.kt b/android/app/src/main/java/com/anonymous/bulwarkmobile/MainApplication.kt new file mode 100644 index 00000000..7dc526bc --- /dev/null +++ b/android/app/src/main/java/com/anonymous/bulwarkmobile/MainApplication.kt @@ -0,0 +1,56 @@ +package com.anonymous.bulwarkmobile + +import android.app.Application +import android.content.res.Configuration + +import com.facebook.react.PackageList +import com.facebook.react.ReactApplication +import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative +import com.facebook.react.ReactNativeHost +import com.facebook.react.ReactPackage +import com.facebook.react.ReactHost +import com.facebook.react.common.ReleaseLevel +import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint +import com.facebook.react.defaults.DefaultReactNativeHost + +import expo.modules.ApplicationLifecycleDispatcher +import expo.modules.ReactNativeHostWrapper + +class MainApplication : Application(), ReactApplication { + + override val reactNativeHost: ReactNativeHost = ReactNativeHostWrapper( + this, + object : DefaultReactNativeHost(this) { + override fun getPackages(): MutableList { + val packages: MutableList = PackageList(this).packages + packages.add(BulwarkFcmPackage()) + return packages + } + + override fun getJSMainModuleName(): String = ".expo/.virtual-metro-entry" + + override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG + + override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED + } + ) + + override val reactHost: ReactHost + get() = ReactNativeHostWrapper.createReactHost(applicationContext, reactNativeHost) + + override fun onCreate() { + super.onCreate() + DefaultNewArchitectureEntryPoint.releaseLevel = try { + ReleaseLevel.valueOf(BuildConfig.REACT_NATIVE_RELEASE_LEVEL.uppercase()) + } catch (e: IllegalArgumentException) { + ReleaseLevel.STABLE + } + loadReactNative(this) + ApplicationLifecycleDispatcher.onApplicationCreate(this) + } + + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig) + } +} diff --git a/android/app/src/main/java/com/anonymous/bulwarkmobile/NotificationTapStore.kt b/android/app/src/main/java/com/anonymous/bulwarkmobile/NotificationTapStore.kt new file mode 100644 index 00000000..4efc4372 --- /dev/null +++ b/android/app/src/main/java/com/anonymous/bulwarkmobile/NotificationTapStore.kt @@ -0,0 +1,49 @@ +package com.anonymous.bulwarkmobile + +import android.content.Intent +import com.facebook.react.bridge.Arguments +import com.facebook.react.bridge.WritableMap + +// Process-wide holder for the most recent notification tap. MainActivity fills +// this on onCreate / onNewIntent; JS drains it via BulwarkFcm.getInitialNotification +// or reacts to the live "fcm:notificationTap" event. +object NotificationTapStore { + @Volatile + private var pending: TapPayload? = null + + fun consume(): TapPayload? { + val value = pending + pending = null + return value + } + + fun captureFromIntent(intent: Intent?): TapPayload? { + val extras = intent?.extras ?: return null + val emailId = extras.getString(EXTRA_EMAIL_ID) ?: return null + val threadId = extras.getString(EXTRA_THREAD_ID) ?: return null + val subject = extras.getString(EXTRA_SUBJECT) + val payload = TapPayload(emailId, threadId, subject) + pending = payload + // Clear so a subsequent activity lifecycle event doesn't replay this. + extras.remove(EXTRA_EMAIL_ID) + extras.remove(EXTRA_THREAD_ID) + extras.remove(EXTRA_SUBJECT) + return payload + } + + data class TapPayload( + val emailId: String, + val threadId: String, + val subject: String?, + ) { + fun toMap(): WritableMap = Arguments.createMap().apply { + putString("emailId", emailId) + putString("threadId", threadId) + if (subject != null) putString("subject", subject) + } + } + + const val EXTRA_EMAIL_ID = "bulwark.notification.emailId" + const val EXTRA_THREAD_ID = "bulwark.notification.threadId" + const val EXTRA_SUBJECT = "bulwark.notification.subject" +} diff --git a/android/app/src/main/res/drawable-hdpi/splashscreen_logo.png b/android/app/src/main/res/drawable-hdpi/splashscreen_logo.png new file mode 100644 index 00000000..9af6bd96 Binary files /dev/null and b/android/app/src/main/res/drawable-hdpi/splashscreen_logo.png differ diff --git a/android/app/src/main/res/drawable-mdpi/splashscreen_logo.png b/android/app/src/main/res/drawable-mdpi/splashscreen_logo.png new file mode 100644 index 00000000..88fad6a0 Binary files /dev/null and b/android/app/src/main/res/drawable-mdpi/splashscreen_logo.png differ diff --git a/android/app/src/main/res/drawable-xhdpi/splashscreen_logo.png b/android/app/src/main/res/drawable-xhdpi/splashscreen_logo.png new file mode 100644 index 00000000..5970e5f3 Binary files /dev/null and b/android/app/src/main/res/drawable-xhdpi/splashscreen_logo.png differ diff --git a/android/app/src/main/res/drawable-xxhdpi/splashscreen_logo.png b/android/app/src/main/res/drawable-xxhdpi/splashscreen_logo.png new file mode 100644 index 00000000..ab792ca5 Binary files /dev/null and b/android/app/src/main/res/drawable-xxhdpi/splashscreen_logo.png differ diff --git a/android/app/src/main/res/drawable-xxxhdpi/splashscreen_logo.png b/android/app/src/main/res/drawable-xxxhdpi/splashscreen_logo.png new file mode 100644 index 00000000..3e6321a8 Binary files /dev/null and b/android/app/src/main/res/drawable-xxxhdpi/splashscreen_logo.png differ diff --git a/android/app/src/main/res/drawable/ic_launcher_background.xml b/android/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 00000000..883b2a08 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/drawable/rn_edit_text_material.xml b/android/app/src/main/res/drawable/rn_edit_text_material.xml new file mode 100644 index 00000000..5c25e728 --- /dev/null +++ b/android/app/src/main/res/drawable/rn_edit_text_material.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 00000000..3941bea9 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 00000000..3941bea9 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 00000000..6a1ea921 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp b/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp new file mode 100644 index 00000000..e03a563e Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp differ diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 00000000..6a1ea921 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 00000000..1f78c2d8 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp b/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp new file mode 100644 index 00000000..c5968390 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 00000000..1f78c2d8 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 00000000..c7c47470 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp new file mode 100644 index 00000000..54c58844 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 00000000..c7c47470 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 00000000..55f5baa6 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp new file mode 100644 index 00000000..968dd171 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 00000000..55f5baa6 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 00000000..bc273aec Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp new file mode 100644 index 00000000..8ed62d71 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 00000000..bc273aec Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/values-night/colors.xml b/android/app/src/main/res/values-night/colors.xml new file mode 100644 index 00000000..3c05de5b --- /dev/null +++ b/android/app/src/main/res/values-night/colors.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 00000000..d1b8dedd --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + #09090b + #09090b + #023c69 + #09090b + \ No newline at end of file diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 00000000..f7c8e036 --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,5 @@ + + Bulwark Mobile + contain + false + \ No newline at end of file diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 00000000..ba943153 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,11 @@ + + + + \ No newline at end of file diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 00000000..85a68693 --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,25 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath('com.android.tools.build:gradle') + classpath('com.facebook.react:react-native-gradle-plugin') + classpath('org.jetbrains.kotlin:kotlin-gradle-plugin') + classpath('com.google.gms:google-services:4.4.2') + } +} + +allprojects { + repositories { + google() + mavenCentral() + maven { url 'https://www.jitpack.io' } + } +} + +apply plugin: "expo-root-project" +apply plugin: "com.facebook.react.rootproject" diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 00000000..8e39f82e --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,65 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx512m -XX:MaxMetaspaceSize=256m +org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +org.gradle.parallel=true + +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true + +# Enable AAPT2 PNG crunching +android.enablePngCrunchInReleaseBuilds=true + +# Use this property to specify which architecture you want to build. +# You can also override it from the CLI using +# ./gradlew -PreactNativeArchitectures=x86_64 +reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 + +# Use this property to enable support to the new architecture. +# This will allow you to use TurboModules and the Fabric render in +# your application. You should enable this flag either if you want +# to write custom TurboModules/Fabric components OR use libraries that +# are providing them. +newArchEnabled=true + +# Use this property to enable or disable the Hermes JS engine. +# If set to false, you will be using JSC instead. +hermesEnabled=true + +# Use this property to enable edge-to-edge display support. +# This allows your app to draw behind system bars for an immersive UI. +# Note: Only works with ReactActivity and should not be used with custom Activity. +edgeToEdgeEnabled=true + +# Enable GIF support in React Native images (~200 B increase) +expo.gif.enabled=true +# Enable webp support in React Native images (~85 KB increase) +expo.webp.enabled=true +# Enable animated webp support (~3.4 MB increase) +# Disabled by default because iOS doesn't support animated webp +expo.webp.animated=false + +# Enable network inspector +EX_DEV_CLIENT_NETWORK_INSPECTOR=true + +# Use legacy packaging to compress native libraries in the resulting APK. +expo.useLegacyPackaging=false + +# Specifies whether the app is configured to use edge-to-edge via the app config or plugin +# WARNING: This property has been deprecated and will be removed in Expo SDK 55. Use `edgeToEdgeEnabled` or `react.edgeToEdgeEnabled` to determine whether the project is using edge-to-edge. +expo.edgeToEdgeEnabled=true diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..1b33c55b Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..d4081da4 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100644 index 00000000..7f94d3d4 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 00000000..db3a6ac2 --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 00000000..77c911fc --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,39 @@ +pluginManagement { + def reactNativeGradlePlugin = new File( + providers.exec { + workingDir(rootDir) + commandLine("node", "--print", "require.resolve('@react-native/gradle-plugin/package.json', { paths: [require.resolve('react-native/package.json')] })") + }.standardOutput.asText.get().trim() + ).getParentFile().absolutePath + includeBuild(reactNativeGradlePlugin) + + def expoPluginsPath = new File( + providers.exec { + workingDir(rootDir) + commandLine("node", "--print", "require.resolve('expo-modules-autolinking/package.json', { paths: [require.resolve('expo/package.json')] })") + }.standardOutput.asText.get().trim(), + "../android/expo-gradle-plugin" + ).absolutePath + includeBuild(expoPluginsPath) +} + +plugins { + id("com.facebook.react.settings") + id("expo-autolinking-settings") +} + +extensions.configure(com.facebook.react.ReactSettingsExtension) { ex -> + if (System.getenv('EXPO_USE_COMMUNITY_AUTOLINKING') == '1') { + ex.autolinkLibrariesFromCommand() + } else { + ex.autolinkLibrariesFromCommand(expoAutolinking.rnConfigCommand) + } +} +expoAutolinking.useExpoModules() + +rootProject.name = 'bulwark-mobile' + +expoAutolinking.useExpoVersionCatalog() + +include ':app' +includeBuild(expoAutolinking.reactNativeGradlePlugin) diff --git a/app.json b/app.json index 44f15320..3e4e28b0 100644 --- a/app.json +++ b/app.json @@ -1,6 +1,6 @@ { "expo": { - "name": "bulwark-mobile", + "name": "Bulwark Mobile", "slug": "bulwark-mobile", "version": "1.0.0", "orientation": "portrait", diff --git a/assets/adaptive-icon.png b/assets/adaptive-icon.png index eae2bd51..18065877 100644 Binary files a/assets/adaptive-icon.png and b/assets/adaptive-icon.png differ diff --git a/assets/favicon.png b/assets/favicon.png index eae2bd51..c9244d56 100644 Binary files a/assets/favicon.png and b/assets/favicon.png differ diff --git a/assets/icon.png b/assets/icon.png index eae2bd51..c2ee6729 100644 Binary files a/assets/icon.png and b/assets/icon.png differ diff --git a/assets/splash-icon.png b/assets/splash-icon.png index 896d4967..a71e3103 100644 Binary files a/assets/splash-icon.png and b/assets/splash-icon.png differ diff --git a/index.ts b/index.ts index 1d6e981e..891003c2 100644 --- a/index.ts +++ b/index.ts @@ -1,6 +1,13 @@ +import { AppRegistry } from 'react-native'; import { registerRootComponent } from 'expo'; import App from './App'; +import { pushBackgroundTask } from './src/lib/push-background-task'; + +// Runs in a fresh headless JS runtime when BulwarkPushTaskService is started +// from BulwarkMessagingService on an FCM data message. Must be registered +// before the native service tries to invoke the task. +AppRegistry.registerHeadlessTask('BulwarkPushTask', () => pushBackgroundTask); // registerRootComponent calls AppRegistry.registerComponent('main', () => App); // It also ensures that whether you load the app in Expo Go or in a native build, diff --git a/package-lock.json b/package-lock.json index a9d27466..3c902deb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5189,6 +5189,20 @@ } } }, + "node_modules/expo-constants": { + "version": "18.0.13", + "resolved": "https://registry.npmjs.org/expo-constants/-/expo-constants-18.0.13.tgz", + "integrity": "sha512-FnZn12E1dRYKDHlAdIyNFhBurKTS3F9CrfrBDJI5m3D7U17KBHMQ6JEfYlSj7LG7t+Ulr+IKaj58L1k5gBwTcQ==", + "license": "MIT", + "dependencies": { + "@expo/config": "~12.0.13", + "@expo/env": "~2.0.8" + }, + "peerDependencies": { + "expo": "*", + "react-native": "*" + } + }, "node_modules/expo-file-system": { "version": "19.0.21", "resolved": "https://registry.npmjs.org/expo-file-system/-/expo-file-system-19.0.21.tgz", @@ -5651,20 +5665,6 @@ "react-native": "*" } }, - "node_modules/expo/node_modules/expo-constants": { - "version": "18.0.13", - "resolved": "https://registry.npmjs.org/expo-constants/-/expo-constants-18.0.13.tgz", - "integrity": "sha512-FnZn12E1dRYKDHlAdIyNFhBurKTS3F9CrfrBDJI5m3D7U17KBHMQ6JEfYlSj7LG7t+Ulr+IKaj58L1k5gBwTcQ==", - "license": "MIT", - "dependencies": { - "@expo/config": "~12.0.13", - "@expo/env": "~2.0.8" - }, - "peerDependencies": { - "expo": "*", - "react-native": "*" - } - }, "node_modules/expo/node_modules/expo-font": { "version": "14.0.11", "resolved": "https://registry.npmjs.org/expo-font/-/expo-font-14.0.11.tgz", diff --git a/scripts/poll-reload.mjs b/scripts/poll-reload.mjs new file mode 100644 index 00000000..96fffbd0 --- /dev/null +++ b/scripts/poll-reload.mjs @@ -0,0 +1,48 @@ +import { readdir, stat } from 'node:fs/promises'; +import { watchFile } from 'node:fs'; +import { join, extname } from 'node:path'; + +const ROOTS = ['src', 'App.tsx', 'index.ts', 'app.json']; +const EXTS = new Set(['.ts', '.tsx', '.js', '.jsx', '.json']); +const INTERVAL = 500; +const METRO = 'http://localhost:8081/reload'; + +async function* walk(p) { + const s = await stat(p).catch(() => null); + if (!s) return; + if (s.isFile()) { yield p; return; } + for (const e of await readdir(p, { withFileTypes: true })) { + const f = join(p, e.name); + if (e.isDirectory()) { + if (e.name === 'node_modules' || e.name.startsWith('.')) continue; + yield* walk(f); + } else if (e.isFile() && EXTS.has(extname(e.name))) { + yield f; + } + } +} + +let pending = false; +async function reload(file) { + if (pending) return; + pending = true; + try { + console.log(`change: ${file}`); + const r = await fetch(METRO, { method: 'GET' }); + console.log(`reload -> ${r.status}`); + } catch (e) { + console.log(`reload failed: ${e.message}`); + } + setTimeout(() => { pending = false; }, 500); +} + +const files = []; +for (const r of ROOTS) { + for await (const f of walk(r)) files.push(f); +} +console.log(`watching ${files.length} files (poll ${INTERVAL}ms)`); +for (const f of files) { + watchFile(f, { interval: INTERVAL }, (curr, prev) => { + if (curr.mtimeMs !== prev.mtimeMs) reload(f); + }); +} diff --git a/src/api/email.ts b/src/api/email.ts index 65bdb7c5..fa40d9a3 100644 --- a/src/api/email.ts +++ b/src/api/email.ts @@ -1,6 +1,7 @@ import { jmapClient } from './jmap-client'; import { CAPABILITIES } from './types'; import type { Email, EmailAddress, Mailbox, Thread } from './types'; +import { toWildcardQuery } from '../lib/search-utils'; const EMAIL_LIST_PROPERTIES = [ 'id', 'threadId', 'mailboxIds', 'keywords', 'size', @@ -131,7 +132,7 @@ export async function searchEmails( limit = 30, ): Promise { const accountId = jmapClient.accountId; - const filter: Record = { text: query }; + const filter: Record = { text: toWildcardQuery(query) }; if (mailboxId) filter.inMailbox = mailboxId; const res = await jmapClient.request([ @@ -145,6 +146,24 @@ export async function searchEmails( return res.methodResponses[0][1].ids; } +// Cross-mailbox query with an arbitrary JMAP filter (used by contact activity +// to search "from OR to " without picking a specific mailbox). +export async function queryEmailsByFilter( + filter: Record, + limit = 5, +): Promise { + const accountId = jmapClient.accountId; + const res = await jmapClient.request([ + ['Email/query', { + accountId, + filter, + sort: [{ property: 'receivedAt', isAscending: false }], + limit, + }, '0'], + ]); + return res.methodResponses[0][1].ids; +} + export async function sendEmail( email: { from: EmailAddress[]; diff --git a/src/api/push.ts b/src/api/push.ts index 14ddd3c3..396aeaa4 100644 --- a/src/api/push.ts +++ b/src/api/push.ts @@ -1,9 +1,92 @@ import { jmapClient } from './jmap-client'; import { CAPABILITIES } from './types'; -import type { StateChange } from './types'; +import type { PushSubscription, StateChange } from './types'; export type StateChangeHandler = (change: StateChange) => void; +// ─── PushSubscription (RFC 8620 §7.2) ─────────────────── + +export async function listPushSubscriptions(): Promise { + const res = await jmapClient.request( + [['PushSubscription/get', { ids: null }, '0']], + [CAPABILITIES.CORE], + ); + const [, body] = res.methodResponses[0] ?? []; + return (body?.list as PushSubscription[]) ?? []; +} + +/** + * Create a PushSubscription pointing the JMAP server at the given relay URL. + * Returns the server-assigned id (which the client also registers with the + * relay so the relay can route incoming pushes to an Expo token). + */ +export async function createPushSubscription(params: { + deviceClientId: string; + url: string; + types: string[]; +}): Promise { + const res = await jmapClient.request( + [ + [ + 'PushSubscription/set', + { + create: { + new: { + deviceClientId: params.deviceClientId, + url: params.url, + types: params.types, + }, + }, + }, + '0', + ], + ], + [CAPABILITIES.CORE], + ); + const [, body] = res.methodResponses[0] ?? []; + const created = body?.created?.new as { id?: string } | undefined; + if (!created?.id) { + const notCreated = body?.notCreated?.new; + throw new Error( + `PushSubscription/set create failed: ${JSON.stringify(notCreated ?? body)}`, + ); + } + return created.id; +} + +/** + * Send the verification code back to the server — the call that flips the + * subscription from pending to active (RFC 8620 §7.2.2). + */ +export async function verifyPushSubscription( + id: string, + verificationCode: string, +): Promise { + const res = await jmapClient.request( + [ + [ + 'PushSubscription/set', + { update: { [id]: { verificationCode } } }, + '0', + ], + ], + [CAPABILITIES.CORE], + ); + const [, body] = res.methodResponses[0] ?? []; + if (body?.notUpdated?.[id]) { + throw new Error( + `PushSubscription verification failed: ${JSON.stringify(body.notUpdated[id])}`, + ); + } +} + +export async function destroyPushSubscription(id: string): Promise { + await jmapClient.request( + [['PushSubscription/set', { destroy: [id] }, '0']], + [CAPABILITIES.CORE], + ); +} + /** * Connect to the JMAP EventSource (SSE) endpoint for real-time push updates. * Returns a cleanup function to close the connection. diff --git a/src/api/types.ts b/src/api/types.ts index 272dac14..fa9f6c97 100644 --- a/src/api/types.ts +++ b/src/api/types.ts @@ -418,6 +418,18 @@ export interface StateChange { changed: Record>; } +// RFC 8620 §7.2. A PushSubscription is session-scoped (not per-account) and +// tells the server where to deliver StateChange events for the listed types. +export interface PushSubscription { + id: string; + deviceClientId: string; + url: string; + keys?: { p256dh: string; auth: string } | null; + verificationCode?: string | null; + expires?: string | null; + types?: string[] | null; +} + // ─── Capability URNs ──────────────────────────────────── export const CAPABILITIES = { diff --git a/src/api/vacation.ts b/src/api/vacation.ts new file mode 100644 index 00000000..1aba8a3b --- /dev/null +++ b/src/api/vacation.ts @@ -0,0 +1,67 @@ +import { jmapClient } from './jmap-client'; +import { CAPABILITIES } from './types'; + +export interface VacationResponse { + id: string; + isEnabled: boolean; + fromDate: string | null; + toDate: string | null; + subject: string; + textBody: string; + htmlBody: string | null; +} + +const VACATION_USING = [CAPABILITIES.CORE, CAPABILITIES.MAIL, CAPABILITIES.VACATION]; + +const DEFAULT: VacationResponse = { + id: 'singleton', + isEnabled: false, + fromDate: null, + toDate: null, + subject: '', + textBody: '', + htmlBody: null, +}; + +export async function getVacationResponse(): Promise { + const accountId = jmapClient.accountId; + const res = await jmapClient.request( + [['VacationResponse/get', { accountId, ids: ['singleton'] }, '0']], + VACATION_USING, + ); + const resp = res.methodResponses?.[0]; + if (resp && resp[0] === 'VacationResponse/get') { + const list = (resp[1] as { list?: VacationResponse[] }).list ?? []; + return list[0] ?? DEFAULT; + } + throw new Error('Unexpected response from VacationResponse/get'); +} + +export async function setVacationResponse( + updates: Partial>, +): Promise { + const accountId = jmapClient.accountId; + const res = await jmapClient.request( + [['VacationResponse/set', { + accountId, + update: { singleton: updates }, + }, '0']], + VACATION_USING, + ); + const resp = res.methodResponses?.[0]; + if (resp && resp[0] === 'VacationResponse/set') { + const result = resp[1] as { notUpdated?: Record }; + if (result.notUpdated?.singleton) { + throw new Error(result.notUpdated.singleton.description ?? 'Failed to update vacation responder'); + } + return; + } + throw new Error('Unexpected response from VacationResponse/set'); +} + +export function isVacationSupported(): boolean { + const session = jmapClient.currentSession; + if (!session) return false; + const caps = session.capabilities ?? {}; + return CAPABILITIES.VACATION in caps; +} diff --git a/src/components/calendar/AgendaView.tsx b/src/components/calendar/AgendaView.tsx index 80b1c018..c59f5788 100644 --- a/src/components/calendar/AgendaView.tsx +++ b/src/components/calendar/AgendaView.tsx @@ -54,9 +54,17 @@ export function AgendaView({ for (let i = 0; i < daysAhead; i++) { const day = new Date(start); day.setDate(start.getDate() + i); - const dayEvents = eventsOnDayFromIndex(index, day).slice().sort( - (a, b) => getEventStartDate(a).getTime() - getEventStartDate(b).getTime(), - ); + const dayEvents = eventsOnDayFromIndex(index, day).slice().sort((a, b) => { + // All-day events first within a day, then by start time, then title + // (stable tie-break) — mirrors the comparator the webmail uses for + // packing week segments and keeps multi-event days predictable. + if (a.showWithoutTime !== b.showWithoutTime) { + return a.showWithoutTime ? -1 : 1; + } + const diff = getEventStartDate(a).getTime() - getEventStartDate(b).getTime(); + if (diff !== 0) return diff; + return (a.title || '').localeCompare(b.title || ''); + }); if (dayEvents.length === 0 && !isToday(day)) continue; result.push({ title: formatDayHeader(day), diff --git a/src/components/calendar/WeekView.tsx b/src/components/calendar/WeekView.tsx index 954a975b..47484379 100644 --- a/src/components/calendar/WeekView.tsx +++ b/src/components/calendar/WeekView.tsx @@ -11,9 +11,14 @@ import type { Calendar, CalendarEvent } from '../../api/types'; import { colors, radius, spacing, typography } from '../../theme/tokens'; import { buildEventDayIndex, + buildTimedFullDayWeekSegments, + buildWeekSegmentsRaw, eventsOnDayFromIndex, getEventColor, + isTimedEventFullDayOnDate, layoutOverlappingEvents, + packWeekSegments, + type CalendarWeekSegment, type EventDayIndex, } from '../../lib/calendar-utils'; @@ -56,25 +61,38 @@ export function WeekView({ return Array.from({ length: 7 }, (_, i) => addDays(start, i)); }, [selectedDate, weekStartsOn]); - const allDayByDay = React.useMemo(() => { - return weekDays.map((day) => - eventsOnDayFromIndex(index, day).filter((e) => e.showWithoutTime), + // Multi-day all-day events render as one bar across the days they span. + // Timed events that consume the entire day get promoted to this strip too. + const allDaySegments = React.useMemo(() => { + const explicit = buildWeekSegmentsRaw( + events.filter((e) => e.showWithoutTime), + weekDays, ); - }, [weekDays, index]); + const timedFull = buildTimedFullDayWeekSegments( + events.filter((e) => !e.showWithoutTime), + weekDays, + ); + return packWeekSegments([...explicit, ...timedFull]); + }, [events, weekDays]); const allDayRowCount = React.useMemo(() => { - return allDayByDay.reduce((max, list) => Math.max(max, list.length), 0); - }, [allDayByDay]); + return allDaySegments.reduce((max, s) => Math.max(max, s.row + 1), 0); + }, [allDaySegments]); const allDayStripHeight = allDayRowCount > 0 ? allDayRowCount * (ALL_DAY_CHIP_HEIGHT + ALL_DAY_GAP) + spacing.xs : 0; + // Timed grid excludes events that fill the full day on that day — they're + // already promoted to the all-day strip above. const layoutsByDay = React.useMemo(() => { - return weekDays.map((day) => - layoutOverlappingEvents(eventsOnDayFromIndex(index, day), day), - ); + return weekDays.map((day) => { + const dayEvents = eventsOnDayFromIndex(index, day).filter( + (e) => !e.showWithoutTime && !isTimedEventFullDayOnDate(e, day), + ); + return layoutOverlappingEvents(dayEvents, day); + }); }, [weekDays, index]); const [nowMinutes, setNowMinutes] = React.useState(() => { @@ -148,25 +166,45 @@ export function WeekView({ all-day - {allDayByDay.map((dayEvents, idx) => ( - - {dayEvents.map((event) => ( + {/* Empty per-day columns to draw vertical separators */} + {weekDays.map((day) => ( + + ))} + {/* Segments overlay — multi-day events span their date range */} + + {allDaySegments.map((segment) => { + const color = getEventColor(segment.event, calendars); + const leftPct = (segment.startIndex / weekDays.length) * 100; + const widthPct = (segment.span / weekDays.length) * 100; + return ( onSelectEvent?.(segment.event)} style={[ styles.allDayChip, - { backgroundColor: getEventColor(event, calendars) + '33' }, - { borderLeftColor: getEventColor(event, calendars) }, + { + position: 'absolute', + left: `${leftPct}%`, + width: `${widthPct}%`, + top: segment.row * (ALL_DAY_CHIP_HEIGHT + ALL_DAY_GAP), + backgroundColor: color + '33', + borderLeftColor: color, + borderTopLeftRadius: segment.continuesBefore ? 0 : radius.xs, + borderBottomLeftRadius: segment.continuesBefore ? 0 : radius.xs, + borderTopRightRadius: segment.continuesAfter ? 0 : radius.xs, + borderBottomRightRadius: segment.continuesAfter ? 0 : radius.xs, + marginHorizontal: 1, + }, ]} - onPress={() => onSelectEvent?.(event)} > - {event.title || 'Untitled'} + {segment.continuesBefore ? '… ' : ''} + {segment.event.title || 'Untitled'} - ))} - - ))} + ); + })} + )} @@ -316,11 +354,18 @@ const styles = StyleSheet.create({ }, allDayLabelWrap: { alignItems: 'flex-end', justifyContent: 'flex-start', paddingRight: 4 }, allDayLabel: { ...typography.small, color: colors.textMuted }, - allDayGrid: { flex: 1, flexDirection: 'row' }, + allDayGrid: { flex: 1, flexDirection: 'row', position: 'relative' }, allDayCol: { flex: 1, - paddingHorizontal: 1, - gap: ALL_DAY_GAP, + borderLeftWidth: 1, + borderLeftColor: colors.borderLight, + }, + allDayOverlay: { + position: 'absolute', + left: 0, + right: 0, + top: 0, + bottom: 0, }, allDayChip: { height: ALL_DAY_CHIP_HEIGHT, diff --git a/src/components/contacts/ContactActivity.tsx b/src/components/contacts/ContactActivity.tsx new file mode 100644 index 00000000..294a771c --- /dev/null +++ b/src/components/contacts/ContactActivity.tsx @@ -0,0 +1,258 @@ +import React from 'react'; +import { ActivityIndicator, Pressable, StyleSheet, Text, View } from 'react-native'; +import { useNavigation } from '@react-navigation/native'; +import type { NativeStackNavigationProp } from '@react-navigation/native-stack'; +import { Mail as MailIcon, CalendarDays } from 'lucide-react-native'; +import { format, isAfter, parseISO } from 'date-fns'; +import type { ContactCard, Email, CalendarEvent } from '../../api/types'; +import type { RootStackParamList } from '../../navigation/types'; +import { getEmails, queryEmailsByFilter } from '../../api/email'; +import { useCalendarStore } from '../../stores/calendar-store'; +import SenderAvatar from '../SenderAvatar'; +import { colors, radius, spacing, typography } from '../../theme/tokens'; + +const EMAIL_LIMIT = 5; +const EVENT_LIMIT = 5; + +type Nav = NativeStackNavigationProp; + +function getContactEmails(contact: ContactCard): string[] { + if (!contact.emails) return []; + const seen = new Set(); + const out: string[] = []; + for (const e of Object.values(contact.emails)) { + const addr = e.address?.trim().toLowerCase(); + if (addr && !seen.has(addr)) { + seen.add(addr); + out.push(addr); + } + } + return out; +} + +function buildEmailFilter(addresses: string[]): Record { + const conditions: Record[] = []; + for (const addr of addresses) { + conditions.push({ from: addr }); + conditions.push({ to: addr }); + } + if (conditions.length === 1) return conditions[0]; + return { operator: 'OR', conditions }; +} + +function eventInvolvesContact(event: CalendarEvent, addresses: Set): boolean { + if (event.participants) { + for (const p of Object.values(event.participants)) { + const addr = p.email?.trim().toLowerCase(); + if (addr && addresses.has(addr)) return true; + if (p.sendTo) { + for (const target of Object.values(p.sendTo)) { + const m = typeof target === 'string' ? target.match(/mailto:(.+)/i) : null; + if (m && addresses.has(m[1].trim().toLowerCase())) return true; + } + } + } + } + return false; +} + +function formatRelativeDate(iso: string): string { + try { + const d = parseISO(iso); + const now = new Date(); + return d.getFullYear() === now.getFullYear() + ? format(d, 'MMM d') + : format(d, 'MMM d, yyyy'); + } catch { + return ''; + } +} + +function formatEventTime(event: CalendarEvent): string { + if (event.showWithoutTime) return 'All day'; + try { + return format(parseISO(event.start), 'HH:mm'); + } catch { + return ''; + } +} + +interface Props { + contact: ContactCard; +} + +export function ContactActivity({ contact }: Props) { + const navigation = useNavigation