Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a8cc22ff9 | ||
|
|
72c933ca61 | ||
|
|
68d834cd72 | ||
|
|
e6adb35e5b | ||
|
|
d03e9493f0 | ||
|
|
dc01018105 | ||
|
|
8efd06d2b5 | ||
|
|
ac6321aa3e | ||
|
|
e54429fa3b | ||
|
|
47f6e5a890 | ||
|
|
dd89b87aea | ||
|
|
d47e42401c | ||
|
|
39511a3224 | ||
|
|
1b7bbe4b8a | ||
|
|
00c221a805 | ||
|
|
b37189e798 | ||
|
|
4b3c1042fc | ||
|
|
2856d1f107 | ||
|
|
6ed5417ba1 | ||
|
|
43212d3cdc | ||
|
|
ff3bcd91f1 | ||
|
|
7a1ff2e11d | ||
|
|
d0802e96d9 | ||
|
|
04caae7725 | ||
|
|
230418ca76 | ||
|
|
0270e46f4b | ||
|
|
a4593f723b | ||
|
|
58926a4a05 | ||
|
|
a831c0612b | ||
|
|
04798614fb | ||
|
|
fc12cb3467 | ||
|
|
d00ea1e80b | ||
|
|
0867048106 | ||
|
|
6d90f5f716 | ||
|
|
beb5442a9a | ||
|
|
58725ea57f | ||
|
|
e68d348355 | ||
|
|
eb8cea132e | ||
|
|
5da90f708d | ||
|
|
492c93400c | ||
|
|
2fa800e4d6 | ||
|
|
e817b4e608 | ||
|
|
b1b2d916fe | ||
|
|
28430b6f2e | ||
|
|
0bbc371603 | ||
|
|
aa86414532 | ||
|
|
83c42d7985 | ||
|
|
898e674160 | ||
|
|
0133505baf | ||
|
|
0ca65c5a13 | ||
|
|
ec2c7634bb |
@@ -9,6 +9,10 @@ on:
|
|||||||
- 'v*'
|
- 'v*'
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: build
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
increment-version:
|
increment-version:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -75,6 +79,13 @@ jobs:
|
|||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '22'
|
node-version: '22'
|
||||||
|
|
||||||
|
- name: Cache npm packages
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ~/.npm
|
||||||
|
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json', 'cinny/package-lock.json') }}
|
||||||
|
restore-keys: ${{ runner.os }}-npm-
|
||||||
|
|
||||||
- name: Setup Java
|
- name: Setup Java
|
||||||
uses: actions/setup-java@v4
|
uses: actions/setup-java@v4
|
||||||
@@ -83,7 +94,19 @@ jobs:
|
|||||||
java-version: '21'
|
java-version: '21'
|
||||||
|
|
||||||
- name: Setup Android SDK
|
- name: Setup Android SDK
|
||||||
uses: android-actions/setup-android@v3
|
uses: android-actions/setup-android@v4
|
||||||
|
with:
|
||||||
|
# Google removed the legacy `tools` package; v3 still tries to install it.
|
||||||
|
packages: platform-tools
|
||||||
|
|
||||||
|
- name: Cache Gradle
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.gradle/caches
|
||||||
|
~/.gradle/wrapper/dists
|
||||||
|
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
|
||||||
|
restore-keys: ${{ runner.os }}-gradle-
|
||||||
|
|
||||||
- name: Install dependencies (root)
|
- name: Install dependencies (root)
|
||||||
run: npm ci --prefer-offline
|
run: npm ci --prefer-offline
|
||||||
|
|||||||
@@ -62,23 +62,36 @@
|
|||||||
|
|
||||||
<service
|
<service
|
||||||
android:name=".MatrixSyncService"
|
android:name=".MatrixSyncService"
|
||||||
android:foregroundServiceType="dataSync"
|
android:process=":listener"
|
||||||
|
android:foregroundServiceType="specialUse|dataSync"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:stopWithTask="false" />
|
android:stopWithTask="false">
|
||||||
|
<property
|
||||||
<service
|
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||||
android:name=".UnifiedPushService"
|
android:value="matrix_message_listener" />
|
||||||
android:exported="false">
|
|
||||||
<intent-filter>
|
|
||||||
<action android:name="org.unifiedpush.android.connector.PUSH_EVENT" />
|
|
||||||
</intent-filter>
|
|
||||||
</service>
|
</service>
|
||||||
|
|
||||||
<receiver
|
<receiver
|
||||||
android:name=".BootReceiver"
|
android:name=".BootReceiver"
|
||||||
android:exported="true">
|
android:exported="true"
|
||||||
|
android:enabled="true">
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||||
|
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
|
||||||
|
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
|
||||||
|
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
|
||||||
|
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
|
||||||
|
</intent-filter>
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".ListenerWatchdogReceiver"
|
||||||
|
android:process=":listener"
|
||||||
|
android:exported="false"
|
||||||
|
android:enabled="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="com.paarrot.app.LISTENER_WATCHDOG" />
|
||||||
|
<action android:name="com.paarrot.app.LISTENER_RESTART" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</receiver>
|
</receiver>
|
||||||
</application>
|
</application>
|
||||||
@@ -86,31 +99,18 @@
|
|||||||
<!-- Permissions -->
|
<!-- Permissions -->
|
||||||
|
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||||
|
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
<uses-permission android:name="android.permission.VIBRATE" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||||
|
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
|
||||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||||
<uses-permission android:name="android.permission.CAMERA" />
|
<uses-permission android:name="android.permission.CAMERA" />
|
||||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||||
<uses-permission android:name="android.permission.BLUETOOTH" />
|
<uses-permission android:name="android.permission.BLUETOOTH" />
|
||||||
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
|
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
|
||||||
|
|
||||||
<!-- Android 11+ package visibility for UnifiedPush distributors (ntfy, etc.) -->
|
|
||||||
<queries>
|
|
||||||
<intent>
|
|
||||||
<action android:name="org.unifiedpush.android.distributor.REGISTER" />
|
|
||||||
</intent>
|
|
||||||
<intent>
|
|
||||||
<action android:name="org.unifiedpush.android.distributor.UNREGISTER" />
|
|
||||||
</intent>
|
|
||||||
<intent>
|
|
||||||
<action android:name="org.unifiedpush.android.distributor.LINK" />
|
|
||||||
</intent>
|
|
||||||
<intent>
|
|
||||||
<action android:name="android.intent.action.VIEW" />
|
|
||||||
<data android:scheme="unifiedpush" />
|
|
||||||
</intent>
|
|
||||||
<package android:name="io.heckel.ntfy" />
|
|
||||||
</queries>
|
|
||||||
</manifest>
|
</manifest>
|
||||||
|
|||||||
@@ -5,17 +5,23 @@ import android.content.Context
|
|||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Re-registers UnifiedPush after boot when credentials still exist.
|
* Starts the message listener again after boot / update when credentials still exist.
|
||||||
*/
|
*/
|
||||||
class BootReceiver : BroadcastReceiver() {
|
class BootReceiver : BroadcastReceiver() {
|
||||||
|
|
||||||
override fun onReceive(context: Context, intent: Intent) {
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
if (intent.action != Intent.ACTION_BOOT_COMPLETED) return
|
val action = intent.action ?: return
|
||||||
|
when (action) {
|
||||||
val prefs = context.getSharedPreferences(SyncServicePlugin.PREFS, Context.MODE_PRIVATE)
|
Intent.ACTION_BOOT_COMPLETED,
|
||||||
prefs.getString(MatrixSyncService.EXTRA_HOMESERVER, null) ?: return
|
Intent.ACTION_LOCKED_BOOT_COMPLETED,
|
||||||
prefs.getString(MatrixSyncService.EXTRA_TOKEN, null) ?: return
|
Intent.ACTION_MY_PACKAGE_REPLACED,
|
||||||
|
"android.intent.action.QUICKBOOT_POWERON",
|
||||||
UnifiedPushManager.register(context, activity = null)
|
"com.htc.intent.action.QUICKBOOT_POWERON",
|
||||||
|
-> {
|
||||||
|
if (!MatrixSyncService.hasCredentials(context)) return
|
||||||
|
MatrixSyncService.scheduleKeepAlive(context)
|
||||||
|
MatrixSyncService.requestSyncFetch(context, "boot:$action")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package com.paarrot.app
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.util.Log
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keeps the Matrix message listener alive after OEM kills, idle, or package update.
|
||||||
|
* Each fire re-chains the next one-shot watchdog alarm.
|
||||||
|
*
|
||||||
|
* Health is the persisted sync heartbeat (works across UI vs `:listener` processes).
|
||||||
|
*/
|
||||||
|
class ListenerWatchdogReceiver : BroadcastReceiver() {
|
||||||
|
|
||||||
|
override fun onReceive(context: Context, intent: Intent?) {
|
||||||
|
val action = intent?.action ?: ACTION_WATCHDOG
|
||||||
|
val healthy = MatrixSyncService.isListenerHealthy(context)
|
||||||
|
val ageMs = MatrixSyncService.heartbeatAgeMs(context)
|
||||||
|
val inProc = MatrixSyncService.isListenerRunning()
|
||||||
|
Log.i(
|
||||||
|
TAG,
|
||||||
|
"watchdog fired action=$action healthy=$healthy heartbeatAgeMs=$ageMs inProcAlive=$inProc",
|
||||||
|
)
|
||||||
|
if (!MatrixSyncService.hasCredentials(context)) {
|
||||||
|
Log.w(TAG, "watchdog skip — no credentials")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Always re-arm the chain first — even if start fails under OEM limits.
|
||||||
|
MatrixSyncService.scheduleKeepAlive(context)
|
||||||
|
val needsRestart = action == ACTION_RESTART || !healthy
|
||||||
|
if (needsRestart) {
|
||||||
|
Log.w(TAG, "watchdog restarting reason=${if (action == ACTION_RESTART) "explicit" else "stale-or-missing-heartbeat"}")
|
||||||
|
MatrixSyncService.requestSyncFetch(context, "watchdog:$action")
|
||||||
|
} else {
|
||||||
|
Log.i(TAG, "watchdog ok — listener healthy, no restart")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "PaarrotWatchdog"
|
||||||
|
const val ACTION_WATCHDOG = "com.paarrot.app.LISTENER_WATCHDOG"
|
||||||
|
const val ACTION_RESTART = "com.paarrot.app.LISTENER_RESTART"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,18 @@
|
|||||||
package com.paarrot.app;
|
package com.paarrot.app;
|
||||||
|
|
||||||
|
import android.Manifest;
|
||||||
|
import android.content.pm.PackageManager;
|
||||||
|
import android.os.Build;
|
||||||
import android.os.Bundle;
|
import android.os.Bundle;
|
||||||
import android.webkit.WebView;
|
import android.webkit.WebView;
|
||||||
|
import androidx.core.app.ActivityCompat;
|
||||||
|
import androidx.core.content.ContextCompat;
|
||||||
import androidx.core.view.ViewCompat;
|
import androidx.core.view.ViewCompat;
|
||||||
import com.getcapacitor.BridgeActivity;
|
import com.getcapacitor.BridgeActivity;
|
||||||
|
|
||||||
public class MainActivity extends BridgeActivity {
|
public class MainActivity extends BridgeActivity {
|
||||||
|
private boolean askedNotifications = false;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void onCreate(Bundle savedInstanceState) {
|
protected void onCreate(Bundle savedInstanceState) {
|
||||||
registerPlugin(SyncServicePlugin.class);
|
registerPlugin(SyncServicePlugin.class);
|
||||||
@@ -13,18 +20,47 @@ public class MainActivity extends BridgeActivity {
|
|||||||
registerPlugin(PluginStoragePlugin.class);
|
registerPlugin(PluginStoragePlugin.class);
|
||||||
super.onCreate(savedInstanceState);
|
super.onCreate(savedInstanceState);
|
||||||
setupImageKeyboardSupport();
|
setupImageKeyboardSupport();
|
||||||
|
ensureListener();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onResume() {
|
public void onResume() {
|
||||||
super.onResume();
|
super.onResume();
|
||||||
// Keep native sync suppression in sync with the real Activity lifecycle.
|
MatrixSyncService.setAppInForeground(this, true);
|
||||||
MatrixSyncService.appInForeground = true;
|
ensureListener();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
|
||||||
|
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
|
||||||
|
if (requestCode == REQUEST_NOTIFICATIONS
|
||||||
|
&& grantResults.length > 0
|
||||||
|
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
|
||||||
|
MatrixSyncService.requestSyncFetch(this, MatrixSyncService.MODE_LISTENER);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keep the foreground listener up once this phone has a saved login. */
|
||||||
|
private void ensureListener() {
|
||||||
|
if (Build.VERSION.SDK_INT >= 33
|
||||||
|
&& ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
|
||||||
|
!= PackageManager.PERMISSION_GRANTED) {
|
||||||
|
if (!askedNotifications) {
|
||||||
|
askedNotifications = true;
|
||||||
|
ActivityCompat.requestPermissions(
|
||||||
|
this,
|
||||||
|
new String[] {Manifest.permission.POST_NOTIFICATIONS},
|
||||||
|
REQUEST_NOTIFICATIONS
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
MatrixSyncService.requestSyncFetch(this, MatrixSyncService.MODE_LISTENER);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onPause() {
|
public void onPause() {
|
||||||
MatrixSyncService.appInForeground = false;
|
MatrixSyncService.setAppInForeground(this, false);
|
||||||
super.onPause();
|
super.onPause();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,4 +75,6 @@ public class MainActivity extends BridgeActivity {
|
|||||||
new ImageKeyboardContentReceiver()
|
new ImageKeyboardContentReceiver()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static final int REQUEST_NOTIFICATIONS = 4101;
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,16 @@
|
|||||||
package com.paarrot.app
|
package com.paarrot.app
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.app.Activity
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.PowerManager
|
||||||
|
import android.provider.Settings
|
||||||
|
import androidx.core.app.ActivityCompat
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
import com.getcapacitor.JSObject
|
import com.getcapacitor.JSObject
|
||||||
import com.getcapacitor.Plugin
|
import com.getcapacitor.Plugin
|
||||||
import com.getcapacitor.PluginCall
|
import com.getcapacitor.PluginCall
|
||||||
@@ -12,13 +21,12 @@ import com.getcapacitor.annotation.CapacitorPlugin
|
|||||||
* Capacitor plugin that controls [MatrixSyncService] from JS.
|
* Capacitor plugin that controls [MatrixSyncService] from JS.
|
||||||
*
|
*
|
||||||
* JS API:
|
* JS API:
|
||||||
* - `start({ homeserverUrl, accessToken, userId, deviceId })` — persist credentials and register UnifiedPush
|
* - `start({ homeserverUrl, accessToken, userId, deviceId })` — persist credentials and keep the listener running
|
||||||
* - `triggerPing({ reason })` — force a one-shot fetch (for testing/manual wake)
|
* - `triggerPing({ reason })` — make sure the listener is running
|
||||||
* - `stop()` — clear persisted credentials and unregister UnifiedPush
|
* - `stop()` — clear persisted credentials and stop the listener
|
||||||
* - `setAppForeground({ foreground })` — tell the service whether the app UI is visible
|
* - `setAppForeground({ foreground })` — tell the service whether the app UI is visible
|
||||||
* - `getStatus()` — returns current fetch and UnifiedPush state
|
* - `getStatus()` — returns whether the listener is running and battery is unrestricted
|
||||||
* - `requestDistributorSetup()` — clear saved distributor and re-open OS picker
|
* - `requestBatteryExemption()` — ask Android to leave the listener unrestricted
|
||||||
* - `resolveUnifiedPushGateway({ endpoint })` — native Matrix gateway discovery
|
|
||||||
* - `clearRoomNotifications({ roomId })` — dismiss native tray notifs for a room
|
* - `clearRoomNotifications({ roomId })` — dismiss native tray notifs for a room
|
||||||
* - `setNotificationGroups({ rooms })` — persist space/DM grouping for tray nesting
|
* - `setNotificationGroups({ rooms })` — persist space/DM grouping for tray nesting
|
||||||
* - `showNotification({ title, body, roomId, groupId, groupName, kind, largeIconBase64 })`
|
* - `showNotification({ title, body, roomId, groupId, groupName, kind, largeIconBase64 })`
|
||||||
@@ -26,13 +34,8 @@ import com.getcapacitor.annotation.CapacitorPlugin
|
|||||||
@CapacitorPlugin(name = "MatrixBackgroundSync")
|
@CapacitorPlugin(name = "MatrixBackgroundSync")
|
||||||
class SyncServicePlugin : Plugin() {
|
class SyncServicePlugin : Plugin() {
|
||||||
|
|
||||||
fun emitUnifiedPushEvent(eventName: String, payload: JSObject) {
|
|
||||||
notifyListeners(eventName, payload, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun load() {
|
override fun load() {
|
||||||
super.load()
|
super.load()
|
||||||
UnifiedPushManager.setPlugin(this)
|
|
||||||
NotificationNavStore.plugin = this
|
NotificationNavStore.plugin = this
|
||||||
NotificationNavStore.handleIntent(activity?.intent)
|
NotificationNavStore.handleIntent(activity?.intent)
|
||||||
}
|
}
|
||||||
@@ -46,7 +49,6 @@ class SyncServicePlugin : Plugin() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun handleOnDestroy() {
|
override fun handleOnDestroy() {
|
||||||
UnifiedPushManager.clearPlugin(this)
|
|
||||||
if (NotificationNavStore.plugin === this) {
|
if (NotificationNavStore.plugin === this) {
|
||||||
NotificationNavStore.plugin = null
|
NotificationNavStore.plugin = null
|
||||||
}
|
}
|
||||||
@@ -71,7 +73,7 @@ class SyncServicePlugin : Plugin() {
|
|||||||
call.resolve(result)
|
call.resolve(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Persists Matrix credentials and starts UnifiedPush registration. */
|
/** Persists Matrix credentials and keeps the message listener in the foreground. */
|
||||||
@PluginMethod
|
@PluginMethod
|
||||||
fun start(call: PluginCall) {
|
fun start(call: PluginCall) {
|
||||||
val homeserver = call.getString("homeserverUrl")
|
val homeserver = call.getString("homeserverUrl")
|
||||||
@@ -86,11 +88,13 @@ class SyncServicePlugin : Plugin() {
|
|||||||
.putString(MatrixSyncService.EXTRA_TOKEN, token)
|
.putString(MatrixSyncService.EXTRA_TOKEN, token)
|
||||||
.putString(MatrixSyncService.EXTRA_USER_ID, userId)
|
.putString(MatrixSyncService.EXTRA_USER_ID, userId)
|
||||||
.putString(MatrixSyncService.EXTRA_DEVICE_ID, deviceId)
|
.putString(MatrixSyncService.EXTRA_DEVICE_ID, deviceId)
|
||||||
.apply()
|
.commit()
|
||||||
|
|
||||||
UnifiedPushManager.register(context, activity)
|
askNotificationPermission()
|
||||||
|
MatrixSyncService.scheduleKeepAlive(context)
|
||||||
call.resolve()
|
MatrixSyncService.requestSyncFetch(context, MatrixSyncService.MODE_LISTENER)
|
||||||
|
val ignored = askBatteryExemption(context, activity)
|
||||||
|
call.resolve(JSObject().put("batteryIgnored", ignored))
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Manually triggers a one-shot sync fetch (mainly for diagnostics/testing). */
|
/** Manually triggers a one-shot sync fetch (mainly for diagnostics/testing). */
|
||||||
@@ -104,9 +108,9 @@ class SyncServicePlugin : Plugin() {
|
|||||||
/** Stops the sync service and erases persisted credentials. */
|
/** Stops the sync service and erases persisted credentials. */
|
||||||
@PluginMethod
|
@PluginMethod
|
||||||
fun stop(call: PluginCall) {
|
fun stop(call: PluginCall) {
|
||||||
|
MatrixSyncService.cancelKeepAlive(context)
|
||||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().clear().apply()
|
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().clear().apply()
|
||||||
context.stopService(Intent(context, MatrixSyncService::class.java))
|
context.stopService(Intent(context, MatrixSyncService::class.java))
|
||||||
UnifiedPushManager.unregister(context)
|
|
||||||
call.resolve()
|
call.resolve()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,49 +121,40 @@ class SyncServicePlugin : Plugin() {
|
|||||||
*/
|
*/
|
||||||
@PluginMethod
|
@PluginMethod
|
||||||
fun setAppForeground(call: PluginCall) {
|
fun setAppForeground(call: PluginCall) {
|
||||||
MatrixSyncService.appInForeground = call.getBoolean("foreground", false) ?: false
|
val foreground = call.getBoolean("foreground", false) ?: false
|
||||||
|
MatrixSyncService.setAppInForeground(context, foreground)
|
||||||
call.resolve()
|
call.resolve()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Returns whether the sync service is currently running. */
|
/** Returns whether the sync service is currently running. */
|
||||||
@PluginMethod
|
@PluginMethod
|
||||||
fun getStatus(call: PluginCall) {
|
fun getStatus(call: PluginCall) {
|
||||||
val am = context.getSystemService(Context.ACTIVITY_SERVICE)
|
try {
|
||||||
as android.app.ActivityManager
|
val result = JSObject()
|
||||||
@Suppress("DEPRECATION")
|
// The service runs in :listener, so its in-memory flag is not shared with this plugin process.
|
||||||
val running = am.getRunningServices(Int.MAX_VALUE)
|
val running =
|
||||||
.any { it.service.className == MatrixSyncService::class.java.name }
|
MatrixSyncService.hasCredentials(context) && MatrixSyncService.isListenerHealthy(context)
|
||||||
val result = UnifiedPushManager.getStatus(context).apply { put("running", running) }
|
result.put("running", running)
|
||||||
call.resolve(result)
|
result.put("listening", running)
|
||||||
}
|
result.put("batteryIgnored", isBatteryIgnored(context))
|
||||||
|
val notificationsAllowed =
|
||||||
/**
|
Build.VERSION.SDK_INT < 33 ||
|
||||||
* Clears the saved UnifiedPush distributor and opens the OS default-distributor
|
ContextCompat.checkSelfPermission(
|
||||||
* picker (`unifiedpush://link`), then re-registers on success.
|
context,
|
||||||
*/
|
Manifest.permission.POST_NOTIFICATIONS,
|
||||||
@PluginMethod
|
) == PackageManager.PERMISSION_GRANTED
|
||||||
fun requestDistributorSetup(call: PluginCall) {
|
result.put("notificationsAllowed", notificationsAllowed)
|
||||||
val currentActivity = activity
|
call.resolve(result)
|
||||||
?: return call.reject("Activity required to select a UnifiedPush distributor")
|
} catch (e: Exception) {
|
||||||
UnifiedPushManager.requestDistributorSetup(context, currentActivity) { success ->
|
call.reject("getStatus failed: ${e.message}", e)
|
||||||
call.resolve(JSObject().put("success", success))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Asks Android to leave Paarrot out of battery optimization so the listener stays up. */
|
||||||
* Resolves the Matrix push gateway for a UnifiedPush endpoint using native HTTP
|
|
||||||
* so discovery is not blocked by missing CORS headers in the WebView.
|
|
||||||
*/
|
|
||||||
@PluginMethod
|
@PluginMethod
|
||||||
fun resolveUnifiedPushGateway(call: PluginCall) {
|
fun requestBatteryExemption(call: PluginCall) {
|
||||||
val endpoint = call.getString("endpoint")
|
val ignored = askBatteryExemption(context, activity)
|
||||||
?: return call.reject("endpoint required")
|
call.resolve(JSObject().put("ignored", ignored))
|
||||||
Thread {
|
|
||||||
val gateway = UnifiedPushManager.resolveMatrixGateway(endpoint)
|
|
||||||
bridge?.executeOnMainThread {
|
|
||||||
call.resolve(JSObject().put("gatewayUrl", gateway))
|
|
||||||
}
|
|
||||||
}.start()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -227,5 +222,39 @@ class SyncServicePlugin : Plugin() {
|
|||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
const val PREFS = "sync_service_prefs"
|
const val PREFS = "sync_service_prefs"
|
||||||
|
|
||||||
|
fun isBatteryIgnored(context: Context): Boolean {
|
||||||
|
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||||
|
return pm.isIgnoringBatteryOptimizations(context.packageName)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun askBatteryExemption(context: Context, activity: Activity?): Boolean {
|
||||||
|
if (isBatteryIgnored(context)) return true
|
||||||
|
val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {
|
||||||
|
data = Uri.parse("package:${context.packageName}")
|
||||||
|
}
|
||||||
|
if (activity != null) {
|
||||||
|
activity.startActivity(intent)
|
||||||
|
} else {
|
||||||
|
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
context.startActivity(intent)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun askNotificationPermission() {
|
||||||
|
if (Build.VERSION.SDK_INT < 33) return
|
||||||
|
val act = activity ?: return
|
||||||
|
if (ContextCompat.checkSelfPermission(act, Manifest.permission.POST_NOTIFICATIONS)
|
||||||
|
== PackageManager.PERMISSION_GRANTED
|
||||||
|
) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ActivityCompat.requestPermissions(
|
||||||
|
act,
|
||||||
|
arrayOf(Manifest.permission.POST_NOTIFICATIONS),
|
||||||
|
4101,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,390 +0,0 @@
|
|||||||
package com.paarrot.app
|
|
||||||
|
|
||||||
import android.app.Activity
|
|
||||||
import android.app.AlertDialog
|
|
||||||
import android.app.AppOpsManager
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.pm.PackageManager
|
|
||||||
import android.os.Build
|
|
||||||
import android.os.Handler
|
|
||||||
import android.os.Looper
|
|
||||||
import android.os.Process
|
|
||||||
import android.os.SystemClock
|
|
||||||
import android.util.Log
|
|
||||||
import com.getcapacitor.JSArray
|
|
||||||
import com.getcapacitor.JSObject
|
|
||||||
import org.json.JSONObject
|
|
||||||
import org.unifiedpush.android.connector.FailedReason
|
|
||||||
import org.unifiedpush.android.connector.INSTANCE_DEFAULT
|
|
||||||
import org.unifiedpush.android.connector.UnifiedPush
|
|
||||||
import java.net.HttpURLConnection
|
|
||||||
import java.net.URL
|
|
||||||
|
|
||||||
/** Coordinates UnifiedPush registration state and bridges events back to JS. */
|
|
||||||
object UnifiedPushManager {
|
|
||||||
private const val TAG = "UnifiedPushManager"
|
|
||||||
private const val PREFS = "unifiedpush_prefs"
|
|
||||||
private const val KEY_ENDPOINT = "endpoint"
|
|
||||||
private const val KEY_INSTANCE = "instance"
|
|
||||||
private const val KEY_LAST_FAILURE = "last_failure"
|
|
||||||
private const val EVENT_NEW_ENDPOINT = "unifiedPushNewEndpoint"
|
|
||||||
private const val EVENT_UNREGISTERED = "unifiedPushUnregistered"
|
|
||||||
private const val EVENT_REGISTRATION_FAILED = "unifiedPushRegistrationFailed"
|
|
||||||
private const val DEFAULT_MESSAGE = "Paarrot notifications"
|
|
||||||
private const val REGISTER_DELAY_MS = 750L
|
|
||||||
private const val IGNORE_UNREGISTER_MS = 2_500L
|
|
||||||
const val DEFAULT_MATRIX_GATEWAY = "https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify"
|
|
||||||
|
|
||||||
private val mainHandler = Handler(Looper.getMainLooper())
|
|
||||||
|
|
||||||
@Volatile
|
|
||||||
private var plugin: SyncServicePlugin? = null
|
|
||||||
|
|
||||||
@Volatile
|
|
||||||
private var setupGeneration = 0
|
|
||||||
|
|
||||||
@Volatile
|
|
||||||
private var ignoreUnregisteredUntilElapsed = 0L
|
|
||||||
|
|
||||||
fun setPlugin(plugin: SyncServicePlugin) {
|
|
||||||
this.plugin = plugin
|
|
||||||
}
|
|
||||||
|
|
||||||
fun clearPlugin(plugin: SyncServicePlugin) {
|
|
||||||
if (this.plugin === plugin) {
|
|
||||||
this.plugin = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun register(context: Context, activity: Activity?) {
|
|
||||||
val savedDistributor = runCatching { UnifiedPush.getSavedDistributor(context) }.getOrNull().orEmpty()
|
|
||||||
if (savedDistributor.isNotBlank()) {
|
|
||||||
requestRegistration(context)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (activity == null) {
|
|
||||||
dispatchRegistrationFailed(FailedReason.ACTION_REQUIRED.name, INSTANCE_DEFAULT)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Prefer an explicit in-app picker so the user always sees something;
|
|
||||||
// tryUseDefaultDistributor is silent when only one distributor is installed.
|
|
||||||
requestDistributorSetup(context, activity) { success ->
|
|
||||||
if (!success) {
|
|
||||||
dispatchRegistrationFailed(FailedReason.ACTION_REQUIRED.name, INSTANCE_DEFAULT)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Shows an in-app distributor picker, then registers after a short delay.
|
|
||||||
*
|
|
||||||
* Important: we intentionally avoid calling [UnifiedPush.removeDistributor] before the
|
|
||||||
* user picks. That sent an UNREGISTER that could arrive *after* the new REGISTER and
|
|
||||||
* wipe the fresh endpoint (looked like "found ntfy but never connects").
|
|
||||||
*/
|
|
||||||
fun requestDistributorSetup(context: Context, activity: Activity, onDone: (Boolean) -> Unit) {
|
|
||||||
val gen = ++setupGeneration
|
|
||||||
ignoreUnregisteredUntilElapsed = SystemClock.elapsedRealtime() + IGNORE_UNREGISTER_MS
|
|
||||||
clearEndpoint(context)
|
|
||||||
clearLastFailure(context)
|
|
||||||
|
|
||||||
val distributors = runCatching { UnifiedPush.getDistributors(context) }
|
|
||||||
.getOrDefault(emptyList())
|
|
||||||
Log.i(TAG, "Distributor setup: found=${distributors.joinToString()}")
|
|
||||||
if (distributors.isEmpty()) {
|
|
||||||
Log.w(TAG, "No UnifiedPush distributors installed")
|
|
||||||
persistLastFailure(context, "NO_DISTRIBUTOR")
|
|
||||||
dispatchRegistrationFailed(FailedReason.ACTION_REQUIRED.name, INSTANCE_DEFAULT)
|
|
||||||
onDone(false)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
val labels = distributors.map { packageName ->
|
|
||||||
distributorLabel(context, packageName)
|
|
||||||
}.toTypedArray()
|
|
||||||
|
|
||||||
// Guard against cancel + dismiss double-firing the callback.
|
|
||||||
val finished = java.util.concurrent.atomic.AtomicBoolean(false)
|
|
||||||
val finish: (Boolean) -> Unit = { success ->
|
|
||||||
if (finished.compareAndSet(false, true)) onDone(success)
|
|
||||||
}
|
|
||||||
|
|
||||||
activity.runOnUiThread {
|
|
||||||
AlertDialog.Builder(activity)
|
|
||||||
.setTitle("Choose push distributor")
|
|
||||||
.setItems(labels) { _, which ->
|
|
||||||
val chosen = distributors.getOrNull(which)
|
|
||||||
if (chosen.isNullOrBlank()) {
|
|
||||||
finish(false)
|
|
||||||
return@setItems
|
|
||||||
}
|
|
||||||
activateDistributor(context, chosen, gen, finish)
|
|
||||||
}
|
|
||||||
.setNegativeButton(android.R.string.cancel) { _, _ -> finish(false) }
|
|
||||||
.setOnCancelListener { finish(false) }
|
|
||||||
.show()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Saves [chosen] as the distributor and registers after a delay so any prior
|
|
||||||
* UNREGISTER from a distributor switch can settle first.
|
|
||||||
*/
|
|
||||||
private fun activateDistributor(
|
|
||||||
context: Context,
|
|
||||||
chosen: String,
|
|
||||||
gen: Int,
|
|
||||||
finish: (Boolean) -> Unit,
|
|
||||||
) {
|
|
||||||
ignoreUnregisteredUntilElapsed = SystemClock.elapsedRealtime() + IGNORE_UNREGISTER_MS
|
|
||||||
val previous = runCatching { UnifiedPush.getSavedDistributor(context) }.getOrNull().orEmpty()
|
|
||||||
Log.i(TAG, "Activating distributor=$chosen previous=$previous")
|
|
||||||
|
|
||||||
if (previous.isNotBlank() && previous != chosen) {
|
|
||||||
runCatching { UnifiedPush.removeDistributor(context) }
|
|
||||||
.onFailure { Log.w(TAG, "removeDistributor failed: ${it.message}") }
|
|
||||||
}
|
|
||||||
|
|
||||||
mainHandler.postDelayed({
|
|
||||||
if (gen != setupGeneration) {
|
|
||||||
Log.w(TAG, "Skipping stale distributor activation gen=$gen current=$setupGeneration")
|
|
||||||
finish(false)
|
|
||||||
return@postDelayed
|
|
||||||
}
|
|
||||||
|
|
||||||
runCatching { UnifiedPush.saveDistributor(context, chosen) }
|
|
||||||
.onFailure {
|
|
||||||
Log.w(TAG, "saveDistributor failed: ${it.message}")
|
|
||||||
persistLastFailure(context, "SAVE_FAILED")
|
|
||||||
finish(false)
|
|
||||||
return@postDelayed
|
|
||||||
}
|
|
||||||
|
|
||||||
val saved = runCatching { UnifiedPush.getSavedDistributor(context) }.getOrNull()
|
|
||||||
if (saved != chosen) {
|
|
||||||
Log.e(TAG, "Distributor not saved after saveDistributor (got=$saved)")
|
|
||||||
persistLastFailure(context, "SAVE_NOT_PERSISTED")
|
|
||||||
finish(false)
|
|
||||||
return@postDelayed
|
|
||||||
}
|
|
||||||
|
|
||||||
requestRegistration(context)
|
|
||||||
// Report true once register was requested; JS polls for the endpoint.
|
|
||||||
finish(true)
|
|
||||||
|
|
||||||
// One retry if the distributor is slow to ack.
|
|
||||||
mainHandler.postDelayed({
|
|
||||||
if (gen != setupGeneration) return@postDelayed
|
|
||||||
if (!getEndpoint(context).isNullOrBlank()) return@postDelayed
|
|
||||||
Log.w(TAG, "No endpoint yet after ${REGISTER_DELAY_MS}ms — retrying register")
|
|
||||||
requestRegistration(context)
|
|
||||||
|
|
||||||
// OEM "App Boot" / AUTO_START can silently drop NEW_ENDPOINT (seen on TCL).
|
|
||||||
mainHandler.postDelayed({
|
|
||||||
if (gen != setupGeneration) return@postDelayed
|
|
||||||
if (!getEndpoint(context).isNullOrBlank()) return@postDelayed
|
|
||||||
val reason = if (isAutoStartRestricted(context)) {
|
|
||||||
"AUTO_START_BLOCKED"
|
|
||||||
} else {
|
|
||||||
"NO_ENDPOINT"
|
|
||||||
}
|
|
||||||
Log.w(TAG, "Still no endpoint after register retries — $reason")
|
|
||||||
persistLastFailure(context, reason)
|
|
||||||
dispatchRegistrationFailed(reason, INSTANCE_DEFAULT)
|
|
||||||
}, 4_000L)
|
|
||||||
}, REGISTER_DELAY_MS)
|
|
||||||
}, if (previous.isNotBlank() && previous != chosen) REGISTER_DELAY_MS else 150L)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Human-readable label for a distributor package (falls back to package name). */
|
|
||||||
private fun distributorLabel(context: Context, packageName: String): String {
|
|
||||||
return try {
|
|
||||||
val pm = context.packageManager
|
|
||||||
val appInfo = pm.getApplicationInfo(packageName, 0)
|
|
||||||
val label = pm.getApplicationLabel(appInfo)?.toString().orEmpty()
|
|
||||||
if (label.isNotBlank() && label != packageName) "$label ($packageName)" else packageName
|
|
||||||
} catch (_: PackageManager.NameNotFoundException) {
|
|
||||||
packageName
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Discovers the Matrix push gateway for a UnifiedPush endpoint via native HTTP
|
|
||||||
* (WebView `fetch` fails — ntfy responses omit CORS headers).
|
|
||||||
*/
|
|
||||||
fun resolveMatrixGateway(endpoint: String): String {
|
|
||||||
return try {
|
|
||||||
val endpointUrl = URL(endpoint)
|
|
||||||
val discoveryUrl = URL(
|
|
||||||
endpointUrl.protocol,
|
|
||||||
endpointUrl.host,
|
|
||||||
endpointUrl.port,
|
|
||||||
"/_matrix/push/v1/notify",
|
|
||||||
)
|
|
||||||
val conn = discoveryUrl.openConnection() as HttpURLConnection
|
|
||||||
try {
|
|
||||||
conn.requestMethod = "GET"
|
|
||||||
conn.connectTimeout = 4_000
|
|
||||||
conn.readTimeout = 6_000
|
|
||||||
conn.setRequestProperty("Accept", "application/json")
|
|
||||||
if (conn.responseCode != 200) return DEFAULT_MATRIX_GATEWAY
|
|
||||||
|
|
||||||
val body = JSONObject(conn.inputStream.bufferedReader().readText())
|
|
||||||
val gateway =
|
|
||||||
body.optString("gateway").takeIf { it.isNotBlank() }
|
|
||||||
?: body.optJSONObject("unifiedpush")?.optString("gateway")
|
|
||||||
if (gateway == "matrix") discoveryUrl.toString() else DEFAULT_MATRIX_GATEWAY
|
|
||||||
} finally {
|
|
||||||
conn.disconnect()
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "Matrix gateway discovery failed: ${e.message}")
|
|
||||||
DEFAULT_MATRIX_GATEWAY
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun unregister(context: Context) {
|
|
||||||
runCatching {
|
|
||||||
UnifiedPush.unregister(context, INSTANCE_DEFAULT)
|
|
||||||
}.onFailure {
|
|
||||||
Log.w(TAG, "Failed to unregister UnifiedPush: ${it.message}")
|
|
||||||
}
|
|
||||||
val previousEndpoint = getEndpoint(context)
|
|
||||||
clearEndpoint(context)
|
|
||||||
dispatchUnregistered(previousEndpoint, INSTANCE_DEFAULT)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun getStatus(context: Context): JSObject {
|
|
||||||
val status = JSObject()
|
|
||||||
status.put("endpoint", getEndpoint(context) ?: "")
|
|
||||||
status.put("instance", getInstance(context) ?: INSTANCE_DEFAULT)
|
|
||||||
status.put("registered", !getEndpoint(context).isNullOrBlank())
|
|
||||||
status.put("distributor", runCatching { UnifiedPush.getSavedDistributor(context) }.getOrDefault(""))
|
|
||||||
status.put("lastFailure", getLastFailure(context) ?: "")
|
|
||||||
status.put("autoStartBlocked", isAutoStartRestricted(context))
|
|
||||||
val distributors = JSArray()
|
|
||||||
runCatching { UnifiedPush.getDistributors(context) }
|
|
||||||
.getOrDefault(emptyList())
|
|
||||||
.forEach { distributors.put(it) }
|
|
||||||
status.put("distributors", distributors)
|
|
||||||
return status
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* TCL / some OEMs expose an AUTO_START app-op. When it is not MODE_ALLOWED,
|
|
||||||
* [AppBootManager] drops distributor broadcasts such as NEW_ENDPOINT, so
|
|
||||||
* UnifiedPush never finishes registering even though ntfy is selected.
|
|
||||||
*/
|
|
||||||
private fun isAutoStartRestricted(context: Context): Boolean {
|
|
||||||
return try {
|
|
||||||
val appOps = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
|
|
||||||
val mode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
|
||||||
appOps.unsafeCheckOpNoThrow("android:auto_start", Process.myUid(), context.packageName)
|
|
||||||
} else {
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
appOps.checkOpNoThrow("android:auto_start", Process.myUid(), context.packageName)
|
|
||||||
}
|
|
||||||
mode != AppOpsManager.MODE_ALLOWED && mode != AppOpsManager.MODE_DEFAULT
|
|
||||||
} catch (_: Exception) {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onNewEndpoint(context: Context, endpoint: String, instance: String) {
|
|
||||||
Log.i(TAG, "onNewEndpoint instance=$instance endpoint=$endpoint")
|
|
||||||
clearLastFailure(context)
|
|
||||||
val previousEndpoint = getEndpoint(context)
|
|
||||||
persistEndpoint(context, endpoint, instance)
|
|
||||||
val payload = JSObject().apply {
|
|
||||||
put("endpoint", endpoint)
|
|
||||||
put("instance", instance)
|
|
||||||
put("previousEndpoint", previousEndpoint ?: "")
|
|
||||||
}
|
|
||||||
dispatch(EVENT_NEW_ENDPOINT, payload)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onRegistrationFailed(context: Context, reason: String, instance: String) {
|
|
||||||
Log.w(TAG, "onRegistrationFailed reason=$reason instance=$instance")
|
|
||||||
persistLastFailure(context, reason)
|
|
||||||
dispatchRegistrationFailed(reason, instance)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onUnregistered(context: Context, instance: String) {
|
|
||||||
if (SystemClock.elapsedRealtime() < ignoreUnregisteredUntilElapsed) {
|
|
||||||
Log.i(TAG, "Ignoring unregistered during setup window instance=$instance")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
Log.i(TAG, "onUnregistered instance=$instance")
|
|
||||||
val previousEndpoint = getEndpoint(context)
|
|
||||||
clearEndpoint(context)
|
|
||||||
dispatchUnregistered(previousEndpoint, instance)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun requestRegistration(context: Context) {
|
|
||||||
runCatching {
|
|
||||||
Log.i(TAG, "Calling UnifiedPush.register instance=$INSTANCE_DEFAULT")
|
|
||||||
UnifiedPush.register(context, INSTANCE_DEFAULT, DEFAULT_MESSAGE, null)
|
|
||||||
}.onFailure {
|
|
||||||
Log.w(TAG, "UnifiedPush register failed: ${it.message}")
|
|
||||||
persistLastFailure(context, FailedReason.INTERNAL_ERROR.name)
|
|
||||||
dispatchRegistrationFailed(FailedReason.INTERNAL_ERROR.name, INSTANCE_DEFAULT)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun dispatchUnregistered(previousEndpoint: String?, instance: String) {
|
|
||||||
val payload = JSObject().apply {
|
|
||||||
put("previousEndpoint", previousEndpoint ?: "")
|
|
||||||
put("instance", instance)
|
|
||||||
}
|
|
||||||
dispatch(EVENT_UNREGISTERED, payload)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun dispatchRegistrationFailed(reason: String, instance: String) {
|
|
||||||
val payload = JSObject().apply {
|
|
||||||
put("reason", reason)
|
|
||||||
put("instance", instance)
|
|
||||||
}
|
|
||||||
dispatch(EVENT_REGISTRATION_FAILED, payload)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun dispatch(eventName: String, payload: JSObject) {
|
|
||||||
plugin?.emitUnifiedPushEvent(eventName, payload)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun persistEndpoint(context: Context, endpoint: String, instance: String) {
|
|
||||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
|
|
||||||
.putString(KEY_ENDPOINT, endpoint)
|
|
||||||
.putString(KEY_INSTANCE, instance)
|
|
||||||
.apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun clearEndpoint(context: Context) {
|
|
||||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
|
|
||||||
.remove(KEY_ENDPOINT)
|
|
||||||
.remove(KEY_INSTANCE)
|
|
||||||
.apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun persistLastFailure(context: Context, reason: String) {
|
|
||||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
|
|
||||||
.putString(KEY_LAST_FAILURE, reason)
|
|
||||||
.apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun clearLastFailure(context: Context) {
|
|
||||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
|
|
||||||
.remove(KEY_LAST_FAILURE)
|
|
||||||
.apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun getLastFailure(context: Context): String? =
|
|
||||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY_LAST_FAILURE, null)
|
|
||||||
|
|
||||||
private fun getEndpoint(context: Context): String? =
|
|
||||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY_ENDPOINT, null)
|
|
||||||
|
|
||||||
private fun getInstance(context: Context): String? =
|
|
||||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY_INSTANCE, null)
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package com.paarrot.app
|
|
||||||
|
|
||||||
import android.util.Log
|
|
||||||
import org.unifiedpush.android.connector.FailedReason
|
|
||||||
import org.unifiedpush.android.connector.PushService
|
|
||||||
import org.unifiedpush.android.connector.data.PushEndpoint
|
|
||||||
import org.unifiedpush.android.connector.data.PushMessage
|
|
||||||
|
|
||||||
/** Receives UnifiedPush events and turns push messages into Matrix fetch wakes. */
|
|
||||||
class UnifiedPushService : PushService() {
|
|
||||||
|
|
||||||
override fun onNewEndpoint(endpoint: PushEndpoint, instance: String) {
|
|
||||||
Log.i(TAG, "UnifiedPush endpoint updated for instance=$instance")
|
|
||||||
UnifiedPushManager.onNewEndpoint(applicationContext, endpoint.url, instance)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onMessage(message: PushMessage, instance: String) {
|
|
||||||
Log.d(TAG, "UnifiedPush wake ping received for instance=$instance, bytes=${message.content.size}")
|
|
||||||
MatrixSyncService.requestSyncFetch(applicationContext, "unifiedpush_message")
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onRegistrationFailed(reason: FailedReason, instance: String) {
|
|
||||||
Log.w(TAG, "UnifiedPush registration failed: $reason")
|
|
||||||
UnifiedPushManager.onRegistrationFailed(applicationContext, reason.name, instance)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onUnregistered(instance: String) {
|
|
||||||
Log.i(TAG, "UnifiedPush unregistered for instance=$instance")
|
|
||||||
UnifiedPushManager.onUnregistered(applicationContext, instance)
|
|
||||||
}
|
|
||||||
|
|
||||||
private companion object {
|
|
||||||
const val TAG = "UnifiedPushService"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -7,6 +7,9 @@
|
|||||||
"LocalNotifications": {
|
"LocalNotifications": {
|
||||||
"smallIcon": "ic_stat_paarrot",
|
"smallIcon": "ic_stat_paarrot",
|
||||||
"iconColor": "#FF8A00"
|
"iconColor": "#FF8A00"
|
||||||
|
},
|
||||||
|
"CapacitorHttp": {
|
||||||
|
"enabled": true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
Submodule cinny updated: e65a516350...9b657e3ab4
@@ -6,16 +6,8 @@ export const Editor = style([
|
|||||||
{
|
{
|
||||||
backgroundColor: color.SurfaceVariant.Container,
|
backgroundColor: color.SurfaceVariant.Container,
|
||||||
color: color.SurfaceVariant.OnContainer,
|
color: color.SurfaceVariant.OnContainer,
|
||||||
boxShadow: `inset 0 0 0 ${config.borderWidth.B300} ${color.SurfaceVariant.ContainerLine}`,
|
borderTop: `${config.borderWidth.B300} solid ${color.SurfaceVariant.ContainerLine}`,
|
||||||
borderRadius: config.radii.R400,
|
|
||||||
overflow: 'hidden',
|
overflow: 'hidden',
|
||||||
selectors: {
|
|
||||||
// Keyboard-flush dock: only a top edge so the input can sit on the IME.
|
|
||||||
'[data-composer-flush="true"] &': {
|
|
||||||
borderRadius: 0,
|
|
||||||
boxShadow: `inset 0 ${config.borderWidth.B300} 0 0 ${color.SurfaceVariant.ContainerLine}`,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,8 @@ import { RoomTimeline } from './RoomTimeline';
|
|||||||
import { RoomViewTyping } from './RoomViewTyping';
|
import { RoomViewTyping } from './RoomViewTyping';
|
||||||
import { RoomTombstone } from './RoomTombstone';
|
import { RoomTombstone } from './RoomTombstone';
|
||||||
import { RoomInput } from './RoomInput';
|
import { RoomInput } from './RoomInput';
|
||||||
import { RoomViewFollowing, RoomViewFollowingPlaceholder } from './RoomViewFollowing';
|
import { RoomViewFollowing } from './RoomViewFollowing';
|
||||||
|
import * as roomViewCss from './RoomViewFollowing.css';
|
||||||
import { Page } from '../../components/page';
|
import { Page } from '../../components/page';
|
||||||
import { RoomViewHeader } from './RoomViewHeader';
|
import { RoomViewHeader } from './RoomViewHeader';
|
||||||
import { useKeyDown } from '../../hooks/useKeyDown';
|
import { useKeyDown } from '../../hooks/useKeyDown';
|
||||||
@@ -105,7 +106,7 @@ export function RoomView({ room, eventId }: { room: Room; eventId?: string }) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const flushComposer = immersive;
|
const flushComposer = immersive;
|
||||||
const composerPadding = flushComposer ? '0' : `0 ${config.space.S400}`;
|
const composerPadding = '0';
|
||||||
const showHeader = !immersive;
|
const showHeader = !immersive;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -116,7 +117,7 @@ export function RoomView({ room, eventId }: { room: Room; eventId?: string }) {
|
|||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<MobileSwipeToReplyLayer room={room} editor={editor}>
|
<MobileSwipeToReplyLayer room={room} editor={editor}>
|
||||||
<Box grow="Yes" direction="Column">
|
<Box grow="Yes" direction="Column" style={{ position: 'relative', minHeight: 0 }}>
|
||||||
<RoomTimeline
|
<RoomTimeline
|
||||||
key={roomId}
|
key={roomId}
|
||||||
room={room}
|
room={room}
|
||||||
@@ -124,7 +125,10 @@ export function RoomView({ room, eventId }: { room: Room; eventId?: string }) {
|
|||||||
roomInputRef={roomInputRef}
|
roomInputRef={roomInputRef}
|
||||||
editor={editor}
|
editor={editor}
|
||||||
/>
|
/>
|
||||||
<RoomViewTyping room={room} />
|
<div className={roomViewCss.RoomViewBottomFloat}>
|
||||||
|
<RoomViewTyping room={room} />
|
||||||
|
{!hideActivity && <RoomViewFollowing room={room} />}
|
||||||
|
</div>
|
||||||
</Box>
|
</Box>
|
||||||
</MobileSwipeToReplyLayer>
|
</MobileSwipeToReplyLayer>
|
||||||
<Box
|
<Box
|
||||||
@@ -134,13 +138,6 @@ export function RoomView({ room, eventId }: { room: Room; eventId?: string }) {
|
|||||||
data-composer-flush={flushComposer ? 'true' : undefined}
|
data-composer-flush={flushComposer ? 'true' : undefined}
|
||||||
className={composerCss.ComposerDock}
|
className={composerCss.ComposerDock}
|
||||||
>
|
>
|
||||||
{immersive && !hideActivity && (
|
|
||||||
<div className={composerCss.FollowingFloat}>
|
|
||||||
<div className={composerCss.FollowingFloatHit}>
|
|
||||||
<RoomViewFollowing room={room} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div style={{ padding: composerPadding }}>
|
<div style={{ padding: composerPadding }}>
|
||||||
{tombstoneEvent ? (
|
{tombstoneEvent ? (
|
||||||
<RoomTombstone
|
<RoomTombstone
|
||||||
@@ -171,12 +168,6 @@ export function RoomView({ room, eventId }: { room: Room; eventId?: string }) {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{!immersive &&
|
|
||||||
(hideActivity ? (
|
|
||||||
<RoomViewFollowingPlaceholder />
|
|
||||||
) : (
|
|
||||||
<RoomViewFollowing room={room} />
|
|
||||||
))}
|
|
||||||
</Box>
|
</Box>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -2,6 +2,20 @@ import { style } from '@vanilla-extract/css';
|
|||||||
import { recipe } from '@vanilla-extract/recipes';
|
import { recipe } from '@vanilla-extract/recipes';
|
||||||
import { DefaultReset, color, config, toRem } from 'folds';
|
import { DefaultReset, color, config, toRem } from 'folds';
|
||||||
|
|
||||||
|
/** Floats typing + read receipts over the bottom of the timeline. */
|
||||||
|
export const RoomViewBottomFloat = style({
|
||||||
|
position: 'absolute',
|
||||||
|
bottom: 0,
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
zIndex: 1,
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'row',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: config.space.S200,
|
||||||
|
pointerEvents: 'none',
|
||||||
|
});
|
||||||
|
|
||||||
export const RoomViewFollowingPlaceholder = style([
|
export const RoomViewFollowingPlaceholder = style([
|
||||||
DefaultReset,
|
DefaultReset,
|
||||||
{
|
{
|
||||||
@@ -15,20 +29,12 @@ export const RoomViewFollowing = recipe({
|
|||||||
{
|
{
|
||||||
minHeight: toRem(28),
|
minHeight: toRem(28),
|
||||||
padding: `0 ${config.space.S400}`,
|
padding: `0 ${config.space.S400}`,
|
||||||
width: '100%',
|
marginLeft: 'auto',
|
||||||
backgroundColor: color.Surface.Container,
|
maxWidth: '50%',
|
||||||
|
backgroundColor: 'transparent',
|
||||||
color: color.Surface.OnContainer,
|
color: color.Surface.OnContainer,
|
||||||
outline: 'none',
|
outline: 'none',
|
||||||
selectors: {
|
pointerEvents: 'auto',
|
||||||
// Compact floating chip while the keyboard is open.
|
|
||||||
'[data-composer-flush="true"] &': {
|
|
||||||
minHeight: 0,
|
|
||||||
width: 'auto',
|
|
||||||
maxWidth: '100%',
|
|
||||||
padding: `${config.space.S100} ${config.space.S200}`,
|
|
||||||
backgroundColor: 'transparent',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
variants: {
|
variants: {
|
||||||
|
|||||||
@@ -62,6 +62,10 @@ import colorMXID from '../../../../util/colorMXID';
|
|||||||
import { getPowerTagIconSrc } from '../../../hooks/useMemberPowerTag';
|
import { getPowerTagIconSrc } from '../../../hooks/useMemberPowerTag';
|
||||||
import { Presence, useUserPresence } from '../../../hooks/useUserPresence';
|
import { Presence, useUserPresence } from '../../../hooks/useUserPresence';
|
||||||
import { useOtherUserColor } from '../../../hooks/useUserColor';
|
import { useOtherUserColor } from '../../../hooks/useUserColor';
|
||||||
|
import { useIsDirectRoom } from '../../../hooks/useRoom';
|
||||||
|
import { useOtherUserCollectibles } from '../../../hooks/useUserCollectibles';
|
||||||
|
import { pickAvatarDecorationUrl, pickNameplateUrl } from '../../../utils/collectibleAssets';
|
||||||
|
import * as avatarDecorationCss from '../../../styles/AvatarDecoration.css';
|
||||||
|
|
||||||
export type ReactionHandler = (keyOrMxc: string, shortcode: string) => void;
|
export type ReactionHandler = (keyOrMxc: string, shortcode: string) => void;
|
||||||
|
|
||||||
@@ -754,8 +758,15 @@ export const Message = as<'div', MessageProps>(
|
|||||||
) => {
|
) => {
|
||||||
const mx = useMatrixClient();
|
const mx = useMatrixClient();
|
||||||
const useAuthentication = useMediaAuthentication();
|
const useAuthentication = useMediaAuthentication();
|
||||||
|
const direct = useIsDirectRoom();
|
||||||
const senderId = mEvent.getSender() ?? '';
|
const senderId = mEvent.getSender() ?? '';
|
||||||
const senderPresence = useUserPresence(senderId);
|
const senderPresence = useUserPresence(senderId);
|
||||||
|
const { assetUrls } = useOtherUserCollectibles(senderId);
|
||||||
|
const nameplateUrl = pickNameplateUrl(assetUrls);
|
||||||
|
const nameplateIsVideo = Boolean(
|
||||||
|
assetUrls['nameplate:animated'] || assetUrls['nameplate:asset.webm']
|
||||||
|
);
|
||||||
|
const avatarDecorationUrl = pickAvatarDecorationUrl(assetUrls);
|
||||||
|
|
||||||
const [hover, setHover] = useState(false);
|
const [hover, setHover] = useState(false);
|
||||||
const { hoverProps } = useHover({ onHoverChange: setHover });
|
const { hoverProps } = useHover({ onHoverChange: setHover });
|
||||||
@@ -785,7 +796,7 @@ export const Message = as<'div', MessageProps>(
|
|||||||
const senderAvatarMxc = getMemberAvatarMxc(room, senderId);
|
const senderAvatarMxc = getMemberAvatarMxc(room, senderId);
|
||||||
|
|
||||||
// Get custom user color from avatar metadata (takes priority)
|
// Get custom user color from avatar metadata (takes priority)
|
||||||
const customUserColor = useOtherUserColor(senderId, senderAvatarMxc);
|
const customUserColor = useOtherUserColor(senderId, room);
|
||||||
|
|
||||||
const tagColor = memberPowerTag?.color
|
const tagColor = memberPowerTag?.color
|
||||||
? accessibleTagColors?.get(memberPowerTag.color)
|
? accessibleTagColors?.get(memberPowerTag.color)
|
||||||
@@ -796,6 +807,7 @@ export const Message = as<'div', MessageProps>(
|
|||||||
|
|
||||||
// Priority: custom user color > tag color (non-legacy) > colorMXID (legacy)
|
// Priority: custom user color > tag color (non-legacy) > colorMXID (legacy)
|
||||||
const usernameColor = customUserColor ?? (legacyUsernameColor ? colorMXID(senderId) : tagColor);
|
const usernameColor = customUserColor ?? (legacyUsernameColor ? colorMXID(senderId) : tagColor);
|
||||||
|
const showNameplate = direct && hover && Boolean(nameplateUrl);
|
||||||
|
|
||||||
const headerJSX = !collapse && (
|
const headerJSX = !collapse && (
|
||||||
<Box
|
<Box
|
||||||
@@ -824,23 +836,41 @@ export const Message = as<'div', MessageProps>(
|
|||||||
</Username>
|
</Username>
|
||||||
{tagIconSrc && <PowerIcon size="100" iconSrc={tagIconSrc} />}
|
{tagIconSrc && <PowerIcon size="100" iconSrc={tagIconSrc} />}
|
||||||
</Box>
|
</Box>
|
||||||
<Box shrink="No" gap="100">
|
<Box shrink="No" className={css.MessageNameplateAnchor}>
|
||||||
{messageLayout === MessageLayout.Modern && hover && (
|
<Box shrink="No" gap="100" alignItems="Center">
|
||||||
<>
|
{messageLayout === MessageLayout.Modern && hover && (
|
||||||
<Text as="span" size="T200" priority="300">
|
<>
|
||||||
{senderId}
|
<Text as="span" size="T200" priority="300">
|
||||||
</Text>
|
{senderId}
|
||||||
<Text as="span" size="T200" priority="300">
|
</Text>
|
||||||
|
|
<Text as="span" size="T200" priority="300">
|
||||||
</Text>
|
|
|
||||||
</>
|
</Text>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<Time
|
||||||
|
ts={mEvent.getTs()}
|
||||||
|
compact={messageLayout === MessageLayout.Compact}
|
||||||
|
hour24Clock={hour24Clock}
|
||||||
|
dateFormatString={dateFormatString}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
{showNameplate && (
|
||||||
|
<div className={css.MessageNameplateWrap}>
|
||||||
|
{nameplateIsVideo ? (
|
||||||
|
<video
|
||||||
|
className={css.MessageNameplateOverlay}
|
||||||
|
src={nameplateUrl}
|
||||||
|
autoPlay
|
||||||
|
loop
|
||||||
|
muted
|
||||||
|
playsInline
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<img className={css.MessageNameplateOverlay} src={nameplateUrl} alt="" draggable={false} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
<Time
|
|
||||||
ts={mEvent.getTs()}
|
|
||||||
compact={messageLayout === MessageLayout.Compact}
|
|
||||||
hour24Clock={hour24Clock}
|
|
||||||
dateFormatString={dateFormatString}
|
|
||||||
/>
|
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
@@ -857,24 +887,38 @@ export const Message = as<'div', MessageProps>(
|
|||||||
<AvatarBase
|
<AvatarBase
|
||||||
className={messageLayout === MessageLayout.Bubble ? css.BubbleAvatarBase : undefined}
|
className={messageLayout === MessageLayout.Bubble ? css.BubbleAvatarBase : undefined}
|
||||||
>
|
>
|
||||||
<Avatar
|
<div className={css.MessageAvatarStack}>
|
||||||
className={classNames(css.MessageAvatar, presenceClass)}
|
<Avatar
|
||||||
as="button"
|
className={classNames(
|
||||||
size="300"
|
avatarDecorationUrl ? css.MessageAvatarCircular : css.MessageAvatar,
|
||||||
data-user-id={senderId}
|
!avatarDecorationUrl && presenceClass
|
||||||
onClick={onUserClick}
|
)}
|
||||||
>
|
radii={avatarDecorationUrl ? 'Pill' : undefined}
|
||||||
<UserAvatar
|
as="button"
|
||||||
userId={senderId}
|
size="300"
|
||||||
src={
|
data-user-id={senderId}
|
||||||
senderAvatarMxc
|
onClick={onUserClick}
|
||||||
? mxcUrlToHttp(mx, senderAvatarMxc, useAuthentication, 48, 48, 'crop') ?? undefined
|
>
|
||||||
: undefined
|
<UserAvatar
|
||||||
}
|
userId={senderId}
|
||||||
alt={senderDisplayName}
|
src={
|
||||||
renderFallback={() => <Icon size="200" src={Icons.User} filled />}
|
senderAvatarMxc
|
||||||
/>
|
? mxcUrlToHttp(mx, senderAvatarMxc, useAuthentication, 48, 48, 'crop') ?? undefined
|
||||||
</Avatar>
|
: undefined
|
||||||
|
}
|
||||||
|
alt={senderDisplayName}
|
||||||
|
renderFallback={() => <Icon size="200" src={Icons.User} filled />}
|
||||||
|
/>
|
||||||
|
</Avatar>
|
||||||
|
{avatarDecorationUrl && (
|
||||||
|
<img
|
||||||
|
className={avatarDecorationCss.AvatarDecorationOverlay}
|
||||||
|
src={avatarDecorationUrl}
|
||||||
|
alt=""
|
||||||
|
draggable={false}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</AvatarBase>
|
</AvatarBase>
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -959,6 +1003,10 @@ export const Message = as<'div', MessageProps>(
|
|||||||
{...focusWithinProps}
|
{...focusWithinProps}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
>
|
>
|
||||||
|
<div
|
||||||
|
className={css.MessageContentLayer}
|
||||||
|
data-message-nameplate-readable={showNameplate ? '' : undefined}
|
||||||
|
>
|
||||||
{!edit && (hover || !!menuAnchor || !!emojiBoardAnchor) && (
|
{!edit && (hover || !!menuAnchor || !!emojiBoardAnchor) && (
|
||||||
<div className={css.MessageOptionsBase}>
|
<div className={css.MessageOptionsBase}>
|
||||||
<Menu className={css.MessageOptionsBar} variant="SurfaceVariant">
|
<Menu className={css.MessageOptionsBar} variant="SurfaceVariant">
|
||||||
@@ -1247,6 +1295,7 @@ export const Message = as<'div', MessageProps>(
|
|||||||
{msgContentJSX}
|
{msgContentJSX}
|
||||||
</ModernLayout>
|
</ModernLayout>
|
||||||
)}
|
)}
|
||||||
|
</div>
|
||||||
</MessageBase>
|
</MessageBase>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,63 +1,5 @@
|
|||||||
import { style } from '@vanilla-extract/css';
|
import { style } from '@vanilla-extract/css';
|
||||||
import { recipe } from '@vanilla-extract/recipes';
|
|
||||||
import { DefaultReset, color, config } from 'folds';
|
|
||||||
|
|
||||||
export const ComposerDock = style({
|
export const ComposerDock = style({
|
||||||
position: 'relative',
|
position: 'relative',
|
||||||
});
|
});
|
||||||
|
|
||||||
/** Read receipts float above the input so they don't reserve layout height. */
|
|
||||||
export const FollowingFloat = style({
|
|
||||||
position: 'absolute',
|
|
||||||
bottom: '100%',
|
|
||||||
left: 0,
|
|
||||||
right: 0,
|
|
||||||
zIndex: 2,
|
|
||||||
display: 'flex',
|
|
||||||
justifyContent: 'flex-end',
|
|
||||||
pointerEvents: 'none',
|
|
||||||
padding: `0 ${config.space.S200}`,
|
|
||||||
});
|
|
||||||
|
|
||||||
export const FollowingFloatHit = style({
|
|
||||||
pointerEvents: 'auto',
|
|
||||||
maxWidth: '100%',
|
|
||||||
});
|
|
||||||
|
|
||||||
export const RoomViewFollowingPlaceholder = style([
|
|
||||||
DefaultReset,
|
|
||||||
{
|
|
||||||
display: 'none',
|
|
||||||
height: 0,
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const RoomViewFollowing = recipe({
|
|
||||||
base: [
|
|
||||||
DefaultReset,
|
|
||||||
{
|
|
||||||
minHeight: 0,
|
|
||||||
padding: `${config.space.S100} ${config.space.S200}`,
|
|
||||||
width: 'auto',
|
|
||||||
maxWidth: '100%',
|
|
||||||
backgroundColor: 'transparent',
|
|
||||||
color: color.Surface.OnContainer,
|
|
||||||
outline: 'none',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
variants: {
|
|
||||||
clickable: {
|
|
||||||
true: {
|
|
||||||
cursor: 'pointer',
|
|
||||||
selectors: {
|
|
||||||
'&:hover, &:focus-visible': {
|
|
||||||
color: color.Primary.Main,
|
|
||||||
},
|
|
||||||
'&:active': {
|
|
||||||
color: color.Primary.Main,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -14,8 +14,10 @@ import { isCapacitorNative, requestSystemNotificationPermission } from '../../..
|
|||||||
import {
|
import {
|
||||||
isBackgroundSyncSupported,
|
isBackgroundSyncSupported,
|
||||||
getBackgroundSyncStatus,
|
getBackgroundSyncStatus,
|
||||||
requestResetPushRegistration,
|
requestBatteryExemption,
|
||||||
|
startBackgroundSync,
|
||||||
triggerBackgroundSyncPing,
|
triggerBackgroundSyncPing,
|
||||||
|
type ListenerStatus,
|
||||||
} from '../../../utils/backgroundSync';
|
} from '../../../utils/backgroundSync';
|
||||||
|
|
||||||
function EmailNotification() {
|
function EmailNotification() {
|
||||||
@@ -166,119 +168,107 @@ export function SystemNotification() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
type PushStatus = {
|
/** Android-only controls for Paarrot's persistent message listener. */
|
||||||
registered: boolean;
|
|
||||||
distributor: string;
|
|
||||||
endpoint: string;
|
|
||||||
distributors: string[];
|
|
||||||
lastFailure: string;
|
|
||||||
autoStartBlocked: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Android-only section showing UnifiedPush registration status and controls. */
|
|
||||||
function AndroidPushNotifications() {
|
function AndroidPushNotifications() {
|
||||||
const [status, setStatus] = useState<PushStatus | undefined>(undefined);
|
const mx = useMatrixClient();
|
||||||
|
const [status, setStatus] = useState<ListenerStatus | undefined>(undefined);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [lastError, setLastError] = useState<string | undefined>(undefined);
|
|
||||||
|
|
||||||
const refresh = useCallback(async () => {
|
const refresh = useCallback(async () => {
|
||||||
setLoading(true);
|
setStatus(await getBackgroundSyncStatus());
|
||||||
const s = await getBackgroundSyncStatus();
|
|
||||||
const distributors = Array.isArray(s?.distributors)
|
|
||||||
? s.distributors
|
|
||||||
: typeof s?.distributors === 'string' && s.distributors && s.distributors !== '[]'
|
|
||||||
? [s.distributors]
|
|
||||||
: [];
|
|
||||||
setStatus(
|
|
||||||
s
|
|
||||||
? {
|
|
||||||
registered: s.registered,
|
|
||||||
distributor: s.distributor || '',
|
|
||||||
endpoint: s.endpoint || '',
|
|
||||||
distributors,
|
|
||||||
lastFailure: s.lastFailure || '',
|
|
||||||
autoStartBlocked: Boolean(s.autoStartBlocked),
|
|
||||||
}
|
|
||||||
: undefined
|
|
||||||
);
|
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void refresh();
|
void refresh();
|
||||||
|
const id = window.setInterval(() => void refresh(), 4000);
|
||||||
|
return () => window.clearInterval(id);
|
||||||
}, [refresh]);
|
}, [refresh]);
|
||||||
|
|
||||||
const [resetState, reset] = useAsyncCallback(
|
const [batteryState, allowBattery] = useAsyncCallback(
|
||||||
useCallback(async () => {
|
useCallback(async () => {
|
||||||
setLastError(undefined);
|
await requestBatteryExemption();
|
||||||
const result = await requestResetPushRegistration();
|
|
||||||
await refresh();
|
await refresh();
|
||||||
if (!result.success) {
|
|
||||||
setLastError(
|
|
||||||
'Selected distributor but did not get a push endpoint. In ntfy: enable UnifiedPush, allow unrestricted battery, then try Reset again.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}, [refresh])
|
}, [refresh])
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const [startState, startListener] = useAsyncCallback(
|
||||||
|
useCallback(async () => {
|
||||||
|
await requestSystemNotificationPermission();
|
||||||
|
await startBackgroundSync(mx);
|
||||||
|
await refresh();
|
||||||
|
}, [mx, refresh])
|
||||||
|
);
|
||||||
|
|
||||||
const [pingState, ping] = useAsyncCallback(
|
const [pingState, ping] = useAsyncCallback(
|
||||||
useCallback(async () => {
|
useCallback(async () => {
|
||||||
await triggerBackgroundSyncPing('manual-test');
|
await triggerBackgroundSyncPing('manual-test');
|
||||||
}, [])
|
await refresh();
|
||||||
|
}, [refresh])
|
||||||
);
|
);
|
||||||
|
|
||||||
const isBusy =
|
const isBusy =
|
||||||
loading ||
|
loading ||
|
||||||
resetState.status === AsyncStatus.Loading ||
|
batteryState.status === AsyncStatus.Loading ||
|
||||||
|
startState.status === AsyncStatus.Loading ||
|
||||||
pingState.status === AsyncStatus.Loading;
|
pingState.status === AsyncStatus.Loading;
|
||||||
|
|
||||||
|
const actionError =
|
||||||
|
startState.status === AsyncStatus.Error
|
||||||
|
? startState.error
|
||||||
|
: batteryState.status === AsyncStatus.Error
|
||||||
|
? batteryState.error
|
||||||
|
: pingState.status === AsyncStatus.Error
|
||||||
|
? pingState.error
|
||||||
|
: undefined;
|
||||||
|
|
||||||
const statusDescription = (() => {
|
const statusDescription = (() => {
|
||||||
if (loading) return 'Loading status…';
|
if (loading) return 'Loading status…';
|
||||||
if (status === undefined) {
|
if (status === undefined) {
|
||||||
return (
|
return (
|
||||||
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
|
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
|
||||||
Failed to read push status.
|
Failed to read the message listener status.
|
||||||
</Text>
|
</Text>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (status.registered) {
|
if (status.error) {
|
||||||
|
return (
|
||||||
|
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
|
||||||
|
{status.error}
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (status.notificationsAllowed === false) {
|
||||||
|
return (
|
||||||
|
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
|
||||||
|
Allow notifications for Paarrot, then tap Start.
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (status.listening && status.batteryIgnored) {
|
||||||
return (
|
return (
|
||||||
<Text as="span" size="T200">
|
<Text as="span" size="T200">
|
||||||
{`Distributor: ${status.distributor || 'unknown'}`}
|
Paarrot is listening for messages.
|
||||||
</Text>
|
</Text>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (status.lastFailure === 'AUTO_START_BLOCKED' || status.autoStartBlocked) {
|
if (status.listening) {
|
||||||
return (
|
return (
|
||||||
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
|
<Text as="span" size="T200">
|
||||||
Phone is blocking auto-start for Paarrot. Open App Boot / Auto-start settings, allow Paarrot (and ntfy), then tap Reset.
|
Paarrot is listening. Allow unrestricted battery so Android leaves it running.
|
||||||
</Text>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (status.lastFailure) {
|
|
||||||
return (
|
|
||||||
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
|
|
||||||
{`Registration failed (${status.lastFailure}). Tap Reset and pick ntfy again.`}
|
|
||||||
</Text>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (status.distributors.length === 0) {
|
|
||||||
return (
|
|
||||||
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
|
|
||||||
No UnifiedPush distributor found. Install ntfy from Play Store/F-Droid and enable UnifiedPush in ntfy settings.
|
|
||||||
</Text>
|
</Text>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<Text as="span" style={{ color: color.Warning?.Main ?? color.Critical.Main }} size="T200">
|
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
|
||||||
{`Found ${status.distributors.join(', ')} but not registered yet. Tap Reset and pick ntfy.`}
|
The message listener is stopped. Tap Start.
|
||||||
</Text>
|
</Text>
|
||||||
);
|
);
|
||||||
})();
|
})();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box direction="Column" gap="100">
|
<Box direction="Column" gap="100">
|
||||||
<Text size="L400">Android Push (UnifiedPush)</Text>
|
<Text size="L400">Android Notifications</Text>
|
||||||
<SequenceCard
|
<SequenceCard
|
||||||
className={SequenceCardStyle}
|
className={SequenceCardStyle}
|
||||||
variant="SurfaceVariant"
|
variant="SurfaceVariant"
|
||||||
@@ -286,48 +276,78 @@ function AndroidPushNotifications() {
|
|||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Background Notifications"
|
title="Message listener"
|
||||||
description={
|
description={
|
||||||
<>
|
<>
|
||||||
{statusDescription}
|
{statusDescription}
|
||||||
{lastError ? (
|
{actionError !== undefined && (
|
||||||
<Text as="span" style={{ color: color.Critical.Main, display: 'block' }} size="T200">
|
<Text as="span" style={{ color: color.Critical.Main, display: 'block' }} size="T200">
|
||||||
{lastError}
|
{actionError instanceof Error ? actionError.message : String(actionError)}
|
||||||
</Text>
|
</Text>
|
||||||
) : null}
|
)}
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
after={loading ? <Spinner variant="Secondary" /> : undefined}
|
after={
|
||||||
|
loading ? (
|
||||||
|
<Spinner variant="Secondary" />
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
size="300"
|
||||||
|
radii="300"
|
||||||
|
variant="Secondary"
|
||||||
|
disabled={isBusy || Boolean(status?.listening)}
|
||||||
|
onClick={() =>
|
||||||
|
void startListener().catch((err) =>
|
||||||
|
console.error('[AndroidNotifications] Failed to start listener:', err)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{startState.status === AsyncStatus.Loading ? (
|
||||||
|
<Spinner variant="Secondary" size="200" />
|
||||||
|
) : (
|
||||||
|
<Text size="B300">{status?.listening ? 'Running' : 'Start'}</Text>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Change Distributor"
|
title="Unrestricted battery"
|
||||||
description="Shows a list of installed UnifiedPush apps (ntfy, etc.) and registers the one you pick."
|
description="Lets the listener stay awake when the screen is off."
|
||||||
after={
|
after={
|
||||||
<Button
|
<Button
|
||||||
size="300"
|
size="300"
|
||||||
radii="300"
|
radii="300"
|
||||||
variant="Secondary"
|
variant="Secondary"
|
||||||
disabled={isBusy}
|
disabled={isBusy || Boolean(status?.batteryIgnored)}
|
||||||
onClick={() => void reset()}
|
onClick={() =>
|
||||||
|
void allowBattery().catch((err) =>
|
||||||
|
console.error('[AndroidNotifications] Failed to request battery exemption:', err)
|
||||||
|
)
|
||||||
|
}
|
||||||
>
|
>
|
||||||
{resetState.status === AsyncStatus.Loading ? (
|
{batteryState.status === AsyncStatus.Loading ? (
|
||||||
<Spinner variant="Secondary" size="200" />
|
<Spinner variant="Secondary" size="200" />
|
||||||
) : (
|
) : (
|
||||||
<Text size="B300">Reset</Text>
|
<Text size="B300">{status?.batteryIgnored ? 'Allowed' : 'Allow'}</Text>
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Test Notification"
|
title="Test Notification"
|
||||||
description="Trigger a test push ping to verify the pipeline works."
|
description="Ask the listener to check for messages now."
|
||||||
after={
|
after={
|
||||||
<Button
|
<Button
|
||||||
size="300"
|
size="300"
|
||||||
radii="300"
|
radii="300"
|
||||||
variant="Secondary"
|
variant="Secondary"
|
||||||
disabled={isBusy}
|
disabled={isBusy}
|
||||||
onClick={() => void ping()}
|
onClick={() =>
|
||||||
|
void ping().catch((err) =>
|
||||||
|
console.error('[AndroidNotifications] Failed to trigger listener sync:', err)
|
||||||
|
)
|
||||||
|
}
|
||||||
>
|
>
|
||||||
{pingState.status === AsyncStatus.Loading ? (
|
{pingState.status === AsyncStatus.Loading ? (
|
||||||
<Spinner variant="Secondary" size="200" />
|
<Spinner variant="Secondary" size="200" />
|
||||||
|
|||||||
@@ -724,7 +724,7 @@ function MessageNotifications() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Configures native Android push-ping background sync on login, keeps it
|
* Configures the native Android message listener on login, keeps it
|
||||||
* informed of foreground state so it doesn't double-fire notifications,
|
* informed of foreground state so it doesn't double-fire notifications,
|
||||||
* and clears it cleanly on unmount (logout).
|
* and clears it cleanly on unmount (logout).
|
||||||
* Only active on Android Capacitor builds.
|
* Only active on Android Capacitor builds.
|
||||||
@@ -741,15 +741,25 @@ function BackgroundSyncSetup() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
console.log('BackgroundSyncSetup: Starting background sync for', mx.getUserId());
|
console.log('BackgroundSyncSetup: Starting background sync for', mx.getUserId());
|
||||||
startBackgroundSync(mx);
|
void startBackgroundSync(mx).catch((err) => {
|
||||||
|
console.error('[BackgroundSyncSetup] Failed to start message listener:', err);
|
||||||
|
});
|
||||||
|
|
||||||
const onVisibility = () => setAppForegroundState(!document.hidden);
|
const onVisibility = () => {
|
||||||
|
void setAppForegroundState(!document.hidden).catch((err) => {
|
||||||
|
console.error('[BackgroundSyncSetup] Failed to update foreground state:', err);
|
||||||
|
});
|
||||||
|
};
|
||||||
document.addEventListener('visibilitychange', onVisibility);
|
document.addEventListener('visibilitychange', onVisibility);
|
||||||
setAppForegroundState(!document.hidden);
|
void setAppForegroundState(!document.hidden).catch((err) => {
|
||||||
|
console.error('[BackgroundSyncSetup] Failed to set initial foreground state:', err);
|
||||||
|
});
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
document.removeEventListener('visibilitychange', onVisibility);
|
document.removeEventListener('visibilitychange', onVisibility);
|
||||||
stopBackgroundSync();
|
void stopBackgroundSync().catch((err) => {
|
||||||
|
console.error('[BackgroundSyncSetup] Failed to stop message listener:', err);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
}, [mx]);
|
}, [mx]);
|
||||||
|
|
||||||
|
|||||||
@@ -1,627 +1,191 @@
|
|||||||
import { Capacitor, registerPlugin, type PluginListenerHandle } from '@capacitor/core';
|
|
||||||
import type { IPusherRequest, MatrixClient } from 'matrix-js-sdk';
|
import type { IPusherRequest, MatrixClient } from 'matrix-js-sdk';
|
||||||
|
|
||||||
type UnifiedPushStatus = {
|
export type ListenerStatus = {
|
||||||
running: boolean;
|
running: boolean;
|
||||||
endpoint: string;
|
listening: boolean;
|
||||||
instance: string;
|
batteryIgnored: boolean;
|
||||||
registered: boolean;
|
notificationsAllowed?: boolean;
|
||||||
distributor: string;
|
error?: string;
|
||||||
distributors: string[] | string;
|
|
||||||
lastFailure?: string;
|
|
||||||
/** OEM App Boot / AUTO_START is blocking distributor broadcasts (e.g. TCL). */
|
|
||||||
autoStartBlocked?: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
type ClearRoomNotificationsResult = {
|
|
||||||
cleared: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
type UnifiedPushEndpointEvent = {
|
|
||||||
endpoint: string;
|
|
||||||
previousEndpoint: string;
|
|
||||||
instance: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
type UnifiedPushUnregisteredEvent = {
|
|
||||||
previousEndpoint: string;
|
|
||||||
instance: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
type UnifiedPushRegistrationFailedEvent = {
|
|
||||||
reason: string;
|
|
||||||
instance: string;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
interface MatrixBackgroundSyncPlugin {
|
interface MatrixBackgroundSyncPlugin {
|
||||||
/** Persist credentials and request UnifiedPush registration. */
|
|
||||||
start(options: {
|
start(options: {
|
||||||
homeserverUrl: string;
|
homeserverUrl: string;
|
||||||
accessToken: string;
|
accessToken: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
deviceId: string;
|
deviceId: string;
|
||||||
}): Promise<void>;
|
}): Promise<{ batteryIgnored?: boolean }>;
|
||||||
/** Trigger a one-shot fetch as if a push ping arrived. */
|
|
||||||
triggerPing(options: { reason?: string }): Promise<void>;
|
triggerPing(options: { reason?: string }): Promise<void>;
|
||||||
/** Re-open distributor setup flow and retry registration. */
|
|
||||||
requestDistributorSetup(): Promise<{ success: boolean }>;
|
|
||||||
/** Stop any in-flight fetch, clear credentials, and unregister UnifiedPush. */
|
|
||||||
stop(): Promise<void>;
|
stop(): Promise<void>;
|
||||||
/**
|
|
||||||
* Notify the service whether the app UI is visible.
|
|
||||||
* When foreground is true, the service suppresses native notifications
|
|
||||||
* because the JS layer handles them via LocalNotifications.
|
|
||||||
*/
|
|
||||||
setAppForeground(options: { foreground: boolean }): Promise<void>;
|
setAppForeground(options: { foreground: boolean }): Promise<void>;
|
||||||
/** Returns fetch state and current UnifiedPush registration details. */
|
getStatus(): Promise<ListenerStatus>;
|
||||||
getStatus(): Promise<UnifiedPushStatus>;
|
requestBatteryExemption(): Promise<{ ignored: boolean }>;
|
||||||
/** Native Matrix gateway discovery for a UnifiedPush endpoint (avoids WebView CORS). */
|
getPendingNotificationNav(): Promise<NotificationNavTarget>;
|
||||||
resolveUnifiedPushGateway(options: { endpoint: string }): Promise<{ gatewayUrl: string }>;
|
clearRoomNotifications(options: { roomId: string }): Promise<void>;
|
||||||
/** Cancel native tray notifications posted for a Matrix room. */
|
|
||||||
clearRoomNotifications(options: { roomId: string }): Promise<ClearRoomNotificationsResult>;
|
|
||||||
/**
|
|
||||||
* Persist room → space/group metadata so background notifications can nest
|
|
||||||
* under Direct messages / Space name / Home.
|
|
||||||
*/
|
|
||||||
setNotificationGroups(options: {
|
setNotificationGroups(options: {
|
||||||
rooms: Record<
|
rooms: Record<string, { groupId: string; groupName: string; roomName: string; kind: string }>;
|
||||||
string,
|
}): Promise<void>;
|
||||||
{ groupId: string; groupName: string; roomName: string; kind: string }
|
showNotification(options: NativeNotificationOptions): Promise<{ shown: boolean }>;
|
||||||
>;
|
addListener?(
|
||||||
}): Promise<{ success: boolean }>;
|
|
||||||
/** Post a message notification with optional avatar (base64) from the JS layer. */
|
|
||||||
showNotification(options: {
|
|
||||||
title?: string;
|
|
||||||
body?: string;
|
|
||||||
senderName?: string;
|
|
||||||
messageText?: string;
|
|
||||||
conversationTitle?: string;
|
|
||||||
path?: string;
|
|
||||||
roomId: string;
|
|
||||||
groupId: string;
|
|
||||||
groupName: string;
|
|
||||||
kind: string;
|
|
||||||
largeIconBase64?: string;
|
|
||||||
bigPictureBase64?: string;
|
|
||||||
}): Promise<{ shown: boolean }>;
|
|
||||||
/** Pending navigation target from a native notification tap. */
|
|
||||||
getPendingNotificationNav(): Promise<{ path?: string | null; roomId?: string | null }>;
|
|
||||||
addListener(
|
|
||||||
eventName: 'notificationOpened',
|
eventName: 'notificationOpened',
|
||||||
listenerFunc: (event: { path?: string; roomId?: string }) => void
|
listener: (target: NotificationNavTarget) => void
|
||||||
): Promise<PluginListenerHandle>;
|
): Promise<{ remove: () => void }>;
|
||||||
addListener(
|
|
||||||
eventName: 'unifiedPushNewEndpoint',
|
|
||||||
listenerFunc: (event: UnifiedPushEndpointEvent) => void
|
|
||||||
): Promise<PluginListenerHandle>;
|
|
||||||
addListener(
|
|
||||||
eventName: 'unifiedPushUnregistered',
|
|
||||||
listenerFunc: (event: UnifiedPushUnregisteredEvent) => void
|
|
||||||
): Promise<PluginListenerHandle>;
|
|
||||||
addListener(
|
|
||||||
eventName: 'unifiedPushRegistrationFailed',
|
|
||||||
listenerFunc: (event: UnifiedPushRegistrationFailedEvent) => void
|
|
||||||
): Promise<PluginListenerHandle>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type StoredPusherState = {
|
type CapacitorGlobal = {
|
||||||
endpoint: string;
|
isNativePlatform?: () => boolean;
|
||||||
appId: string;
|
getPlatform?: () => string;
|
||||||
|
isPluginAvailable?: (name: string) => boolean;
|
||||||
|
registerPlugin?: <T>(name: string) => T;
|
||||||
|
nativePromise?: (plugin: string, method: string, options?: unknown) => Promise<unknown>;
|
||||||
|
Plugins?: Record<string, Partial<MatrixBackgroundSyncPlugin> | undefined>;
|
||||||
};
|
};
|
||||||
|
|
||||||
const MatrixBackgroundSync = registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
|
const PLUGIN = 'MatrixBackgroundSync';
|
||||||
const DEFAULT_UNIFIED_PUSH_GATEWAY = 'https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify';
|
const LEGACY_PUSHER_APP_ID = 'com.paarrot.app.android';
|
||||||
const PUSHER_APP_ID_BASE = 'com.paarrot.app.android';
|
const LEGACY_PUSHER_STORAGE_PREFIX = 'paarrot.unifiedpush';
|
||||||
const PUSHER_STORAGE_PREFIX = 'paarrot.unifiedpush';
|
|
||||||
|
const capacitor = (): CapacitorGlobal | undefined =>
|
||||||
|
(window as typeof window & { Capacitor?: CapacitorGlobal }).Capacitor;
|
||||||
|
|
||||||
/** Returns true when the current platform is Android Capacitor. */
|
/** Returns true when the current platform is Android Capacitor. */
|
||||||
export const isBackgroundSyncSupported = (): boolean =>
|
export const isBackgroundSyncSupported = (): boolean => {
|
||||||
Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android';
|
const cap = capacitor();
|
||||||
|
return Boolean(cap?.isNativePlatform?.() && cap.getPlatform?.() === 'android');
|
||||||
const getStoredPusherKey = (userId: string | null, deviceId: string | null): string =>
|
|
||||||
`${PUSHER_STORAGE_PREFIX}:${userId ?? 'unknown'}:${deviceId ?? 'unknown'}`;
|
|
||||||
|
|
||||||
const buildPusherAppId = (deviceId: string | null): string => {
|
|
||||||
const raw = deviceId ? `${PUSHER_APP_ID_BASE}.${deviceId}` : PUSHER_APP_ID_BASE;
|
|
||||||
return raw.length > 64 ? raw.slice(0, 64) : raw;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadStoredPusherState = (
|
const waitForBridge = async (tries = 50): Promise<CapacitorGlobal> => {
|
||||||
userId: string | null,
|
for (let i = 0; i < tries; i += 1) {
|
||||||
deviceId: string | null
|
const cap = capacitor();
|
||||||
): StoredPusherState | undefined => {
|
if (
|
||||||
if (typeof window === 'undefined' || !window.localStorage) return undefined;
|
cap?.isNativePlatform?.() &&
|
||||||
|
(cap.Plugins?.[PLUGIN] || cap.nativePromise || cap.registerPlugin)
|
||||||
const raw = window.localStorage.getItem(getStoredPusherKey(userId, deviceId));
|
) {
|
||||||
if (!raw) return undefined;
|
return cap;
|
||||||
|
}
|
||||||
try {
|
await new Promise((resolve) => window.setTimeout(resolve, 100));
|
||||||
return JSON.parse(raw) as StoredPusherState;
|
|
||||||
} catch {
|
|
||||||
return undefined;
|
|
||||||
}
|
}
|
||||||
|
throw new Error('Capacitor bridge did not become ready');
|
||||||
};
|
};
|
||||||
|
|
||||||
const saveStoredPusherState = (
|
/** Android injects plugins on Capacitor.Plugins — registerPlugin is often missing. */
|
||||||
userId: string | null,
|
const plugin = async (): Promise<MatrixBackgroundSyncPlugin> => {
|
||||||
deviceId: string | null,
|
const cap = await waitForBridge();
|
||||||
state: StoredPusherState
|
const existing = cap.Plugins?.[PLUGIN];
|
||||||
): void => {
|
if (existing?.getStatus && existing.start) {
|
||||||
if (typeof window === 'undefined' || !window.localStorage) return;
|
return existing as MatrixBackgroundSyncPlugin;
|
||||||
window.localStorage.setItem(getStoredPusherKey(userId, deviceId), JSON.stringify(state));
|
|
||||||
};
|
|
||||||
|
|
||||||
const clearStoredPusherState = (userId: string | null, deviceId: string | null): void => {
|
|
||||||
if (typeof window === 'undefined' || !window.localStorage) return;
|
|
||||||
window.localStorage.removeItem(getStoredPusherKey(userId, deviceId));
|
|
||||||
};
|
|
||||||
|
|
||||||
const normalizeDistributors = (raw: UnifiedPushStatus['distributors']): string[] => {
|
|
||||||
if (Array.isArray(raw)) return raw;
|
|
||||||
if (typeof raw !== 'string') return [];
|
|
||||||
|
|
||||||
const trimmed = raw.trim();
|
|
||||||
if (!trimmed || trimmed === '[]') return [];
|
|
||||||
|
|
||||||
if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
|
|
||||||
return trimmed
|
|
||||||
.slice(1, -1)
|
|
||||||
.split(',')
|
|
||||||
.map((entry) => entry.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return [trimmed];
|
if (typeof cap.nativePromise === 'function') {
|
||||||
};
|
const call = <T>(method: string, options?: unknown) =>
|
||||||
|
cap.nativePromise!(PLUGIN, method, options ?? {}) as Promise<T>;
|
||||||
const resolveUnifiedPushGateway = async (endpoint: string): Promise<string> => {
|
return {
|
||||||
// Prefer native HTTP — ntfy/Matrix gateway responses omit CORS headers, so
|
start: (options) => call('start', options),
|
||||||
// WebView fetch fails with TypeError: Failed to fetch and wrongly falls back.
|
triggerPing: (options) => call('triggerPing', options),
|
||||||
try {
|
stop: () => call('stop'),
|
||||||
const result = await MatrixBackgroundSync.resolveUnifiedPushGateway({ endpoint });
|
setAppForeground: (options) => call('setAppForeground', options),
|
||||||
if (result?.gatewayUrl) return result.gatewayUrl;
|
getStatus: () => call('getStatus'),
|
||||||
} catch (err) {
|
requestBatteryExemption: () => call('requestBatteryExemption'),
|
||||||
console.warn('[BackgroundSync] Native UnifiedPush gateway discovery failed:', err);
|
getPendingNotificationNav: () => call('getPendingNotificationNav'),
|
||||||
}
|
clearRoomNotifications: (options) => call('clearRoomNotifications', options),
|
||||||
|
setNotificationGroups: (options) => call('setNotificationGroups', options),
|
||||||
try {
|
showNotification: (options) => call('showNotification', options),
|
||||||
const discoveryUrl = new URL(endpoint);
|
|
||||||
discoveryUrl.pathname = '/_matrix/push/v1/notify';
|
|
||||||
discoveryUrl.search = '';
|
|
||||||
|
|
||||||
const response = await fetch(discoveryUrl.toString(), { method: 'GET' });
|
|
||||||
if (!response.ok) return DEFAULT_UNIFIED_PUSH_GATEWAY;
|
|
||||||
|
|
||||||
const body = (await response.json()) as {
|
|
||||||
gateway?: string;
|
|
||||||
unifiedpush?: { gateway?: string };
|
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
if (body.gateway === 'matrix' || body.unifiedpush?.gateway === 'matrix') {
|
if (cap.registerPlugin) {
|
||||||
return discoveryUrl.toString();
|
return cap.registerPlugin<MatrixBackgroundSyncPlugin>(PLUGIN);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('MatrixBackgroundSync is unavailable on this Capacitor bridge');
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Keep Paarrot's native message listener running without a push distributor. */
|
||||||
|
export const startBackgroundSync = async (mx: MatrixClient): Promise<void> => {
|
||||||
|
if (!isBackgroundSyncSupported()) return;
|
||||||
|
|
||||||
|
const homeserverUrl = mx.getHomeserverUrl();
|
||||||
|
const accessToken = mx.getAccessToken();
|
||||||
|
const userId = mx.getUserId();
|
||||||
|
const deviceId = mx.getDeviceId();
|
||||||
|
if (!homeserverUrl || !accessToken || !userId) return;
|
||||||
|
|
||||||
|
const legacyAppId = `${LEGACY_PUSHER_APP_ID}${deviceId ? `.${deviceId}` : ''}`.slice(0, 64);
|
||||||
|
try {
|
||||||
|
const pushers = (await mx.getPushers())?.pushers ?? [];
|
||||||
|
for (const pusher of pushers) {
|
||||||
|
if (pusher.kind === 'http' && pusher.app_id === legacyAppId) {
|
||||||
|
await mx.setPusher({
|
||||||
|
pushkey: pusher.pushkey,
|
||||||
|
app_id: pusher.app_id,
|
||||||
|
kind: null,
|
||||||
|
} as unknown as IPusherRequest);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.warn('[BackgroundSync] UnifiedPush gateway discovery failed:', err);
|
console.warn('[BackgroundSync] Failed to remove the previous UnifiedPush pusher:', err);
|
||||||
|
}
|
||||||
|
if (typeof window !== 'undefined' && window.localStorage) {
|
||||||
|
window.localStorage.removeItem(
|
||||||
|
`${LEGACY_PUSHER_STORAGE_PREFIX}:${userId}:${deviceId ?? 'unknown'}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return DEFAULT_UNIFIED_PUSH_GATEWAY;
|
await (await plugin()).start({
|
||||||
|
homeserverUrl,
|
||||||
|
accessToken,
|
||||||
|
userId,
|
||||||
|
deviceId: deviceId ?? '',
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
class AndroidUnifiedPushManager {
|
/** Stop the listener and drop saved credentials. Call this on logout. */
|
||||||
private client: MatrixClient | undefined;
|
export const stopBackgroundSync = async (): Promise<void> => {
|
||||||
|
if (!isBackgroundSyncSupported()) return;
|
||||||
private listenerHandles: PluginListenerHandle[] = [];
|
await (await plugin()).stop();
|
||||||
|
|
||||||
private listenersReady = false;
|
|
||||||
|
|
||||||
private distributorSetupAttempted = false;
|
|
||||||
|
|
||||||
private distributorPromptShown = false;
|
|
||||||
|
|
||||||
/** Start native UnifiedPush registration and synchronize the Matrix pusher. */
|
|
||||||
async start(mx: MatrixClient): Promise<void> {
|
|
||||||
console.log('[BackgroundSync] start() called, platform:', Capacitor.getPlatform(), 'isNative:', Capacitor.isNativePlatform());
|
|
||||||
|
|
||||||
if (!isBackgroundSyncSupported()) {
|
|
||||||
console.log('[BackgroundSync] Background sync not supported on this platform');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const homeserverUrl = mx.getHomeserverUrl();
|
|
||||||
const accessToken = mx.getAccessToken();
|
|
||||||
const userId = mx.getUserId();
|
|
||||||
const deviceId = mx.getDeviceId();
|
|
||||||
|
|
||||||
console.log('[BackgroundSync] Credentials check:', { userId, deviceId, hasToken: !!accessToken, hasUrl: !!homeserverUrl });
|
|
||||||
|
|
||||||
if (!homeserverUrl || !accessToken || !userId) {
|
|
||||||
console.warn('[BackgroundSync] Missing credentials, not starting');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.client = mx;
|
|
||||||
this.distributorSetupAttempted = false;
|
|
||||||
this.distributorPromptShown = false;
|
|
||||||
await this.ensureListeners();
|
|
||||||
|
|
||||||
try {
|
|
||||||
console.log('[BackgroundSync] Calling plugin.start()...');
|
|
||||||
await MatrixBackgroundSync.start({
|
|
||||||
homeserverUrl,
|
|
||||||
accessToken,
|
|
||||||
userId,
|
|
||||||
deviceId: deviceId ?? '',
|
|
||||||
});
|
|
||||||
console.log('[BackgroundSync] plugin.start() completed');
|
|
||||||
} catch (err) {
|
|
||||||
console.error('[BackgroundSync] plugin.start() failed:', err);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.syncExistingEndpoint();
|
|
||||||
await this.ensureDistributorPromptFromStatus();
|
|
||||||
console.log('[BackgroundSync] UnifiedPush registration requested');
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Stop native UnifiedPush integration and remove the Matrix pusher for this device. */
|
|
||||||
async stop(): Promise<void> {
|
|
||||||
if (!isBackgroundSyncSupported()) return;
|
|
||||||
|
|
||||||
const client = this.client;
|
|
||||||
if (client) {
|
|
||||||
const deviceId = client.getDeviceId();
|
|
||||||
const userId = client.getUserId();
|
|
||||||
const status = await this.safeGetStatus();
|
|
||||||
const stored = loadStoredPusherState(userId, deviceId);
|
|
||||||
const endpoint = status?.endpoint || stored?.endpoint;
|
|
||||||
const appId = stored?.appId ?? buildPusherAppId(deviceId);
|
|
||||||
|
|
||||||
if (endpoint) {
|
|
||||||
await this.removePusher(client, endpoint, appId);
|
|
||||||
}
|
|
||||||
clearStoredPusherState(userId, deviceId);
|
|
||||||
}
|
|
||||||
|
|
||||||
await MatrixBackgroundSync.stop();
|
|
||||||
await this.disposeListeners();
|
|
||||||
this.client = undefined;
|
|
||||||
console.log('[BackgroundSync] UnifiedPush stopped');
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Update the Matrix pusher when a new native endpoint is published. */
|
|
||||||
private async handleNewEndpoint(event: UnifiedPushEndpointEvent): Promise<void> {
|
|
||||||
const client = this.client;
|
|
||||||
if (!client) return;
|
|
||||||
|
|
||||||
if (event.previousEndpoint) {
|
|
||||||
await this.removePusher(client, event.previousEndpoint);
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.upsertPusher(client, event.endpoint);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Remove the Matrix pusher when UnifiedPush unregisters this instance. */
|
|
||||||
private async handleUnregistered(event: UnifiedPushUnregisteredEvent): Promise<void> {
|
|
||||||
const client = this.client;
|
|
||||||
if (!client) return;
|
|
||||||
|
|
||||||
const stored = loadStoredPusherState(client.getUserId(), client.getDeviceId());
|
|
||||||
const endpoint = event.previousEndpoint || stored?.endpoint;
|
|
||||||
const appId = stored?.appId ?? buildPusherAppId(client.getDeviceId());
|
|
||||||
|
|
||||||
if (endpoint) {
|
|
||||||
await this.removePusher(client, endpoint, appId);
|
|
||||||
}
|
|
||||||
|
|
||||||
clearStoredPusherState(client.getUserId(), client.getDeviceId());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Log native registration failures so the missing distributor path is visible. */
|
|
||||||
private handleRegistrationFailed(event: UnifiedPushRegistrationFailedEvent): void {
|
|
||||||
console.warn('[BackgroundSync] UnifiedPush registration failed:', event.reason);
|
|
||||||
|
|
||||||
if (event.reason !== 'ACTION_REQUIRED' || this.distributorSetupAttempted) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.distributorSetupAttempted = true;
|
|
||||||
void this.tryRequestDistributorSetup();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Re-opens distributor selection once after ACTION_REQUIRED and logs actionable status. */
|
|
||||||
private async tryRequestDistributorSetup(): Promise<void> {
|
|
||||||
try {
|
|
||||||
const setupResult = await MatrixBackgroundSync.requestDistributorSetup();
|
|
||||||
console.warn('[BackgroundSync] requestDistributorSetup result:', setupResult);
|
|
||||||
const status = await this.safeGetStatus();
|
|
||||||
console.warn('[BackgroundSync] UnifiedPush status after setup attempt:', status);
|
|
||||||
const distributors = normalizeDistributors(status?.distributors ?? []);
|
|
||||||
if (distributors.length === 0) {
|
|
||||||
console.error(
|
|
||||||
'[BackgroundSync] No UnifiedPush distributor installed. Install one (for example ntfy) to enable Android background notifications.'
|
|
||||||
);
|
|
||||||
this.showNoDistributorPrompt();
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] requestDistributorSetup failed:', err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Fallback check so users still get prompted even when ACTION_REQUIRED event is missed. */
|
|
||||||
private async ensureDistributorPromptFromStatus(): Promise<void> {
|
|
||||||
const status = await this.safeGetStatus();
|
|
||||||
if (!status) return;
|
|
||||||
|
|
||||||
const distributors = normalizeDistributors(status.distributors);
|
|
||||||
if (!status.registered && distributors.length === 0) {
|
|
||||||
console.error(
|
|
||||||
'[BackgroundSync] No UnifiedPush distributor installed. Install one (for example ntfy) to enable Android background notifications.'
|
|
||||||
);
|
|
||||||
this.showNoDistributorPrompt();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Show a one-time actionable prompt when no distributor app is installed. */
|
|
||||||
private showNoDistributorPrompt(): void {
|
|
||||||
if (this.distributorPromptShown) return;
|
|
||||||
this.distributorPromptShown = true;
|
|
||||||
|
|
||||||
const message =
|
|
||||||
'Android background notifications need a UnifiedPush distributor app. Install one (for example ntfy), then reopen Paarrot.';
|
|
||||||
const docsUrl = 'https://unifiedpush.org/users/distributors/';
|
|
||||||
|
|
||||||
if (typeof window === 'undefined') return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const openDocs = window.confirm(`${message}\n\nOpen distributor list now?`);
|
|
||||||
if (openDocs) {
|
|
||||||
window.open(docsUrl, '_blank', 'noopener,noreferrer');
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
window.alert(message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Install plugin listeners once for the active Matrix client. */
|
|
||||||
private async ensureListeners(): Promise<void> {
|
|
||||||
if (this.listenersReady) return;
|
|
||||||
|
|
||||||
this.listenerHandles = [
|
|
||||||
await MatrixBackgroundSync.addListener('unifiedPushNewEndpoint', (event) => {
|
|
||||||
void this.handleNewEndpoint(event).catch((err) => {
|
|
||||||
console.error('[BackgroundSync] handleNewEndpoint failed:', err);
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
await MatrixBackgroundSync.addListener('unifiedPushUnregistered', (event) => {
|
|
||||||
void this.handleUnregistered(event);
|
|
||||||
}),
|
|
||||||
await MatrixBackgroundSync.addListener('unifiedPushRegistrationFailed', (event) => {
|
|
||||||
this.handleRegistrationFailed(event);
|
|
||||||
}),
|
|
||||||
];
|
|
||||||
this.listenersReady = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Remove all plugin listeners when the manager stops. */
|
|
||||||
private async disposeListeners(): Promise<void> {
|
|
||||||
await Promise.all(this.listenerHandles.map((handle) => handle.remove()));
|
|
||||||
this.listenerHandles = [];
|
|
||||||
this.listenersReady = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Reconcile an already-persisted native endpoint after app startup. */
|
|
||||||
private async syncExistingEndpoint(): Promise<void> {
|
|
||||||
const client = this.client;
|
|
||||||
if (!client) return;
|
|
||||||
|
|
||||||
const status = await this.safeGetStatus();
|
|
||||||
console.log('[BackgroundSync] Native status before pusher sync:', status);
|
|
||||||
if (status?.registered && status.endpoint) {
|
|
||||||
await this.upsertPusher(client, status.endpoint);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Create or refresh the Matrix HTTP pusher for the current device. */
|
|
||||||
private async upsertPusher(mx: MatrixClient, endpoint: string): Promise<void> {
|
|
||||||
const deviceId = mx.getDeviceId();
|
|
||||||
const userId = mx.getUserId();
|
|
||||||
const appId = buildPusherAppId(deviceId);
|
|
||||||
const gatewayUrl = await resolveUnifiedPushGateway(endpoint);
|
|
||||||
|
|
||||||
console.log('[BackgroundSync] Upserting Matrix pusher', {
|
|
||||||
appId,
|
|
||||||
endpoint,
|
|
||||||
gatewayUrl,
|
|
||||||
deviceId,
|
|
||||||
userId,
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
await mx.setPusher({
|
|
||||||
kind: 'http',
|
|
||||||
app_id: appId,
|
|
||||||
pushkey: endpoint,
|
|
||||||
app_display_name: 'Paarrot',
|
|
||||||
device_display_name: deviceId ?? 'Android',
|
|
||||||
lang: 'en',
|
|
||||||
data: {
|
|
||||||
url: gatewayUrl,
|
|
||||||
format: 'event_id_only',
|
|
||||||
},
|
|
||||||
append: false,
|
|
||||||
device_id: deviceId ?? undefined,
|
|
||||||
} as unknown as IPusherRequest);
|
|
||||||
|
|
||||||
const pushers = (await mx.getPushers())?.pushers ?? [];
|
|
||||||
const thisPusher = pushers.find((p) => p.pushkey === endpoint && p.app_id === appId);
|
|
||||||
console.log('[BackgroundSync] Matrix pusher upserted successfully', {
|
|
||||||
totalPushers: pushers.length,
|
|
||||||
foundThisPusher: Boolean(thisPusher),
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
console.error('[BackgroundSync] Matrix pusher upsert failed:', err);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
|
|
||||||
saveStoredPusherState(userId, deviceId, { endpoint, appId });
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Remove a previously-registered Matrix HTTP pusher for this device. */
|
|
||||||
private async removePusher(
|
|
||||||
mx: MatrixClient,
|
|
||||||
endpoint: string,
|
|
||||||
appId = buildPusherAppId(mx.getDeviceId())
|
|
||||||
): Promise<void> {
|
|
||||||
try {
|
|
||||||
await mx.setPusher({
|
|
||||||
pushkey: endpoint,
|
|
||||||
app_id: appId,
|
|
||||||
kind: null,
|
|
||||||
} as unknown as IPusherRequest);
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] Failed to remove UnifiedPush pusher:', err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Read native registration state without failing the caller. */
|
|
||||||
private async safeGetStatus(): Promise<UnifiedPushStatus | undefined> {
|
|
||||||
try {
|
|
||||||
return await MatrixBackgroundSync.getStatus();
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] Failed to read UnifiedPush status:', err);
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const unifiedPushManager = new AndroidUnifiedPushManager();
|
|
||||||
|
|
||||||
/** Start native UnifiedPush registration and sync the Matrix pusher. */
|
|
||||||
export const startBackgroundSync = async (mx: MatrixClient): Promise<void> => {
|
|
||||||
await unifiedPushManager.start(mx);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/** Ask the listener to sync now. */
|
||||||
* Manually triggers a one-shot native fetch.
|
|
||||||
* Useful for diagnostics and bridge testing.
|
|
||||||
*/
|
|
||||||
export const triggerBackgroundSyncPing = async (reason?: string): Promise<void> => {
|
export const triggerBackgroundSyncPing = async (reason?: string): Promise<void> => {
|
||||||
if (!isBackgroundSyncSupported()) return;
|
if (!isBackgroundSyncSupported()) return;
|
||||||
|
await (await plugin()).triggerPing({ reason });
|
||||||
try {
|
|
||||||
await MatrixBackgroundSync.triggerPing({ reason });
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] triggerPing failed:', err);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Stop UnifiedPush integration and remove the Matrix pusher for this session. */
|
/** Tell the listener whether the chat UI is on screen. */
|
||||||
export const stopBackgroundSync = async (): Promise<void> => {
|
|
||||||
await unifiedPushManager.stop();
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tells the native service whether the app UI is in the foreground.
|
|
||||||
* Call when document visibility changes so the service can suppress
|
|
||||||
* duplicate notifications while the JS layer is active.
|
|
||||||
* @param foreground true if the WebView UI is currently visible
|
|
||||||
*/
|
|
||||||
export const setAppForegroundState = async (foreground: boolean): Promise<void> => {
|
export const setAppForegroundState = async (foreground: boolean): Promise<void> => {
|
||||||
if (!isBackgroundSyncSupported()) return;
|
if (!isBackgroundSyncSupported()) return;
|
||||||
|
await (await plugin()).setAppForeground({ foreground });
|
||||||
try {
|
|
||||||
await MatrixBackgroundSync.setAppForeground({ foreground });
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] setAppForeground failed:', err);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/** Ask Android to leave the listener out of battery optimization. */
|
||||||
* Re-opens the UnifiedPush distributor selection dialog.
|
export const requestBatteryExemption = async (): Promise<{ ignored: boolean }> => {
|
||||||
* Allows users to re-select or change their push notification distributor without terminal access.
|
if (!isBackgroundSyncSupported()) return { ignored: false };
|
||||||
* Useful when the current endpoint becomes unavailable.
|
return (await plugin()).requestBatteryExemption();
|
||||||
* Waits briefly for the distributor to return an endpoint so the settings UI can refresh accurately.
|
|
||||||
*/
|
|
||||||
export const requestResetPushRegistration = async (): Promise<{ success: boolean }> => {
|
|
||||||
if (!isBackgroundSyncSupported()) {
|
|
||||||
console.warn('[BackgroundSync] Background sync not supported on this platform');
|
|
||||||
return { success: false };
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = await MatrixBackgroundSync.requestDistributorSetup();
|
|
||||||
console.log('[BackgroundSync] requestDistributorSetup completed:', result);
|
|
||||||
if (!result?.success) return { success: false };
|
|
||||||
|
|
||||||
// Endpoint arrives asynchronously from the distributor after register().
|
|
||||||
for (let i = 0; i < 40; i += 1) {
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
||||||
const status = await getBackgroundSyncStatus();
|
|
||||||
if (status?.registered && status.endpoint) {
|
|
||||||
return { success: true };
|
|
||||||
}
|
|
||||||
if (status?.lastFailure) {
|
|
||||||
console.warn('[BackgroundSync] Registration failed while waiting:', status.lastFailure);
|
|
||||||
return { success: false };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
console.warn('[BackgroundSync] Distributor selected but no endpoint received in time');
|
|
||||||
return { success: false };
|
|
||||||
} catch (err) {
|
|
||||||
console.error('[BackgroundSync] requestDistributorSetup failed:', err);
|
|
||||||
return { success: false };
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Returns the current native UnifiedPush status, or undefined if unavailable. */
|
/** Returns listener and battery-exemption state. */
|
||||||
export const getBackgroundSyncStatus = async (): Promise<UnifiedPushStatus | undefined> => {
|
export const getBackgroundSyncStatus = async (): Promise<ListenerStatus | undefined> => {
|
||||||
if (!isBackgroundSyncSupported()) return undefined;
|
if (!isBackgroundSyncSupported()) return undefined;
|
||||||
try {
|
try {
|
||||||
return await MatrixBackgroundSync.getStatus();
|
return await (await plugin()).getStatus();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
console.warn('[BackgroundSync] getStatus failed:', err);
|
console.warn('[BackgroundSync] getStatus failed:', err);
|
||||||
return undefined;
|
return {
|
||||||
|
running: false,
|
||||||
|
listening: false,
|
||||||
|
batteryIgnored: false,
|
||||||
|
error: message,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
export type NotificationNavTarget = {
|
||||||
* Clears native (MatrixSyncService) tray notifications for a room after it is read.
|
path?: string | null;
|
||||||
* No-op when background sync / native Android is unavailable.
|
roomId?: string | null;
|
||||||
*/
|
|
||||||
export const clearNativeRoomNotifications = async (roomId: string): Promise<void> => {
|
|
||||||
if (!isBackgroundSyncSupported() || !roomId) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
await MatrixBackgroundSync.clearRoomNotifications({ roomId });
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] clearRoomNotifications failed:', err);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
export type NativeNotificationOptions = {
|
||||||
* Syncs space/DM grouping metadata to the native layer for background notifications.
|
|
||||||
*/
|
|
||||||
export const syncNotificationGroupMap = async (
|
|
||||||
rooms: Record<
|
|
||||||
string,
|
|
||||||
{ groupId: string; groupName: string; roomName: string; kind: string }
|
|
||||||
>
|
|
||||||
): Promise<void> => {
|
|
||||||
if (!isBackgroundSyncSupported()) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
await MatrixBackgroundSync.setNotificationGroups({ rooms });
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] setNotificationGroups failed:', err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Posts a native tray notification (supports dynamic/authenticated avatar icons).
|
|
||||||
* Prefer this over Capacitor LocalNotifications on Android.
|
|
||||||
*/
|
|
||||||
export const showNativeNotification = async (options: {
|
|
||||||
title?: string;
|
title?: string;
|
||||||
body?: string;
|
body?: string;
|
||||||
senderName?: string;
|
senderName?: string;
|
||||||
@@ -634,41 +198,122 @@ export const showNativeNotification = async (options: {
|
|||||||
kind: string;
|
kind: string;
|
||||||
largeIconBase64?: string;
|
largeIconBase64?: string;
|
||||||
bigPictureBase64?: string;
|
bigPictureBase64?: string;
|
||||||
}): Promise<boolean> => {
|
};
|
||||||
if (!isBackgroundSyncSupported()) return false;
|
|
||||||
|
|
||||||
|
/** Read a tray-tap target that opened the app before JS listeners attached. */
|
||||||
|
export const getPendingNotificationNav = async (): Promise<NotificationNavTarget | undefined> => {
|
||||||
|
if (!isBackgroundSyncSupported()) return undefined;
|
||||||
try {
|
try {
|
||||||
await MatrixBackgroundSync.showNotification(options);
|
const cap = await waitForBridge();
|
||||||
return true;
|
if (typeof cap.nativePromise === 'function') {
|
||||||
|
return (await cap.nativePromise(
|
||||||
|
PLUGIN,
|
||||||
|
'getPendingNotificationNav',
|
||||||
|
{}
|
||||||
|
)) as NotificationNavTarget;
|
||||||
|
}
|
||||||
|
const existing = cap.Plugins?.[PLUGIN] as
|
||||||
|
| { getPendingNotificationNav?: () => Promise<NotificationNavTarget> }
|
||||||
|
| undefined;
|
||||||
|
if (existing?.getPendingNotificationNav) {
|
||||||
|
return existing.getPendingNotificationNav();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[BackgroundSync] getPendingNotificationNav failed:', err);
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Subscribe to tray notification taps while the app is already running. */
|
||||||
|
export const subscribeNotificationOpened = async (
|
||||||
|
callback: (target: NotificationNavTarget) => void
|
||||||
|
): Promise<() => void> => {
|
||||||
|
if (!isBackgroundSyncSupported()) return () => undefined;
|
||||||
|
try {
|
||||||
|
const cap = await waitForBridge();
|
||||||
|
const existing = cap.Plugins?.[PLUGIN] as
|
||||||
|
| {
|
||||||
|
addListener?: (
|
||||||
|
event: string,
|
||||||
|
cb: (data: NotificationNavTarget) => void
|
||||||
|
) => Promise<{ remove: () => void }> | { remove: () => void };
|
||||||
|
}
|
||||||
|
| undefined;
|
||||||
|
const nativePlugin =
|
||||||
|
existing?.addListener
|
||||||
|
? existing
|
||||||
|
: cap.registerPlugin?.<MatrixBackgroundSyncPlugin>(PLUGIN);
|
||||||
|
if (!nativePlugin?.addListener) return () => undefined;
|
||||||
|
const handle = await nativePlugin.addListener('notificationOpened', callback);
|
||||||
|
return () => {
|
||||||
|
void handle.remove();
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[BackgroundSync] subscribeNotificationOpened failed:', err);
|
||||||
|
return () => undefined;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Dismiss native tray notifications for a room after it is opened / marked read. */
|
||||||
|
export const clearRoomNotifications = async (roomId: string): Promise<void> => {
|
||||||
|
if (!isBackgroundSyncSupported() || !roomId) return;
|
||||||
|
try {
|
||||||
|
const cap = await waitForBridge();
|
||||||
|
if (typeof cap.nativePromise === 'function') {
|
||||||
|
await cap.nativePromise(PLUGIN, 'clearRoomNotifications', { roomId });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const existing = cap.Plugins?.[PLUGIN] as
|
||||||
|
| { clearRoomNotifications?: (o: { roomId: string }) => Promise<void> }
|
||||||
|
| undefined;
|
||||||
|
await existing?.clearRoomNotifications?.({ roomId });
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[BackgroundSync] clearRoomNotifications failed:', err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Compatibility name used by the notification utility layer. */
|
||||||
|
export const clearNativeRoomNotifications = clearRoomNotifications;
|
||||||
|
|
||||||
|
/** Keep background notification grouping in sync with the active room list. */
|
||||||
|
export const syncNotificationGroupMap = async (
|
||||||
|
rooms: Record<string, { groupId: string; groupName: string; roomName: string; kind: string }>
|
||||||
|
): Promise<void> => {
|
||||||
|
if (!isBackgroundSyncSupported()) return;
|
||||||
|
try {
|
||||||
|
const cap = await waitForBridge();
|
||||||
|
if (typeof cap.nativePromise === 'function') {
|
||||||
|
await cap.nativePromise(PLUGIN, 'setNotificationGroups', { rooms });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const existing = cap.Plugins?.[PLUGIN] as
|
||||||
|
| { setNotificationGroups?: (options: { rooms: typeof rooms }) => Promise<void> }
|
||||||
|
| undefined;
|
||||||
|
await existing?.setNotificationGroups?.({ rooms });
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[BackgroundSync] setNotificationGroups failed:', err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Post a notification using Android's native NotificationManager. */
|
||||||
|
export const showNativeNotification = async (
|
||||||
|
options: NativeNotificationOptions
|
||||||
|
): Promise<boolean> => {
|
||||||
|
if (!isBackgroundSyncSupported()) return false;
|
||||||
|
try {
|
||||||
|
const cap = await waitForBridge();
|
||||||
|
if (typeof cap.nativePromise === 'function') {
|
||||||
|
const result = (await cap.nativePromise(PLUGIN, 'showNotification', options)) as {
|
||||||
|
shown?: boolean;
|
||||||
|
};
|
||||||
|
return result.shown === true;
|
||||||
|
}
|
||||||
|
const existing = cap.Plugins?.[PLUGIN] as
|
||||||
|
| { showNotification?: (options: NativeNotificationOptions) => Promise<{ shown: boolean }> }
|
||||||
|
| undefined;
|
||||||
|
return (await existing?.showNotification?.(options))?.shown === true;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.warn('[BackgroundSync] showNotification failed:', err);
|
console.warn('[BackgroundSync] showNotification failed:', err);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Consume a pending native notification navigation target, if any. */
|
|
||||||
export const getPendingNotificationNav = async (): Promise<{
|
|
||||||
path?: string | null;
|
|
||||||
roomId?: string | null;
|
|
||||||
}> => {
|
|
||||||
if (!isBackgroundSyncSupported()) return {};
|
|
||||||
try {
|
|
||||||
return await MatrixBackgroundSync.getPendingNotificationNav();
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] getPendingNotificationNav failed:', err);
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Subscribe to native notification taps that open the app. */
|
|
||||||
export const listenForNotificationOpens = async (
|
|
||||||
listener: (event: { path?: string; roomId?: string }) => void
|
|
||||||
): Promise<PluginListenerHandle | undefined> => {
|
|
||||||
if (!isBackgroundSyncSupported()) return undefined;
|
|
||||||
try {
|
|
||||||
return await MatrixBackgroundSync.addListener('notificationOpened', listener);
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] notificationOpened listener failed:', err);
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -226,7 +226,7 @@ export const setupNotificationTapListener = async (onTap: (path: string) => void
|
|||||||
try {
|
try {
|
||||||
const {
|
const {
|
||||||
getPendingNotificationNav,
|
getPendingNotificationNav,
|
||||||
listenForNotificationOpens,
|
subscribeNotificationOpened,
|
||||||
} = await import('./backgroundSync');
|
} = await import('./backgroundSync');
|
||||||
|
|
||||||
const deliver = (path?: string | null, roomId?: string | null) => {
|
const deliver = (path?: string | null, roomId?: string | null) => {
|
||||||
@@ -241,9 +241,9 @@ export const setupNotificationTapListener = async (onTap: (path: string) => void
|
|||||||
};
|
};
|
||||||
|
|
||||||
const pending = await getPendingNotificationNav();
|
const pending = await getPendingNotificationNav();
|
||||||
deliver(pending.path, pending.roomId);
|
deliver(pending?.path, pending?.roomId);
|
||||||
|
|
||||||
await listenForNotificationOpens((event) => {
|
await subscribeNotificationOpened((event) => {
|
||||||
void focusWindow();
|
void focusWindow();
|
||||||
deliver(event.path, event.roomId);
|
deliver(event.path, event.roomId);
|
||||||
});
|
});
|
||||||
|
|||||||
+2
-1
@@ -1,12 +1,13 @@
|
|||||||
{
|
{
|
||||||
"name": "paarrot",
|
"name": "paarrot",
|
||||||
"version": "4.11.153",
|
"version": "4.11.178",
|
||||||
"description": "Paarrot - A Matrix client based on Cinny",
|
"description": "Paarrot - A Matrix client based on Cinny",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18.0.0"
|
"node": ">=18.0.0"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"apply-overlay": "node scripts/apply-overlay.mjs",
|
"apply-overlay": "node scripts/apply-overlay.mjs",
|
||||||
|
"push": "bash scripts/push.sh",
|
||||||
"android:prepare": "cd cinny && npm run build && cd .. && npx cap sync android",
|
"android:prepare": "cd cinny && npm run build && cd .. && npx cap sync android",
|
||||||
"android:open": "npx cap open android",
|
"android:open": "npx cap open android",
|
||||||
"android:run": "npx cap run android",
|
"android:run": "npx cap run android",
|
||||||
|
|||||||
Executable
+197
@@ -0,0 +1,197 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Commit working changes, rebase onto the tracked remote branch, and push.
|
||||||
|
# Stashes leftover dirty files (common: cinny submodule pointer, gradlew +x)
|
||||||
|
# around the pull/push so they don't block rebase.
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
# scripts/push.sh -m "commit message" [path ...]
|
||||||
|
# scripts/push.sh "commit message" [path ...]
|
||||||
|
#
|
||||||
|
# If no paths are given:
|
||||||
|
# - uses already-staged files, or
|
||||||
|
# - auto-stages modified tracked files + overlay/android/scripts/config changes
|
||||||
|
# (skips cinny submodule + android/gradlew unless -a)
|
||||||
|
#
|
||||||
|
# Flags:
|
||||||
|
# -m MSG Commit message
|
||||||
|
# -a Include noisy paths (cinny, android/gradlew) when auto-staging
|
||||||
|
# -n Dry run: show what would be committed, then exit
|
||||||
|
# -h Help
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
cd "$ROOT"
|
||||||
|
|
||||||
|
MSG=""
|
||||||
|
INCLUDE_NOISE=0
|
||||||
|
DRY_RUN=0
|
||||||
|
PATHS=()
|
||||||
|
STAGED_PATHS=()
|
||||||
|
|
||||||
|
NOISE_PATHS=(
|
||||||
|
"cinny"
|
||||||
|
"android/gradlew"
|
||||||
|
)
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
awk '
|
||||||
|
NR == 1 { next }
|
||||||
|
/^#/ { sub(/^# ?/, ""); print; next }
|
||||||
|
{ exit }
|
||||||
|
' "$0"
|
||||||
|
exit "${1:-0}"
|
||||||
|
}
|
||||||
|
|
||||||
|
is_noise() {
|
||||||
|
local p="$1"
|
||||||
|
for n in "${NOISE_PATHS[@]}"; do
|
||||||
|
[[ "$p" == "$n" || "$p" == "./$n" ]] && return 0
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
should_autostage() {
|
||||||
|
local p="$1"
|
||||||
|
case "$p" in
|
||||||
|
overlay/*|android/*|scripts/*|package.json|package-lock.json|.gitea/*|config.json|capacitor.config.json)
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
# Modified tracked files outside those dirs are fine; skip random untracked junk.
|
||||||
|
git ls-files --error-unmatch -- "$p" >/dev/null 2>&1
|
||||||
|
}
|
||||||
|
|
||||||
|
while [[ $# -gt 0 ]]; do
|
||||||
|
case "$1" in
|
||||||
|
-m)
|
||||||
|
[[ $# -ge 2 ]] || { echo "error: -m needs a message" >&2; exit 1; }
|
||||||
|
MSG="$2"
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
-a)
|
||||||
|
INCLUDE_NOISE=1
|
||||||
|
shift
|
||||||
|
;;
|
||||||
|
-n)
|
||||||
|
DRY_RUN=1
|
||||||
|
shift
|
||||||
|
;;
|
||||||
|
-h|--help)
|
||||||
|
usage 0
|
||||||
|
;;
|
||||||
|
--)
|
||||||
|
shift
|
||||||
|
PATHS+=("$@")
|
||||||
|
break
|
||||||
|
;;
|
||||||
|
-*)
|
||||||
|
echo "error: unknown flag: $1" >&2
|
||||||
|
usage 1
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
if [[ -z "$MSG" ]]; then
|
||||||
|
MSG="$1"
|
||||||
|
else
|
||||||
|
PATHS+=("$1")
|
||||||
|
fi
|
||||||
|
shift
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ -z "$MSG" ]]; then
|
||||||
|
echo "error: commit message required" >&2
|
||||||
|
usage 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||||
|
echo "error: not a git repo" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
BRANCH="$(git rev-parse --abbrev-ref HEAD)"
|
||||||
|
if [[ "$BRANCH" == "HEAD" ]]; then
|
||||||
|
echo "error: detached HEAD — check out a branch first" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
REMOTE="$(git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null || true)"
|
||||||
|
if [[ -n "$REMOTE" ]]; then
|
||||||
|
REMOTE_NAME="${REMOTE%%/*}"
|
||||||
|
REMOTE_BRANCH="${REMOTE#*/}"
|
||||||
|
else
|
||||||
|
REMOTE_NAME="origin"
|
||||||
|
REMOTE_BRANCH="$BRANCH"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ ${#PATHS[@]} -gt 0 ]]; then
|
||||||
|
STAGED_PATHS=("${PATHS[@]}")
|
||||||
|
git add -- "${STAGED_PATHS[@]}"
|
||||||
|
elif git diff --cached --quiet; then
|
||||||
|
mapfile -t candidates < <({
|
||||||
|
git diff --name-only --diff-filter=ACMRD
|
||||||
|
git ls-files --others --exclude-standard
|
||||||
|
} | awk 'NF && !seen[$0]++')
|
||||||
|
|
||||||
|
for p in "${candidates[@]}"; do
|
||||||
|
[[ -z "$p" ]] && continue
|
||||||
|
if [[ "$INCLUDE_NOISE" -eq 0 ]] && is_noise "$p"; then
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
if should_autostage "$p"; then
|
||||||
|
STAGED_PATHS+=("$p")
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ ${#STAGED_PATHS[@]} -eq 0 ]]; then
|
||||||
|
echo "error: nothing to commit (pass paths, or stage files first)" >&2
|
||||||
|
git status -sb
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
git add -- "${STAGED_PATHS[@]}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if git diff --cached --quiet; then
|
||||||
|
echo "error: nothing staged to commit" >&2
|
||||||
|
git status -sb
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> branch $BRANCH (tracking ${REMOTE_NAME}/${REMOTE_BRANCH})"
|
||||||
|
echo "==> staged:"
|
||||||
|
git diff --cached --stat
|
||||||
|
|
||||||
|
if [[ "$DRY_RUN" -eq 1 ]]; then
|
||||||
|
if [[ ${#STAGED_PATHS[@]} -gt 0 ]]; then
|
||||||
|
git reset -q HEAD -- "${STAGED_PATHS[@]}"
|
||||||
|
fi
|
||||||
|
echo "==> dry run; not committing or pushing"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
STASHED=0
|
||||||
|
if [[ -n "$(git diff --name-only)" || -n "$(git ls-files --others --exclude-standard)" ]]; then
|
||||||
|
echo "==> stashing leftover dirty files"
|
||||||
|
git stash push --keep-index -u -m "push.sh leftover before ${BRANCH} push"
|
||||||
|
STASHED=1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> commit"
|
||||||
|
git commit -m "$MSG"
|
||||||
|
|
||||||
|
echo "==> pull --rebase ${REMOTE_NAME}/${REMOTE_BRANCH}"
|
||||||
|
git pull --rebase "$REMOTE_NAME" "$REMOTE_BRANCH"
|
||||||
|
|
||||||
|
echo "==> push ${REMOTE_NAME} HEAD"
|
||||||
|
git push "$REMOTE_NAME" HEAD
|
||||||
|
|
||||||
|
if [[ "$STASHED" -eq 1 ]]; then
|
||||||
|
echo "==> restoring stash"
|
||||||
|
git stash pop
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> done"
|
||||||
|
git status -sb
|
||||||
|
git log -1 --oneline
|
||||||
Reference in New Issue
Block a user