refining the android app

This commit is contained in:
Egor 2026-01-15 18:43:46 -08:00
parent 116dc0df9d
commit bc53a6cae2
142 changed files with 9776 additions and 396 deletions

1
.gitignore vendored
View file

@ -13,3 +13,4 @@ android/.externalNativeBuild
android/.cxx
android/*.keystore
android/*.jks
android/.kotlin

30
NOTICE Normal file
View file

@ -0,0 +1,30 @@
# SUP - Signal Unified Push
Copyright (c) 2026 LoneCloud
This product includes software developed by Philipp C. Heckel (ntfy)
Licensed under the Apache License 2.0
The Android application (android/) contains modified code from:
ntfy-android (https://github.com/binwiederhier/ntfy-android)
Copyright (c) 2021-2024 Philipp C. Heckel
Licensed under Apache License 2.0
Major modifications:
- Replaced HTTP polling with Signal-based message delivery for privacy
- Removed web-based features and simplified UI
- Intended for self-hosted, low-volume personal use
The original ntfy-android license is included below:
================================================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
[Full Apache 2.0 license text would go here]
================================================================================

View file

@ -1,6 +1,7 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("com.google.devtools.ksp") version "2.1.0-1.0.29"
}
android {
@ -49,23 +50,86 @@ android {
buildFeatures {
viewBinding = true
buildConfig = true
}
lint {
checkReleaseBuilds = false
abortOnError = false
}
ksp {
arg("room.schemaLocation", "$projectDir/schemas")
}
defaultConfig {
// Build config fields
buildConfigField("boolean", "FIREBASE_AVAILABLE", "false")
buildConfigField("boolean", "RATE_APP_AVAILABLE", "false")
buildConfigField("boolean", "PAYMENT_LINKS_AVAILABLE", "false")
buildConfigField("String", "FLAVOR", "\"sup\"")
}
}
dependencies {
implementation("androidx.core:core-ktx:1.15.0")
// AndroidX Core
implementation("androidx.appcompat:appcompat:1.7.1")
implementation("com.google.android.material:material:1.12.0") // Skip alpha
implementation("androidx.core:core-ktx:1.17.0")
implementation("androidx.constraintlayout:constraintlayout:2.2.1")
implementation("androidx.activity:activity-ktx:1.12.2")
implementation("androidx.fragment:fragment-ktx:1.8.9")
implementation("androidx.work:work-runtime-ktx:2.11.0")
implementation("androidx.preference:preference-ktx:1.2.1")
// JSON (Gson)
implementation("com.google.code.gson:gson:2.13.2")
// Room (SQLite)
val roomVersion = "2.6.1"
implementation("androidx.room:room-runtime:$roomVersion")
ksp("androidx.room:room-compiler:$roomVersion")
implementation("androidx.room:room-ktx:$roomVersion")
// OkHttp
implementation("com.squareup.okhttp3:okhttp:5.3.2")
// RecyclerView
implementation("androidx.recyclerview:recyclerview:1.4.0")
// Swipe to refresh
implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.2.0")
// Material Design
implementation("com.google.android.material:material:1.13.0")
// LiveData
implementation("androidx.lifecycle:lifecycle-livedata-ktx:2.10.0")
implementation("androidx.legacy:legacy-support-v4:1.0.0")
// Image viewer
implementation("com.github.stfalcon-studio:StfalconImageViewer:1.0.1")
// Glide (GIF support)
val glideVersion = "5.0.5"
implementation("com.github.bumptech.glide:glide:$glideVersion")
ksp("com.github.bumptech.glide:ksp:$glideVersion")
// Better click handling for links
implementation("me.saket:better-link-movement-method:2.2.0")
// Markdown
implementation("io.noties.markwon:core:4.6.2")
implementation("io.noties.markwon:image-picasso:4.6.2")
implementation("io.noties.markwon:image:4.6.2")
implementation("io.noties.markwon:linkify:4.6.2")
implementation("io.noties.markwon:ext-tables:4.6.2")
implementation("io.noties.markwon:ext-strikethrough:4.6.2")
// Markdown dependencies (R8 requirements)
implementation("pl.droidsonroids.gif:android-gif-drawable:1.2.29")
implementation("com.caverock:androidsvg:1.4")
// UnifiedPush
implementation("com.github.UnifiedPush:android-connector:3.0.10")
implementation("com.squareup.okhttp3:okhttp:5.0.0-alpha.16")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0")
}

View file

@ -0,0 +1,216 @@
{
"formatVersion": 1,
"database": {
"version": 18,
"identityHash": "35364cf175ffcf5aa672eabaabe12397",
"entities": [
{
"tableName": "Subscription",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `baseUrl` TEXT NOT NULL, `topic` TEXT NOT NULL, `mutedUntil` INTEGER NOT NULL, `minPriority` INTEGER NOT NULL, `autoDelete` INTEGER NOT NULL, `insistent` INTEGER NOT NULL, `upAppId` TEXT, `upConnectorToken` TEXT, `displayName` TEXT, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "baseUrl",
"columnName": "baseUrl",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "topic",
"columnName": "topic",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "mutedUntil",
"columnName": "mutedUntil",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "minPriority",
"columnName": "minPriority",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "autoDelete",
"columnName": "autoDelete",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "insistent",
"columnName": "insistent",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "upAppId",
"columnName": "upAppId",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "upConnectorToken",
"columnName": "upConnectorToken",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "displayName",
"columnName": "displayName",
"affinity": "TEXT",
"notNull": false
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": ["id"]
},
"indices": [
{
"name": "index_Subscription_baseUrl_topic",
"unique": true,
"columnNames": ["baseUrl", "topic"],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_Subscription_baseUrl_topic` ON `${TABLE_NAME}` (`baseUrl`, `topic`)"
},
{
"name": "index_Subscription_upConnectorToken",
"unique": true,
"columnNames": ["upConnectorToken"],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_Subscription_upConnectorToken` ON `${TABLE_NAME}` (`upConnectorToken`)"
}
],
"foreignKeys": []
},
{
"tableName": "Notification",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `subscriptionId` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `title` TEXT NOT NULL, `message` TEXT NOT NULL, `notificationId` INTEGER NOT NULL, `priority` INTEGER NOT NULL DEFAULT 3, `tags` TEXT NOT NULL, `deleted` INTEGER NOT NULL, PRIMARY KEY(`id`, `subscriptionId`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "subscriptionId",
"columnName": "subscriptionId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "timestamp",
"columnName": "timestamp",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "title",
"columnName": "title",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "notificationId",
"columnName": "notificationId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "priority",
"columnName": "priority",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "3"
},
{
"fieldPath": "tags",
"columnName": "tags",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "deleted",
"columnName": "deleted",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": ["id", "subscriptionId"]
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "Log",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `tag` TEXT NOT NULL, `level` INTEGER NOT NULL, `message` TEXT NOT NULL, `exception` TEXT)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "timestamp",
"columnName": "timestamp",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "tag",
"columnName": "tag",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "level",
"columnName": "level",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "exception",
"columnName": "exception",
"affinity": "TEXT",
"notNull": false
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": ["id"]
},
"indices": [],
"foreignKeys": []
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '35364cf175ffcf5aa672eabaabe12397')"
]
}
}

View file

@ -1,47 +1,114 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<queries>
<intent>
<action android:name="org.unifiedpush.android.connector.RAISE_TO_FOREGROUND" />
</intent>
</queries>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.SUP">
<!-- Main activity -->
android:name=".app.Application"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:networkSecurityConfig="@xml/network_security_config"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:name=".ui.MainActivity"
android:label="@string/app_name"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- UnifiedPush Distributor Service -->
<service
android:name=".DistributorService"
android:exported="true">
<intent-filter>
<action android:name="org.unifiedpush.android.distributor.REGISTER" />
<action android:name="org.unifiedpush.android.distributor.UNREGISTER" />
</intent-filter>
</service>
<activity
android:name=".ui.DetailActivity"
android:parentActivityName=".ui.MainActivity"
android:windowSoftInputMode="adjustResize"
android:exported="false">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ui.MainActivity"/>
</activity>
<!-- Notification Listener Service -->
<service
android:name=".SignalNotificationListener"
android:exported="true"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
<!-- Hack: Activity used for "view" action button with "clear=true" (to be able to cancel notifications and show a URL) -->
<activity
android:name=".msg.NotificationService$ViewActionWithClearActivity"
android:exported="false">
</activity>
<!-- UnifiedPush link activity to facilitate distributor selection, see https://unifiedpush.org/developers/spec/android/#link-activity -->
<activity android:name=".up.LinkActivity" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="unifiedpush" android:host="link" />
</intent-filter>
</activity>
<!-- Signal listener foreground service -->
<service
android:name=".service.SignalListenerService"
android:foregroundServiceType="dataSync"
android:exported="false" />
<!-- Broadcast receiver to send messages via intents -->
<receiver
android:name=".msg.BroadcastService$BroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.lonecloud.sup.SEND_MESSAGE"/>
</intent-filter>
</receiver>
<!-- Broadcast receiver for UnifiedPush; must match https://github.com/UnifiedPush/UP-spec/blob/main/specifications.md -->
<receiver
android:name=".up.BroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="org.unifiedpush.android.distributor.REGISTER"/>
<action android:name="org.unifiedpush.android.distributor.UNREGISTER"/>
<action android:name="org.unifiedpush.android.distributor.feature.BYTES_MESSAGE"/>
</intent-filter>
</receiver>
<!-- Broadcast receiver for the "Download"/"Cancel" attachment action in the notification popup -->
<receiver
android:name=".msg.NotificationService$UserActionBroadcastReceiver"
android:enabled="true"
android:exported="false">
</receiver>
<!-- Broadcast receiver for when the notification is swiped away (currently only to cancel the insistent sound) -->
<receiver
android:name=".msg.NotificationService$DeleteBroadcastReceiver"
android:enabled="true"
android:exported="false">
</receiver>
<!-- FileProvider required for older Android versions (<= P), to allow passing the file URI in the open intent.
Avoids "exposed beyond app through Intent.getData" exception, see see https://stackoverflow.com/a/57288352/1440785 -->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
</application>
</manifest>

View file

@ -63,7 +63,6 @@ class DistributorService : Service() {
val jsonResponse = JSONObject(responseBody)
val endpoint = jsonResponse.getString("endpoint")
// Store mapping
prefs.edit()
.putString("endpoint_$appId", endpoint)
.putString("token_$appId", token)
@ -85,7 +84,6 @@ class DistributorService : Service() {
val token = intent.getStringExtra("token") ?: return
Log.d("SUP", "Unregistering: token=$token")
// Find and remove mapping
val allPrefs = prefs.all
for ((key, value) in allPrefs) {
if (key.startsWith("token_") && value == token) {
@ -129,7 +127,6 @@ class DistributorService : Service() {
}
private fun getAppPackageFromToken(token: String): String {
// Token format is typically package:randomId
return token.split(":").firstOrNull() ?: ""
}
}

View file

@ -1,52 +0,0 @@
package com.lonecloud.sup
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var serverUrlInput: EditText
private lateinit var apiKeyInput: EditText
private lateinit var saveButton: Button
private lateinit var enableListenerButton: Button
private val prefs by lazy {
getSharedPreferences("sup_prefs", MODE_PRIVATE)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
serverUrlInput = findViewById(R.id.server_url)
apiKeyInput = findViewById(R.id.api_key)
saveButton = findViewById(R.id.save_button)
enableListenerButton = findViewById(R.id.enable_listener_button)
// Load saved settings
serverUrlInput.setText(prefs.getString("server_url", ""))
apiKeyInput.setText(prefs.getString("api_key", ""))
saveButton.setOnClickListener {
val serverUrl = serverUrlInput.text.toString().trim()
val apiKey = apiKeyInput.text.toString().trim()
prefs.edit()
.putString("server_url", serverUrl)
.putString("api_key", apiKey)
.apply()
Toast.makeText(this, "Settings saved", Toast.LENGTH_SHORT).show()
}
enableListenerButton.setOnClickListener {
val intent = Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
startActivity(intent)
}
}
}

View file

@ -1,18 +1,47 @@
package com.lonecloud.sup
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import android.util.Log
import androidx.core.app.NotificationCompat
import com.lonecloud.sup.db.Database
import com.lonecloud.sup.db.Notification
import com.lonecloud.sup.ui.MainActivity
import kotlinx.coroutines.*
import kotlin.random.Random
class SignalNotificationListener : NotificationListenerService() {
private val TAG = "SUP_Listener"
private val prefs by lazy {
getSharedPreferences("sup_prefs", MODE_PRIVATE)
}
private val db by lazy { Database.getInstance(this) }
private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
companion object {
private const val CHANNEL_ID = "sup_notifications"
private const val CHANNEL_NAME = "SUP Notifications"
}
override fun onCreate() {
super.onCreate()
createNotificationChannel()
}
override fun onDestroy() {
super.onDestroy()
serviceScope.cancel()
}
override fun onNotificationPosted(sbn: StatusBarNotification?) {
if (sbn?.packageName != "org.thoughtcrime.securesms") return // Signal package
if (sbn?.packageName != "org.thoughtcrime.securesms") return
val notification = sbn.notification
val extras = notification.extras
@ -20,31 +49,73 @@ class SignalNotificationListener : NotificationListenerService() {
val title = extras.getString("android.title") ?: ""
val text = extras.getCharSequence("android.text")?.toString() ?: ""
Log.d("SUP", "Signal notification: title=$title, text=$text")
Log.d(TAG, "Signal notification: title=$title, text=$text")
// Parse SUP message format: **Title**\nbody\nJSON
if (title.startsWith("SUP - ")) {
val appName = title.removePrefix("SUP - ")
parseAndDeliver(appName, text)
when {
title.startsWith("SUP - ") && !title.contains("(UP)") -> {
// Direct notification channel
val topic = title.removePrefix("SUP - ")
parseAndDisplayNotification(topic, text)
}
title.startsWith("SUP - ") && title.contains("(UP)") -> {
// UnifiedPush notification
val appName = title.removePrefix("SUP - ").substringBefore(" (UP)")
parseAndDeliverUnifiedPush(appName, text)
}
}
}
private fun parseAndDeliver(appName: String, message: String) {
private fun parseAndDisplayNotification(topic: String, message: String) {
serviceScope.launch {
try {
val subscription = db.subscriptionDao().get(
prefs.getString("server_url", "") ?: "",
topic
) ?: return@launch
if (subscription.mutedUntil > System.currentTimeMillis() / 1000) {
Log.d(TAG, "Subscription $topic is muted")
return@launch
}
val lines = message.lines()
val (title, body, priority, clickUrl) = parseNotificationMessage(lines)
val notif = Notification(
id = "${System.currentTimeMillis()}-${Random.nextInt()}",
subscriptionId = subscription.id,
timestamp = System.currentTimeMillis() / 1000,
title = title ?: topic,
message = body,
notificationId = Random.nextInt(Int.MAX_VALUE),
priority = priority,
tags = "",
deleted = false
)
db.notificationDao().add(notif)
displayNotification(subscription.displayName ?: topic, notif)
Log.d(TAG, "Displayed notification for topic: $topic")
} catch (e: Exception) {
Log.e(TAG, "Failed to display notification", e)
}
}
}
private fun parseAndDeliverUnifiedPush(appName: String, message: String) {
try {
// Find the endpoint for this app
val endpoint = prefs.getString("endpoint_$appName", null)
val token = prefs.getString("token_$appName", null)
if (endpoint == null || token == null) {
Log.w("SUP", "No mapping found for app: $appName")
Log.w(TAG, "No mapping found for app: $appName")
return
}
// Extract message body (skip the formatted parts)
val lines = message.lines()
val body = lines.getOrNull(1) ?: message
val body = lines.drop(1).joinToString("\n").trim()
// Send to app
val intent = Intent("org.unifiedpush.android.connector.MESSAGE").apply {
putExtra("token", token)
putExtra("message", body)
@ -52,13 +123,108 @@ class SignalNotificationListener : NotificationListenerService() {
}
sendBroadcast(intent)
Log.d("SUP", "Delivered notification to $appName")
Log.d(TAG, "Delivered UnifiedPush notification to $appName")
} catch (e: Exception) {
Log.e("SUP", "Failed to parse/deliver notification", e)
Log.e(TAG, "Failed to parse/deliver UnifiedPush notification", e)
}
}
private fun parseNotificationMessage(lines: List<String>): NotificationData {
var title: String? = null
var body = ""
var priority = 3 // default
var clickUrl: String? = null
for (line in lines) {
when {
line.startsWith("🚨") || line.startsWith("⚠️") || line.startsWith("🔔") ||
line.startsWith("🔉") || line.startsWith("🔕") -> {
// Parse priority from emoji
priority = when {
line.startsWith("🚨") -> 5 // urgent
line.startsWith("⚠️") -> 4 // high
line.startsWith("🔔") -> 3 // default
line.startsWith("🔉") -> 2 // low
line.startsWith("🔕") -> 1 // min
else -> 3
}
// Extract title (remove emoji and **markdown**)
title = line.substring(2).trim()
.removePrefix("**").removeSuffix("**").trim()
}
line.startsWith("🔗") -> {
clickUrl = line.removePrefix("🔗").trim()
}
line.startsWith("_Tags:") -> {
// Ignore tags line for now
}
line.isNotBlank() && title != null -> {
// Body content
if (body.isNotEmpty()) body += "\n"
body += line
}
}
}
return NotificationData(title, body.ifBlank { lines.joinToString("\n") }, priority, clickUrl)
}
private fun displayNotification(topicName: String, notification: Notification) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
this,
notification.notificationId,
intent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(notification.title)
.setContentText(notification.message)
.setStyle(NotificationCompat.BigTextStyle().bigText(notification.message))
.setPriority(mapPriorityToAndroid(notification.priority))
.setContentIntent(pendingIntent)
.setAutoCancel(true)
notificationManager.notify(notification.notificationId, builder.build())
}
private fun mapPriorityToAndroid(priority: Int): Int {
return when (priority) {
1 -> NotificationCompat.PRIORITY_MIN
2 -> NotificationCompat.PRIORITY_LOW
3 -> NotificationCompat.PRIORITY_DEFAULT
4 -> NotificationCompat.PRIORITY_HIGH
5 -> NotificationCompat.PRIORITY_MAX
else -> NotificationCompat.PRIORITY_DEFAULT
}
}
private fun createNotificationChannel() {
val channel = NotificationChannel(
CHANNEL_ID,
CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = "Notifications from SUP topics"
}
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
private fun getAppPackageFromToken(token: String): String {
return token.split(":").firstOrNull() ?: ""
}
private data class NotificationData(
val title: String?,
val body: String,
val priority: Int,
val clickUrl: String?
)
}

View file

@ -0,0 +1,23 @@
package com.lonecloud.sup.app
import android.app.Application
import com.google.android.material.color.DynamicColors
import com.lonecloud.sup.db.Repository
import com.lonecloud.sup.util.Log
class Application : Application() {
val repository by lazy {
val repository = Repository.getInstance(applicationContext)
if (repository.getRecordLogs()) {
Log.setRecord(true)
}
repository
}
override fun onCreate() {
super.onCreate()
if (repository.getDynamicColorsEnabled()) {
DynamicColors.applyToActivitiesIfAvailable(this)
}
}
}

View file

@ -0,0 +1,440 @@
package com.lonecloud.sup.db
import android.content.Context
import androidx.room.ColumnInfo
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.Index
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.Update
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.lonecloud.sup.service.NotAuthorizedException
import com.lonecloud.sup.service.hasCause
import kotlinx.coroutines.flow.Flow
import java.net.ConnectException
@Entity(indices = [Index(value = ["baseUrl", "topic"], unique = true), Index(value = ["upConnectorToken"], unique = true)])
data class Subscription(
@PrimaryKey val id: Long,
@ColumnInfo(name = "baseUrl") val baseUrl: String,
@ColumnInfo(name = "topic") val topic: String,
@ColumnInfo(name = "mutedUntil") val mutedUntil: Long,
@ColumnInfo(name = "minPriority") val minPriority: Int,
@ColumnInfo(name = "autoDelete") val autoDelete: Long, // Seconds
@ColumnInfo(name = "insistent") val insistent: Int, // Ring constantly for max priority notifications (-1 = use global, 0 = off, 1 = on)
@ColumnInfo(name = "upAppId") val upAppId: String?, // UnifiedPush application package name
@ColumnInfo(name = "upConnectorToken") val upConnectorToken: String?, // UnifiedPush connector token
@ColumnInfo(name = "displayName") val displayName: String?,
@Ignore val totalCount: Int = 0, // Total notifications
@Ignore val newCount: Int = 0, // New notifications
@Ignore val lastActive: Long = 0, // Unix timestamp
@Ignore val connectionDetails: ConnectionDetails = ConnectionDetails()
) {
constructor(
id: Long,
baseUrl: String,
topic: String,
mutedUntil: Long,
minPriority: Int,
autoDelete: Long,
insistent: Int,
upAppId: String?,
upConnectorToken: String?,
displayName: String?
) :
this(
id,
baseUrl,
topic,
mutedUntil,
minPriority,
autoDelete,
insistent,
upAppId,
upConnectorToken,
displayName,
totalCount = 0,
newCount = 0,
lastActive = 0,
connectionDetails = ConnectionDetails()
)
}
enum class ConnectionState {
NOT_APPLICABLE, CONNECTING, CONNECTED
}
data class ConnectionDetails(
val state: ConnectionState = ConnectionState.NOT_APPLICABLE,
val error: Throwable? = null,
val nextRetryTime: Long = 0L
) {
fun getStackTraceString(): String {
return error?.stackTraceToString() ?: ""
}
fun hasError(): Boolean {
return error != null
}
fun isConnectionRefused(): Boolean {
return error?.hasCause(ConnectException::class.java) ?: false
}
fun isNotAuthorized(): Boolean {
return error?.hasCause(NotAuthorizedException::class.java) ?: false
}
}
data class SubscriptionWithMetadata(
val id: Long,
val baseUrl: String,
val topic: String,
val mutedUntil: Long,
val autoDelete: Long,
val minPriority: Int,
val insistent: Int,
val upAppId: String?,
val upConnectorToken: String?,
val displayName: String?,
val totalCount: Int,
val newCount: Int,
val lastActive: Long
)
@Entity(primaryKeys = ["id", "subscriptionId"])
data class Notification(
@ColumnInfo(name = "id") val id: String,
@ColumnInfo(name = "subscriptionId") val subscriptionId: Long,
@ColumnInfo(name = "timestamp") val timestamp: Long, // Unix timestamp
@ColumnInfo(name = "title") val title: String,
@ColumnInfo(name = "message") val message: String,
@ColumnInfo(name = "notificationId") val notificationId: Int, // Android notification popup ID
@ColumnInfo(name = "priority", defaultValue = "3") val priority: Int, // 1=min, 3=default, 5=max
@ColumnInfo(name = "tags") val tags: String,
@ColumnInfo(name = "deleted") val deleted: Boolean,
)
@Entity(tableName = "Log")
data class LogEntry(
@PrimaryKey(autoGenerate = true) val id: Long,
@ColumnInfo(name = "timestamp") val timestamp: Long,
@ColumnInfo(name = "tag") val tag: String,
@ColumnInfo(name = "level") val level: Int,
@ColumnInfo(name = "message") val message: String,
@ColumnInfo(name = "exception") val exception: String?
) {
@Ignore constructor(timestamp: Long, tag: String, level: Int, message: String, exception: String?) :
this(0, timestamp, tag, level, message, exception)
}
@androidx.room.Database(
version = 17,
entities = [
Subscription::class,
Notification::class,
LogEntry::class
]
)
abstract class Database : RoomDatabase() {
abstract fun subscriptionDao(): SubscriptionDao
abstract fun notificationDao(): NotificationDao
abstract fun logDao(): LogDao
companion object {
@Volatile
private var instance: Database? = null
fun getInstance(context: Context): Database {
return instance ?: synchronized(this) {
val instance = Room
.databaseBuilder(context.applicationContext, Database::class.java, "AppDatabase")
.addMigrations(MIGRATION_1_2)
.addMigrations(MIGRATION_2_3)
.addMigrations(MIGRATION_3_4)
.addMigrations(MIGRATION_4_5)
.addMigrations(MIGRATION_5_6)
.addMigrations(MIGRATION_6_7)
.addMigrations(MIGRATION_7_8)
.addMigrations(MIGRATION_8_9)
.addMigrations(MIGRATION_9_10)
.addMigrations(MIGRATION_10_11)
.addMigrations(MIGRATION_11_12)
.addMigrations(MIGRATION_12_13)
.addMigrations(MIGRATION_13_14)
.addMigrations(MIGRATION_14_15)
.addMigrations(MIGRATION_15_16)
.addMigrations(MIGRATION_16_17)
.fallbackToDestructiveMigration(true)
.build()
this.instance = instance
instance
}
}
private val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("CREATE TABLE Subscription_New (id INTEGER NOT NULL, baseUrl TEXT NOT NULL, topic TEXT NOT NULL, instant INTEGER NOT NULL DEFAULT('0'), PRIMARY KEY(id))")
db.execSQL("INSERT INTO Subscription_New SELECT id, baseUrl, topic, 0 FROM Subscription")
db.execSQL("DROP TABLE Subscription")
db.execSQL("ALTER TABLE Subscription_New RENAME TO Subscription")
db.execSQL("CREATE UNIQUE INDEX index_Subscription_baseUrl_topic ON Subscription (baseUrl, topic)")
db.execSQL("ALTER TABLE Notification ADD COLUMN notificationId INTEGER NOT NULL DEFAULT('0')")
db.execSQL("ALTER TABLE Notification ADD COLUMN deleted INTEGER NOT NULL DEFAULT('0')")
}
}
private val MIGRATION_2_3 = object : Migration(2, 3) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE Subscription ADD COLUMN mutedUntil INTEGER NOT NULL DEFAULT('0')")
}
}
private val MIGRATION_3_4 = object : Migration(3, 4) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("CREATE TABLE Notification_New (id TEXT NOT NULL, subscriptionId INTEGER NOT NULL, timestamp INTEGER NOT NULL, title TEXT NOT NULL, message TEXT NOT NULL, notificationId INTEGER NOT NULL, priority INTEGER NOT NULL DEFAULT(3), tags TEXT NOT NULL, deleted INTEGER NOT NULL, PRIMARY KEY(id, subscriptionId))")
db.execSQL("INSERT INTO Notification_New SELECT id, subscriptionId, timestamp, '', message, notificationId, 3, '', deleted FROM Notification")
db.execSQL("DROP TABLE Notification")
db.execSQL("ALTER TABLE Notification_New RENAME TO Notification")
}
}
private val MIGRATION_4_5 = object : Migration(4, 5) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE Subscription ADD COLUMN upAppId TEXT")
db.execSQL("ALTER TABLE Subscription ADD COLUMN upConnectorToken TEXT")
db.execSQL("CREATE UNIQUE INDEX index_Subscription_upConnectorToken ON Subscription (upConnectorToken)")
}
}
private val MIGRATION_5_6 = object : Migration(5, 6) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE Notification ADD COLUMN click TEXT NOT NULL DEFAULT('')")
db.execSQL("ALTER TABLE Notification ADD COLUMN attachment_name TEXT")
db.execSQL("ALTER TABLE Notification ADD COLUMN attachment_type TEXT")
db.execSQL("ALTER TABLE Notification ADD COLUMN attachment_size INT")
db.execSQL("ALTER TABLE Notification ADD COLUMN attachment_expires INT")
db.execSQL("ALTER TABLE Notification ADD COLUMN attachment_url TEXT")
db.execSQL("ALTER TABLE Notification ADD COLUMN attachment_contentUri TEXT")
db.execSQL("ALTER TABLE Notification ADD COLUMN attachment_progress INT")
}
}
private val MIGRATION_6_7 = object : Migration(6, 7) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("CREATE TABLE Log (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, timestamp INT NOT NULL, tag TEXT NOT NULL, level INT NOT NULL, message TEXT NOT NULL, exception TEXT)")
}
}
private val MIGRATION_7_8 = object : Migration(7, 8) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("CREATE TABLE User (baseUrl TEXT NOT NULL, username TEXT NOT NULL, password TEXT NOT NULL, PRIMARY KEY(baseUrl))")
}
}
private val MIGRATION_8_9 = object : Migration(8, 9) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE Notification ADD COLUMN encoding TEXT NOT NULL DEFAULT('')")
}
}
private val MIGRATION_9_10 = object : Migration(9, 10) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE Notification ADD COLUMN actions TEXT")
}
}
private val MIGRATION_10_11 = object : Migration(10, 11) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE Subscription ADD COLUMN minPriority INT NOT NULL DEFAULT (0)")
db.execSQL("ALTER TABLE Subscription ADD COLUMN autoDelete INT NOT NULL DEFAULT (-1)")
db.execSQL("ALTER TABLE Subscription ADD COLUMN icon TEXT")
}
}
private val MIGRATION_11_12 = object : Migration(11, 12) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE Subscription ADD COLUMN lastNotificationId TEXT")
db.execSQL("ALTER TABLE Subscription ADD COLUMN displayName TEXT")
db.execSQL("ALTER TABLE Notification ADD COLUMN icon_url TEXT")
db.execSQL("ALTER TABLE Notification ADD COLUMN icon_contentUri TEXT")
}
}
private val MIGRATION_12_13 = object : Migration(12, 13) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE Subscription ADD COLUMN insistent INTEGER NOT NULL DEFAULT (-1)")
db.execSQL("ALTER TABLE Subscription ADD COLUMN dedicatedChannels INTEGER NOT NULL DEFAULT (0)")
}
}
private val MIGRATION_13_14 = object : Migration(13, 14) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE Notification ADD COLUMN contentType TEXT NOT NULL DEFAULT ('')")
}
}
private val MIGRATION_14_15 = object : Migration(14, 15) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("CREATE TABLE CustomHeader (baseUrl TEXT NOT NULL, name TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY(baseUrl, name))")
}
}
private val MIGRATION_15_16 = object : Migration(15, 16) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("CREATE TABLE TrustedCertificate (baseUrl TEXT NOT NULL, pem TEXT NOT NULL, PRIMARY KEY(baseUrl))")
db.execSQL("CREATE TABLE ClientCertificate (baseUrl TEXT NOT NULL, p12Base64 TEXT NOT NULL, password TEXT NOT NULL, PRIMARY KEY(baseUrl))")
}
}
private val MIGRATION_16_17 = object : Migration(16, 17) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("UPDATE Notification SET icon_contentUri = NULL WHERE icon_url IS NULL AND icon_contentUri IS NOT NULL")
}
}
}
}
@Dao
interface SubscriptionDao {
@Query("""
SELECT
s.id, s.baseUrl, s.topic, s.mutedUntil, s.minPriority, s.autoDelete, s.insistent, s.upAppId, s.upConnectorToken, s.displayName,
COUNT(n.id) totalCount,
COUNT(CASE n.notificationId WHEN 0 THEN NULL ELSE n.id END) newCount,
IFNULL(MAX(n.timestamp),0) AS lastActive
FROM Subscription AS s
LEFT JOIN Notification AS n ON s.id=n.subscriptionId AND n.deleted != 1
GROUP BY s.id
ORDER BY s.upAppId ASC, MAX(n.timestamp) DESC
""")
fun listFlow(): Flow<List<SubscriptionWithMetadata>>
@Query("""
SELECT
s.id, s.baseUrl, s.topic, s.mutedUntil, s.minPriority, s.autoDelete, s.insistent, s.upAppId, s.upConnectorToken, s.displayName,
COUNT(n.id) totalCount,
COUNT(CASE n.notificationId WHEN 0 THEN NULL ELSE n.id END) newCount,
IFNULL(MAX(n.timestamp),0) AS lastActive
FROM Subscription AS s
LEFT JOIN Notification AS n ON s.id=n.subscriptionId AND n.deleted != 1
GROUP BY s.id
ORDER BY s.upAppId ASC, MAX(n.timestamp) DESC
""")
suspend fun list(): List<SubscriptionWithMetadata>
@Query("""
SELECT
s.id, s.baseUrl, s.topic, s.mutedUntil, s.minPriority, s.autoDelete, s.insistent, s.upAppId, s.upConnectorToken, s.displayName,
COUNT(n.id) totalCount,
COUNT(CASE n.notificationId WHEN 0 THEN NULL ELSE n.id END) newCount,
IFNULL(MAX(n.timestamp),0) AS lastActive
FROM Subscription AS s
LEFT JOIN Notification AS n ON s.id=n.subscriptionId AND n.deleted != 1
WHERE s.baseUrl = :baseUrl AND s.topic = :topic
GROUP BY s.id
""")
fun get(baseUrl: String, topic: String): SubscriptionWithMetadata?
@Query("""
SELECT
s.id, s.baseUrl, s.topic, s.mutedUntil, s.minPriority, s.autoDelete, s.insistent, s.upAppId, s.upConnectorToken, s.displayName,
COUNT(n.id) totalCount,
COUNT(CASE n.notificationId WHEN 0 THEN NULL ELSE n.id END) newCount,
IFNULL(MAX(n.timestamp),0) AS lastActive
FROM Subscription AS s
LEFT JOIN Notification AS n ON s.id=n.subscriptionId AND n.deleted != 1
WHERE s.id = :subscriptionId
GROUP BY s.id
""")
fun get(subscriptionId: Long): SubscriptionWithMetadata?
@Query("""
SELECT
s.id, s.baseUrl, s.topic, s.mutedUntil, s.minPriority, s.autoDelete, s.insistent, s.upAppId, s.upConnectorToken, s.displayName,
COUNT(n.id) totalCount,
COUNT(CASE n.notificationId WHEN 0 THEN NULL ELSE n.id END) newCount,
IFNULL(MAX(n.timestamp),0) AS lastActive
FROM Subscription AS s
LEFT JOIN Notification AS n ON s.id=n.subscriptionId AND n.deleted != 1
WHERE s.upConnectorToken = :connectorToken
GROUP BY s.id
""")
fun getByConnectorToken(connectorToken: String): SubscriptionWithMetadata?
@Insert
fun add(subscription: Subscription)
@Update
fun update(subscription: Subscription)
@Query("DELETE FROM subscription WHERE id = :subscriptionId")
fun remove(subscriptionId: Long)
}
@Dao
interface NotificationDao {
@Query("SELECT * FROM notification")
suspend fun list(): List<Notification>
@Query("SELECT * FROM notification WHERE subscriptionId = :subscriptionId AND deleted != 1 ORDER BY timestamp DESC")
fun listFlow(subscriptionId: Long): Flow<List<Notification>>
@Query("SELECT id FROM notification WHERE subscriptionId = :subscriptionId")
fun listIds(subscriptionId: Long): List<String>
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun add(notification: Notification)
@Update(onConflict = OnConflictStrategy.IGNORE)
fun update(notification: Notification)
@Query("SELECT * FROM notification WHERE id = :notificationId")
fun get(notificationId: String): Notification?
@Query("UPDATE notification SET notificationId = 0 WHERE subscriptionId = :subscriptionId")
fun clearAllNotificationIds(subscriptionId: Long)
@Query("UPDATE notification SET deleted = 1 WHERE id = :notificationId")
fun markAsDeleted(notificationId: String)
@Query("UPDATE notification SET deleted = 1 WHERE subscriptionId = :subscriptionId")
fun markAllAsDeleted(subscriptionId: Long)
@Query("UPDATE notification SET deleted = 1 WHERE subscriptionId = :subscriptionId AND timestamp < :olderThanTimestamp")
fun markAsDeletedIfOlderThan(subscriptionId: Long, olderThanTimestamp: Long)
@Query("UPDATE notification SET deleted = 0 WHERE id = :notificationId")
fun undelete(notificationId: String)
@Query("DELETE FROM notification WHERE subscriptionId = :subscriptionId AND timestamp < :olderThanTimestamp")
fun removeIfOlderThan(subscriptionId: Long, olderThanTimestamp: Long)
@Query("DELETE FROM notification WHERE subscriptionId = :subscriptionId")
fun removeAll(subscriptionId: Long)
}
@Dao
interface LogDao {
@Insert
suspend fun insert(entry: LogEntry)
@Query("DELETE FROM log WHERE id NOT IN (SELECT id FROM log ORDER BY timestamp DESC, id DESC LIMIT :keepCount)")
suspend fun prune(keepCount: Int)
@Query("SELECT * FROM log ORDER BY timestamp ASC, id ASC")
fun getAll(): List<LogEntry>
@Query("DELETE FROM log")
fun deleteAll()
}

View file

@ -0,0 +1,515 @@
package com.lonecloud.sup.db
import android.content.Context
import android.content.SharedPreferences
import android.media.MediaPlayer
import android.os.Build
import androidx.annotation.WorkerThread
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.edit
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.asLiveData
import androidx.lifecycle.map
import com.lonecloud.sup.util.Log
import com.lonecloud.sup.util.validUrl
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong
class Repository(private val sharedPrefs: SharedPreferences, database: Database) {
private val subscriptionDao = database.subscriptionDao()
private val notificationDao = database.notificationDao()
private val connectionDetails = ConcurrentHashMap<String, ConnectionDetails>()
private val connectionDetailsLiveData = MutableLiveData<Map<String, ConnectionDetails>>(connectionDetails)
private val connectionForceReconnectVersions = ConcurrentHashMap<String, Long>()
// TODO Move these into an ApplicationState singleton
val detailViewSubscriptionId = AtomicLong(0L) // Omg, what a hack ...
val mediaPlayer = MediaPlayer()
init {
Log.d(TAG, "Created $this")
}
fun getSubscriptionsLiveData(): LiveData<List<Subscription>> {
return subscriptionDao
.listFlow()
.asLiveData()
.combineWith(connectionDetailsLiveData) { subscriptionsWithMetadata, _ ->
toSubscriptionList(subscriptionsWithMetadata.orEmpty())
}
}
fun getSubscriptionIdsWithInstantStatusLiveData(): LiveData<Set<Pair<Long, Boolean>>> {
return subscriptionDao
.listFlow()
.asLiveData()
.map { list -> list.map { Pair(it.id, false) }.toSet() }
}
suspend fun getSubscriptions(): List<Subscription> {
return toSubscriptionList(subscriptionDao.list())
}
fun getSubscription(subscriptionId: Long): Subscription? {
return toSubscription(subscriptionDao.get(subscriptionId))
}
@Suppress("RedundantSuspendModifier")
@WorkerThread
suspend fun getSubscription(baseUrl: String, topic: String): Subscription? {
return toSubscription(subscriptionDao.get(baseUrl, topic))
}
@Suppress("RedundantSuspendModifier")
@WorkerThread
suspend fun getSubscriptionByConnectorToken(connectorToken: String): Subscription? {
return toSubscription(subscriptionDao.getByConnectorToken(connectorToken))
}
@Suppress("RedundantSuspendModifier")
@WorkerThread
suspend fun addSubscription(subscription: Subscription) {
subscriptionDao.add(subscription)
}
@Suppress("RedundantSuspendModifier")
@WorkerThread
suspend fun updateSubscription(subscription: Subscription) {
subscriptionDao.update(subscription)
}
@Suppress("RedundantSuspendModifier")
@WorkerThread
suspend fun removeSubscription(subscriptionId: Long) {
subscriptionDao.remove(subscriptionId)
}
suspend fun getNotifications(): List<Notification> {
return notificationDao.list()
}
fun getNotificationsLiveData(subscriptionId: Long): LiveData<List<Notification>> {
return notificationDao.listFlow(subscriptionId).asLiveData()
}
fun clearAllNotificationIds(subscriptionId: Long) {
return notificationDao.clearAllNotificationIds(subscriptionId)
}
fun getNotification(notificationId: String): Notification? {
return notificationDao.get(notificationId)
}
fun onlyNewNotifications(subscriptionId: Long, notifications: List<Notification>): List<Notification> {
val existingIds = notificationDao.listIds(subscriptionId)
return notifications.filterNot { existingIds.contains(it.id) }
}
@Suppress("RedundantSuspendModifier")
@WorkerThread
suspend fun addNotification(notification: Notification): Boolean {
val maybeExistingNotification = notificationDao.get(notification.id)
if (maybeExistingNotification != null) {
return false
}
notificationDao.add(notification)
return true
}
fun updateNotification(notification: Notification) {
notificationDao.update(notification)
}
fun undeleteNotification(notificationId: String) {
notificationDao.undelete(notificationId)
}
fun markAsDeleted(notificationId: String) {
notificationDao.markAsDeleted(notificationId)
}
fun markAllAsDeleted(subscriptionId: Long) {
notificationDao.markAllAsDeleted(subscriptionId)
}
fun markAsDeletedIfOlderThan(subscriptionId: Long, olderThanTimestamp: Long) {
notificationDao.markAsDeletedIfOlderThan(subscriptionId, olderThanTimestamp)
}
fun removeNotificationsIfOlderThan(subscriptionId: Long, olderThanTimestamp: Long) {
notificationDao.removeIfOlderThan(subscriptionId, olderThanTimestamp)
}
fun removeAllNotifications(subscriptionId: Long) {
notificationDao.removeAll(subscriptionId)
}
fun getDeleteWorkerVersion(): Int {
return sharedPrefs.getInt(SHARED_PREFS_DELETE_WORKER_VERSION, 0)
}
fun setDeleteWorkerVersion(version: Int) {
sharedPrefs.edit {
putInt(SHARED_PREFS_DELETE_WORKER_VERSION, version)
}
}
fun getAutoRestartWorkerVersion(): Int {
return sharedPrefs.getInt(SHARED_PREFS_AUTO_RESTART_WORKER_VERSION, 0)
}
fun setAutoRestartWorkerVersion(version: Int) {
sharedPrefs.edit {
putInt(SHARED_PREFS_AUTO_RESTART_WORKER_VERSION, version)
}
}
fun setMinPriority(minPriority: Int) {
if (minPriority <= MIN_PRIORITY_ANY) {
sharedPrefs.edit {
remove(SHARED_PREFS_MIN_PRIORITY)
}
} else {
sharedPrefs.edit {
putInt(SHARED_PREFS_MIN_PRIORITY, minPriority)
}
}
}
fun getMinPriority(): Int {
return sharedPrefs.getInt(SHARED_PREFS_MIN_PRIORITY, MIN_PRIORITY_ANY)
}
fun getAutoDownloadMaxSize(): Long {
val defaultValue = if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
AUTO_DOWNLOAD_NEVER // Need to request permission on older versions
} else {
AUTO_DOWNLOAD_DEFAULT
}
return sharedPrefs.getLong(SHARED_PREFS_AUTO_DOWNLOAD_MAX_SIZE, defaultValue)
}
fun setAutoDownloadMaxSize(maxSize: Long) {
sharedPrefs.edit {
putLong(SHARED_PREFS_AUTO_DOWNLOAD_MAX_SIZE, maxSize)
}
}
fun getAutoDeleteSeconds(): Long {
return sharedPrefs.getLong(SHARED_PREFS_AUTO_DELETE_SECONDS, AUTO_DELETE_DEFAULT_SECONDS)
}
fun setAutoDeleteSeconds(seconds: Long) {
sharedPrefs.edit {
putLong(SHARED_PREFS_AUTO_DELETE_SECONDS, seconds)
}
}
fun setDarkMode(mode: Int) {
if (mode == AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) {
sharedPrefs.edit {
remove(SHARED_PREFS_DARK_MODE)
}
} else {
sharedPrefs.edit {
putInt(SHARED_PREFS_DARK_MODE, mode)
}
}
}
fun getDarkMode(): Int {
return sharedPrefs.getInt(SHARED_PREFS_DARK_MODE, AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
}
fun setDynamicColorsEnabled(enabled: Boolean) {
sharedPrefs.edit(commit = true) {
putBoolean(SHARED_PREFS_DYNAMIC_COLORS, enabled)
}
}
fun getDynamicColorsEnabled(): Boolean {
return sharedPrefs.getBoolean(SHARED_PREFS_DYNAMIC_COLORS, false)
}
fun getBroadcastEnabled(): Boolean {
return sharedPrefs.getBoolean(SHARED_PREFS_BROADCAST_ENABLED, true) // Enabled by default
}
fun setBroadcastEnabled(enabled: Boolean) {
sharedPrefs.edit {
putBoolean(SHARED_PREFS_BROADCAST_ENABLED, enabled)
}
}
fun getUnifiedPushEnabled(): Boolean {
return sharedPrefs.getBoolean(SHARED_PREFS_UNIFIEDPUSH_ENABLED, true) // Enabled by default
}
fun setUnifiedPushEnabled(enabled: Boolean) {
sharedPrefs.edit {
putBoolean(SHARED_PREFS_UNIFIEDPUSH_ENABLED, enabled)
}
}
fun getInsistentMaxPriorityEnabled(): Boolean {
return sharedPrefs.getBoolean(SHARED_PREFS_INSISTENT_MAX_PRIORITY_ENABLED, false) // Disabled by default
}
fun setInsistentMaxPriorityEnabled(enabled: Boolean) {
sharedPrefs.edit {
putBoolean(SHARED_PREFS_INSISTENT_MAX_PRIORITY_ENABLED, enabled)
}
}
fun getRecordLogs(): Boolean {
return sharedPrefs.getBoolean(SHARED_PREFS_RECORD_LOGS_ENABLED, false) // Disabled by default
}
fun setRecordLogsEnabled(enabled: Boolean) {
sharedPrefs.edit {
putBoolean(SHARED_PREFS_RECORD_LOGS_ENABLED, enabled)
}
}
fun getMessageBarEnabled(): Boolean {
return sharedPrefs.getBoolean(SHARED_PREFS_MESSAGE_BAR_ENABLED, true) // Enabled by default
}
fun setMessageBarEnabled(enabled: Boolean) {
sharedPrefs.edit {
putBoolean(SHARED_PREFS_MESSAGE_BAR_ENABLED, enabled)
}
}
fun getBatteryOptimizationsRemindTime(): Long {
return sharedPrefs.getLong(SHARED_PREFS_BATTERY_OPTIMIZATIONS_REMIND_TIME, BATTERY_OPTIMIZATIONS_REMIND_TIME_ALWAYS)
}
fun setBatteryOptimizationsRemindTime(timeMillis: Long) {
sharedPrefs.edit {
putLong(SHARED_PREFS_BATTERY_OPTIMIZATIONS_REMIND_TIME, timeMillis)
}
}
fun getDefaultBaseUrl(): String? {
return sharedPrefs.getString(SHARED_PREFS_DEFAULT_BASE_URL, null) ?:
sharedPrefs.getString(SHARED_PREFS_UNIFIED_PUSH_BASE_URL, null) // Fall back to UP URL, removed when default is set!
}
fun setDefaultBaseUrl(baseUrl: String) {
if (baseUrl == "") {
sharedPrefs.edit {
remove(SHARED_PREFS_UNIFIED_PUSH_BASE_URL) // Remove legacy key
.remove(SHARED_PREFS_DEFAULT_BASE_URL)
}
} else {
sharedPrefs.edit {
remove(SHARED_PREFS_UNIFIED_PUSH_BASE_URL) // Remove legacy key
.putString(SHARED_PREFS_DEFAULT_BASE_URL, baseUrl)
}
}
}
fun isGlobalMuted(): Boolean {
val mutedUntil = getGlobalMutedUntil()
return mutedUntil == 1L || (mutedUntil > 1L && mutedUntil > System.currentTimeMillis()/1000)
}
fun getGlobalMutedUntil(): Long {
return sharedPrefs.getLong(SHARED_PREFS_MUTED_UNTIL_TIMESTAMP, 0L)
}
fun setGlobalMutedUntil(mutedUntilTimestamp: Long) {
sharedPrefs.edit {
putLong(SHARED_PREFS_MUTED_UNTIL_TIMESTAMP, mutedUntilTimestamp)
}
}
fun checkGlobalMutedUntil(): Boolean {
val mutedUntil = sharedPrefs.getLong(SHARED_PREFS_MUTED_UNTIL_TIMESTAMP, 0L)
val expired = mutedUntil > 1L && System.currentTimeMillis()/1000 > mutedUntil
if (expired) {
sharedPrefs.edit {
putLong(SHARED_PREFS_MUTED_UNTIL_TIMESTAMP, 0L)
}
return true
}
return false
}
fun getLastShareTopics(): List<String> {
val topics = sharedPrefs.getString(SHARED_PREFS_LAST_TOPICS, "") ?: ""
return topics.split("\n").filter { validUrl(it) }
}
fun addLastShareTopic(topic: String) {
val topics = (getLastShareTopics().filterNot { it == topic } + topic).takeLast(LAST_TOPICS_COUNT)
sharedPrefs.edit {
putString(SHARED_PREFS_LAST_TOPICS, topics.joinToString(separator = "\n"))
}
}
private fun toSubscriptionList(list: List<SubscriptionWithMetadata>): List<Subscription> {
return list.map { s ->
Subscription(
id = s.id,
baseUrl = s.baseUrl,
topic = s.topic,
mutedUntil = s.mutedUntil,
minPriority = s.minPriority,
autoDelete = s.autoDelete,
insistent = s.insistent,
upAppId = s.upAppId,
upConnectorToken = s.upConnectorToken,
displayName = s.displayName,
totalCount = s.totalCount,
newCount = s.newCount,
lastActive = s.lastActive,
connectionDetails = connectionDetails[s.baseUrl] ?: ConnectionDetails()
)
}
}
private fun toSubscription(s: SubscriptionWithMetadata?): Subscription? {
if (s == null) {
return null
}
return Subscription(
id = s.id,
baseUrl = s.baseUrl,
topic = s.topic,
mutedUntil = s.mutedUntil,
minPriority = s.minPriority,
autoDelete = s.autoDelete,
insistent = s.insistent,
upAppId = s.upAppId,
upConnectorToken = s.upConnectorToken,
displayName = s.displayName,
totalCount = s.totalCount,
newCount = s.newCount,
lastActive = s.lastActive,
connectionDetails = connectionDetails[s.baseUrl] ?: ConnectionDetails()
)
}
fun updateConnectionDetails(baseUrl: String, state: ConnectionState, error: Throwable? = null, nextRetryTime: Long = 0L) {
val details = ConnectionDetails(state, error, nextRetryTime)
val current = connectionDetails[baseUrl]
if (current != details) {
if (state == ConnectionState.NOT_APPLICABLE && error == null) {
connectionDetails.remove(baseUrl)
} else {
connectionDetails[baseUrl] = details
}
connectionDetailsLiveData.postValue(connectionDetails.toMap())
Log.d(TAG, "Connection details updated for $baseUrl: state=$state, error=${error?.message}, nextRetry=$nextRetryTime")
}
}
fun getConnectionDetailsLiveData(): LiveData<Map<String, ConnectionDetails>> {
return connectionDetailsLiveData
}
fun getConnectionDetails(): Map<String, ConnectionDetails> {
return connectionDetails.toMap()
}
fun getConnectionDetailsForBaseUrl(baseUrl: String): ConnectionDetails? {
return connectionDetails[baseUrl]
}
fun getConnectionForceReconnectVersion(baseUrl: String): Long {
return connectionForceReconnectVersions[baseUrl] ?: 0L
}
fun incrementConnectionForceReconnectVersion(baseUrl: String) {
connectionForceReconnectVersions.compute(baseUrl) { _, current -> (current ?: 0L) + 1 }
Log.d(TAG, "Connection force reconnect version incremented for $baseUrl: ${connectionForceReconnectVersions[baseUrl]}")
}
companion object {
const val SHARED_PREFS_ID = "MainPreferences"
const val SHARED_PREFS_DELETE_WORKER_VERSION = "DeleteWorkerVersion"
const val SHARED_PREFS_AUTO_RESTART_WORKER_VERSION = "AutoRestartWorkerVersion"
const val SHARED_PREFS_MUTED_UNTIL_TIMESTAMP = "MutedUntil"
const val SHARED_PREFS_MIN_PRIORITY = "MinPriority"
const val SHARED_PREFS_AUTO_DOWNLOAD_MAX_SIZE = "AutoDownload"
const val SHARED_PREFS_AUTO_DELETE_SECONDS = "AutoDelete"
const val SHARED_PREFS_DARK_MODE = "DarkMode"
const val SHARED_PREFS_DYNAMIC_COLORS = "DynamicColors"
const val SHARED_PREFS_BROADCAST_ENABLED = "BroadcastEnabled"
const val SHARED_PREFS_UNIFIEDPUSH_ENABLED = "UnifiedPushEnabled"
const val SHARED_PREFS_INSISTENT_MAX_PRIORITY_ENABLED = "InsistentMaxPriority"
const val SHARED_PREFS_RECORD_LOGS_ENABLED = "RecordLogs"
const val SHARED_PREFS_MESSAGE_BAR_ENABLED = "MessageBarEnabled"
const val SHARED_PREFS_BATTERY_OPTIMIZATIONS_REMIND_TIME = "BatteryOptimizationsRemindTime"
const val SHARED_PREFS_UNIFIED_PUSH_BASE_URL = "UnifiedPushBaseURL" // Legacy key required for migration to DefaultBaseURL
const val SHARED_PREFS_DEFAULT_BASE_URL = "DefaultBaseURL"
const val SHARED_PREFS_LAST_TOPICS = "LastTopics"
private const val LAST_TOPICS_COUNT = 3
const val MIN_PRIORITY_USE_GLOBAL = 0
const val MIN_PRIORITY_ANY = 1
const val MUTED_UNTIL_SHOW_ALL = 0L
const val MUTED_UNTIL_FOREVER = 1L
const val MUTED_UNTIL_TOMORROW = 2L
private const val ONE_MB = 1024 * 1024L
const val AUTO_DOWNLOAD_NEVER = 0L // Values must match values.xml
const val AUTO_DOWNLOAD_ALWAYS = 1L
const val AUTO_DOWNLOAD_DEFAULT = ONE_MB
private const val ONE_DAY_SECONDS = 24 * 60 * 60L
const val AUTO_DELETE_USE_GLOBAL = -1L // Values must match values.xml
const val AUTO_DELETE_NEVER = 0L
const val AUTO_DELETE_ONE_DAY_SECONDS = ONE_DAY_SECONDS
const val AUTO_DELETE_THREE_DAYS_SECONDS = 3 * ONE_DAY_SECONDS
const val AUTO_DELETE_ONE_WEEK_SECONDS = 7 * ONE_DAY_SECONDS
const val AUTO_DELETE_ONE_MONTH_SECONDS = 30 * ONE_DAY_SECONDS
const val AUTO_DELETE_THREE_MONTHS_SECONDS = 90 * ONE_DAY_SECONDS
const val AUTO_DELETE_DEFAULT_SECONDS = AUTO_DELETE_ONE_MONTH_SECONDS
const val INSISTENT_MAX_PRIORITY_USE_GLOBAL = -1 // Values must match values.xml
const val INSISTENT_MAX_PRIORITY_ENABLED = 1 // 0 = Disabled (but not needed in code)
const val BATTERY_OPTIMIZATIONS_REMIND_TIME_ALWAYS = 1L
const val BATTERY_OPTIMIZATIONS_REMIND_TIME_NEVER = Long.MAX_VALUE
private const val TAG = "NtfyRepository"
private var instance: Repository? = null
fun getInstance(context: Context): Repository {
val database = Database.getInstance(context.applicationContext)
val sharedPrefs = context.getSharedPreferences(SHARED_PREFS_ID, Context.MODE_PRIVATE)
return getInstance(sharedPrefs, database)
}
private fun getInstance(sharedPrefs: SharedPreferences, database: Database): Repository {
return synchronized(Repository::class) {
val newInstance = instance ?: Repository(sharedPrefs, database)
instance = newInstance
newInstance
}
}
}
}
/* https://stackoverflow.com/a/57079290/1440785 */
fun <T, K, R> LiveData<T>.combineWith(
liveData: LiveData<K>,
block: (T?, K?) -> R
): LiveData<R> {
val result = MediatorLiveData<R>()
result.addSource(this) {
result.value = block(this.value, liveData.value)
}
result.addSource(liveData) {
result.value = block(this.value, liveData.value)
}
return result
}

View file

@ -0,0 +1,193 @@
package com.lonecloud.sup.msg
import android.content.Context
import com.google.gson.Gson
import com.lonecloud.sup.db.Notification
import com.lonecloud.sup.db.Repository
import com.lonecloud.sup.service.NotAuthorizedException
import com.lonecloud.sup.util.ALL_PRIORITIES
import com.lonecloud.sup.util.HttpUtil
import com.lonecloud.sup.util.Log
import com.lonecloud.sup.util.PRIORITY_DEFAULT
import com.lonecloud.sup.util.topicUrl
import com.lonecloud.sup.util.topicUrlAuth
import com.lonecloud.sup.util.topicUrlJson
import com.lonecloud.sup.util.topicUrlJsonPoll
import okhttp3.Call
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okio.BufferedSource
import java.io.IOException
import java.net.URLEncoder
import kotlin.random.Random
class ApiService(private val context: Context) {
private val repository = Repository.getInstance(context)
private val gson = Gson()
private val parser = NotificationParser()
suspend fun publish(
baseUrl: String,
topic: String,
message: String,
title: String = "",
priority: Int = PRIORITY_DEFAULT,
tags: List<String> = emptyList(),
delay: String = "",
body: RequestBody? = null,
filename: String = "",
click: String = "",
attach: String = "",
email: String = "",
call: String = "",
markdown: Boolean = false,
onCancelAvailable: ((cancel: () -> Unit) -> Unit)? = null // Called when the HTTP request was started and cancellable (caller can cancel)
) {
val url = topicUrl(baseUrl, topic)
val query = mutableListOf<String>()
if (priority in ALL_PRIORITIES) {
query.add("priority=$priority")
}
if (tags.isNotEmpty()) {
query.add("tags=${URLEncoder.encode(tags.joinToString(","), "UTF-8")}")
}
if (title.isNotEmpty()) {
query.add("title=${URLEncoder.encode(title, "UTF-8")}")
}
if (delay.isNotEmpty()) {
query.add("delay=${URLEncoder.encode(delay, "UTF-8")}")
}
if (filename.isNotEmpty()) {
query.add("filename=${URLEncoder.encode(filename, "UTF-8")}")
}
if (click.isNotEmpty()) {
query.add("click=${URLEncoder.encode(click, "UTF-8")}")
}
if (attach.isNotEmpty()) {
query.add("attach=${URLEncoder.encode(attach, "UTF-8")}")
}
if (email.isNotEmpty()) {
query.add("email=${URLEncoder.encode(email, "UTF-8")}")
}
if (call.isNotEmpty()) {
query.add("call=${URLEncoder.encode(call, "UTF-8")}")
}
if (markdown) {
query.add("markdown=true")
}
if (body != null) {
query.add("message=${URLEncoder.encode(message.replace("\n", "\\n"), "UTF-8")}")
}
val urlWithQuery = if (query.isNotEmpty()) {
url + "?" + query.joinToString("&")
} else {
url
}
val request = HttpUtil.requestBuilder(urlWithQuery)
.put(body ?: message.toRequestBody())
.build()
Log.d(TAG, "Publishing to $request")
val httpCall = HttpUtil.longCallClient(context, baseUrl).newCall(request)
onCancelAvailable?.invoke { httpCall.cancel() } // Notify caller that HTTP request can now be canceled
httpCall.execute().use { response ->
if (response.code == 401 || response.code == 403) {
throw UnauthorizedException()
} else if (response.code == 413) {
throw EntityTooLargeException()
} else if (!response.isSuccessful) {
// Try to parse error response from server
val errorBody = response.body.string()
val apiError = try {
gson.fromJson(errorBody, ErrorResponse::class.java)
} catch (e: Exception) {
null
}
if (apiError?.error != null && apiError.code != null) {
throw ApiException(apiError.error, apiError.code)
}
throw Exception("Unexpected response ${response.code} when publishing to $url")
}
Log.d(TAG, "Successfully published to $url")
}
}
suspend fun poll(subscriptionId: Long, baseUrl: String, topic: String, since: String? = null): List<Notification> {
val sinceVal = since ?: "all"
val url = topicUrlJsonPoll(baseUrl, topic, sinceVal)
Log.d(TAG, "Polling topic $url")
val request = HttpUtil.requestBuilder(url).build()
HttpUtil.defaultClient(context, baseUrl).newCall(request).execute().use { response ->
if (!response.isSuccessful) {
throw Exception("Unexpected response ${response.code} when polling topic $url")
}
val body = response.body.string().trim()
if (body.isEmpty()) return emptyList()
val notifications = body.lines().mapNotNull { line ->
parser.parse(line, subscriptionId = subscriptionId, notificationId = 0) // No notification when we poll
}
Log.d(TAG, "Notifications: $notifications")
return notifications
}
}
suspend fun subscribe(
baseUrl: String,
topics: String,
since: String?
): Pair<Call, BufferedSource> {
val sinceVal = since ?: "all"
val url = topicUrlJson(baseUrl, topics, sinceVal)
Log.d(TAG, "Opening subscription connection to $url")
val request = HttpUtil.requestBuilder(url).build()
val call = HttpUtil.subscriberClient(context, baseUrl).newCall(request)
val response = call.execute()
if (!response.isSuccessful) {
val code = response.code
val message = response.message
response.close()
if (code == 401 || code == 403) {
throw NotAuthorizedException("$code $message")
}
throw IOException("Unexpected response $code when subscribing to $url")
}
return Pair(call, response.body.source())
}
suspend fun checkAuth(baseUrl: String, topic: String): Boolean {
Log.d(TAG, "Checking anonymous read against ${topicUrl(baseUrl, topic)}")
val url = topicUrlAuth(baseUrl, topic)
val request = HttpUtil.requestBuilder(url).build()
HttpUtil.defaultClient(context, baseUrl).newCall(request).execute().use { response ->
if (response.isSuccessful) {
return true
} else if (response.code == 404) {
return true // Special case: Anonymous login to old servers return 404 since /<topic>/auth doesn't exist
} else if (response.code == 401 || response.code == 403) { // See server/server.go
return false
}
throw Exception("Unexpected server response ${response.code}")
}
}
class UnauthorizedException : Exception()
class EntityTooLargeException : Exception()
class ApiException(val error: String, val code: Int) : Exception(error)
private data class ErrorResponse(
val code: Int?,
val http: Int?,
val error: String?
)
companion object {
private const val TAG = "NtfyApiService"
// These constants have corresponding values in the server codebase!
const val CONTROL_TOPIC = "~control"
const val EVENT_MESSAGE = "message"
const val EVENT_KEEPALIVE = "keepalive"
const val EVENT_POLL_REQUEST = "poll_request"
}
}

View file

@ -0,0 +1,109 @@
package com.lonecloud.sup.msg
import android.content.Context
import android.content.Intent
import com.lonecloud.sup.R
import com.lonecloud.sup.db.Notification
import com.lonecloud.sup.db.Repository
import com.lonecloud.sup.db.Subscription
import com.lonecloud.sup.util.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
/**
* The broadcast service is responsible for sending and receiving broadcast intents
* in order to facilitate tasks app integrations.
*/
class BroadcastService(private val ctx: Context) {
fun sendMessage(subscription: Subscription, notification: Notification, muted: Boolean) {
val intent = Intent()
intent.action = MESSAGE_RECEIVED_ACTION
intent.putExtra("id", notification.id)
intent.putExtra("base_url", subscription.baseUrl)
intent.putExtra("topic", subscription.topic)
intent.putExtra("time", notification.timestamp.toInt())
intent.putExtra("title", notification.title)
intent.putExtra("message", decodeMessage(notification))
intent.putExtra("message_bytes", decodeBytesMessage(notification))
intent.putExtra("tags", notification.tags)
intent.putExtra("tags_map", joinTagsMap(splitTags(notification.tags)))
intent.putExtra("priority", notification.priority)
intent.putExtra("muted", muted)
intent.putExtra("muted_str", muted.toString())
Log.d(TAG, "Sending message intent broadcast: ${intent.action} with extras ${intent.extras}")
ctx.sendBroadcast(intent)
}
/**
* This receiver is triggered when the SEND_MESSAGE intent is received.
* See AndroidManifest.xml for details.
*/
class BroadcastReceiver : android.content.BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d(TAG, "Broadcast received: $intent")
when (intent.action) {
MESSAGE_SEND_ACTION -> send(context, intent)
}
}
private fun send(ctx: Context, intent: Intent) {
val api = ApiService(ctx)
val baseUrl = getStringExtra(intent, "base_url") ?: ctx.getString(R.string.app_base_url)
val topic = getStringExtra(intent, "topic") ?: return
val message = getStringExtra(intent, "message") ?: return
val title = getStringExtra(intent, "title") ?: ""
val tags = getStringExtra(intent,"tags") ?: ""
val priority = when (getStringExtra(intent, "priority")) {
"min", "1" -> 1
"low", "2" -> 2
"default", "3" -> 3
"high", "4" -> 4
"urgent", "max", "5" -> 5
else -> 0
}
val delay = getStringExtra(intent,"delay") ?: ""
GlobalScope.launch(Dispatchers.IO) {
try {
Log.d(TAG, "Publishing message $intent")
api.publish(
baseUrl = baseUrl,
topic = topic,
message = message,
title = title,
priority = priority,
tags = splitTags(tags),
delay = delay
)
} catch (e: Exception) {
Log.w(TAG, "Unable to publish message: ${e.message}", e)
}
}
}
/**
* Gets an extra as a String value, even if the extra may be an int or a long.
*/
private fun getStringExtra(intent: Intent, name: String): String? {
if (intent.getStringExtra(name) != null) {
return intent.getStringExtra(name)
} else if (intent.getIntExtra(name, DOES_NOT_EXIST) != DOES_NOT_EXIST) {
return intent.getIntExtra(name, DOES_NOT_EXIST).toString()
} else if (intent.getLongExtra(name, DOES_NOT_EXIST.toLong()) != DOES_NOT_EXIST.toLong()) {
return intent.getLongExtra(name, DOES_NOT_EXIST.toLong()).toString()
}
return null
}
}
companion object {
private const val TAG = "NtfyBroadcastService"
private const val DOES_NOT_EXIST = -2586000
// These constants cannot be changed without breaking the contract; also see manifest
private const val MESSAGE_RECEIVED_ACTION = "io.heckel.ntfy.MESSAGE_RECEIVED"
private const val MESSAGE_SEND_ACTION = "io.heckel.ntfy.SEND_MESSAGE"
private const val USER_ACTION_ACTION = "io.heckel.ntfy.USER_ACTION"
}
}

View file

@ -0,0 +1,49 @@
package com.lonecloud.sup.msg
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
/* This annotation ensures that proguard still works in production builds,
* see https://stackoverflow.com/a/62753300/1440785 */
@Keep
data class Message(
val id: String,
val time: Long,
val event: String,
val topic: String,
val priority: Int?,
val tags: List<String>?,
val click: String?,
val icon: String?,
val actions: List<MessageAction>?,
val title: String?,
val message: String,
@SerializedName("content_type") val contentType: String?,
val encoding: String?,
val attachment: MessageAttachment?,
)
@Keep
data class MessageAttachment(
val name: String,
val type: String?,
val size: Long?,
val expires: Long?,
val url: String,
)
@Keep
data class MessageAction(
val id: String,
val action: String,
val label: String, // "view", "broadcast" or "http"
val clear: Boolean?, // clear notification after successful execution
val url: String?, // used in "view" and "http" actions
val method: String?, // used in "http" action, default is POST (!)
val headers: Map<String,String>?, // used in "http" action
val body: String?, // used in "http" action
val intent: String?, // used in "broadcast" action
val extras: Map<String,String>?, // used in "broadcast" action
)
const val MESSAGE_ENCODING_BASE64 = "base64"

View file

@ -0,0 +1,79 @@
package com.lonecloud.sup.msg
import android.content.Context
import com.lonecloud.sup.db.Notification
import com.lonecloud.sup.db.Repository
import com.lonecloud.sup.db.Subscription
import com.lonecloud.sup.util.Log
import com.lonecloud.sup.up.Distributor
import com.lonecloud.sup.util.decodeBytesMessage
import com.lonecloud.sup.util.safeLet
/**
* The notification dispatcher figures out what to do with a notification.
* It may display a notification, send out a broadcast, or forward via UnifiedPush.
*/
class NotificationDispatcher(val context: Context, val repository: Repository) {
private val notifier = NotificationService(context)
private val broadcaster = BroadcastService(context)
private val distributor = Distributor(context)
fun init() {
notifier.createNotificationChannels()
}
fun dispatch(subscription: Subscription, notification: Notification) {
Log.d(TAG, "Dispatching $notification for subscription $subscription")
val muted = getMuted(subscription)
val notify = shouldNotify(subscription, notification, muted)
val broadcast = shouldBroadcast(subscription)
val distribute = shouldDistribute(subscription)
if (notify) {
notifier.display(subscription, notification)
}
if (broadcast) {
broadcaster.sendMessage(subscription, notification, muted)
}
if (distribute) {
safeLet(subscription.upAppId, subscription.upConnectorToken) { appId, connectorToken ->
distributor.sendMessage(appId, connectorToken, decodeBytesMessage(notification))
}
}
}
private fun shouldNotify(subscription: Subscription, notification: Notification, muted: Boolean): Boolean {
if (subscription.upAppId != null) {
return false
}
val priority = if (notification.priority > 0) notification.priority else 3
val minPriority = if (subscription.minPriority > 0) subscription.minPriority else repository.getMinPriority()
if (priority < minPriority) {
return false
}
val detailsVisible = repository.detailViewSubscriptionId.get() == notification.subscriptionId
return !detailsVisible && !muted
}
private fun shouldBroadcast(subscription: Subscription): Boolean {
if (subscription.upAppId != null) { // Never broadcast for UnifiedPush subscriptions
return false
}
return repository.getBroadcastEnabled()
}
private fun shouldDistribute(subscription: Subscription): Boolean {
return subscription.upAppId != null // Only distribute for UnifiedPush subscriptions
}
private fun getMuted(subscription: Subscription): Boolean {
if (repository.isGlobalMuted()) {
return true
}
return subscription.mutedUntil == 1L || (subscription.mutedUntil > 1L && subscription.mutedUntil > System.currentTimeMillis()/1000)
}
companion object {
private const val TAG = "NtfyNotifDispatch"
}
}

View file

@ -0,0 +1,37 @@
package com.lonecloud.sup.msg
import com.google.gson.Gson
import com.lonecloud.sup.db.Notification
import com.lonecloud.sup.util.joinTags
import com.lonecloud.sup.util.toPriority
import java.lang.reflect.Type
class NotificationParser {
private val gson = Gson()
fun parse(s: String, subscriptionId: Long = 0, notificationId: Int = 0): Notification? {
val notificationWithTopic = parseWithTopic(s, subscriptionId = subscriptionId, notificationId = notificationId)
return notificationWithTopic?.notification
}
fun parseWithTopic(s: String, subscriptionId: Long = 0, notificationId: Int = 0): NotificationWithTopic? {
val message = gson.fromJson(s, Message::class.java)
if (message.event != ApiService.EVENT_MESSAGE) {
return null
}
val notification = Notification(
id = message.id,
subscriptionId = subscriptionId,
timestamp = message.time,
title = message.title ?: "",
message = message.message,
priority = toPriority(message.priority),
tags = joinTags(message.tags),
notificationId = notificationId,
deleted = false
)
return NotificationWithTopic(message.topic, notification)
}
data class NotificationWithTopic(val topic: String, val notification: Notification)
}

View file

@ -0,0 +1,232 @@
package com.lonecloud.sup.msg
import android.app.*
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.RingtoneManager
import android.net.Uri
import androidx.core.app.NotificationCompat
import com.lonecloud.sup.R
import com.lonecloud.sup.db.*
import com.lonecloud.sup.db.Notification
import com.lonecloud.sup.ui.Colors
import com.lonecloud.sup.ui.DetailActivity
import com.lonecloud.sup.ui.MainActivity
import com.lonecloud.sup.util.*
import java.util.*
class NotificationService(val context: Context) {
private val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
private val repository = Repository.getInstance(context)
private val appBaseUrl = context.getString(R.string.app_base_url)
fun display(subscription: Subscription, notification: Notification) {
displayInternal(subscription, notification, update = false)
}
fun update(subscription: Subscription, notification: Notification, isNew: Boolean) {
displayInternal(subscription, notification, update = !isNew)
}
fun cancel(notificationId: Int) {
notificationManager.cancel(notificationId)
}
fun cancel(subscription: Subscription, notification: Notification) {
notificationManager.cancel(notification.notificationId)
}
fun createNotificationChannels() {
val groupId = DEFAULT_GROUP
val groupName = context.getString(R.string.channel_notifications_group_default_name)
maybeCreateNotificationGroup(groupId, groupName)
(PRIORITY_MIN..PRIORITY_MAX).forEach { priority ->
maybeCreateNotificationChannel(groupId, priority)
}
}
private fun displayInternal(subscription: Subscription, notification: Notification, update: Boolean = false) {
val title = formatTitle(appBaseUrl, subscription, notification)
val groupId = DEFAULT_GROUP
val channelId = toChannelId(groupId, notification.priority)
val insistent = notification.priority == PRIORITY_MAX &&
(repository.getInsistentMaxPriorityEnabled() || subscription.insistent == Repository.INSISTENT_MAX_PRIORITY_ENABLED)
val builder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setColor(Colors.notificationIcon(context))
.setContentTitle(title)
.setOnlyAlertOnce(true)
.setAutoCancel(true)
setStyleAndText(builder, notification)
setClickAction(builder, subscription)
maybeSetDeleteIntent(builder, insistent)
maybeSetSound(builder, insistent, update)
maybeCreateNotificationGroup(groupId, subscriptionGroupName(subscription))
maybeCreateNotificationChannel(groupId, notification.priority)
maybePlayInsistentSound(groupId, insistent)
notificationManager.notify(notification.notificationId, builder.build())
}
private fun maybeSetDeleteIntent(builder: NotificationCompat.Builder, insistent: Boolean) {
if (!insistent) {
return
}
val intent = Intent(context, DeleteBroadcastReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(context, Random().nextInt(), intent, PendingIntent.FLAG_IMMUTABLE)
builder.setDeleteIntent(pendingIntent)
}
private fun maybeSetSound(builder: NotificationCompat.Builder, insistent: Boolean, update: Boolean) {
val hasSound = !update && !insistent
if (hasSound) {
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
builder.setSound(defaultSoundUri)
} else {
builder.setSound(null)
}
}
private fun setStyleAndText(builder: NotificationCompat.Builder, notification: Notification) {
val message = formatMessage(notification)
builder
.setContentText(message)
.setStyle(NotificationCompat.BigTextStyle().bigText(message))
}
private fun setClickAction(builder: NotificationCompat.Builder, subscription: Subscription) {
builder.setContentIntent(detailActivityIntent(subscription))
}
private fun subscriptionGroupName(subscription: Subscription): String {
return displayName(appBaseUrl, subscription)
}
private fun displayName(appBaseUrl: String?, subscription: Subscription): String {
return subscription.displayName ?: subscriptionTopicShortUrl(subscription)
}
class DeleteBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d(TAG, "Media player: Stopping insistent ring")
val mediaPlayer = Repository.getInstance(context).mediaPlayer
mediaPlayer.stop()
}
}
private fun detailActivityIntent(subscription: Subscription): PendingIntent? {
val intent = Intent(context, DetailActivity::class.java).apply {
putExtra(MainActivity.EXTRA_SUBSCRIPTION_ID, subscription.id)
putExtra(MainActivity.EXTRA_SUBSCRIPTION_BASE_URL, subscription.baseUrl)
putExtra(MainActivity.EXTRA_SUBSCRIPTION_TOPIC, subscription.topic)
putExtra(MainActivity.EXTRA_SUBSCRIPTION_DISPLAY_NAME, displayName(appBaseUrl, subscription))
putExtra(MainActivity.EXTRA_SUBSCRIPTION_MUTED_UNTIL, subscription.mutedUntil)
}
return TaskStackBuilder.create(context).run {
addNextIntentWithParentStack(intent)
getPendingIntent(Random().nextInt(), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}
}
private fun maybeCreateNotificationChannel(group: String, priority: Int) {
val channelId = toChannelId(group, priority)
val pause = 300L
val channel = when (priority) {
PRIORITY_MIN -> NotificationChannel(channelId, context.getString(R.string.common_priority_min_name), NotificationManager.IMPORTANCE_MIN)
PRIORITY_LOW -> NotificationChannel(channelId, context.getString(R.string.common_priority_low_name), NotificationManager.IMPORTANCE_LOW)
PRIORITY_HIGH -> {
val channel = NotificationChannel(channelId, context.getString(R.string.common_priority_high_name), NotificationManager.IMPORTANCE_HIGH)
channel.enableVibration(true)
channel.vibrationPattern = longArrayOf(
pause, 100, pause, 100, pause, 100,
pause, 2000
)
channel
}
PRIORITY_MAX -> {
val channel = NotificationChannel(channelId, context.getString(R.string.common_priority_max_name), NotificationManager.IMPORTANCE_HIGH)
channel.enableLights(true)
channel.enableVibration(true)
channel.setBypassDnd(true)
channel.vibrationPattern = longArrayOf(
pause, 100, pause, 100, pause, 100,
pause, 2000,
pause, 100, pause, 100, pause, 100,
pause, 2000,
pause, 100, pause, 100, pause, 100,
pause, 2000
)
channel
}
else -> NotificationChannel(channelId, context.getString(R.string.common_priority_default_name), NotificationManager.IMPORTANCE_DEFAULT)
}
channel.group = group
notificationManager.createNotificationChannel(channel)
}
private fun maybeDeleteNotificationChannel(group: String, priority: Int) {
notificationManager.deleteNotificationChannel(toChannelId(group, priority))
}
private fun maybeCreateNotificationGroup(id: String, name: String) {
notificationManager.createNotificationChannelGroup(NotificationChannelGroup(id, name))
}
private fun maybeDeleteNotificationGroup(id: String) {
notificationManager.deleteNotificationChannelGroup(id)
}
private fun toChannelId(groupId: String, priority: Int): String {
return when (priority) {
PRIORITY_MIN -> groupId + GROUP_SUFFIX_PRIORITY_MIN
PRIORITY_LOW -> groupId + GROUP_SUFFIX_PRIORITY_LOW
PRIORITY_HIGH -> groupId + GROUP_SUFFIX_PRIORITY_HIGH
PRIORITY_MAX -> groupId + GROUP_SUFFIX_PRIORITY_MAX
else -> groupId + GROUP_SUFFIX_PRIORITY_DEFAULT
}
}
private fun maybePlayInsistentSound(groupId: String, insistent: Boolean) {
if (!insistent) {
return
}
try {
val mediaPlayer = repository.mediaPlayer
val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
Log.d(TAG, "Media player: Playing insistent alarm on alarm channel")
mediaPlayer.reset()
mediaPlayer.setDataSource(context, getInsistentSound(groupId))
mediaPlayer.setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM).build())
mediaPlayer.isLooping = true
mediaPlayer.prepare()
mediaPlayer.start()
} else {
Log.d(TAG, "Media player: Alarm volume is 0; not playing insistent alarm")
}
} catch (e: Exception) {
Log.w(TAG, "Media player: Failed to play insistent alarm", e)
}
}
private fun getInsistentSound(groupId: String): Uri {
val channelId = toChannelId(groupId, PRIORITY_MAX)
val channel = notificationManager.getNotificationChannel(channelId)
return channel.sound
}
companion object {
private const val TAG = "NtfyNotifService"
private const val DEFAULT_GROUP = "ntfy"
private const val SUBSCRIPTION_GROUP_PREFIX = "ntfy-subscription-"
private const val GROUP_SUFFIX_PRIORITY_MIN = "-min"
private const val GROUP_SUFFIX_PRIORITY_LOW = "-low"
private const val GROUP_SUFFIX_PRIORITY_DEFAULT = ""
private const val GROUP_SUFFIX_PRIORITY_HIGH = "-high"
private const val GROUP_SUFFIX_PRIORITY_MAX = "-max"
}
}

View file

@ -0,0 +1,12 @@
package com.lonecloud.sup.service
class NotAuthorizedException(message: String, val user: Any? = null) : Exception(message)
fun Throwable.hasCause(causeClass: Class<out Throwable>): Boolean {
var current: Throwable? = this
while (current != null) {
if (causeClass.isInstance(current)) return true
current = current.cause
}
return false
}

View file

@ -0,0 +1,88 @@
package com.lonecloud.sup.service
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.lonecloud.sup.R
import com.lonecloud.sup.app.Application
import com.lonecloud.sup.db.Notification
import com.lonecloud.sup.msg.NotificationDispatcher
import com.lonecloud.sup.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
/**
* Service that listens for Signal notifications and processes them.
* This replaces ntfy's SubscriberService which polls HTTP/WebSocket.
* We get notifications pushed via Signal instead.
*/
class SignalListenerService : Service() {
private val repository by lazy { (application as Application).repository }
private val dispatcher by lazy { NotificationDispatcher(this, repository) }
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
override fun onCreate() {
super.onCreate()
Log.d(TAG, "Service created")
createForegroundNotification()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d(TAG, "Service started")
// Process notification from intent if present
intent?.getStringExtra(EXTRA_NOTIFICATION_DATA)?.let { data ->
scope.launch {
processNotification(data)
}
}
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
private fun createForegroundNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
NOTIFICATION_CHANNEL_ID,
getString(R.string.channel_subscriber_service_name),
NotificationManager.IMPORTANCE_LOW
)
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(channel)
}
val notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText("Listening for notifications via Signal")
.setSmallIcon(R.drawable.ic_notification)
.build()
startForeground(NOTIFICATION_ID, notification)
}
private suspend fun processNotification(data: String) {
try {
// Parse notification data and dispatch
Log.d(TAG, "Processing notification: $data")
// This will be called by SignalNotificationListener
// with parsed notification data
} catch (e: Exception) {
Log.e(TAG, "Error processing notification: ${e.message}", e)
}
}
companion object {
private const val TAG = "NtfySignalListener"
private const val NOTIFICATION_CHANNEL_ID = "ntfy-signal"
private const val NOTIFICATION_ID = 1
const val EXTRA_NOTIFICATION_DATA = "notification_data"
}
}

View file

@ -0,0 +1,466 @@
package com.lonecloud.sup.ui
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.*
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.lifecycleScope
import com.google.android.material.appbar.MaterialToolbar
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import com.lonecloud.sup.BuildConfig
import com.lonecloud.sup.R
import com.lonecloud.sup.db.Repository
import com.lonecloud.sup.msg.ApiService
import com.lonecloud.sup.util.CertUtil
import com.lonecloud.sup.util.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import androidx.core.view.isVisible
import androidx.core.view.isGone
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.SSLHandshakeException
import javax.net.ssl.SSLPeerUnverifiedException
class AddFragment : DialogFragment() {
private lateinit var repository: Repository
private lateinit var api: ApiService
private lateinit var subscribeListener: SubscribeListener
private lateinit var appBaseUrl: String
private var defaultBaseUrl: String? = null
private lateinit var toolbar: MaterialToolbar
private lateinit var actionMenuItem: MenuItem
private lateinit var subscribeView: View
private lateinit var loginView: View
// Subscribe page
private lateinit var subscribeTopicText: TextInputEditText
private lateinit var subscribeBaseUrlLayout: TextInputLayout
private lateinit var subscribeBaseUrlText: AutoCompleteTextView
private lateinit var subscribeUseAnotherServerCheckbox: CheckBox
private lateinit var subscribeUseAnotherServerDescription: TextView
private lateinit var subscribeInstantDeliveryBox: View
private lateinit var subscribeInstantDeliveryCheckbox: CheckBox
private lateinit var subscribeInstantDeliveryDescription: View
private lateinit var subscribeForegroundDescription: TextView
private lateinit var subscribeProgress: ProgressBar
private lateinit var subscribeErrorText: TextView
private lateinit var subscribeErrorTextImage: View
// Login page
private lateinit var loginUsernameText: TextInputEditText
private lateinit var loginPasswordText: TextInputEditText
private lateinit var loginProgress: ProgressBar
private lateinit var loginErrorText: TextView
private lateinit var loginErrorTextImage: View
interface SubscribeListener {
fun onSubscribe(topic: String, baseUrl: String, instant: Boolean)
}
override fun onAttach(context: Context) {
super.onAttach(context)
subscribeListener = activity as SubscribeListener
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
if (activity == null) {
throw IllegalStateException("Activity cannot be null")
}
// Dependencies (Fragments need a default constructor)
repository = Repository.getInstance(requireActivity())
api = ApiService(requireContext())
appBaseUrl = getString(R.string.app_base_url)
defaultBaseUrl = repository.getDefaultBaseUrl()
// Build root view
val view = requireActivity().layoutInflater.inflate(R.layout.fragment_add_dialog, null)
// Setup toolbar
toolbar = view.findViewById(R.id.add_dialog_toolbar)
toolbar.setNavigationOnClickListener {
dismiss()
}
toolbar.setOnMenuItemClickListener { menuItem ->
if (menuItem.itemId == R.id.add_dialog_action_button) {
onActionButtonClick()
true
} else {
false
}
}
actionMenuItem = toolbar.menu.findItem(R.id.add_dialog_action_button)
// Main "pages"
subscribeView = view.findViewById(R.id.add_dialog_subscribe_view)
subscribeView.visibility = View.VISIBLE
loginView = view.findViewById(R.id.add_dialog_login_view)
loginView.visibility = View.GONE
// Fields for "subscribe page"
subscribeTopicText = view.findViewById(R.id.add_dialog_subscribe_topic_text)
subscribeBaseUrlLayout = view.findViewById(R.id.add_dialog_subscribe_base_url_layout)
subscribeBaseUrlLayout.background = view.background
subscribeBaseUrlLayout.makeEndIconSmaller(resources) // Hack!
subscribeBaseUrlText = view.findViewById(R.id.add_dialog_subscribe_base_url_text)
subscribeBaseUrlText.background = view.background
subscribeBaseUrlText.hint = defaultBaseUrl ?: appBaseUrl
subscribeInstantDeliveryBox = view.findViewById(R.id.add_dialog_subscribe_instant_delivery_box)
subscribeInstantDeliveryCheckbox = view.findViewById(R.id.add_dialog_subscribe_instant_delivery_checkbox)
subscribeInstantDeliveryDescription = view.findViewById(R.id.add_dialog_subscribe_instant_delivery_description)
subscribeUseAnotherServerCheckbox = view.findViewById(R.id.add_dialog_subscribe_use_another_server_checkbox)
subscribeUseAnotherServerDescription = view.findViewById(R.id.add_dialog_subscribe_use_another_server_description)
subscribeForegroundDescription = view.findViewById(R.id.add_dialog_subscribe_foreground_description)
subscribeProgress = view.findViewById(R.id.add_dialog_subscribe_progress)
subscribeErrorText = view.findViewById(R.id.add_dialog_subscribe_error_text)
subscribeErrorText.visibility = View.GONE
subscribeErrorTextImage = view.findViewById(R.id.add_dialog_subscribe_error_text_image)
subscribeErrorTextImage.visibility = View.GONE
// Fields for "login page"
loginUsernameText = view.findViewById(R.id.add_dialog_login_username)
loginPasswordText = view.findViewById(R.id.add_dialog_login_password)
loginProgress = view.findViewById(R.id.add_dialog_login_progress)
loginErrorText = view.findViewById(R.id.add_dialog_login_error_text)
loginErrorTextImage = view.findViewById(R.id.add_dialog_login_error_text_image)
// Set foreground description text
subscribeForegroundDescription.text = getString(R.string.add_dialog_foreground_description, shortUrl(appBaseUrl))
// Hide instant delivery UI (no Firebase)
subscribeInstantDeliveryBox.visibility = View.GONE
// Add baseUrl auto-complete behavior
lifecycleScope.launch(Dispatchers.IO) {
val baseUrlsRaw = repository.getSubscriptions()
.groupBy { it.baseUrl }
.map { it.key }
.filterNot { it == appBaseUrl }
val baseUrls = if (defaultBaseUrl != null) {
(baseUrlsRaw.filterNot { it == defaultBaseUrl } + appBaseUrl).sorted()
} else {
baseUrlsRaw.sorted()
}
val activity = activity ?: return@launch // We may have pressed "Cancel"
activity.runOnUiThread {
initBaseUrlDropdown(baseUrls, subscribeBaseUrlText, subscribeBaseUrlLayout)
}
}
// Subscribe view validation
val subscribeTextWatcher = AfterChangedTextWatcher {
validateInputSubscribeView()
}
subscribeTopicText.addTextChangedListener(subscribeTextWatcher)
subscribeBaseUrlText.addTextChangedListener(subscribeTextWatcher)
subscribeInstantDeliveryCheckbox.setOnCheckedChangeListener { _, _ ->
validateInputSubscribeView()
}
subscribeUseAnotherServerCheckbox.setOnCheckedChangeListener { _, _ ->
validateInputSubscribeView()
}
// Username/password validation on type
val loginTextWatcher = AfterChangedTextWatcher {
validateInputLoginView()
}
loginUsernameText.addTextChangedListener(loginTextWatcher)
loginPasswordText.addTextChangedListener(loginTextWatcher)
// Build dialog
val dialog = Dialog(requireContext(), R.style.Theme_App_FullScreenDialog)
dialog.setContentView(view)
// Initial validation
validateInputSubscribeView()
return dialog
}
override fun onStart() {
super.onStart()
dialog?.window?.apply {
setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
}
}
override fun onResume() {
super.onResume()
// Show keyboard after the dialog is fully visible
subscribeTopicText.postDelayed({
subscribeTopicText.requestFocus()
val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.showSoftInput(subscribeTopicText, InputMethodManager.SHOW_IMPLICIT)
}, 200)
}
private fun onActionButtonClick() {
val topic = subscribeTopicText.text.toString()
val baseUrl = getBaseUrl()
if (subscribeView.isVisible) {
checkReadAndMaybeShowLogin(baseUrl, topic)
} else if (loginView.isVisible) {
loginAndMaybeDismiss(baseUrl, topic)
}
}
private fun checkReadAndMaybeShowLogin(baseUrl: String, topic: String) {
subscribeProgress.visibility = View.VISIBLE
subscribeErrorText.visibility = View.GONE
subscribeErrorTextImage.visibility = View.GONE
enableSubscribeView(false)
lifecycleScope.launch(Dispatchers.IO) {
try {
val authorized = api.checkAuth(baseUrl, topic)
if (authorized) {
Log.d(TAG, "Access granted to topic ${topicUrl(baseUrl, topic)}")
dismissDialog()
} else {
Log.w(TAG, "Access not allowed to topic ${topicUrl(baseUrl, topic)}, showing login dialog")
val activity = activity ?: return@launch // We may have pressed "Cancel"
activity.runOnUiThread {
showLoginView(activity)
}
}
} catch (e: Exception) {
Log.w(TAG, "Connection to topic failed: ${e.message}", e)
// If this is an SSL certificate error, show the trust cert dialog
// Never show the dialog for the app base URL
if (isSSLException(e) && baseUrl != appBaseUrl) {
Log.d(TAG, "SSL certificate error detected, attempting to fetch certificate for user review")
handleSSLException(baseUrl)
} else {
showErrorAndReenableSubscribeView(e.message)
}
}
}
}
private fun isSSLException(e: Exception): Boolean {
var cause: Throwable? = e
while (cause != null) {
if (cause is SSLHandshakeException || cause is SSLPeerUnverifiedException || cause is CertificateException) {
return true
}
cause = cause.cause
}
return false
}
private fun handleSSLException(baseUrl: String) {
// Try to fetch the server's certificate
val activity = activity ?: return
val certUtil = CertUtil.getInstance(requireContext())
val certificate = certUtil.fetchServerCertificate(baseUrl)
activity.runOnUiThread {
if (certificate != null) {
showCertificateTrustDialog(baseUrl, certificate)
} else {
// Could not fetch certificate, show generic SSL error
showErrorAndReenableSubscribeView(getString(R.string.add_dialog_error_ssl_untrusted))
}
}
}
private fun showCertificateTrustDialog(baseUrl: String, certificate: X509Certificate) {
subscribeProgress.visibility = View.GONE
enableSubscribeView(true)
showErrorAndReenableSubscribeView(getString(R.string.add_dialog_error_ssl_untrusted))
}
private fun showErrorAndReenableSubscribeView(message: String?) {
val activity = activity ?: return // We may have pressed "Cancel"
activity.runOnUiThread {
subscribeProgress.visibility = View.GONE
subscribeErrorText.visibility = View.VISIBLE
subscribeErrorText.text = message
subscribeErrorTextImage.visibility = View.VISIBLE
enableSubscribeView(true)
}
}
private fun loginAndMaybeDismiss(baseUrl: String, topic: String) {
loginProgress.visibility = View.VISIBLE
loginErrorText.visibility = View.GONE
loginErrorTextImage.visibility = View.GONE
enableLoginView(false)
val username = loginUsernameText.text.toString()
val password = loginPasswordText.text.toString()
lifecycleScope.launch(Dispatchers.IO) {
Log.d(TAG, "Checking read access for user $username to topic ${topicUrl(baseUrl, topic)}")
try {
val authorized = api.checkAuth(baseUrl, topic)
if (authorized) {
Log.d(TAG, "Access granted for user $username to topic ${topicUrl(baseUrl, topic)}")
dismissDialog()
} else {
Log.w(TAG, "Access not allowed for user $username to topic ${topicUrl(baseUrl, topic)}")
showErrorAndReenableLoginView(getString(R.string.add_dialog_login_error_not_authorized, username))
}
} catch (e: Exception) {
Log.w(TAG, "Connection to topic failed during login: ${e.message}", e)
showErrorAndReenableLoginView(e.message)
}
}
}
private fun showErrorAndReenableLoginView(message: String?) {
val activity = activity ?: return // We may have pressed "Cancel"
activity.runOnUiThread {
loginProgress.visibility = View.GONE
loginErrorText.visibility = View.VISIBLE
loginErrorText.text = message
loginErrorTextImage.visibility = View.VISIBLE
enableLoginView(true)
}
}
private fun validateInputSubscribeView() {
if (!this::actionMenuItem.isInitialized) return // As per crash seen in Google Play
// Show/hide server selection UI
if (subscribeUseAnotherServerCheckbox.isChecked) {
subscribeUseAnotherServerDescription.visibility = View.VISIBLE
subscribeBaseUrlLayout.visibility = View.VISIBLE
} else {
subscribeUseAnotherServerDescription.visibility = View.GONE
subscribeBaseUrlLayout.visibility = View.GONE
}
// Enable/disable "Subscribe" button
lifecycleScope.launch(Dispatchers.IO) {
val baseUrl = getBaseUrl()
val topic = subscribeTopicText.text.toString()
val subscription = repository.getSubscription(baseUrl, topic)
activity?.let {
it.runOnUiThread {
if (subscription != null || DISALLOWED_TOPICS.contains(topic)) {
actionMenuItem.isEnabled = false
} else if (subscribeUseAnotherServerCheckbox.isChecked) {
actionMenuItem.isEnabled = validTopic(topic) && validUrl(baseUrl)
} else {
actionMenuItem.isEnabled = validTopic(topic)
}
}
}
}
}
private fun validateInputLoginView() {
if (!this::actionMenuItem.isInitialized || !this::loginUsernameText.isInitialized || !this::loginPasswordText.isInitialized) {
return // As per crash seen in Google Play
}
if (loginUsernameText.isGone) {
actionMenuItem.isEnabled = true
} else {
actionMenuItem.isEnabled = (loginUsernameText.text?.isNotEmpty() ?: false)
&& (loginPasswordText.text?.isNotEmpty() ?: false)
}
}
private fun dismissDialog() {
Log.d(TAG, "Closing dialog and calling onSubscribe handler")
val activity = activity?: return // We may have pressed "Cancel"
activity.runOnUiThread {
val baseUrl = getBaseUrl()
val topic = subscribeTopicText.text.toString()
val instant = true // Always use foreground service (no Firebase)
subscribeListener.onSubscribe(topic, baseUrl, instant)
dialog?.dismiss()
}
}
private fun getBaseUrl(): String {
return if (subscribeUseAnotherServerCheckbox.isChecked) {
subscribeBaseUrlText.text.toString()
} else {
return defaultBaseUrl ?: appBaseUrl
}
}
private fun showSubscribeView() {
resetSubscribeView()
toolbar.setTitle(R.string.add_dialog_title)
actionMenuItem.setTitle(R.string.add_dialog_button_subscribe)
toolbar.setNavigationOnClickListener {
dismiss()
}
loginView.visibility = View.GONE
subscribeView.visibility = View.VISIBLE
if (subscribeTopicText.requestFocus()) {
val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.showSoftInput(subscribeTopicText, InputMethodManager.SHOW_IMPLICIT)
}
}
private fun showLoginView(activity: Activity) {
resetLoginView()
loginProgress.visibility = View.INVISIBLE
toolbar.setTitle(R.string.add_dialog_login_title)
actionMenuItem.setTitle(R.string.add_dialog_button_login)
toolbar.setNavigationOnClickListener {
showSubscribeView()
}
subscribeView.visibility = View.GONE
loginView.visibility = View.VISIBLE
if (loginUsernameText.requestFocus()) {
val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.showSoftInput(loginUsernameText, InputMethodManager.SHOW_IMPLICIT)
}
}
private fun enableSubscribeView(enable: Boolean) {
subscribeTopicText.isEnabled = enable
subscribeBaseUrlText.isEnabled = enable
subscribeInstantDeliveryCheckbox.isEnabled = enable
subscribeUseAnotherServerCheckbox.isEnabled = enable
actionMenuItem.isEnabled = enable
}
private fun resetSubscribeView() {
subscribeProgress.visibility = View.GONE
subscribeErrorText.visibility = View.GONE
subscribeErrorTextImage.visibility = View.GONE
enableSubscribeView(true)
}
private fun enableLoginView(enable: Boolean) {
loginUsernameText.isEnabled = enable
loginPasswordText.isEnabled = enable
actionMenuItem.isEnabled = enable
if (enable && loginUsernameText.requestFocus()) {
val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.showSoftInput(loginUsernameText, InputMethodManager.SHOW_IMPLICIT)
}
}
private fun resetLoginView() {
loginProgress.visibility = View.GONE
loginErrorText.visibility = View.GONE
loginErrorTextImage.visibility = View.GONE
loginUsernameText.visibility = View.VISIBLE
loginUsernameText.text?.clear()
loginPasswordText.visibility = View.VISIBLE
loginPasswordText.text?.clear()
enableLoginView(true)
}
companion object {
const val TAG = "NtfyAddFragment"
private val DISALLOWED_TOPICS = listOf("docs", "static", "file") // If updated, also update in server
}
}

View file

@ -0,0 +1,68 @@
package com.lonecloud.sup.ui
import android.text.Editable
import android.text.TextWatcher
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import com.google.android.material.textfield.TextInputLayout
import com.lonecloud.sup.R
fun initBaseUrlDropdown(baseUrls: List<String>, textView: AutoCompleteTextView, layout: TextInputLayout) {
// Base URL dropdown behavior; Oh my, why is this so complicated?!
val context = layout.context
val toggleEndIcon = {
if (textView.text.isNotEmpty()) {
layout.setEndIconDrawable(R.drawable.ic_cancel_gray_24dp)
layout.endIconContentDescription = context.getString(R.string.add_dialog_base_urls_dropdown_clear)
} else if (baseUrls.isEmpty()) {
layout.setEndIconDrawable(0)
layout.endIconContentDescription = ""
} else {
layout.setEndIconDrawable(R.drawable.ic_drop_down_gray_24dp)
layout.endIconContentDescription = context.getString(R.string.add_dialog_base_urls_dropdown_choose)
}
}
layout.setEndIconOnClickListener {
if (textView.text.isNotEmpty()) {
textView.text.clear()
if (baseUrls.isEmpty()) {
layout.setEndIconDrawable(0)
layout.endIconContentDescription = ""
} else {
layout.setEndIconDrawable(R.drawable.ic_drop_down_gray_24dp)
layout.endIconContentDescription = context.getString(R.string.add_dialog_base_urls_dropdown_choose)
}
} else if (textView.text.isEmpty() && baseUrls.isNotEmpty()) {
layout.setEndIconDrawable(R.drawable.ic_drop_up_gray_24dp)
layout.endIconContentDescription = context.getString(R.string.add_dialog_base_urls_dropdown_choose)
textView.showDropDown()
}
}
textView.setOnDismissListener { toggleEndIcon() }
textView.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
toggleEndIcon()
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
// Nothing
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
// Nothing
}
})
val adapter = ArrayAdapter(textView.context, R.layout.fragment_add_dialog_dropdown_item, baseUrls)
textView.threshold = 1
textView.setAdapter(adapter)
if (baseUrls.count() == 1) {
layout.setEndIconDrawable(R.drawable.ic_cancel_gray_24dp)
layout.endIconContentDescription = context.getString(R.string.add_dialog_base_urls_dropdown_clear)
textView.setText(baseUrls.first())
} else if (baseUrls.count() > 1) {
layout.setEndIconDrawable(R.drawable.ic_drop_down_gray_24dp)
layout.endIconContentDescription = context.getString(R.string.add_dialog_base_urls_dropdown_choose)
} else {
layout.setEndIconDrawable(0)
layout.endIconContentDescription = ""
}
}

View file

@ -0,0 +1,86 @@
package com.lonecloud.sup.ui
import android.content.Context
import android.graphics.Color
import androidx.core.content.ContextCompat
import com.google.android.material.color.MaterialColors
import com.lonecloud.sup.R
import com.lonecloud.sup.util.isDarkThemeOn
class Colors {
companion object {
fun primary(context: Context): Int {
return MaterialColors.getColor(context, android.R.attr.colorPrimary, Color.GREEN)
}
fun onPrimary(context: Context): Int {
return MaterialColors.getColor(context, com.google.android.material.R.attr.colorOnPrimary, Color.GREEN)
}
fun notificationIcon(context: Context): Int {
return MaterialColors.getColor(context, android.R.attr.colorPrimary, Color.GREEN)
}
fun linkColor(context: Context): Int {
return MaterialColors.getColor(context, android.R.attr.colorPrimary, Color.GREEN)
}
fun itemSelectedBackground(context: Context): Int {
return ContextCompat.getColor(context, R.color.md_theme_surfaceContainerHigh)
}
fun cardBackgroundColor(context: Context): Int {
return if (isDarkThemeOn(context)) {
MaterialColors.getColor(context, com.google.android.material.R.attr.colorSurfaceContainer, Color.GRAY)
} else {
MaterialColors.getColor(context, com.google.android.material.R.attr.colorSurface, Color.WHITE)
}
}
fun cardSelectedBackgroundColor(context: Context): Int {
return if (isDarkThemeOn(context)) {
MaterialColors.getColor(context, com.google.android.material.R.attr.colorSurfaceContainerHigh, Color.GRAY)
} else {
MaterialColors.getColor(context, com.google.android.material.R.attr.colorSurfaceContainerHighest, Color.GRAY)
}
}
fun statusBarNormal(context: Context, dynamicColors: Boolean, darkMode: Boolean): Int {
val default = context.resources.getColor(R.color.action_bar, null)
return if (dynamicColors) {
// Use colorSurface for both light and dark mode when dynamic colors are enabled
MaterialColors.getColor(context, com.google.android.material.R.attr.colorSurface, default)
} else {
default
}
}
fun shouldUseLightStatusBar(dynamicColors: Boolean, darkMode: Boolean): Boolean {
// Use light status bar (dark icons) when dynamic colors are enabled in light mode
return dynamicColors && !darkMode
}
fun toolbarTextColor(context: Context, dynamicColors: Boolean, darkMode: Boolean): Int {
return if (dynamicColors) {
// Use colorOnSurface (dark on light, light on dark) when dynamic colors are enabled
MaterialColors.getColor(context, com.google.android.material.R.attr.colorOnSurface, Color.BLACK)
} else {
if (darkMode) {
// In dark mode, toolbar is gray (surfaceContainer), so use light text
MaterialColors.getColor(context, com.google.android.material.R.attr.colorOnSurface, Color.WHITE)
} else {
// In light mode, toolbar is teal (primary), so use white text
MaterialColors.getColor(context, com.google.android.material.R.attr.colorOnPrimary, Color.WHITE)
}
}
}
fun dangerText(context: Context): Int {
return ContextCompat.getColor(context, android.R.color.holo_red_dark)
}
fun swipeToRefreshColor(context: Context): Int {
return MaterialColors.getColor(context, android.R.attr.colorPrimary, Color.GREEN)
}
}
}

View file

@ -0,0 +1,877 @@
package com.lonecloud.sup.ui
import android.app.AlertDialog
import android.content.Intent
import android.content.Intent.ACTION_VIEW
import android.net.Uri
import android.os.Bundle
import android.text.Html
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.view.ActionMode
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import com.lonecloud.sup.BuildConfig
import com.lonecloud.sup.R
import com.lonecloud.sup.app.Application
import com.lonecloud.sup.db.Notification
import com.lonecloud.sup.db.Repository
import com.lonecloud.sup.db.Subscription
import com.lonecloud.sup.msg.ApiService
import com.lonecloud.sup.msg.NotificationService
import com.lonecloud.sup.util.Log
import com.lonecloud.sup.util.copyToClipboard
import com.lonecloud.sup.util.dangerButton
import com.lonecloud.sup.util.decodeMessage
import com.lonecloud.sup.util.displayName
import com.lonecloud.sup.util.formatDateShort
import com.lonecloud.sup.util.isDarkThemeOn
import com.lonecloud.sup.util.randomSubscriptionId
import com.lonecloud.sup.util.topicShortUrl
import com.lonecloud.sup.util.topicUrl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.util.Date
import kotlin.random.Random
import androidx.core.view.size
import androidx.core.view.get
import androidx.core.net.toUri
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.textfield.TextInputEditText
import android.widget.ImageButton
class DetailActivity : AppCompatActivity() {
private val viewModel by viewModels<DetailViewModel> {
DetailViewModelFactory((application as Application).repository)
}
private val repository by lazy { (application as Application).repository }
private val api by lazy { ApiService(this) }
private var notifier: NotificationService? = null // Context-dependent
private var appBaseUrl: String? = null // Context-dependent
// Which subscription are we looking at
private var subscriptionId: Long = 0L // Set in onCreate()
private var subscriptionBaseUrl: String = "" // Set in onCreate()
private var subscriptionTopic: String = "" // Set in onCreate()
private var subscriptionDisplayName: String = "" // Set in onCreate() & updated by options menu!
private var subscriptionMutedUntil: Long = 0L // Set in onCreate() & updated by options menu!
// UI elements
private lateinit var adapter: DetailAdapter
private lateinit var mainList: RecyclerView
private lateinit var mainListContainer: SwipeRefreshLayout
private lateinit var menu: Menu
private lateinit var fab: FloatingActionButton
private lateinit var messageBar: View
private lateinit var messageBarText: TextInputEditText
private lateinit var messageBarPublishButton: FloatingActionButton
private lateinit var messageBarExpandButton: ImageButton
// Action mode stuff
private var actionMode: ActionMode? = null
private val actionModeCallback = object : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
actionMode = mode
if (mode != null) {
mode.menuInflater.inflate(R.menu.menu_detail_action_mode, menu)
mode.title = "1" // One item selected
}
return true
}
override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?) = false
override fun onActionItemClicked(mode: ActionMode?, item: MenuItem): Boolean {
return when (item.itemId) {
R.id.detail_action_mode_copy -> {
onMultiCopyClick()
true
}
R.id.detail_action_mode_delete -> {
onMultiDeleteClick()
true
}
else -> false
}
}
override fun onDestroyActionMode(mode: ActionMode?) {
endActionModeAndRedraw()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail)
Log.d(TAG, "Create $this")
// Dependencies that depend on Context
notifier = NotificationService(this)
appBaseUrl = getString(R.string.app_base_url)
val toolbarLayout = findViewById<View>(R.id.app_bar_drawer)
val dynamicColors = repository.getDynamicColorsEnabled()
val darkMode = isDarkThemeOn(this)
val statusBarColor = Colors.statusBarNormal(this, dynamicColors, darkMode)
val toolbarTextColor = Colors.toolbarTextColor(this, dynamicColors, darkMode)
toolbarLayout.setBackgroundColor(statusBarColor)
val toolbar = toolbarLayout.findViewById<com.google.android.material.appbar.MaterialToolbar>(R.id.toolbar)
toolbar.setTitleTextColor(toolbarTextColor)
toolbar.setNavigationIconTint(toolbarTextColor)
toolbar.overflowIcon?.setTint(toolbarTextColor)
setSupportActionBar(toolbar)
// Set system status bar appearance
WindowInsetsControllerCompat(window, window.decorView).isAppearanceLightStatusBars =
Colors.shouldUseLightStatusBar(dynamicColors, darkMode)
// Set detail activity background: use theme background for dynamic colors, static gray for non-dynamic
val detailContentLayout = findViewById<View>(R.id.detail_content_layout)
if (repository.getDynamicColorsEnabled()) {
detailContentLayout.setBackgroundColor(
com.google.android.material.color.MaterialColors.getColor(
this,
android.R.attr.colorBackground,
ContextCompat.getColor(this, R.color.detail_activity_background)
)
)
} else {
detailContentLayout.setBackgroundColor(
ContextCompat.getColor(this, R.color.detail_activity_background)
)
}
// Show 'Back' button
supportActionBar?.setDisplayHomeAsUpEnabled(true)
// Hide links that lead to payments, see https://github.com/binwiederhier/ntfy/issues/1463
val howToLink = findViewById<TextView>(R.id.detail_how_to_link)
howToLink.isVisible = BuildConfig.PAYMENT_LINKS_AVAILABLE
// Handle direct deep links to topic "ntfy://..."
val url = intent?.data
if (intent?.action == ACTION_VIEW && url != null) {
maybeSubscribeAndLoadView(url)
} else {
loadView()
}
}
private fun maybeSubscribeAndLoadView(url: Uri) {
if (url.pathSegments.size != 1) {
Log.w(TAG, "Invalid link $url. Aborting.")
finish()
return
}
val secure = url.getBooleanQueryParameter("secure", true) // Default to https://
val displayName = url.getQueryParameter("display")
val baseUrl = extractBaseUrl(url, secure)
val topic = url.pathSegments.first()
title = topicShortUrl(baseUrl, topic)
// Subscribe to topic if it doesn't already exist
lifecycleScope.launch(Dispatchers.IO) {
var subscription = repository.getSubscription(baseUrl, topic)
if (subscription == null) {
subscription = Subscription(
id = randomSubscriptionId(),
baseUrl = baseUrl,
topic = topic,
mutedUntil = 0,
minPriority = Repository.MIN_PRIORITY_USE_GLOBAL,
autoDelete = Repository.AUTO_DELETE_USE_GLOBAL,
insistent = Repository.INSISTENT_MAX_PRIORITY_USE_GLOBAL,
upAppId = null,
upConnectorToken = null,
displayName = displayName,
totalCount = 0,
newCount = 0,
lastActive = Date().time/1000
)
repository.addSubscription(subscription)
// Fetch cached messages
try {
val notifications = api.poll(subscription.id, subscription.baseUrl, subscription.topic)
notifications.forEach { notification -> repository.addNotification(notification) }
} catch (e: Exception) {
Log.e(TAG, "Unable to fetch notifications: ${e.message}", e)
}
runOnUiThread {
val message = getString(R.string.detail_deep_link_subscribed_toast_message, topicShortUrl(baseUrl, topic))
Toast.makeText(this@DetailActivity, message, Toast.LENGTH_LONG).show()
}
}
// Add extras needed in loadView(); normally these are added in MainActivity
intent.putExtra(MainActivity.EXTRA_SUBSCRIPTION_ID, subscription.id)
intent.putExtra(MainActivity.EXTRA_SUBSCRIPTION_BASE_URL, subscription.baseUrl)
intent.putExtra(MainActivity.EXTRA_SUBSCRIPTION_TOPIC, subscription.topic)
intent.putExtra(MainActivity.EXTRA_SUBSCRIPTION_DISPLAY_NAME, displayName(appBaseUrl, subscription))
intent.putExtra(MainActivity.EXTRA_SUBSCRIPTION_MUTED_UNTIL, subscription.mutedUntil)
runOnUiThread {
loadView()
}
}
}
fun extractBaseUrl(url: Uri, secure: Boolean): String {
if (secure) {
return if (url.port != 443 && url.port != -1) "https://${url.host}:${url.port}" else "https://${url.host}"
}
return if (url.port != 80 && url.port != -1) "http://${url.host}:${url.port}" else "http://${url.host}"
}
private fun loadView() {
// Get extras required for the return to the main activity
subscriptionId = intent.getLongExtra(MainActivity.EXTRA_SUBSCRIPTION_ID, 0)
subscriptionBaseUrl = intent.getStringExtra(MainActivity.EXTRA_SUBSCRIPTION_BASE_URL) ?: return
subscriptionTopic = intent.getStringExtra(MainActivity.EXTRA_SUBSCRIPTION_TOPIC) ?: return
subscriptionDisplayName = intent.getStringExtra(MainActivity.EXTRA_SUBSCRIPTION_DISPLAY_NAME) ?: return
subscriptionMutedUntil = intent.getLongExtra(MainActivity.EXTRA_SUBSCRIPTION_MUTED_UNTIL, 0L)
// Set title
val subscriptionBaseUrl = intent.getStringExtra(MainActivity.EXTRA_SUBSCRIPTION_BASE_URL) ?: return
val topicUrl = topicShortUrl(subscriptionBaseUrl, subscriptionTopic)
title = subscriptionDisplayName
// Set "how to instructions"
val howToExample: TextView = findViewById(R.id.detail_how_to_example)
howToExample.linksClickable = true
val howToText = getString(R.string.detail_how_to_example, topicUrl)
howToExample.text = Html.fromHtml(howToText, Html.FROM_HTML_MODE_LEGACY)
// Swipe to refresh
mainListContainer = findViewById(R.id.detail_notification_list_container)
mainListContainer.setOnRefreshListener { refresh() }
mainListContainer.setColorSchemeColors(Colors.swipeToRefreshColor(this))
// Update main list based on viewModel (& its datasource/livedata)
val noEntriesText: View = findViewById(R.id.detail_no_notifications)
val onNotificationClick = { n: Notification -> onNotificationClick(n) }
val onNotificationLongClick = { n: Notification -> onNotificationLongClick(n) }
adapter = DetailAdapter(this, lifecycleScope, repository, onNotificationClick, onNotificationLongClick)
mainList = findViewById(R.id.detail_notification_list)
mainList.adapter = adapter
// Apply window insets to ensure content is not covered by navigation bar
mainList.clipToPadding = false
ViewCompat.setOnApplyWindowInsetsListener(mainList) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.updatePadding(bottom = systemBars.bottom)
insets
}
viewModel.list(subscriptionId).observe(this) {
it?.let {
// Show list view
adapter.submitList(it as MutableList<Notification>)
if (it.isEmpty()) {
mainListContainer.visibility = View.GONE
noEntriesText.visibility = View.VISIBLE
} else {
mainListContainer.visibility = View.VISIBLE
noEntriesText.visibility = View.GONE
}
// Cancel notifications that still have popups
maybeCancelNotificationPopups(it)
}
}
// Swipe to remove
val itemTouchCallback = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, swipeDir: Int) {
val notification = adapter.get(viewHolder.absoluteAdapterPosition)
lifecycleScope.launch(Dispatchers.IO) {
repository.markAsDeleted(notification.id)
}
val snackbar = Snackbar.make(mainList, R.string.detail_item_snack_deleted, Snackbar.LENGTH_SHORT)
snackbar.setAction(R.string.detail_item_snack_undo) {
lifecycleScope.launch(Dispatchers.IO) {
repository.undeleteNotification(notification.id)
}
}
snackbar.show()
}
}
val itemTouchHelper = ItemTouchHelper(itemTouchCallback)
itemTouchHelper.attachToRecyclerView(mainList)
// Scroll up when new notification is added
adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
if (positionStart == 0) {
Log.d(TAG, "$itemCount item(s) inserted at 0, scrolling to the top")
mainList.scrollToPosition(positionStart)
}
}
})
// React to changes in fast delivery setting
repository.getSubscriptionIdsWithInstantStatusLiveData().observe(this) {
// Signal pushes to us, no service to refresh
}
// Observe connection details and update menu item visibility
repository.getConnectionDetailsLiveData().observe(this) { details ->
showHideConnectionErrorMenuItem(details)
}
// Mark this subscription as "open" so we don't receive notifications for it
repository.detailViewSubscriptionId.set(subscriptionId)
// Stop insistent playback (if running, otherwise it'll throw)
try {
repository.mediaPlayer.stop()
} catch (_: Exception) {
// Ignore errors
}
// Setup FAB and message bar
setupPublishUI()
}
private fun setupPublishUI() {
fab = findViewById(R.id.detail_fab)
messageBar = findViewById(R.id.detail_message_bar)
messageBarText = messageBar.findViewById(R.id.message_bar_text)
messageBarPublishButton = messageBar.findViewById(R.id.message_bar_publish_button)
messageBarExpandButton = messageBar.findViewById(R.id.message_bar_expand_button)
// Message bar enabled: Show message bar, hide FAB
if (repository.getMessageBarEnabled()) {
fab.visibility = View.GONE
messageBar.visibility = View.VISIBLE
// Send button click
messageBarPublishButton.setOnClickListener {
publishMessage(messageBarText.text.toString()) // Allow publishing empty messages
}
// Expand button click opens the full dialog
messageBarExpandButton.setOnClickListener {
openPublishDialog(messageBarText.text.toString())
}
// Handle window insets for navigation bar and keyboard
val contentLayout = findViewById<View>(R.id.detail_content_layout)
ViewCompat.setOnApplyWindowInsetsListener(contentLayout) { view, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
val ime = insets.getInsets(WindowInsetsCompat.Type.ime())
// Use the larger of navigation bar or keyboard height
val bottomPadding = maxOf(systemBars.bottom, ime.bottom)
view.setPadding(view.paddingLeft, view.paddingTop, view.paddingRight, bottomPadding)
insets
}
} else {
// Show FAB, hide message bar
fab.visibility = View.VISIBLE
messageBar.visibility = View.GONE
fab.setOnClickListener {
openPublishDialog("")
}
// Add bottom padding to FAB to account for navigation bar
ViewCompat.setOnApplyWindowInsetsListener(fab) { view, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
val layoutParams = view.layoutParams as androidx.coordinatorlayout.widget.CoordinatorLayout.LayoutParams
layoutParams.bottomMargin = systemBars.bottom + resources.getDimensionPixelSize(R.dimen.fab_margin)
view.layoutParams = layoutParams
insets
}
}
}
private fun openPublishDialog(initialMessage: String) {
// Publishing dialog removed - feature not implemented
Log.d(TAG, "Publishing dialog not available")
}
private fun publishMessage(message: String) {
// Disable send button while publishing
messageBarPublishButton.isEnabled = false
lifecycleScope.launch(Dispatchers.IO) {
try {
api.publish(
baseUrl = subscriptionBaseUrl,
topic = subscriptionTopic,
message = message,
title = "",
priority = 3, // Default priority
tags = emptyList(),
delay = ""
)
runOnUiThread {
messageBarText.text?.clear()
messageBarPublishButton.isEnabled = true
}
} catch (e: Exception) {
Log.w(TAG, "Failed to publish message", e)
runOnUiThread {
messageBarPublishButton.isEnabled = true
val errorMessage = when (e) {
is ApiService.UnauthorizedException -> {
getString(R.string.detail_test_message_error_unauthorized_anon)
}
is ApiService.EntityTooLargeException -> {
getString(R.string.detail_test_message_error_too_large)
}
is ApiService.ApiException -> {
getString(R.string.publish_dialog_error_server, e.error, e.code)
}
else -> {
getString(R.string.publish_dialog_error_sending, e.message)
}
}
Toast.makeText(this@DetailActivity, errorMessage, Toast.LENGTH_LONG).show()
}
}
}
}
override fun onResume() {
super.onResume()
// Mark as "open" so we don't send notifications while this is open
repository.detailViewSubscriptionId.set(subscriptionId)
// Update buttons (this is for when we return from the preferences screen)
lifecycleScope.launch(Dispatchers.IO) {
val subscription = repository.getSubscription(subscriptionId) ?: return@launch
subscriptionMutedUntil = subscription.mutedUntil
subscriptionDisplayName = displayName(appBaseUrl, subscription)
showHideMutedUntilMenuItems(subscriptionMutedUntil)
showHideCopyMenuItems(subscription.baseUrl)
showHideConnectionErrorMenuItem(repository.getConnectionDetails())
updateTitle(subscriptionDisplayName)
}
}
override fun onPause() {
super.onPause()
Log.d(TAG, "onPause hook: Removing 'notificationId' from all notifications for $subscriptionId")
GlobalScope.launch(Dispatchers.IO) {
// Note: This is here and not in onDestroy/onStop, because we want to clear notifications as early
// as possible, so that we don't see the "new" bubble in the main list anymore.
repository.clearAllNotificationIds(subscriptionId)
}
Log.d(TAG, "onPause hook: Marking subscription $subscriptionId as 'not open'")
repository.detailViewSubscriptionId.set(0) // Mark as closed
}
private fun maybeCancelNotificationPopups(notifications: List<Notification>) {
val notificationsWithPopups = notifications.filter { notification -> notification.notificationId != 0 }
if (notificationsWithPopups.isNotEmpty()) {
lifecycleScope.launch(Dispatchers.IO) {
notificationsWithPopups.forEach { notification ->
notifier?.cancel(notification.notificationId)
// Do NOT remove the notificationId here, we need that for the UI indicators; we'll remove it in onPause()
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_detail_action_bar, menu)
this.menu = menu
// Tint menu icons based on theme
val toolbarTextColor = Colors.toolbarTextColor(this, repository.getDynamicColorsEnabled(), isDarkThemeOn(this))
for (i in 0 until menu.size) {
menu[i].icon?.setTint(toolbarTextColor)
}
// Show and hide buttons
showHideMutedUntilMenuItems(subscriptionMutedUntil)
showHideCopyMenuItems(subscriptionBaseUrl)
showHideConnectionErrorMenuItem(repository.getConnectionDetails())
// Regularly check if "notification muted" time has passed
// NOTE: This is done here, because then we know that we've initialized the menu items.
startNotificationMutedChecker()
return true
}
private fun startNotificationMutedChecker() {
// FIXME This is awful and has to go.
lifecycleScope.launch(Dispatchers.IO) {
delay(1000) // Just to be sure we've initialized all the things, we wait a bit ...
while (isActive) {
Log.d(TAG, "Checking 'muted until' timestamp for subscription $subscriptionId")
val subscription = repository.getSubscription(subscriptionId) ?: return@launch
val mutedUntilExpired = subscription.mutedUntil > 1L && System.currentTimeMillis()/1000 > subscription.mutedUntil
if (mutedUntilExpired) {
val newSubscription = subscription.copy(mutedUntil = 0L)
repository.updateSubscription(newSubscription)
showHideMutedUntilMenuItems(0L)
}
delay(60_000)
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.detail_menu_test -> {
onTestClick()
true
}
R.id.detail_menu_notifications_enabled -> {
onMutedUntilClick(enable = false)
true
}
R.id.detail_menu_notifications_disabled_until -> {
onMutedUntilClick(enable = true)
true
}
R.id.detail_menu_notifications_disabled_forever -> {
onMutedUntilClick(enable = true)
true
}
R.id.detail_menu_connection_error -> {
onConnectionErrorClick()
true
}
R.id.detail_menu_copy_url -> {
onCopyUrlClick()
true
}
R.id.detail_menu_clear -> {
onClearClick()
true
}
R.id.detail_menu_settings -> {
onSettingsClick()
true
}
R.id.detail_menu_unsubscribe -> {
onDeleteClick()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun onTestClick() {
Log.d(TAG, "Sending test notification to ${topicShortUrl(subscriptionBaseUrl, subscriptionTopic)}")
lifecycleScope.launch(Dispatchers.IO) {
try {
val possibleTags = listOf(
"warning", "skull", "success", "triangular_flag_on_post", "de", "dog", "rotating_light", "cat", "bike", // Emojis
"backup", "rsync", "de-server1", "this-is-a-tag"
)
val priority = Random.nextInt(1, 6)
val tags = possibleTags.shuffled().take(Random.nextInt(0, 4))
val title = if (Random.nextBoolean()) getString(R.string.detail_test_title) else ""
val message = getString(R.string.detail_test_message, priority)
api.publish(subscriptionBaseUrl, subscriptionTopic, message, title, priority, tags, delay = "")
} catch (e: Exception) {
runOnUiThread {
val message = if (e is ApiService.UnauthorizedException) {
getString(R.string.detail_test_message_error_unauthorized_anon)
} else {
getString(R.string.detail_test_message_error, e.message)
}
Toast
.makeText(this@DetailActivity, message, Toast.LENGTH_LONG)
.show()
}
}
}
}
private fun onMutedUntilClick(enable: Boolean) {
if (!enable) {
Log.d(TAG, "Notification settings dialog not available")
} else {
Log.d(TAG, "Re-enabling notifications ${topicShortUrl(subscriptionBaseUrl, subscriptionTopic)}")
onNotificationMutedUntilChanged(Repository.MUTED_UNTIL_SHOW_ALL)
}
}
private fun onConnectionErrorClick() {
Log.d(TAG, "Connection error dialog not available")
}
fun onNotificationMutedUntilChanged(mutedUntilTimestamp: Long) {
lifecycleScope.launch(Dispatchers.IO) {
Log.d(TAG, "Setting subscription 'muted until' to $mutedUntilTimestamp")
val subscription = repository.getSubscription(subscriptionId)
val newSubscription = subscription?.copy(mutedUntil = mutedUntilTimestamp)
newSubscription?.let { repository.updateSubscription(newSubscription) }
subscriptionMutedUntil = mutedUntilTimestamp
showHideMutedUntilMenuItems(mutedUntilTimestamp)
runOnUiThread {
when (mutedUntilTimestamp) {
0L -> Toast.makeText(this@DetailActivity, getString(R.string.notification_dialog_enabled_toast_message), Toast.LENGTH_LONG).show()
1L -> Toast.makeText(this@DetailActivity, getString(R.string.notification_dialog_muted_forever_toast_message), Toast.LENGTH_LONG).show()
else -> {
val formattedDate = formatDateShort(mutedUntilTimestamp)
Toast.makeText(this@DetailActivity, getString(R.string.notification_dialog_muted_until_toast_message, formattedDate), Toast.LENGTH_LONG).show()
}
}
}
}
}
private fun onCopyUrlClick() {
val url = topicUrl(subscriptionBaseUrl, subscriptionTopic)
Log.d(TAG, "Copying topic URL $url to clipboard ")
runOnUiThread {
copyToClipboard(this, "topic address", url)
}
}
private fun refresh() {
Log.d(TAG, "Fetching cached notifications for ${topicShortUrl(subscriptionBaseUrl, subscriptionTopic)}")
lifecycleScope.launch(Dispatchers.IO) {
try {
val subscription = repository.getSubscription(subscriptionId) ?: return@launch
val notifications = api.poll(subscription.id, subscription.baseUrl, subscription.topic, null)
val newNotifications = repository.onlyNewNotifications(subscriptionId, notifications)
val toastMessage = if (newNotifications.isEmpty()) {
getString(R.string.refresh_message_no_results)
} else {
getString(R.string.refresh_message_result, newNotifications.size)
}
newNotifications.forEach { notification -> repository.addNotification(notification) }
runOnUiThread {
Toast.makeText(this@DetailActivity, toastMessage, Toast.LENGTH_LONG).show()
mainListContainer.isRefreshing = false
}
} catch (e: Exception) {
Log.e(TAG, "Error fetching notifications for ${topicShortUrl(subscriptionBaseUrl, subscriptionTopic)}: ${e.stackTrace}", e)
runOnUiThread {
Toast
.makeText(this@DetailActivity, getString(R.string.refresh_message_error_one, e.message), Toast.LENGTH_LONG)
.show()
mainListContainer.isRefreshing = false
}
}
}
}
private fun showHideMutedUntilMenuItems(mutedUntilTimestamp: Long) {
if (!this::menu.isInitialized) {
return
}
subscriptionMutedUntil = mutedUntilTimestamp
runOnUiThread {
val notificationsEnabledItem = menu.findItem(R.id.detail_menu_notifications_enabled)
val notificationsDisabledUntilItem = menu.findItem(R.id.detail_menu_notifications_disabled_until)
val notificationsDisabledForeverItem = menu.findItem(R.id.detail_menu_notifications_disabled_forever)
notificationsEnabledItem?.isVisible = subscriptionMutedUntil == 0L
notificationsDisabledForeverItem?.isVisible = subscriptionMutedUntil == 1L
notificationsDisabledUntilItem?.isVisible = subscriptionMutedUntil > 1L
if (subscriptionMutedUntil > 1L) {
val formattedDate = formatDateShort(subscriptionMutedUntil)
notificationsDisabledUntilItem?.title = getString(R.string.detail_menu_notifications_disabled_until, formattedDate)
}
}
}
private fun showHideCopyMenuItems(subscriptionBaseUrl: String) {
if (!this::menu.isInitialized) {
return
}
runOnUiThread {
// Hide links that lead to payments, see https://github.com/binwiederhier/ntfy/issues/1463
val copyUrlItem = menu.findItem(R.id.detail_menu_copy_url)
copyUrlItem?.isVisible = appBaseUrl != subscriptionBaseUrl || BuildConfig.PAYMENT_LINKS_AVAILABLE
}
}
private fun showHideConnectionErrorMenuItem(details: Map<String, com.lonecloud.sup.db.ConnectionDetails>) {
if (!this::menu.isInitialized) {
return
}
runOnUiThread {
val connectionErrorItem = menu.findItem(R.id.detail_menu_connection_error)
// Only show if there's an error for this subscription's base URL
val hasError = details[subscriptionBaseUrl]?.hasError() == true
connectionErrorItem?.isVisible = hasError
}
}
private fun updateTitle(subscriptionDisplayName: String) {
runOnUiThread {
title = subscriptionDisplayName
}
}
private fun onClearClick() {
Log.d(TAG, "Clearing all notifications for ${topicShortUrl(subscriptionBaseUrl, subscriptionTopic)}")
val dialog = MaterialAlertDialogBuilder(this)
.setMessage(R.string.detail_clear_dialog_message)
.setPositiveButton(R.string.detail_clear_dialog_permanently_delete) { _, _ ->
lifecycleScope.launch(Dispatchers.IO) {
repository.markAllAsDeleted(subscriptionId)
}
}
.setNegativeButton(R.string.detail_clear_dialog_cancel) { _, _ -> /* Do nothing */ }
.create()
dialog.setOnShowListener {
dialog
.getButton(AlertDialog.BUTTON_POSITIVE)
.dangerButton()
}
dialog.show()
}
private fun onSettingsClick() {
Log.d(TAG, "Settings not available")
}
private fun onDeleteClick() {
Log.d(TAG, "Deleting subscription ${topicShortUrl(subscriptionBaseUrl, subscriptionTopic)}")
val dialog = MaterialAlertDialogBuilder(this)
.setMessage(R.string.detail_delete_dialog_message)
.setPositiveButton(R.string.detail_delete_dialog_permanently_delete) { _, _ ->
Log.d(TAG, "Deleting subscription with subscription ID $subscriptionId (topic: $subscriptionTopic)")
GlobalScope.launch(Dispatchers.IO) {
repository.removeAllNotifications(subscriptionId)
repository.removeSubscription(subscriptionId)
// Signal pushes to us, no Firebase to unsubscribe from
}
finish()
}
.setNegativeButton(R.string.detail_delete_dialog_cancel) { _, _ -> /* Do nothing */ }
.create()
dialog.setOnShowListener {
dialog
.getButton(AlertDialog.BUTTON_POSITIVE)
.dangerButton()
}
dialog.show()
}
private fun onNotificationClick(notification: Notification) {
if (actionMode != null) {
handleActionModeClick(notification)
} else {
runOnUiThread {
copyToClipboard(this, "notification", decodeMessage(notification))
}
}
}
private fun onNotificationLongClick(notification: Notification) {
if (actionMode == null) {
beginActionMode(notification)
}
}
private fun handleActionModeClick(notification: Notification) {
adapter.toggleSelection(notification.id)
if (adapter.selected.size == 0) {
finishActionMode()
} else {
actionMode!!.title = adapter.selected.size.toString()
}
}
private fun onMultiCopyClick() {
Log.d(TAG, "Copying multiple notifications to clipboard")
lifecycleScope.launch(Dispatchers.IO) {
val content = adapter.selected.joinToString("\n\n") { notificationId ->
val notification = repository.getNotification(notificationId)
notification?.let {
decodeMessage(it) + "\n" + Date(it.timestamp * 1000).toString()
}.orEmpty()
}
runOnUiThread {
copyToClipboard(this@DetailActivity, "notifications", content)
finishActionMode()
}
}
}
private fun onMultiDeleteClick() {
Log.d(TAG, "Showing multi-delete dialog for selected items")
val dialog = MaterialAlertDialogBuilder(this)
.setMessage(R.string.detail_action_mode_delete_dialog_message)
.setPositiveButton(R.string.detail_action_mode_delete_dialog_permanently_delete) { _, _ ->
adapter.selected.map { notificationId -> viewModel.markAsDeleted(notificationId) }
finishActionMode()
}
.setNegativeButton(R.string.detail_action_mode_delete_dialog_cancel) { _, _ ->
finishActionMode()
}
.create()
dialog.setOnShowListener {
dialog
.getButton(AlertDialog.BUTTON_POSITIVE)
.dangerButton()
}
dialog.show()
}
private fun beginActionMode(notification: Notification) {
actionMode = startSupportActionMode(actionModeCallback)
adapter.toggleSelection(notification.id)
}
private fun finishActionMode() {
actionMode?.finish()
endActionModeAndRedraw()
}
private fun endActionModeAndRedraw() {
actionMode = null
adapter.selected.clear()
adapter.notifyItemRangeChanged(0, adapter.currentList.size)
}
companion object {
const val TAG = "NtfyDetailActivity"
const val EXTRA_SUBSCRIPTION_ID = "subscriptionId"
const val EXTRA_SUBSCRIPTION_BASE_URL = "baseUrl"
const val EXTRA_SUBSCRIPTION_TOPIC = "topic"
const val EXTRA_SUBSCRIPTION_DISPLAY_NAME = "displayName"
}
}

View file

@ -0,0 +1,245 @@
package com.lonecloud.sup.ui
import android.Manifest
import android.app.Activity
import android.content.*
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.util.Linkify
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.cardview.widget.CardView
import androidx.constraintlayout.helper.widget.Flow
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.view.allViews
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.android.material.button.MaterialButton
import com.stfalcon.imageviewer.StfalconImageViewer
import com.lonecloud.sup.R
import com.lonecloud.sup.db.*
import com.lonecloud.sup.msg.NotificationService
import com.lonecloud.sup.util.*
import io.noties.markwon.Markwon
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import me.saket.bettermovementmethod.BetterLinkMovementMethod
import androidx.core.net.toUri
class DetailAdapter(private val activity: Activity, private val lifecycleScope: CoroutineScope, private val repository: Repository, private val onClick: (Notification) -> Unit, private val onLongClick: (Notification) -> Unit) :
ListAdapter<Notification, DetailAdapter.DetailViewHolder>(TopicDiffCallback) {
private val markwon: Markwon = MarkwonFactory.createForMessage(activity)
val selected = mutableSetOf<String>() // Notification IDs
/* Creates and inflates view and return TopicViewHolder. */
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DetailViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.fragment_detail_item, parent, false)
return DetailViewHolder(activity, lifecycleScope, repository, markwon, view, selected, onClick, onLongClick)
}
/* Gets current topic and uses it to bind view. */
override fun onBindViewHolder(holder: DetailViewHolder, position: Int) {
holder.bind(getItem(position))
}
fun get(position: Int): Notification {
return getItem(position)
}
fun toggleSelection(notificationId: String) {
if (selected.contains(notificationId)) {
selected.remove(notificationId)
} else {
selected.add(notificationId)
}
if (selected.isNotEmpty()) {
val listIds = currentList.map { notification -> notification.id }
val notificationPosition = listIds.indexOf(notificationId)
notifyItemChanged(notificationPosition)
}
}
/* ViewHolder for Topic, takes in the inflated view and the onClick behavior. */
class DetailViewHolder(
private val activity: Activity,
private val lifecycleScope: CoroutineScope,
private val repository: Repository,
private val markwon: Markwon,
itemView: View,
private val selected: Set<String>,
val onClick: (Notification) -> Unit,
val onLongClick: (Notification) -> Unit
) :
RecyclerView.ViewHolder(itemView) {
private var notification: Notification? = null
private val layout: View = itemView.findViewById(R.id.detail_item_layout)
private val cardView: CardView = itemView.findViewById(R.id.detail_item_card)
private val priorityImageView: ImageView = itemView.findViewById(R.id.detail_item_priority_image)
private val dateView: TextView = itemView.findViewById(R.id.detail_item_date_text)
private val titleView: TextView = itemView.findViewById(R.id.detail_item_title_text)
private val messageView: TextView = itemView.findViewById(R.id.detail_item_message_text)
private val newDotImageView: View = itemView.findViewById(R.id.detail_item_new_dot)
private val tagsView: TextView = itemView.findViewById(R.id.detail_item_tags_text)
private val menuButton: ImageButton = itemView.findViewById(R.id.detail_item_menu_button)
private val actionsWrapperView: ConstraintLayout = itemView.findViewById(R.id.detail_item_actions_wrapper)
private val actionsFlow: Flow = itemView.findViewById(R.id.detail_item_actions_flow)
fun bind(notification: Notification) {
this.notification = notification
val context = itemView.context
val unmatchedTags = unmatchedTags(splitTags(notification.tags))
val message = formatMessage(notification)
dateView.text = formatDateShort(notification.timestamp)
messageView.autoLinkMask = Linkify.WEB_URLS or Linkify.EMAIL_ADDRESSES or Linkify.PHONE_NUMBERS
messageView.text = message
messageView.movementMethod = BetterLinkMovementMethod.getInstance()
messageView.setOnClickListener {
// Click & Long-click listeners on the text as well, because "autoLink=web" makes them
// clickable, and so we cannot rely on the underlying card to perform the action.
// It's weird because "layout" is the ripple-able, but the card is clickable.
// See https://github.com/binwiederhier/ntfy/issues/226
layout.ripple(lifecycleScope)
onClick(notification)
}
messageView.setOnLongClickListener {
onLongClick(notification); true
}
newDotImageView.visibility = if (notification.notificationId == 0) View.GONE else View.VISIBLE
cardView.setOnClickListener { onClick(notification) }
cardView.setOnLongClickListener { onLongClick(notification); true }
if (notification.title != "") {
titleView.visibility = View.VISIBLE
titleView.text = formatTitle(notification)
} else {
titleView.visibility = View.GONE
}
if (unmatchedTags.isNotEmpty()) {
tagsView.visibility = View.VISIBLE
tagsView.text = context.getString(R.string.detail_item_tags, unmatchedTags.joinToString(", "))
} else {
tagsView.visibility = View.GONE
}
if (selected.contains(notification.id)) {
cardView.setCardBackgroundColor(Colors.cardSelectedBackgroundColor(context))
} else {
cardView.setCardBackgroundColor(Colors.cardBackgroundColor(context))
}
renderPriority(context, notification)
resetCardButtons()
maybeRenderMenu(context, notification)
}
private fun renderPriority(context: Context, notification: Notification) {
when (notification.priority) {
PRIORITY_MIN -> {
priorityImageView.visibility = View.VISIBLE
priorityImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_priority_1_24dp))
}
PRIORITY_LOW -> {
priorityImageView.visibility = View.VISIBLE
priorityImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_priority_2_24dp))
}
PRIORITY_DEFAULT -> {
priorityImageView.visibility = View.GONE
}
PRIORITY_HIGH -> {
priorityImageView.visibility = View.VISIBLE
priorityImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_priority_4_24dp))
}
PRIORITY_MAX -> {
priorityImageView.visibility = View.VISIBLE
priorityImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_priority_5_24dp))
}
}
}
private fun maybeRenderMenu(context: Context, notification: Notification) {
val menuButtonPopupMenu = maybeCreateMenuPopup(context, menuButton, notification) // Heavy lifting not during on-click
if (menuButtonPopupMenu != null) {
menuButton.setOnClickListener { menuButtonPopupMenu.show() }
menuButton.visibility = View.VISIBLE
} else {
menuButton.visibility = View.GONE
}
}
private fun resetCardButtons() {
// clear any previously created dynamic buttons
actionsFlow.allViews.forEach { actionsFlow.removeView(it) }
actionsWrapperView.removeAllViews()
actionsWrapperView.addView(actionsFlow)
}
private fun addButtonToCard(button: View) {
actionsWrapperView.addView(button)
actionsFlow.addView(button)
}
private fun createCardButton(context: Context, label: String, onClick: () -> Boolean): View {
// See https://stackoverflow.com/a/41139179/1440785
val button = LayoutInflater.from(context).inflate(R.layout.button_action, null) as MaterialButton
button.id = View.generateViewId()
button.text = label
button.setOnClickListener { onClick() }
return button
}
private fun maybeCreateMenuPopup(context: Context, anchor: View?, notification: Notification): PopupMenu? {
val popup = PopupMenu(context, anchor)
popup.menuInflater.inflate(R.menu.menu_detail_attachment, popup.menu)
val downloadItem = popup.menu.findItem(R.id.detail_item_menu_download)
val cancelItem = popup.menu.findItem(R.id.detail_item_menu_cancel)
val openItem = popup.menu.findItem(R.id.detail_item_menu_open)
val deleteItem = popup.menu.findItem(R.id.detail_item_menu_delete)
val saveFileItem = popup.menu.findItem(R.id.detail_item_menu_save_file)
val copyUrlItem = popup.menu.findItem(R.id.detail_item_menu_copy_url)
val copyContentsItem = popup.menu.findItem(R.id.detail_item_menu_copy_contents)
copyContentsItem.setOnMenuItemClickListener {
copyToClipboard(context, "notification", decodeMessage(notification)); true
}
openItem.isVisible = false
downloadItem.isVisible = false
deleteItem.isVisible = false
saveFileItem.isVisible = false
copyUrlItem.isVisible = false
cancelItem.isVisible = false
copyContentsItem.isVisible = true
return popup
}
}
object TopicDiffCallback : DiffUtil.ItemCallback<Notification>() {
override fun areItemsTheSame(oldItem: Notification, newItem: Notification): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Notification, newItem: Notification): Boolean {
return oldItem == newItem
}
}
companion object {
const val TAG = "NtfyDetailAdapter"
const val REQUEST_CODE_WRITE_STORAGE_PERMISSION_FOR_DOWNLOAD = 9876
const val IMAGE_PREVIEW_MAX_BYTES = 5 * 1024 * 1024 // Too large images crash the app with "Canvas: trying to draw too large(233280000bytes) bitmap."
}
}

View file

@ -0,0 +1,31 @@
package com.lonecloud.sup.ui
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.lonecloud.sup.db.Notification
import com.lonecloud.sup.db.Repository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class DetailViewModel(private val repository: Repository) : ViewModel() {
fun list(subscriptionId: Long): LiveData<List<Notification>> {
return repository.getNotificationsLiveData(subscriptionId)
}
fun markAsDeleted(notificationId: String) = viewModelScope.launch(Dispatchers.IO) {
repository.markAsDeleted(notificationId)
}
}
class DetailViewModelFactory(private val repository: Repository) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T =
with(modelClass){
when {
isAssignableFrom(DetailViewModel::class.java) -> DetailViewModel(repository) as T
else -> throw IllegalArgumentException("Unknown viewModel class $modelClass")
}
}
}

View file

@ -0,0 +1,738 @@
package com.lonecloud.sup.ui
import android.Manifest
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.app.AlarmManager
import android.app.AlertDialog
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.provider.Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM
import android.text.method.LinkMovementMethod
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.appcompat.view.ActionMode
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import androidx.core.text.HtmlCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.core.view.updatePadding
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.lonecloud.sup.BuildConfig
import com.lonecloud.sup.R
import com.lonecloud.sup.app.Application
import com.lonecloud.sup.db.Repository
import com.lonecloud.sup.db.Subscription
import com.lonecloud.sup.msg.ApiService
import com.lonecloud.sup.msg.NotificationDispatcher
import com.lonecloud.sup.util.Log
import com.lonecloud.sup.util.dangerButton
import com.lonecloud.sup.util.displayName
import com.lonecloud.sup.util.formatDateShort
import com.lonecloud.sup.util.isDarkThemeOn
import com.lonecloud.sup.util.isIgnoringBatteryOptimizations
import com.lonecloud.sup.util.maybeSplitTopicUrl
import com.lonecloud.sup.util.randomSubscriptionId
import com.lonecloud.sup.util.shortUrl
import com.lonecloud.sup.util.topicShortUrl
import com.lonecloud.sup.work.DeleteWorker
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.isActive
import java.util.Date
import java.util.concurrent.TimeUnit
import kotlin.random.Random
import androidx.core.view.size
import androidx.core.view.get
import androidx.core.net.toUri
class MainActivity : AppCompatActivity(), AddFragment.SubscribeListener {
private val viewModel by viewModels<SubscriptionsViewModel> {
SubscriptionsViewModelFactory((application as Application).repository)
}
private val repository by lazy { (application as Application).repository }
private val api by lazy { ApiService(this) }
// UI elements
private lateinit var menu: Menu
private lateinit var mainList: RecyclerView
private lateinit var mainListContainer: SwipeRefreshLayout
private lateinit var adapter: MainAdapter
private lateinit var fab: FloatingActionButton
// Other stuff
private var workManager: WorkManager? = null // Context-dependent
private var dispatcher: NotificationDispatcher? = null // Context-dependent
private var appBaseUrl: String? = null // Context-dependent
// Action mode stuff
private var actionMode: ActionMode? = null
private val actionModeCallback = object : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
actionMode = mode
if (mode != null) {
mode.menuInflater.inflate(R.menu.menu_main_action_mode, menu)
mode.title = "1" // One item selected
}
return true
}
override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?) = false
override fun onActionItemClicked(mode: ActionMode?, item: MenuItem): Boolean {
return when (item.itemId) {
R.id.main_action_mode_delete -> {
onMultiDeleteClick()
true
}
else -> false
}
}
override fun onDestroyActionMode(mode: ActionMode?) {
endActionModeAndRedraw()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.init(this) // Init logs in all entry points
Log.d(TAG, "Create $this")
// Dependencies that depend on Context
workManager = WorkManager.getInstance(this)
dispatcher = NotificationDispatcher(this, repository)
appBaseUrl = getString(R.string.app_base_url)
// Action bar
val toolbarLayout = findViewById<AppBarLayout>(R.id.app_bar_drawer)
val dynamicColors = repository.getDynamicColorsEnabled()
val darkMode = isDarkThemeOn(this)
val statusBarColor = Colors.statusBarNormal(this, dynamicColors, darkMode)
val toolbarTextColor = Colors.toolbarTextColor(this, dynamicColors, darkMode)
toolbarLayout.setBackgroundColor(statusBarColor)
val toolbar = toolbarLayout.findViewById<com.google.android.material.appbar.MaterialToolbar>(R.id.toolbar)
toolbar.setTitleTextColor(toolbarTextColor)
toolbar.setNavigationIconTint(toolbarTextColor)
toolbar.overflowIcon?.setTint(toolbarTextColor)
setSupportActionBar(toolbar)
title = getString(R.string.main_action_bar_title)
// Set system status bar appearance
WindowInsetsControllerCompat(window, window.decorView).isAppearanceLightStatusBars =
Colors.shouldUseLightStatusBar(dynamicColors, darkMode)
// Floating action button ("+")
fab = findViewById(R.id.fab)
fab.setOnClickListener {
onSubscribeButtonClick()
}
// Add bottom padding to FAB to account for navigation bar
ViewCompat.setOnApplyWindowInsetsListener(fab) { view, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
val layoutParams = view.layoutParams as androidx.constraintlayout.widget.ConstraintLayout.LayoutParams
layoutParams.bottomMargin = systemBars.bottom
view.layoutParams = layoutParams
insets
}
// Swipe to refresh
mainListContainer = findViewById(R.id.main_subscriptions_list_container)
mainListContainer.setOnRefreshListener { refreshAllSubscriptions() }
mainListContainer.setColorSchemeColors(Colors.swipeToRefreshColor(this))
// Update main list based on viewModel (& its datasource/livedata)
val noEntries: View = findViewById(R.id.main_no_subscriptions)
val onSubscriptionClick = { s: Subscription -> onSubscriptionItemClick(s) }
val onSubscriptionLongClick = { s: Subscription -> onSubscriptionItemLongClick(s) }
mainList = findViewById(R.id.main_subscriptions_list)
adapter = MainAdapter(
repository,
onSubscriptionClick,
onSubscriptionLongClick,
ResourcesCompat.getDrawable(resources, R.drawable.ic_circle, theme)!!.apply {
setTint(Colors.primary(this@MainActivity))
},
Colors.onPrimary(this)
)
mainList.adapter = adapter
// Apply window insets to ensure content is not covered by navigation bar
mainList.clipToPadding = false
ViewCompat.setOnApplyWindowInsetsListener(mainList) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.updatePadding(bottom = systemBars.bottom)
insets
}
viewModel.list().observe(this) {
it?.let { subscriptions ->
// Update main list
adapter.submitList(subscriptions as MutableList<Subscription>)
if (it.isEmpty()) {
mainListContainer.visibility = View.GONE
noEntries.visibility = View.VISIBLE
} else {
mainListContainer.visibility = View.VISIBLE
noEntries.visibility = View.GONE
}
// Add scrub terms to log (in case it gets exported)
subscriptions.forEach { s ->
Log.addScrubTerm(shortUrl(s.baseUrl), Log.TermType.Domain)
Log.addScrubTerm(s.topic)
}
// Update battery banner
showHideBatteryBanner(subscriptions)
}
}
// Scrub terms for last topics // FIXME this should be in Log.getFormatted
repository.getLastShareTopics().forEach { topicUrl ->
maybeSplitTopicUrl(topicUrl)?.let {
Log.addScrubTerm(shortUrl(it.first), Log.TermType.Domain)
Log.addScrubTerm(shortUrl(it.second), Log.TermType.Term)
}
}
// React to changes in instant delivery setting
viewModel.listIdsWithInstantStatus().observe(this) {
// Signal pushes to us, no service to refresh
}
// Observe connection details and update menu item visibility
repository.getConnectionDetailsLiveData().observe(this) { details ->
showHideConnectionErrorMenuItem(details)
}
// Battery banner
val batteryBanner = findViewById<View>(R.id.main_banner_battery) // Banner visibility is toggled in onResume()
val dontAskAgainButton = findViewById<Button>(R.id.main_banner_battery_dontaskagain)
val askLaterButton = findViewById<Button>(R.id.main_banner_battery_ask_later)
val fixNowButton = findViewById<Button>(R.id.main_banner_battery_fix_now)
dontAskAgainButton.setOnClickListener {
batteryBanner.visibility = View.GONE
repository.setBatteryOptimizationsRemindTime(Repository.BATTERY_OPTIMIZATIONS_REMIND_TIME_NEVER)
}
askLaterButton.setOnClickListener {
batteryBanner.visibility = View.GONE
repository.setBatteryOptimizationsRemindTime(System.currentTimeMillis() + ONE_DAY_MILLIS)
}
fixNowButton.setOnClickListener {
try {
Log.d(TAG, "package:$packageName".toUri().toString())
startActivity(
Intent(
Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
"package:$packageName".toUri()
)
)
} catch (_: ActivityNotFoundException) {
try {
startActivity(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS))
} catch (_: ActivityNotFoundException) {
startActivity(Intent(Settings.ACTION_SETTINGS))
}
}
// Hide, at least for now
val batteryBanner = findViewById<View>(R.id.main_banner_battery)
batteryBanner.visibility = View.GONE
}
// Hide links that lead to payments, see https://github.com/binwiederhier/ntfy/issues/1463
val howToLink = findViewById<TextView>(R.id.main_how_to_link)
howToLink.isVisible = BuildConfig.PAYMENT_LINKS_AVAILABLE
// Create notification channels right away, so we can configure them immediately after installing the app
dispatcher?.init()
// Signal pushes to us, no Firebase to subscribe to
// Darrkkkk mode
AppCompatDelegate.setDefaultNightMode(repository.getDarkMode())
// Background things
schedulePeriodicServiceRestartWorker()
schedulePeriodicDeleteWorker()
// Permissions
maybeRequestNotificationPermission()
}
private fun maybeRequestNotificationPermission() {
// Android 13 (SDK 33) requires that we ask for permission to post notifications
// https://developer.android.com/develop/ui/views/notifications/notification-permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), 0)
}
}
override fun onResume() {
super.onResume()
showHideNotificationMenuItems()
showHideConnectionErrorMenuItem(repository.getConnectionDetails())
redrawList()
}
override fun onPause() {
super.onPause()
}
private fun showHideBatteryBanner(subscriptions: List<Subscription>) {
val batteryRemindTimeReached = repository.getBatteryOptimizationsRemindTime() < System.currentTimeMillis()
val ignoringOptimizations = isIgnoringBatteryOptimizations(this@MainActivity)
val showBanner = batteryRemindTimeReached && !ignoringOptimizations
val batteryBanner = findViewById<View>(R.id.main_banner_battery)
batteryBanner.visibility = if (showBanner) View.VISIBLE else View.GONE
Log.d(TAG, "Battery: ignoring optimizations = $ignoringOptimizations (we want this to be true); remind time reached = $batteryRemindTimeReached; banner = $showBanner")
}
private fun schedulePeriodicDeleteWorker() {
val workerVersion = repository.getDeleteWorkerVersion()
val workPolicy = if (workerVersion == DeleteWorker.VERSION) {
Log.d(TAG, "Delete worker version matches: choosing KEEP as existing work policy")
ExistingPeriodicWorkPolicy.KEEP
} else {
Log.d(TAG, "Delete worker version DOES NOT MATCH: choosing REPLACE as existing work policy")
repository.setDeleteWorkerVersion(DeleteWorker.VERSION)
ExistingPeriodicWorkPolicy.REPLACE
}
val work = PeriodicWorkRequestBuilder<DeleteWorker>(DELETE_WORKER_INTERVAL_MINUTES, TimeUnit.MINUTES)
.addTag(DeleteWorker.TAG)
.addTag(DeleteWorker.WORK_NAME_PERIODIC_ALL)
.build()
Log.d(TAG, "Delete worker: Scheduling period work every $DELETE_WORKER_INTERVAL_MINUTES minutes")
workManager!!.enqueueUniquePeriodicWork(DeleteWorker.WORK_NAME_PERIODIC_ALL, workPolicy, work)
}
private fun schedulePeriodicServiceRestartWorker() {
// Service restart worker not needed for Signal-based implementation
Log.d(TAG, "ServiceStartWorker: Not scheduling (using Signal push notifications)")
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main_action_bar, menu)
this.menu = menu
// Tint menu icons based on theme
val toolbarTextColor = Colors.toolbarTextColor(this, repository.getDynamicColorsEnabled(), isDarkThemeOn(this))
for (i in 0 until menu.size) {
menu[i].icon?.setTint(toolbarTextColor)
}
showHideNotificationMenuItems()
showHideConnectionErrorMenuItem(repository.getConnectionDetails())
checkSubscriptionsMuted() // This is done here, because then we know that we've initialized the menu
return true
}
private fun checkSubscriptionsMuted(delayMillis: Long = 0L) {
lifecycleScope.launch(Dispatchers.IO) {
delay(delayMillis) // Just to be sure we've initialized all the things, we wait a bit ...
Log.d(TAG, "Checking global and subscription-specific 'muted until' timestamp")
// Check global
val changed = repository.checkGlobalMutedUntil()
if (changed) {
Log.d(TAG, "Global muted until timestamp expired; updating prefs")
showHideNotificationMenuItems()
}
// Check subscriptions
var rerenderList = false
repository.getSubscriptions().forEach { subscription ->
val mutedUntilExpired = subscription.mutedUntil > 1L && System.currentTimeMillis()/1000 > subscription.mutedUntil
if (mutedUntilExpired) {
Log.d(TAG, "Subscription ${subscription.id}: Muted until timestamp expired, updating subscription")
val newSubscription = subscription.copy(mutedUntil = 0L)
repository.updateSubscription(newSubscription)
rerenderList = true
}
}
if (rerenderList) {
mainList.post {
redrawList()
}
}
}
}
private fun showHideNotificationMenuItems() {
if (!this::menu.isInitialized) {
return
}
val mutedUntilSeconds = repository.getGlobalMutedUntil()
runOnUiThread {
// Show/hide menu items based on build config
val rateAppItem = menu.findItem(R.id.main_menu_rate)
val docsItem = menu.findItem(R.id.main_menu_docs)
val reportBugItem = menu.findItem(R.id.main_menu_report_bug)
rateAppItem.isVisible = BuildConfig.RATE_APP_AVAILABLE
docsItem.isVisible = BuildConfig.PAYMENT_LINKS_AVAILABLE // Google Payments Policy, see https://github.com/binwiederhier/ntfy/issues/1463
reportBugItem.isVisible = BuildConfig.PAYMENT_LINKS_AVAILABLE // Google Payments Policy, see https://github.com/binwiederhier/ntfy/issues/1463
// Pause notification icons
val notificationsEnabledItem = menu.findItem(R.id.main_menu_notifications_enabled)
val notificationsDisabledUntilItem = menu.findItem(R.id.main_menu_notifications_disabled_until)
val notificationsDisabledForeverItem = menu.findItem(R.id.main_menu_notifications_disabled_forever)
notificationsEnabledItem?.isVisible = mutedUntilSeconds == 0L
notificationsDisabledForeverItem?.isVisible = mutedUntilSeconds == 1L
notificationsDisabledUntilItem?.isVisible = mutedUntilSeconds > 1L
if (mutedUntilSeconds > 1L) {
val formattedDate = formatDateShort(mutedUntilSeconds)
notificationsDisabledUntilItem?.title = getString(R.string.main_menu_notifications_disabled_until, formattedDate)
}
}
}
private fun showHideConnectionErrorMenuItem(details: Map<String, com.lonecloud.sup.db.ConnectionDetails>) {
if (!this::menu.isInitialized) {
return
}
runOnUiThread {
val connectionErrorItem = menu.findItem(R.id.main_menu_connection_error)
val hasErrors = details.values.any { it.hasError() }
connectionErrorItem?.isVisible = hasErrors
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.main_menu_notifications_enabled -> {
onNotificationSettingsClick(enable = false)
true
}
R.id.main_menu_notifications_disabled_forever -> {
onNotificationSettingsClick(enable = true)
true
}
R.id.main_menu_notifications_disabled_until -> {
onNotificationSettingsClick(enable = true)
true
}
R.id.main_menu_connection_error -> {
onConnectionErrorClick()
true
}
R.id.main_menu_settings -> {
// Settings activity not implemented
Log.d(TAG, "Settings not available")
true
}
R.id.main_menu_report_bug -> {
startActivity(
Intent(Intent.ACTION_VIEW, getString(R.string.main_menu_report_bug_url).toUri())
)
true
}
R.id.main_menu_rate -> {
try {
startActivity(
Intent(Intent.ACTION_VIEW, "market://details?id=$packageName".toUri())
)
} catch (_: ActivityNotFoundException) {
startActivity(
Intent(Intent.ACTION_VIEW, "https://play.google.com/store/apps/details?id=$packageName".toUri())
)
}
true
}
R.id.main_menu_docs -> {
startActivity(
Intent(Intent.ACTION_VIEW, getString(R.string.main_menu_docs_url).toUri())
)
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun onNotificationSettingsClick(enable: Boolean) {
if (!enable) {
Log.d(TAG, "Notification settings dialog not available")
} else {
Log.d(TAG, "Re-enabling global notifications")
onNotificationMutedUntilChanged(Repository.MUTED_UNTIL_SHOW_ALL)
}
}
private fun onConnectionErrorClick() {
Log.d(TAG, "Connection error dialog not available")
}
fun onNotificationMutedUntilChanged(mutedUntilTimestamp: Long) {
repository.setGlobalMutedUntil(mutedUntilTimestamp)
showHideNotificationMenuItems()
runOnUiThread {
redrawList() // Update the "muted until" icons
when (mutedUntilTimestamp) {
0L -> Toast.makeText(this@MainActivity, getString(R.string.notification_dialog_enabled_toast_message), Toast.LENGTH_LONG).show()
1L -> Toast.makeText(this@MainActivity, getString(R.string.notification_dialog_muted_forever_toast_message), Toast.LENGTH_LONG).show()
else -> {
val formattedDate = formatDateShort(mutedUntilTimestamp)
Toast.makeText(this@MainActivity, getString(R.string.notification_dialog_muted_until_toast_message, formattedDate), Toast.LENGTH_LONG).show()
}
}
}
}
private fun onSubscribeButtonClick() {
val newFragment = AddFragment()
newFragment.show(supportFragmentManager, AddFragment.TAG)
}
override fun onSubscribe(topic: String, baseUrl: String, instant: Boolean) {
Log.d(TAG, "Adding subscription ${topicShortUrl(baseUrl, topic)} (instant = $instant)")
// Add subscription to database
val subscription = Subscription(
id = randomSubscriptionId(),
baseUrl = baseUrl,
topic = topic,
mutedUntil = 0,
minPriority = Repository.MIN_PRIORITY_USE_GLOBAL,
autoDelete = Repository.AUTO_DELETE_USE_GLOBAL,
insistent = Repository.INSISTENT_MAX_PRIORITY_USE_GLOBAL,
upAppId = null,
upConnectorToken = null,
displayName = null,
totalCount = 0,
newCount = 0,
lastActive = Date().time/1000
)
viewModel.add(subscription)
// Signal pushes to us, no Firebase to subscribe to
// Fetch cached messages
lifecycleScope.launch(Dispatchers.IO) {
try {
val notifications = api.poll(subscription.id, subscription.baseUrl, subscription.topic)
notifications.forEach { notification ->
repository.addNotification(notification)
// Icon download not implemented
}
} catch (e: Exception) {
Log.e(TAG, "Unable to fetch notifications: ${e.message}", e)
}
}
// Switch to detail view after adding it
onSubscriptionItemClick(subscription)
}
private fun onSubscriptionItemClick(subscription: Subscription) {
if (actionMode != null) {
handleActionModeClick(subscription)
} else if (subscription.upAppId != null) { // UnifiedPush
startDetailSettingsView(subscription)
} else {
startDetailView(subscription)
}
}
private fun onSubscriptionItemLongClick(subscription: Subscription) {
if (actionMode == null) {
beginActionMode(subscription)
}
}
private fun refreshAllSubscriptions() {
lifecycleScope.launch(Dispatchers.IO) {
Log.d(TAG, "Polling for new notifications")
var errors = 0
var errorMessage = "" // First error
var newNotificationsCount = 0
repository.getSubscriptions().forEach { subscription ->
Log.d(TAG, "subscription: $subscription")
try {
val notifications = api.poll(subscription.id, subscription.baseUrl, subscription.topic, null)
val newNotifications = repository.onlyNewNotifications(subscription.id, notifications)
newNotifications.forEach { notification ->
newNotificationsCount++
val notificationWithId = notification.copy(notificationId = Random.nextInt())
if (repository.addNotification(notificationWithId)) {
dispatcher?.dispatch(subscription, notificationWithId)
}
}
} catch (e: Exception) {
val topic = displayName(appBaseUrl, subscription)
if (errorMessage == "") errorMessage = "$topic: ${e.message}"
errors++
}
}
val toastMessage = if (errors > 0) {
getString(R.string.refresh_message_error, errors, errorMessage)
} else if (newNotificationsCount == 0) {
getString(R.string.refresh_message_no_results)
} else {
getString(R.string.refresh_message_result, newNotificationsCount)
}
runOnUiThread {
Toast.makeText(this@MainActivity, toastMessage, Toast.LENGTH_LONG).show()
mainListContainer.isRefreshing = false
}
Log.d(TAG, "Finished polling for new notifications")
}
}
private fun startDetailView(subscription: Subscription) {
Log.d(TAG, "Entering detail view for subscription $subscription")
val intent = Intent(this, DetailActivity::class.java)
intent.putExtra(EXTRA_SUBSCRIPTION_ID, subscription.id)
intent.putExtra(EXTRA_SUBSCRIPTION_BASE_URL, subscription.baseUrl)
intent.putExtra(EXTRA_SUBSCRIPTION_TOPIC, subscription.topic)
intent.putExtra(EXTRA_SUBSCRIPTION_DISPLAY_NAME, displayName(appBaseUrl, subscription))
intent.putExtra(EXTRA_SUBSCRIPTION_MUTED_UNTIL, subscription.mutedUntil)
startActivity(intent)
}
private fun startDetailSettingsView(subscription: Subscription) {
Log.d(TAG, "Opening subscription settings for ${topicShortUrl(subscription.baseUrl, subscription.topic)}")
// Detail settings removed
// val intent = Intent(this, DetailSettingsActivity::class.java)
// intent.putExtra(DetailActivity.EXTRA_SUBSCRIPTION_ID, subscription.id)
// intent.putExtra(DetailActivity.EXTRA_SUBSCRIPTION_BASE_URL, subscription.baseUrl)
// intent.putExtra(DetailActivity.EXTRA_SUBSCRIPTION_TOPIC, subscription.topic)
// intent.putExtra(DetailActivity.EXTRA_SUBSCRIPTION_DISPLAY_NAME, displayName(appBaseUrl, subscription))
// startActivity(intent)
}
private fun handleActionModeClick(subscription: Subscription) {
adapter.toggleSelection(subscription.id)
if (adapter.selected.size == 0) {
finishActionMode()
} else {
actionMode!!.title = adapter.selected.size.toString()
}
}
private fun onMultiDeleteClick() {
Log.d(DetailActivity.TAG, "Showing multi-delete dialog for selected items")
val dialog = MaterialAlertDialogBuilder(this)
.setMessage(R.string.main_action_mode_delete_dialog_message)
.setPositiveButton(R.string.main_action_mode_delete_dialog_permanently_delete) { _, _ ->
adapter.selected.map { subscriptionId -> viewModel.remove(this, subscriptionId) }
finishActionMode()
}
.setNegativeButton(R.string.main_action_mode_delete_dialog_cancel) { _, _ ->
finishActionMode()
}
.create()
dialog.setOnShowListener {
dialog
.getButton(AlertDialog.BUTTON_POSITIVE)
.dangerButton()
}
dialog.show()
}
private fun beginActionMode(subscription: Subscription) {
actionMode = startSupportActionMode(actionModeCallback)
adapter.toggleSelection(subscription.id)
// Fade out FAB
fab.alpha = 1f
fab
.animate()
.alpha(0f)
.setDuration(ANIMATION_DURATION)
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
fab.visibility = View.GONE
}
})
}
private fun finishActionMode() {
actionMode!!.finish()
endActionModeAndRedraw()
}
private fun endActionModeAndRedraw() {
actionMode = null
adapter.selected.clear()
redrawList()
// Fade in FAB
fab.alpha = 0f
fab.visibility = View.VISIBLE
fab
.animate()
.alpha(1f)
.setDuration(ANIMATION_DURATION)
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
fab.visibility = View.VISIBLE // Required to replace the old listener
}
})
}
private fun redrawList() {
if (!this::mainList.isInitialized) {
return
}
adapter.notifyItemRangeChanged(0, adapter.currentList.size)
}
companion object {
const val TAG = "NtfyMainActivity"
const val EXTRA_SUBSCRIPTION_ID = "subscriptionId"
const val EXTRA_SUBSCRIPTION_BASE_URL = "subscriptionBaseUrl"
const val EXTRA_SUBSCRIPTION_TOPIC = "subscriptionTopic"
const val EXTRA_SUBSCRIPTION_DISPLAY_NAME = "subscriptionDisplayName"
const val EXTRA_SUBSCRIPTION_MUTED_UNTIL = "subscriptionMutedUntil"
const val ANIMATION_DURATION = 80L
const val ONE_DAY_MILLIS = 86400000L
// As per documentation: The minimum repeat interval that can be defined is 15 minutes
// (same as the JobScheduler API), but in practice 15 doesn't work. Using 16 here.
// Thanks to varunon9 (https://gist.github.com/varunon9/f2beec0a743c96708eb0ef971a9ff9cd) for this!
const val POLL_WORKER_INTERVAL_MINUTES = 60L
const val DELETE_WORKER_INTERVAL_MINUTES = 8 * 60L
const val SERVICE_START_WORKER_INTERVAL_MINUTES = 3 * 60L
}
}

View file

@ -0,0 +1,154 @@
package com.lonecloud.sup.ui
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.lonecloud.sup.BuildConfig
import com.lonecloud.sup.R
import com.lonecloud.sup.db.ConnectionState
import com.lonecloud.sup.db.Repository
import com.lonecloud.sup.db.Subscription
import com.lonecloud.sup.util.displayName
import com.lonecloud.sup.util.readBitmapFromUriOrNull
import java.text.DateFormat
import java.util.*
class MainAdapter(
private val repository: Repository,
private val onClick: (Subscription) -> Unit,
private val onLongClick: (Subscription) -> Unit,
private val countDrawable: Drawable,
private val onPrimaryColor: Int
) :
ListAdapter<Subscription, MainAdapter.SubscriptionViewHolder>(TopicDiffCallback) {
val selected = mutableSetOf<Long>() // Subscription IDs
/* Creates and inflates view and return TopicViewHolder. */
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SubscriptionViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.fragment_main_item, parent, false)
return SubscriptionViewHolder(view, repository, selected, onClick, onLongClick, countDrawable, onPrimaryColor)
}
/* Gets current topic and uses it to bind view. */
override fun onBindViewHolder(holder: SubscriptionViewHolder, position: Int) {
val subscription = getItem(position)
holder.bind(subscription)
}
fun toggleSelection(subscriptionId: Long) {
if (selected.contains(subscriptionId)) {
selected.remove(subscriptionId)
} else {
selected.add(subscriptionId)
}
if (selected.isNotEmpty()) {
val listIds = currentList.map { subscription -> subscription.id }
val subscriptionPosition = listIds.indexOf(subscriptionId)
notifyItemChanged(subscriptionPosition)
}
}
/* ViewHolder for Topic, takes in the inflated view and the onClick behavior. */
class SubscriptionViewHolder(
itemView: View,
private val repository: Repository,
private val selected: Set<Long>,
val onClick: (Subscription) -> Unit,
val onLongClick: (Subscription) -> Unit,
private val countDrawable: Drawable,
private val onPrimaryColor: Int
) :
RecyclerView.ViewHolder(itemView) {
private var subscription: Subscription? = null
private val context: Context = itemView.context
private val imageView: ImageView = itemView.findViewById(R.id.main_item_image)
private val nameView: TextView = itemView.findViewById(R.id.main_item_text)
private val statusView: TextView = itemView.findViewById(R.id.main_item_status)
private val dateView: TextView = itemView.findViewById(R.id.main_item_date)
private val connectionErrorImageView: View = itemView.findViewById(R.id.main_item_connection_error_image)
private val notificationDisabledUntilImageView: View = itemView.findViewById(R.id.main_item_notification_disabled_until_image)
private val notificationDisabledForeverImageView: View = itemView.findViewById(R.id.main_item_notification_disabled_forever_image)
private val instantImageView: View = itemView.findViewById(R.id.main_item_instant_image)
private val newItemsView: TextView = itemView.findViewById(R.id.main_item_new)
private val appBaseUrl = context.getString(R.string.app_base_url)
fun bind(subscription: Subscription) {
this.subscription = subscription
val isUnifiedPush = subscription.upAppId != null
var statusMessage = if (isUnifiedPush) {
context.getString(R.string.main_item_status_unified_push, subscription.upAppId)
} else if (subscription.totalCount == 1) {
context.getString(R.string.main_item_status_text_one, subscription.totalCount)
} else {
context.getString(R.string.main_item_status_text_not_one, subscription.totalCount)
}
if (subscription.connectionDetails.state == ConnectionState.CONNECTING) {
statusMessage += ", " + context.getString(R.string.main_item_status_reconnecting)
}
val date = Date(subscription.lastActive * 1000)
val dateStr = DateFormat.getDateInstance(DateFormat.SHORT).format(date)
val moreThanOneDay = System.currentTimeMillis()/1000 - subscription.lastActive > 24 * 60 * 60
val sameDay = dateStr == DateFormat.getDateInstance(DateFormat.SHORT).format(Date()) // Omg this is horrible
val dateText = if (subscription.lastActive == 0L) {
""
} else if (sameDay) {
DateFormat.getTimeInstance(DateFormat.SHORT).format(date)
} else if (!moreThanOneDay) {
context.getString(R.string.main_item_date_yesterday)
} else {
dateStr
}
val globalMutedUntil = repository.getGlobalMutedUntil()
val showMutedForeverIcon = (subscription.mutedUntil == 1L || globalMutedUntil == 1L) && !isUnifiedPush
val showMutedUntilIcon = !showMutedForeverIcon && (subscription.mutedUntil > 1L || globalMutedUntil > 1L) && !isUnifiedPush
imageView.setImageResource(R.drawable.ic_sms_gray_24dp)
nameView.text = displayName(appBaseUrl, subscription)
statusView.text = statusMessage
dateView.text = dateText
dateView.visibility = if (isUnifiedPush) View.GONE else View.VISIBLE
val showConnectionError = subscription.connectionDetails.hasError()
connectionErrorImageView.visibility = if (showConnectionError) View.VISIBLE else View.GONE
notificationDisabledUntilImageView.visibility = if (showMutedUntilIcon) View.VISIBLE else View.GONE
notificationDisabledForeverImageView.visibility = if (showMutedForeverIcon) View.VISIBLE else View.GONE
if (isUnifiedPush || subscription.newCount == 0) {
newItemsView.visibility = View.GONE
} else {
newItemsView.visibility = View.VISIBLE
newItemsView.text = if (subscription.newCount <= 99) subscription.newCount.toString() else "99+"
newItemsView.setTextColor(onPrimaryColor)
newItemsView.background = countDrawable
}
itemView.setOnClickListener { onClick(subscription) }
itemView.setOnLongClickListener { onLongClick(subscription); true }
if (selected.contains(subscription.id)) {
itemView.setBackgroundColor(Colors.itemSelectedBackground(context))
} else {
itemView.setBackgroundColor(Color.TRANSPARENT)
}
}
}
object TopicDiffCallback : DiffUtil.ItemCallback<Subscription>() {
override fun areItemsTheSame(oldItem: Subscription, newItem: Subscription): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Subscription, newItem: Subscription): Boolean {
return oldItem == newItem
}
}
companion object {
const val TAG = "NtfyMainAdapter"
}
}

View file

@ -0,0 +1,53 @@
package com.lonecloud.sup.ui
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.lonecloud.sup.R
import com.lonecloud.sup.db.*
import com.lonecloud.sup.up.Distributor
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import androidx.core.net.toUri
class SubscriptionsViewModel(private val repository: Repository) : ViewModel() {
fun list(): LiveData<List<Subscription>> {
return repository.getSubscriptionsLiveData()
}
fun listIdsWithInstantStatus(): LiveData<Set<Pair<Long, Boolean>>> {
return repository.getSubscriptionIdsWithInstantStatusLiveData()
}
fun add(subscription: Subscription) = viewModelScope.launch(Dispatchers.IO) {
repository.addSubscription(subscription)
}
fun remove(context: Context, subscriptionId: Long) = viewModelScope.launch(Dispatchers.IO) {
val subscription = repository.getSubscription(subscriptionId) ?: return@launch
if (subscription.upAppId != null && subscription.upConnectorToken != null) {
val distributor = Distributor(context)
distributor.sendUnregistered(subscription.upAppId, subscription.upConnectorToken)
}
repository.removeAllNotifications(subscriptionId)
repository.removeSubscription(subscriptionId)
// Firebase unsubscribe removed
}
suspend fun get(baseUrl: String, topic: String): Subscription? {
return repository.getSubscription(baseUrl, topic)
}
}
class SubscriptionsViewModelFactory(private val repository: Repository) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T =
with(modelClass){
when {
isAssignableFrom(SubscriptionsViewModel::class.java) -> SubscriptionsViewModel(repository) as T
else -> throw IllegalArgumentException("Unknown viewModel class $modelClass")
}
}
}

View file

@ -0,0 +1,58 @@
package com.lonecloud.sup.ui
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import com.lonecloud.sup.R
data class PriorityItem(
val priority: Int,
val label: String,
val iconResId: Int
) {
override fun toString(): String = label
}
class PriorityAdapter(
context: Context,
private val items: List<PriorityItem>
) : ArrayAdapter<PriorityItem>(context, R.layout.item_priority_dropdown, items) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
return createItemView(position, convertView, parent)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
return createItemView(position, convertView, parent)
}
private fun createItemView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = convertView ?: LayoutInflater.from(context)
.inflate(R.layout.item_priority_dropdown, parent, false)
val item = items[position]
val iconView = view.findViewById<ImageView>(R.id.priority_icon)
val textView = view.findViewById<TextView>(R.id.priority_text)
iconView.setImageResource(item.iconResId)
textView.text = item.label
return view
}
companion object {
fun createPriorityItems(context: Context): List<PriorityItem> {
return listOf(
PriorityItem(5, context.getString(R.string.common_priority_max_name), R.drawable.ic_priority_5_24dp),
PriorityItem(4, context.getString(R.string.common_priority_high_name), R.drawable.ic_priority_4_24dp),
PriorityItem(3, context.getString(R.string.common_priority_default_name), R.drawable.ic_priority_3_24dp),
PriorityItem(2, context.getString(R.string.common_priority_low_name), R.drawable.ic_priority_2_24dp),
PriorityItem(1, context.getString(R.string.common_priority_min_name), R.drawable.ic_priority_1_24dp)
)
}
}
}

View file

@ -0,0 +1,221 @@
package com.lonecloud.sup.up
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.annotation.RequiresApi
import com.lonecloud.sup.R
import com.lonecloud.sup.app.Application
import com.lonecloud.sup.db.Repository
import com.lonecloud.sup.db.Subscription
import com.lonecloud.sup.util.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.util.*
/**
* This is the UnifiedPush broadcast receiver to handle the distributor actions REGISTER and UNREGISTER.
* See https://unifiedpush.org/spec/android/ for details.
*/
class BroadcastReceiver : android.content.BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (context == null || intent == null) {
return
}
Log.init(context) // Init in all entrypoints
when (intent.action) {
ACTION_REGISTER -> register(context, intent)
ACTION_UNREGISTER -> unregister(context, intent)
}
}
private fun register(context: Context, intent: Intent) {
val appId = getApplication(context, intent) ?: return
val connectorToken = intent.getStringExtra(EXTRA_TOKEN) ?: return
val app = context.applicationContext as Application
val repository = app.repository
val distributor = Distributor(app)
Log.d(TAG, "REGISTER received for app $appId (connectorToken=$connectorToken)")
if (!repository.getUnifiedPushEnabled()) {
Log.w(TAG, "Refusing registration because 'EnableUP' is disabled")
// Action required: tell the app to not try again before an action as be done manuall by the user
distributor.sendRegistrationFailed(appId, connectorToken, FailedReason.ACTION_REQUIRED)
return
}
if (appId.isBlank()) {
Log.w(TAG, "Refusing registration: Empty application")
return
}
GlobalScope.launch(Dispatchers.IO) {
// We're doing all of this inside a critical section, because of possible races.
// See https://github.com/binwiederhier/ntfy/issues/230 for details.
mutex.withLock {
val existingSubscription = repository.getSubscriptionByConnectorToken(connectorToken)
if (existingSubscription != null) {
if (existingSubscription.upAppId == appId) {
val endpoint = topicUrlUp(existingSubscription.baseUrl, existingSubscription.topic)
Log.d(TAG, "Subscription with connectorToken $connectorToken exists. Sending endpoint $endpoint.")
distributor.sendEndpoint(appId, connectorToken, endpoint)
} else {
Log.d(TAG, "Subscription with connectorToken $connectorToken exists for a different app. Refusing registration.")
// Internal_error: try again with a new token
distributor.sendRegistrationFailed(appId, connectorToken, FailedReason.INTERNAL_ERROR)
}
return@launch
}
// Add subscription
val baseUrl = repository.getDefaultBaseUrl() ?: context.getString(R.string.app_base_url)
val topic = UP_PREFIX + randomString(TOPIC_RANDOM_ID_LENGTH)
val endpoint = topicUrlUp(baseUrl, topic)
val subscription = Subscription(
id = randomSubscriptionId(),
baseUrl = baseUrl,
topic = topic,
mutedUntil = 0,
minPriority = Repository.MIN_PRIORITY_USE_GLOBAL,
autoDelete = Repository.AUTO_DELETE_USE_GLOBAL,
insistent = Repository.INSISTENT_MAX_PRIORITY_USE_GLOBAL,
upAppId = appId,
upConnectorToken = connectorToken,
displayName = null,
totalCount = 0,
newCount = 0,
lastActive = Date().time/1000
)
Log.d(TAG, "Adding subscription with for app $appId (connectorToken $connectorToken): $subscription")
try {
// Note, this may fail due to a SQL constraint exception, see https://github.com/binwiederhier/ntfy/issues/185
repository.addSubscription(subscription)
distributor.sendEndpoint(appId, connectorToken, endpoint)
// Signal pushes to us, no service to refresh
} catch (e: Exception) {
Log.w(TAG, "Failed to add subscription", e)
// Try again when there is network
distributor.sendRegistrationFailed(appId, connectorToken, FailedReason.NETWORK)
}
// Add to log scrubber
Log.addScrubTerm(shortUrl(baseUrl), Log.TermType.Domain)
Log.addScrubTerm(topic)
}
}
}
/**
* Get application package name
*/
private fun getApplication(context: Context, intent: Intent): String? {
return getApplicationAnd3(context, intent)
?: getApplicationAnd2(intent)
}
/**
* Get application package name following AND_3 specifications.
*/
private fun getApplicationAnd3(context: Context, intent: Intent): String? {
return if (Build.VERSION.SDK_INT >= 34) {
getApplicationAnd3SharedId(context, intent)
} else {
getApplicationAnd3PendingIntent(intent)
}
}
/**
* Try get application package name following AND_3 specifications for SDK>=34, with the shared
* identity.
*
* It fallback to [getApplicationAnd3PendingIntent] if the other application targets SDK<34.
*/
@RequiresApi(34)
private fun getApplicationAnd3SharedId(context: Context, intent: Intent): String? {
return sentFromPackage?.also {
// We got the package name with the shared identity
android.util.Log.d(TAG, "Registering $it. Package name retrieved with shared identity")
} ?: getApplicationAnd3PendingIntent(intent)?.let { packageId ->
// We got the package name with the pending intent, checking if that app targets SDK<34
return if (Build.VERSION.SDK_INT >= 33) {
context.packageManager.getApplicationInfo(
packageId,
PackageManager.ApplicationInfoFlags.of(
PackageManager.GET_META_DATA.toLong()
)
)
} else {
context.packageManager.getApplicationInfo(packageId, 0)
}.let { ai ->
if (ai.targetSdkVersion >= 34) {
android.util.Log.d(TAG, "App targeting Sdk >= 34 without shared identity, ignoring.")
null
} else {
packageId
}
}
}
}
/**
* Try get application package name following AND_3 specifications when running on
* a device with SDK<34 or receiving message from an application targeting SDK<34, with a pending
* intent.
*
* Always prefer [getApplicationAnd3SharedId] if possible.
*/
private fun getApplicationAnd3PendingIntent(intent: Intent): String? {
return intent.getParcelableExtra<PendingIntent>(EXTRA_PI)?.creatorPackage?.also {
android.util.Log.d(TAG, "Registering $it. Package name retrieved with PendingIntent")
}
}
/**
* Try get the application package name using AND_2 specifications
*/
@Deprecated("This follows AND_2 specifications. Will be removed.")
private fun getApplicationAnd2(intent: Intent): String? {
return intent.getStringExtra(EXTRA_APPLICATION)?.also {
android.util.Log.d(TAG, "Registering $it. Package name retrieved with legacy String extra")
}
}
private fun unregister(context: Context, intent: Intent) {
val connectorToken = intent.getStringExtra(EXTRA_TOKEN) ?: return
val app = context.applicationContext as Application
val repository = app.repository
val distributor = Distributor(app)
Log.d(TAG, "UNREGISTER received (connectorToken=$connectorToken)")
GlobalScope.launch(Dispatchers.IO) {
// We're doing all of this inside a critical section, because of possible races.
// See https://github.com/binwiederhier/ntfy/issues/230 for details.
mutex.withLock {
val existingSubscription = repository.getSubscriptionByConnectorToken(connectorToken)
if (existingSubscription == null) {
Log.d(TAG, "Subscription with connectorToken $connectorToken does not exist. Ignoring.")
return@launch
}
// Remove subscription
Log.d(TAG, "Removing subscription ${existingSubscription.id} with connectorToken $connectorToken")
repository.removeSubscription(existingSubscription.id)
existingSubscription.upAppId?.let { appId -> distributor.sendUnregistered(appId, connectorToken) }
// Signal pushes to us, no service to refresh
}
}
}
companion object {
private const val TAG = "NtfyUpBroadcastRecv"
private const val UP_PREFIX = "up"
private const val TOPIC_RANDOM_ID_LENGTH = 12
val mutex = Mutex() // https://github.com/binwiederhier/ntfy/issues/230
}
}

View file

@ -0,0 +1,21 @@
package com.lonecloud.sup.up
/**
* Constants as defined on the specs
* https://github.com/UnifiedPush/UP-spec/blob/main/specifications.md
*/
const val ACTION_NEW_ENDPOINT = "org.unifiedpush.android.connector.NEW_ENDPOINT"
const val ACTION_REGISTRATION_FAILED = "org.unifiedpush.android.connector.REGISTRATION_FAILED"
const val ACTION_UNREGISTERED = "org.unifiedpush.android.connector.UNREGISTERED"
const val ACTION_MESSAGE = "org.unifiedpush.android.connector.MESSAGE"
const val ACTION_REGISTER = "org.unifiedpush.android.distributor.REGISTER"
const val ACTION_UNREGISTER = "org.unifiedpush.android.distributor.UNREGISTER"
const val EXTRA_APPLICATION = "application"
const val EXTRA_PI = "pi"
const val EXTRA_TOKEN = "token"
const val EXTRA_ENDPOINT = "endpoint"
const val EXTRA_FAILED_REASON = "reason"
const val EXTRA_BYTES_MESSAGE = "bytesMessage"

View file

@ -0,0 +1,51 @@
package com.lonecloud.sup.up
import android.content.Context
import android.content.Intent
import com.lonecloud.sup.util.Log
/**
* This is the UnifiedPush distributor, an amalgamation of messages to be sent as part of the spec.
* See https://unifiedpush.org/spec/android/ for details.
*/
class Distributor(val context: Context) {
fun sendMessage(app: String, connectorToken: String, message: ByteArray) {
Log.d(TAG, "Sending MESSAGE to $app (token=$connectorToken): ${message.size} bytes")
RaiseAppToForegroundFactory
.getInstance(context, app)
.raiseAndSend(connectorToken, message)
}
fun sendEndpoint(app: String, connectorToken: String, endpoint: String) {
Log.d(TAG, "Sending NEW_ENDPOINT to $app (token=$connectorToken): $endpoint")
val broadcastIntent = Intent()
broadcastIntent.`package` = app
broadcastIntent.action = ACTION_NEW_ENDPOINT
broadcastIntent.putExtra(EXTRA_TOKEN, connectorToken)
broadcastIntent.putExtra(EXTRA_ENDPOINT, endpoint)
context.sendBroadcast(broadcastIntent)
}
fun sendUnregistered(app: String, connectorToken: String) {
Log.d(TAG, "Sending UNREGISTERED to $app (token=$connectorToken)")
val broadcastIntent = Intent()
broadcastIntent.`package` = app
broadcastIntent.action = ACTION_UNREGISTERED
broadcastIntent.putExtra(EXTRA_TOKEN, connectorToken)
context.sendBroadcast(broadcastIntent)
}
fun sendRegistrationFailed(app: String, connectorToken: String, reason: FailedReason) {
Log.d(TAG, "Sending REGISTRATION_FAILED to $app (token=$connectorToken)")
val broadcastIntent = Intent()
broadcastIntent.`package` = app
broadcastIntent.action = ACTION_REGISTRATION_FAILED
broadcastIntent.putExtra(EXTRA_TOKEN, connectorToken)
broadcastIntent.putExtra(EXTRA_FAILED_REASON, reason)
context.sendBroadcast(broadcastIntent)
}
companion object {
private const val TAG = "NtfyUpDistributor"
}
}

View file

@ -0,0 +1,23 @@
package com.lonecloud.sup.up
/**
* A registration request may fail for different reasons.
*/
enum class FailedReason {
/**
* This is a generic error type, you can try to register again directly.
*/
INTERNAL_ERROR,
/**
* The registration failed because of missing network connection, try again when network is back.
*/
NETWORK,
/**
* The distributor requires a user action to work. For instance, the distributor may be log out of the push server and requires the user to log in. The user must interact with the distributor or sending a new registration will fail again.
*/
ACTION_REQUIRED,
/**
* The distributor requires a VAPID key and the app didn't provide one during registration.
*/
VAPID_REQUIRED, // Currently unused
}

View file

@ -0,0 +1,36 @@
package com.lonecloud.sup.up
import android.app.Activity
import android.app.PendingIntent
import android.content.Intent
import android.os.Bundle
import android.util.Log
/**
* This implements the "Select default distributor" selection for UnifiedPush.
*
* To test, install ntfy and another distributor (e.g. SunUp) on the same phone.
* Install an app that uses UnifiedPush (e.g. UP Example) and click "Register".
*
* You should see a popup to select the default distributor.
* See https://unifiedpush.org/developers/spec/android/#link-activity
*/
class LinkActivity: Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
intent?.data?.run {
Log.d(TAG, "Received request for $callingPackage")
val intent = Intent("org.unifiedpush.register.dummy_app")
val pendingIntent = PendingIntent.getBroadcast(this@LinkActivity, 0, intent, PendingIntent.FLAG_IMMUTABLE)
val result = Intent().apply {
putExtra(EXTRA_PI, pendingIntent)
}
setResult(RESULT_OK, result)
} ?: setResult(RESULT_CANCELED)
finish()
}
companion object {
private val TAG = "NtfyUpLinkActivity"
}
}

View file

@ -0,0 +1,311 @@
package com.lonecloud.sup.up
import android.app.ActivityManager
import android.app.ActivityManager.RunningAppProcessInfo
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.os.Build
import android.os.IBinder
import android.util.Log
import kotlinx.coroutines.Runnable
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
/**
* Raises the target application to foreground importance before delivering a UnifiedPush message.
*
* ## Background
*
* Starting with Android 12 (API level 31), apps running in the background are restricted from
* starting foreground services. This is problematic for push notification scenarios where the
* target app (e.g., a messenger like Element, Molly, etc.) needs to start a foreground service
* to process incoming messages reliably.
*
* See: https://developer.android.com/develop/background-work/services/fgs/restrictions-bg-start
*
* ## How This Works
*
* This class implements the **AND_3 specification** from UnifiedPush, which defines a mechanism
* for distributors (like ntfy) to "raise" the target application to foreground importance before
* sending the push message.
*
* See: https://unifiedpush.org/developers/spec/android/#service-to-raise-to-the-foreground
*
* Here's the flow:
*
* 1. **Check ntfy's foreground status**: When ntfy receives a message for a UnifiedPush app,
* it temporarily has foreground importance (IMPORTANCE_FOREGROUND or IMPORTANCE_FOREGROUND_SERVICE).
* The [checkForeground] method verifies this.
*
* 2. **Check target app support**: The target app must export a service with the action
* `org.unifiedpush.android.connector.RAISE_TO_FOREGROUND`. This is checked via
* [hasRaiseToForegroundService].
*
* 3. **Bind to target's service**: If both conditions are met, ntfy binds to the target app's
* "raise to foreground" service using [Context.bindService] with [Context.BIND_AUTO_CREATE].
* **This is the key mechanism**: when a foreground process binds to a service, the Android
* system grants foreground importance to the bound service's process. This allows the target
* app to escape background restrictions and start its own foreground service if needed.
*
* 4. **Send the message**: Once bound (or immediately if binding isn't possible), the push
* message is delivered via a broadcast with action `org.unifiedpush.android.connector.MESSAGE`.
*
* 5. **Maintain binding briefly**: The binding is kept alive for 5 seconds (or extended if more
* messages arrive) to give the target app time to start its foreground service. After the
* timeout, the binding is released via [unbind].
*
* ## Example logs (using UP-Example app, see https://github.com/binwiederhier/ntfy-android/pull/98#issuecomment-3681330111)
*
* ```
* NtfyUpDistributor D Sending MESSAGE to org.unifiedpush.example (token=e9830034-b97d-485d-a7f1-c8a03af9cbd2): 107 bytes
* NtfyUpRaiseFgFactory D New instance for org.unifiedpush.example
* NtfyUpRaiseFg I Found foreground process: io.heckel.ntfy.debug
* NtfyUpRaiseFg D Binding to org.unifiedpush.example
* NtfyUpRaiseFg D onServiceConnected ComponentInfo{org.unifiedpush.example/org.unifiedpush.android.connector.internal.RaiseToForegroundService}
* NtfyUpRaiseFg D Sending msg for org.unifiedpush.example
* NtfyUpRaiseFg D Timeout expired, unbinding
* NtfyUpRaiseFgFactory D Removing instance for org.unifiedpush.example
* NtfyUpRaiseFg D Unbound
* ```
*
* ## Why "Foreground" Matters
*
* "Foreground" in this context does NOT mean the app is visible on screen (alt-tab style).
* Rather, it refers to the app's **process importance level** as tracked by the Android system.
* An app with foreground importance:
* - Is exempt from doze mode restrictions
* - Can start foreground services from the background
* - Has higher priority and is less likely to be killed
*
* This mechanism allows ntfy to temporarily "lend" its foreground importance to the target app,
* enabling reliable push notification processing even when both apps are in the background.
*
* ## Fallback Behavior
*
* If ntfy isn't in the foreground or the target app doesn't support the raise-to-foreground
* service, the message is sent directly via broadcast without the binding step. This maintains
* backward compatibility with older apps but may result in delayed or missed notifications
* on devices with aggressive battery optimization.
*
* ## Connection Lifecycle
*
* - [Bound.Unbound]: No active connection. Will attempt to bind on next message.
* - [Bound.Binding]: Binding in progress. Messages are queued until connected.
* - [Bound.Bound]: Connected. Messages are sent immediately.
*
* The connection auto-unbinds after 5 seconds of inactivity. Subsequent messages reset this timer.
*
* @param context The application context for binding services and sending broadcasts.
* @param app The package name of the target application.
* @param onUnbound Callback invoked when the service connection is unbound (used by
* [RaiseAppToForegroundFactory] for cleanup).
*
* @see RaiseAppToForegroundFactory For singleton management of instances per app.
* @see Distributor.sendMessage Entry point for sending UnifiedPush messages.
*/
class RaiseAppToForeground(private val context: Context, private val app: String, private val onUnbound: () -> Unit) : ServiceConnection, Runnable {
class Message(val token: String, val content: ByteArray)
private enum class Bound {
Binding,
Bound,
Unbound
}
/**
* Is the service bound ? This is a per service connection
*/
private var bound = Bound.Unbound
private var scheduledFuture: ScheduledFuture<*>? = null
private val msgsQueue = mutableListOf<Message>()
private val foregroundImportance = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
listOf(
RunningAppProcessInfo.IMPORTANCE_FOREGROUND,
RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE,
)
} else {
listOf(
RunningAppProcessInfo.IMPORTANCE_FOREGROUND,
)
}
/**
* Raise [app] to the foreground, to follow AND_3 specifications
*
* @return `true` if have successfully raised app to foreground
*/
fun raiseAndSend(token: String, message: ByteArray): Boolean {
val msg = Message(token, message)
// Per instance lock
synchronized(this) {
when (bound) {
Bound.Bound -> {
Log.d(TAG, "Service connection already bound to ${this.app}")
delayUnbinding()
send(msg)
}
Bound.Binding -> {
delayUnbinding()
queue(msg)
}
Bound.Unbound -> {
val isForeground = checkForeground()
val targetHasService = hasRaiseToForegroundService()
if (isForeground && targetHasService) {
bind()
queue(msg)
} else {
Log.d(
TAG,
"Cannot raise to foreground: isForeground=$isForeground, targetHasService=$targetHasService"
)
send(msg)
return false
}
}
}
return true
}
}
/**
* @return `true` if the app is in Foreground importance
*/
private fun checkForeground(): Boolean {
val appProcesses = (context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).runningAppProcesses
for (appProcess in appProcesses) {
if (appProcess.importance in foregroundImportance) {
Log.i(TAG, "Found foreground process: ${appProcess.processName}")
return true
}
}
return false
}
private fun hasRaiseToForegroundService(): Boolean {
val intent = Intent(ACTION).apply {
`package` = app
}
return (if (Build.VERSION.SDK_INT >= 33) {
context.packageManager.queryIntentServices(
intent,
PackageManager.ResolveInfoFlags.of(
PackageManager.GET_META_DATA.toLong() +
PackageManager.GET_RESOLVED_FILTER.toLong(),
),
)
} else {
context.packageManager.queryIntentServices(
Intent(ACTION_REGISTER),
PackageManager.GET_RESOLVED_FILTER,
)
}).any {
it.serviceInfo.exported
}
}
private fun send(message: Message) {
Log.d(TAG, "Sending msg for $app")
val broadcastIntent = Intent()
broadcastIntent.`package` = app
broadcastIntent.action = ACTION_MESSAGE
broadcastIntent.putExtra(EXTRA_TOKEN, message.token)
broadcastIntent.putExtra(EXTRA_BYTES_MESSAGE, message.content)
context.sendBroadcast(broadcastIntent)
}
/**
* Queue message when the service is binding
*/
private fun queue(message: Message) {
msgsQueue.add(message)
}
/**
* If the service is already bound, we delay its unbinding
*/
private fun delayUnbinding() {
/**
* Close current scheduledFuture. We interrupt if it is running (mayInterruptIfRunning = true), so [run] won't
* unbind this new connection after we release the lock.
*/
scheduledFuture?.cancel(true)
/** Call [run] (unbind) in 5 seconds */
scheduledFuture = unbindExecutor.schedule(this, 5L, TimeUnit.SECONDS)
}
private fun bind() {
Log.d(TAG, "Binding to ${this.app}")
val intent = Intent().apply {
`package` = this@RaiseAppToForeground.app
action = ACTION
}
/** Bind to the target raise to the foreground service */
context.bindService(intent, this, Context.BIND_AUTO_CREATE)
/** Call [run] (unbind) in 5 seconds */
scheduledFuture = unbindExecutor.schedule(this, 5L, TimeUnit.SECONDS)
bound = Bound.Binding
}
private fun unbind() {
// Per instance lock
synchronized(this) {
if (bound != Bound.Unbound) {
msgsQueue.clear()
context.unbindService(this)
bound = Bound.Unbound
onUnbound()
Log.d(TAG, "Unbound")
}
}
}
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
Log.d(TAG, "onServiceConnected $name")
synchronized(this) {
bound = Bound.Bound
}
msgsQueue.forEach { msg ->
send(msg)
}
msgsQueue.clear()
}
override fun onServiceDisconnected(name: ComponentName?) {
Log.d(TAG, "onServiceDisconnected $name")
unbind()
}
override fun onBindingDied(name: ComponentName?) {
Log.d(TAG, "onBindingDied")
unbind()
}
override fun onNullBinding(name: ComponentName?) {
Log.d(TAG, "onBindingDied")
unbind()
}
/**
* Unbinding when the timeout passes.
*/
override fun run() {
Log.d(TAG, "Timeout expired, unbinding")
unbind()
}
private companion object {
private const val TAG = "NtfyUpRaiseFg"
private const val ACTION = "org.unifiedpush.android.connector.RAISE_TO_FOREGROUND"
/** Executor to unbind 5 seconds later */
private val unbindExecutor = Executors.newSingleThreadScheduledExecutor()
}
}

View file

@ -0,0 +1,39 @@
package com.lonecloud.sup.up
import android.content.Context
import android.util.Log
/**
* [RaiseAppToForeground] Factory, to avoid having one service connection per push message
*
* There is a very small chance that 2 connections exist at the same time\*, but that's not important.
* We just want to avoid tens of it.
*
* \* When [getInstance] returns an existing instance, that runs [remove] before
* [RaiseAppToForeground.raiseAndSend] is called.
*/
object RaiseAppToForegroundFactory {
fun getInstance(context: Context, app: String): RaiseAppToForeground {
synchronized(this) {
return instances[app] ?: new(context, app)
}
}
private fun new(context: Context, app: String): RaiseAppToForeground {
return RaiseAppToForeground(context, app, onUnbound = {
remove(app)
}).also {
Log.d(TAG, "New instance for $app")
instances[app] = it
}
}
private fun remove(app: String) {
Log.d(TAG, "Removing instance for $app")
synchronized(this) {
instances.remove(app)
}
}
private val instances: MutableMap<String, RaiseAppToForeground> = mutableMapOf()
private const val TAG = "NtfyUpRaiseFgFactory"
}

View file

@ -0,0 +1,98 @@
package com.lonecloud.sup.util
import android.annotation.SuppressLint
import android.content.Context
import android.util.Base64
import com.lonecloud.sup.db.Repository
import okhttp3.OkHttpClient
import java.io.ByteArrayInputStream
import java.net.URL
import java.security.KeyStore
import java.security.MessageDigest
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
import javax.net.ssl.KeyManager
import javax.net.ssl.KeyManagerFactory
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLException
import javax.net.ssl.SSLSocket
import javax.net.ssl.TrustManager
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.X509TrustManager
/**
* TLS config:
* - For each baseUrl, either use the pinned certificate (if one exists) OR system trust
* - Pinned cert = ONLY that exact certificate is trusted (strict pinning)
* - Hostname verification is bypassed for pinned certificates (the fingerprint match is the trust anchor)
* - Optional mTLS via per-baseUrl PKCS#12 client cert
*/
class CertUtil private constructor(context: Context) {
private val appContext: Context = context.applicationContext
private val repository: Repository by lazy { Repository.getInstance(appContext) }
/**
* Configure OkHttp client with TLS config using system trust.
*/
suspend fun withTLSConfig(builder: OkHttpClient.Builder, baseUrl: String): OkHttpClient.Builder {
// Using system trust only - custom certificates not supported
return builder
}
/**
* Fetch the server certificate without trusting it.
* Used to display certificate details before user decides to trust.
*/
fun fetchServerCertificate(baseUrl: String): X509Certificate? {
// Certificate fetching not implemented
return null
}
companion object {
private const val TAG = "NtfyCertUtil"
@Volatile
@SuppressLint("StaticFieldLeak")
private var instance: CertUtil? = null
fun getInstance(context: Context): CertUtil =
instance ?: synchronized(this) { instance ?: CertUtil(context).also { instance = it } }
fun calculateFingerprint(cert: X509Certificate): String {
val md = MessageDigest.getInstance("SHA-256")
val digest = md.digest(cert.encoded)
return digest.joinToString(":") { "%02X".format(it) }
}
fun parsePemCertificate(pem: String): X509Certificate {
val factory = CertificateFactory.getInstance("X.509")
return factory.generateCertificate(pem.byteInputStream()) as X509Certificate
}
fun encodeCertificateToPem(cert: X509Certificate): String {
val base64 = Base64.encodeToString(cert.encoded, Base64.NO_WRAP)
return buildString {
append("-----BEGIN CERTIFICATE-----\n")
var i = 0
while (i < base64.length) {
val end = minOf(i + 64, base64.length)
append(base64.substring(i, end))
append("\n")
i += 64
}
append("-----END CERTIFICATE-----")
}
}
fun parsePkcs12Certificate(p12Base64: String, password: String): X509Certificate {
val p12Data = Base64.decode(p12Base64, Base64.DEFAULT)
val keyStore = KeyStore.getInstance("PKCS12")
ByteArrayInputStream(p12Data).use { keyStore.load(it, password.toCharArray()) }
val alias = keyStore.aliases().nextElement()
return keyStore.getCertificate(alias) as X509Certificate
}
}
}

View file

@ -0,0 +1,11 @@
package com.lonecloud.sup.util
const val ANDROID_APP_MIME_TYPE = "application/vnd.android.package-archive"
const val PRIORITY_MIN = 1
const val PRIORITY_LOW = 2
const val PRIORITY_DEFAULT = 3
const val PRIORITY_HIGH = 4
const val PRIORITY_MAX = 5
val ALL_PRIORITIES = listOf(PRIORITY_MIN, PRIORITY_LOW, PRIORITY_DEFAULT, PRIORITY_HIGH, PRIORITY_MAX)

View file

@ -0,0 +1,29 @@
package io.heckel.ntfy.util;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
/**
* This class represents an emoji.
*
* This class was originally written by Vincent DURMONT (vdurmont@gmail.com) as part of
* https://github.com/vdurmont/emoji-java, but has since been heavily stripped and modified.
*/
public class Emoji {
private final List<String> aliases;
private final String unicode;
protected Emoji(List<String> aliases, byte... bytes) {
this.aliases = Collections.unmodifiableList(aliases);
this.unicode = new String(bytes, StandardCharsets.UTF_8);
}
public List<String> getAliases() {
return this.aliases;
}
public String getUnicode() {
return this.unicode;
}
}

View file

@ -0,0 +1,70 @@
package io.heckel.ntfy.util;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* Loads the emojis from a JSON database.
*
* This was originally written to load
* https://github.com/vdurmont/emoji-java/blob/master/src/main/resources/emojis.json
*
* But now uses
* https://github.com/github/gemoji/blob/master/db/emoji.json
*
* This class was originally written by Vincent DURMONT (vdurmont@gmail.com) as part of
* https://github.com/vdurmont/emoji-java, but has since been heavily stripped and modified.
*/
public class EmojiLoader {
public static List<Emoji> loadEmojis(InputStream stream) throws IOException, JSONException {
JSONArray emojisJSON = new JSONArray(inputStreamToString(stream));
List<Emoji> emojis = new ArrayList<Emoji>(emojisJSON.length());
for (int i = 0; i < emojisJSON.length(); i++) {
Emoji emoji = buildEmojiFromJSON(emojisJSON.getJSONObject(i));
if (emoji != null) {
emojis.add(emoji);
}
}
return emojis;
}
private static String inputStreamToString(
InputStream stream
) throws IOException {
StringBuilder sb = new StringBuilder();
InputStreamReader isr = new InputStreamReader(stream, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
String read;
while((read = br.readLine()) != null) {
sb.append(read);
}
br.close();
return sb.toString();
}
protected static Emoji buildEmojiFromJSON(
JSONObject json
) throws JSONException {
if (!json.has("emoji")) {
return null;
}
byte[] bytes = json.getString("emoji").getBytes(StandardCharsets.UTF_8);
List<String> aliases = jsonArrayToStringList(json.getJSONArray("aliases"));
return new Emoji(aliases, bytes);
}
private static List<String> jsonArrayToStringList(JSONArray array) throws JSONException {
List<String> strings = new ArrayList<String>(array.length());
for (int i = 0; i < array.length(); i++) {
strings.add(array.getString(i));
}
return strings;
}
}

View file

@ -0,0 +1,46 @@
package io.heckel.ntfy.util;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Holds the loaded emojis and provides search functions.
*
* This class was originally written by Vincent DURMONT (vdurmont@gmail.com) as part of
* https://github.com/vdurmont/emoji-java, but has since been heavily stripped and modified.
*/
public class EmojiManager {
private static final String PATH = "/emoji.json"; // https://github.com/github/gemoji/blob/master/db/emoji.json
private static final Map<String, Emoji> EMOJIS_BY_ALIAS = new HashMap<String, Emoji>();
static {
try {
InputStream stream = EmojiLoader.class.getResourceAsStream(PATH);
List<Emoji> emojis = EmojiLoader.loadEmojis(stream);
for (Emoji emoji : emojis) {
for (String alias : emoji.getAliases()) {
EMOJIS_BY_ALIAS.put(alias, emoji);
}
}
stream.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Emoji getForAlias(String alias) {
if (alias == null || alias.isEmpty()) {
return null;
}
return EMOJIS_BY_ALIAS.get(trimAlias(alias));
}
private static String trimAlias(String alias) {
int len = alias.length();
return alias.substring(
alias.charAt(0) == ':' ? 1 : 0,
alias.charAt(len - 1) == ':' ? len - 1 : len);
}
}

View file

@ -0,0 +1,75 @@
package com.lonecloud.sup.util
import android.content.Context
import android.os.Build
import com.lonecloud.sup.BuildConfig
import okhttp3.OkHttpClient
import okhttp3.Request
import java.util.concurrent.TimeUnit
/**
* Utility class for creating OkHttpClient instances and Request builders.
* All clients are configured with SSL/TLS settings from CertUtil for custom certificate support.
*/
object HttpUtil {
val USER_AGENT = "ntfy/${BuildConfig.VERSION_NAME} (${BuildConfig.FLAVOR}; Android ${Build.VERSION.RELEASE}; SDK ${Build.VERSION.SDK_INT})"
/**
* Client for regular API calls (auth, poll, etc.).
*/
suspend fun defaultClient(context: Context, baseUrl: String): OkHttpClient {
return defaultClientBuilder(context, baseUrl).build()
}
/**
* Client with a longer call timeout (5 minutes).
* Allows for large file uploads or downloads.
*/
suspend fun longCallClient(context: Context, baseUrl: String): OkHttpClient {
return defaultClientBuilder(context, baseUrl)
.callTimeout(5, TimeUnit.MINUTES)
.build()
}
/**
* Client for long-polling/streaming subscriptions.
*/
suspend fun subscriberClient(context: Context, baseUrl: String): OkHttpClient {
return emptyClientBuilder(context, baseUrl)
.readTimeout(77, TimeUnit.SECONDS) // Long enough to allow for server-side keepalive messages
.build()
}
/**
* Client for WebSocket connections.
* No read timeout, 1 minute ping interval, 10s connect timeout.
*/
suspend fun wsClient(context: Context, baseUrl: String): OkHttpClient {
return emptyClientBuilder(context, baseUrl)
.readTimeout(0, TimeUnit.MILLISECONDS)
.pingInterval(1, TimeUnit.MINUTES) // Technically not necessary, the server also pings us
.connectTimeout(10, TimeUnit.SECONDS)
.build()
}
fun requestBuilder(url: String): Request.Builder {
return Request.Builder()
.url(url)
.addHeader("User-Agent", USER_AGENT)
}
private suspend fun emptyClientBuilder(context: Context, baseUrl: String): OkHttpClient.Builder {
return CertUtil
.getInstance(context)
.withTLSConfig(OkHttpClient.Builder(), baseUrl)
}
private suspend fun defaultClientBuilder(context: Context, baseUrl: String): OkHttpClient.Builder {
return emptyClientBuilder(context, baseUrl)
.callTimeout(1, TimeUnit.MINUTES) // Increased to 1min (from 15s) to reduce client variance
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
}
}

View file

@ -0,0 +1,204 @@
package com.lonecloud.sup.util
import android.content.Context
import android.os.Build
import com.lonecloud.sup.BuildConfig
import com.lonecloud.sup.db.Database
import com.lonecloud.sup.db.LogDao
import com.lonecloud.sup.db.LogEntry
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
class Log(private val logsDao: LogDao) {
private val record: AtomicBoolean = AtomicBoolean(false)
private val count: AtomicInteger = AtomicInteger(0)
private val scrubNum: AtomicInteger = AtomicInteger(-1)
private val scrubTerms = Collections.synchronizedMap(mutableMapOf<String, ReplaceTerm>())
private fun log(level: Int, tag: String, message: String, exception: Throwable?) {
if (!record.get()) return
GlobalScope.launch(Dispatchers.IO) { // FIXME This does not guarantee the log order
logsDao.insert(LogEntry(System.currentTimeMillis(), tag, level, message, exception?.stackTraceToString()))
val current = count.incrementAndGet()
if (current >= PRUNE_EVERY) {
logsDao.prune(ENTRIES_MAX)
count.set(0) // I know there is a race here, but this is good enough
}
}
}
fun getFormatted(context: Context, scrub: Boolean): String {
val logs = formatEntries(if (scrub) scrubEntries(logsDao.getAll()) else logsDao.getAll())
val settings = "" // Settings backup removed
return prependDeviceInfo(logs, settings, scrubLine = scrub)
}
private fun prependDeviceInfo(logs: String, settings: String, scrubLine: Boolean): String {
val maybeScrubLine = if (scrubLine) "Server URLs (aside from ntfy.sh) and topics have been replaced with fruits 🍌🥝🍋🥥🥑🍊🍎🍑.\n" else ""
return """
This is a log of the ntfy Android app. The log shows up to 1,000 entries.
$maybeScrubLine
Device info:
--
ntfy: ${BuildConfig.VERSION_NAME} (${BuildConfig.FLAVOR})
OS: ${System.getProperty("os.version")}
Android: ${Build.VERSION.RELEASE} (SDK ${Build.VERSION.SDK_INT})
Model: ${Build.DEVICE}
Product: ${Build.PRODUCT}
--
Settings:
""".trimIndent() + "\n$settings\n\nLogs\n--\n\n$logs"
}
fun addScrubTerm(term: String, type: TermType = TermType.Term) {
if (scrubTerms[term] != null || IGNORE_TERMS.contains(term)) {
return
}
if (type == TermType.Password) {
scrubTerms[term] = ReplaceTerm(type, "********")
return
}
val replaceTermIndex = scrubNum.incrementAndGet()
val replaceTerm = REPLACE_TERMS.getOrNull(replaceTermIndex) ?: "fruit${replaceTermIndex}"
scrubTerms[term] = ReplaceTerm(type, when (type) {
TermType.Domain -> "$replaceTerm.example.com"
TermType.Username -> "${replaceTerm}user"
else -> replaceTerm
})
}
private fun scrubEntries(entries: List<LogEntry>): List<LogEntry> {
return entries
.map { e ->
e.copy(
message = scrub(e.message)!!,
exception = scrub(e.exception)
)
}
}
private fun scrub(line: String?): String? {
var newLine = line ?: return null
scrubTerms.forEach { (scrubTerm, replaceTerm) ->
newLine = newLine.replace(scrubTerm, replaceTerm.replaceTerm)
}
return newLine
}
private fun formatEntries(entries: List<LogEntry>): String {
return entries.joinToString(separator = "\n") { e ->
val date = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(Date(e.timestamp))
val level = when (e.level) {
android.util.Log.DEBUG -> "D"
android.util.Log.INFO -> "I"
android.util.Log.WARN -> "W"
android.util.Log.ERROR -> "E"
else -> "?"
}
val tag = e.tag.format("%23s")
val prefix = "${e.timestamp} $date $level $tag"
val message = if (e.exception != null) {
"${e.message}\nException:\n${e.exception}"
} else {
e.message
}
"$prefix $message"
}
}
private fun deleteAll() {
return logsDao.deleteAll()
}
enum class TermType {
Domain, Username, Password, Term
}
data class ReplaceTerm(
val termType: TermType,
val replaceTerm: String
)
companion object {
private const val TAG = "NtfyLog"
private const val PRUNE_EVERY = 100
private const val ENTRIES_MAX = 1000
private val IGNORE_TERMS = listOf("ntfy.sh")
private val REPLACE_TERMS = listOf(
"banana", "kiwi", "lemon", "coconut", "avocado", "orange", "apple", "peach",
"pineapple", "dragonfruit", "durian", "starfruit"
)
private var instance: Log? = null
fun d(tag: String, message: String, exception: Throwable? = null) {
if (exception == null) android.util.Log.d(tag, message) else android.util.Log.d(tag, message, exception)
getInstance()?.log(android.util.Log.DEBUG, tag, message, exception)
}
fun i(tag: String, message: String, exception: Throwable? = null) {
if (exception == null) android.util.Log.i(tag, message) else android.util.Log.i(tag, message, exception)
getInstance()?.log(android.util.Log.INFO, tag, message, exception)
}
fun w(tag: String, message: String, exception: Throwable? = null) {
if (exception == null) android.util.Log.w(tag, message) else android.util.Log.w(tag, message, exception)
getInstance()?.log(android.util.Log.WARN, tag, message, exception)
}
fun e(tag: String, message: String, exception: Throwable? = null) {
if (exception == null) android.util.Log.e(tag, message) else android.util.Log.e(tag, message, exception)
getInstance()?.log(android.util.Log.ERROR, tag, message, exception)
}
fun setRecord(enable: Boolean) {
if (!enable) d(TAG, "Disabled log recording")
getInstance()?.record?.set(enable)
if (enable) d(TAG, "Enabled log recording")
}
fun getRecord(): Boolean {
return getInstance()?.record?.get() ?: false
}
fun getFormatted(context: Context, scrub: Boolean): String {
return getInstance()?.getFormatted(context, scrub) ?: "(no logs)"
}
fun getScrubTerms(): Map<String, String> {
return getInstance()?.scrubTerms!!
.filter { e -> e.value.termType != TermType.Password } // We do not want to display passwords
.map { e -> e.key to e.value.replaceTerm }
.toMap()
}
fun deleteAll() {
getInstance()?.deleteAll()
d(TAG, "Log was truncated")
}
fun addScrubTerm(term: String, type: TermType = TermType.Term) {
getInstance()?.addScrubTerm(term, type)
}
fun init(context: Context) {
return synchronized(Log::class) {
if (instance == null) {
val database = Database.getInstance(context.applicationContext)
instance = Log(database.logDao())
}
}
}
private fun getInstance(): Log? {
return synchronized(Log::class) {
instance
}
}
}
}

View file

@ -0,0 +1,100 @@
package com.lonecloud.sup.util
import android.content.Context
import android.graphics.Typeface
import android.text.style.*
import android.text.util.Linkify
import com.lonecloud.sup.ui.Colors
import io.noties.markwon.*
import io.noties.markwon.core.CorePlugin
import io.noties.markwon.core.CoreProps
import io.noties.markwon.core.MarkwonTheme
import io.noties.markwon.ext.strikethrough.StrikethroughPlugin
import io.noties.markwon.image.ImagesPlugin
import io.noties.markwon.linkify.LinkifyPlugin
import io.noties.markwon.movement.MovementMethodPlugin
import me.saket.bettermovementmethod.BetterLinkMovementMethod
import org.commonmark.ext.gfm.tables.TableCell
import org.commonmark.ext.gfm.tables.TablesExtension
import org.commonmark.node.*
import org.commonmark.parser.Parser
internal object MarkwonFactory {
fun createForMessage(context: Context): Markwon {
val headingSizes = floatArrayOf(1.7f, 1.5f, 1.2f, 1f, .8f, .7f)
val bulletGapWidth = (8 * context.resources.displayMetrics.density + 0.5f).toInt()
return Markwon.builder(context)
.usePlugin(CorePlugin.create())
.usePlugin(SoftBreakAddsNewLinePlugin.create())
.usePlugin(MovementMethodPlugin.create(BetterLinkMovementMethod.getInstance()))
.usePlugin(ImagesPlugin.create())
.usePlugin(LinkifyPlugin.create(Linkify.WEB_URLS))
.usePlugin(StrikethroughPlugin.create())
.usePlugin(object : AbstractMarkwonPlugin() {
override fun configureTheme(builder: MarkwonTheme.Builder) {
builder
.linkColor(Colors.linkColor(context))
.isLinkUnderlined(true)
}
override fun configureConfiguration(builder: MarkwonConfiguration.Builder) {
builder
.linkResolver(LinkResolverDef())
}
override fun configureSpansFactory(builder: MarkwonSpansFactory.Builder) {
builder
.setFactory(Heading::class.java) { _, props: RenderProps? ->
arrayOf(
RelativeSizeSpan(headingSizes[CoreProps.HEADING_LEVEL.require(props!!) - 1]),
StyleSpan(Typeface.BOLD)
)
}
.setFactory(Emphasis::class.java) { _, _ -> StyleSpan(Typeface.ITALIC) }
.setFactory(StrongEmphasis::class.java) { _, _ -> StyleSpan(Typeface.BOLD) }
.setFactory(ListItem::class.java) { _, _ -> BulletSpan(bulletGapWidth) }
}
})
.build()
}
fun createForNotification(context: Context): Markwon {
val headingSizes = floatArrayOf(2f, 1.5f, 1.17f, 1f, .83f, .67f)
val bulletGapWidth = (8 * context.resources.displayMetrics.density + 0.5f).toInt()
return Markwon.builder(context)
.usePlugin(CorePlugin.create())
.usePlugin(SoftBreakAddsNewLinePlugin.create())
.usePlugin(ImagesPlugin.create())
.usePlugin(StrikethroughPlugin.create())
.usePlugin(object : AbstractMarkwonPlugin() {
override fun configureSpansFactory(builder: MarkwonSpansFactory.Builder) {
builder
.setFactory(Heading::class.java) { _, props: RenderProps? ->
arrayOf(
RelativeSizeSpan(headingSizes[CoreProps.HEADING_LEVEL.require(props!!) - 1]),
StyleSpan(Typeface.BOLD)
)
}
.setFactory(Emphasis::class.java) { _, _ -> StyleSpan(Typeface.ITALIC) }
.setFactory(StrongEmphasis::class.java) { _, _ -> StyleSpan(Typeface.BOLD) }
.setFactory(ListItem::class.java) { _, _ -> BulletSpan(bulletGapWidth) }
.setFactory(Link::class.java) { _, _ -> null }
}
override fun configureParser(builder: Parser.Builder) {
builder.extensions(setOf(TablesExtension.create()))
}
override fun configureVisitor(builder: MarkwonVisitor.Builder) {
builder.on(TableCell::class.java) { visitor: MarkwonVisitor, node: TableCell? ->
visitor.visitChildren(node!!)
visitor.builder().append(' ')
}
}
})
.build()
}
}

View file

@ -0,0 +1,37 @@
package com.lonecloud.sup.util
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.Buffer
import okio.BufferedSink
import okio.ForwardingSink
import okio.buffer
/**
* A RequestBody wrapper that reports upload progress.
*/
class ProgressRequestBody(
private val delegate: RequestBody,
private val onProgress: (bytesWritten: Long, totalBytes: Long) -> Unit
) : RequestBody() {
override fun contentType(): MediaType? = delegate.contentType()
override fun contentLength(): Long = delegate.contentLength()
override fun writeTo(sink: BufferedSink) {
val totalBytes = contentLength()
val countingSink = object : ForwardingSink(sink) {
var bytesWritten = 0L
override fun write(source: Buffer, byteCount: Long) {
super.write(source, byteCount)
bytesWritten += byteCount
onProgress(bytesWritten, totalBytes)
}
}
val bufferedSink = countingSink.buffer()
delegate.writeTo(bufferedSink)
bufferedSink.flush()
}
}

View file

@ -0,0 +1,456 @@
package com.lonecloud.sup.util
import android.content.ClipData
import android.content.ClipboardManager
import android.content.ContentResolver
import android.content.Context
import android.content.res.Configuration
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.RippleDrawable
import android.net.Uri
import android.os.Build
import android.os.PowerManager
import android.provider.OpenableColumns
import android.text.Editable
import android.text.TextWatcher
import android.util.Base64
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatDelegate
import com.lonecloud.sup.R
import com.lonecloud.sup.db.Notification
import com.lonecloud.sup.db.Repository
import com.lonecloud.sup.db.Subscription
import com.lonecloud.sup.msg.MESSAGE_ENCODING_BASE64
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okio.BufferedSink
import okio.source
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.security.MessageDigest
import java.security.SecureRandom
import java.text.DateFormat
import java.text.StringCharacterIterator
import java.util.Date
import kotlin.math.abs
import kotlin.math.absoluteValue
import androidx.core.net.toUri
fun topicUrl(baseUrl: String, topic: String) = "${baseUrl}/${topic}"
fun topicUrlUp(baseUrl: String, topic: String) = "${baseUrl}/${topic}?up=1" // UnifiedPush
fun topicUrlJson(baseUrl: String, topic: String, since: String) = "${topicUrl(baseUrl, topic)}/json?since=$since"
fun topicUrlWs(baseUrl: String, topic: String, since: String) = "${topicUrl(baseUrl, topic)}/ws?since=$since"
fun topicUrlAuth(baseUrl: String, topic: String) = "${topicUrl(baseUrl, topic)}/auth"
fun topicUrlJsonPoll(baseUrl: String, topic: String, since: String) = "${topicUrl(baseUrl, topic)}/json?poll=1&since=$since"
fun topicShortUrl(baseUrl: String, topic: String) = shortUrl(topicUrl(baseUrl, topic))
fun subscriptionTopicShortUrl(subscription: Subscription) : String {
return topicShortUrl(subscription.baseUrl, subscription.topic)
}
fun displayName(appBaseUrl: String?, subscription: Subscription) : String {
if (subscription.displayName != null) {
return subscription.displayName
} else if (appBaseUrl == subscription.baseUrl) {
return subscription.topic
}
return subscriptionTopicShortUrl(subscription)
}
fun shortUrl(url: String) = url
.replace("http://", "")
.replace("https://", "")
fun extractBaseUrl(url: String): String {
val httpUrl = url.toHttpUrlOrNull() ?: return ""
val schemeAndHost = "${httpUrl.scheme}://${httpUrl.host}"
val maybePort = if (httpUrl.port != 80 && httpUrl.port != 443) ":${httpUrl.port}" else ""
return schemeAndHost + maybePort
}
fun splitTopicUrl(topicUrl: String): Pair<String, String> {
if (topicUrl.lastIndexOf("/") == -1) throw Exception("Invalid argument $topicUrl")
return Pair(topicUrl.substringBeforeLast("/"), topicUrl.substringAfterLast("/"))
}
fun maybeSplitTopicUrl(topicUrl: String): Pair<String, String>? {
return try {
splitTopicUrl(topicUrl)
} catch (_: Exception) {
null
}
}
fun validTopic(topic: String): Boolean {
return "[-_A-Za-z0-9]{1,64}".toRegex().matches(topic) // Must match server side!
}
fun validUrl(url: String): Boolean {
return "^https?://\\S+".toRegex().matches(url)
}
fun formatDateShort(timestampSecs: Long): String {
val date = Date(timestampSecs*1000)
return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(date)
}
fun toPriority(priority: Int?): Int {
return if (priority != null && ALL_PRIORITIES.contains(priority)) priority else PRIORITY_DEFAULT
}
fun toPriorityString(context: Context, priority: Int): String {
return when (priority) {
PRIORITY_MIN -> context.getString(R.string.settings_notifications_priority_min)
PRIORITY_LOW -> context.getString(R.string.settings_notifications_priority_low)
PRIORITY_DEFAULT -> context.getString(R.string.settings_notifications_priority_default)
PRIORITY_HIGH -> context.getString(R.string.settings_notifications_priority_high)
PRIORITY_MAX -> context.getString(R.string.settings_notifications_priority_max)
else -> context.getString(R.string.settings_notifications_priority_default)
}
}
fun joinTags(tags: List<String>?): String {
return tags?.joinToString(",") ?: ""
}
fun joinTagsMap(tags: List<String>?): String {
return tags?.mapIndexed { i, tag -> "${i+1}=${tag}" }?.joinToString(",") ?: ""
}
fun splitTags(tags: String?): List<String> {
return if (tags == null || tags == "") {
emptyList()
} else {
tags.split(",")
}
}
fun toEmojis(tags: List<String>): List<String> {
return tags.mapNotNull { tag -> toEmoji(tag) }
}
fun toEmoji(tag: String): String? {
// EmojiManager removed - no emoji support
return null
}
fun unmatchedTags(tags: List<String>): List<String> {
// All tags are unmatched without EmojiManager
return tags
}
/**
* Prepend tags/emojis to message, but only if there is a non-empty title.
* Otherwise, the tags will be prepended to the title.
*/
fun formatMessage(notification: Notification): String {
return if (notification.title != "") {
decodeMessage(notification)
} else {
val emojis = toEmojis(splitTags(notification.tags))
if (emojis.isEmpty()) {
decodeMessage(notification)
} else {
emojis.joinToString("") + " " + decodeMessage(notification)
}
}
}
fun decodeMessage(notification: Notification): String {
return notification.message
}
fun decodeBytesMessage(notification: Notification): ByteArray {
return notification.message.toByteArray()
}
/**
* See above; prepend emojis to title if the title is non-empty.
* Otherwise, they are prepended to the message.
*/
fun formatTitle(appBaseUrl: String?, subscription: Subscription, notification: Notification): String {
return if (notification.title != "") {
formatTitle(notification)
} else {
displayName(appBaseUrl, subscription)
}
}
fun formatTitle(notification: Notification): String {
val emojis = toEmojis(splitTags(notification.tags))
return if (emojis.isEmpty()) {
notification.title
} else {
emojis.joinToString("") + " " + notification.title
}
}
// Queries the filename of a content URI
fun fileName(context: Context, contentUri: String?, fallbackName: String): String {
return try {
val info = fileStat(context, contentUri?.toUri())
info.filename
} catch (_: Exception) {
fallbackName
}
}
fun fileStat(context: Context, contentUri: Uri?): FileInfo {
if (contentUri == null) {
throw FileNotFoundException("URI is null")
}
val resolver = context.applicationContext.contentResolver
val cursor = resolver.query(contentUri, null, null, null, null) ?: throw Exception("Query returned null")
return cursor.use { c ->
val nameIndex = c.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME)
val sizeIndex = c.getColumnIndexOrThrow(OpenableColumns.SIZE)
if (!c.moveToFirst()) {
throw FileNotFoundException("Not found: $contentUri")
}
val size = c.getLong(sizeIndex)
if (size == 0L) {
// Content provider URIs (e.g. content://io.heckel.ntfy.provider/cache_files/DQ4o7DitZAmw) return an entry, even
// when they do not exist, but with an empty size. This is a practical/fast way to weed out non-existing files.
throw FileNotFoundException("Not found or empty: $contentUri")
}
FileInfo(
filename = c.getString(nameIndex),
size = c.getLong(sizeIndex)
)
}
}
fun maybeFileStat(context: Context, contentUri: String?): FileInfo? {
return try {
fileStat(context, contentUri?.toUri()) // Throws if the file does not exist
} catch (_: Exception) {
null
}
}
data class FileInfo(
val filename: String,
val size: Long,
)
// Generates a (cryptographically secure) random string of a certain length
fun randomString(len: Int): String {
val random = SecureRandom()
val chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray()
return (1..len).map { chars[random.nextInt(chars.size)] }.joinToString("")
}
// Generates a random, positive subscription ID between 0-10M. This ensures that it doesn't have issues
// when exported to JSON. It uses SecureRandom, because Random causes issues in the emulator (generating the
// same value again and again), sometimes.
fun randomSubscriptionId(): Long {
return SecureRandom().nextLong().absoluteValue % 100_000_000
}
// Allows letting multiple variables at once, see https://stackoverflow.com/a/35522422/1440785
inline fun <T1: Any, T2: Any, R: Any> safeLet(p1: T1?, p2: T2?, block: (T1, T2)->R?): R? {
return if (p1 != null && p2 != null) block(p1, p2) else null
}
fun formatBytes(bytes: Long, decimals: Int = 1): String {
val absB = if (bytes == Long.MIN_VALUE) Long.MAX_VALUE else abs(bytes)
if (absB < 1024) {
return "$bytes B"
}
var value = absB
val ci = StringCharacterIterator("KMGTPE")
var i = 40
while (i >= 0 && absB > 0xfffccccccccccccL shr i) {
value = value shr 10
ci.next()
i -= 10
}
value *= java.lang.Long.signum(bytes).toLong()
return java.lang.String.format("%.${decimals}f %cB", value / 1024.0, ci.current())
}
fun mimeTypeToIconResource(mimeType: String?): Int {
return if (mimeType?.startsWith("image/") == true) {
R.drawable.ic_file_image_red_24dp
} else if (mimeType?.startsWith("video/") == true) {
R.drawable.ic_file_video_orange_24dp
} else if (mimeType?.startsWith("audio/") == true) {
R.drawable.ic_file_audio_purple_24dp
} else if (mimeType == ANDROID_APP_MIME_TYPE) {
R.drawable.ic_file_app_gray_24dp
} else {
R.drawable.ic_file_document_blue_24dp
}
}
// Check if battery optimization is enabled, see https://stackoverflow.com/a/49098293/1440785
fun isIgnoringBatteryOptimizations(context: Context): Boolean {
val powerManager = context.applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager
val appName = context.applicationContext.packageName
return powerManager.isIgnoringBatteryOptimizations(appName)
}
// Returns true if dark mode is on, see https://stackoverflow.com/a/60761189/1440785
fun Context.systemDarkThemeOn(): Boolean {
return resources.configuration.uiMode and
Configuration.UI_MODE_NIGHT_MASK == UI_MODE_NIGHT_YES
}
fun isDarkThemeOn(context: Context): Boolean {
val darkMode = Repository.getInstance(context).getDarkMode()
if (darkMode == AppCompatDelegate.MODE_NIGHT_YES) {
return true
}
if (darkMode == AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM && context.systemDarkThemeOn()) {
return true
}
return false
}
// https://cketti.de/2020/05/23/content-uris-and-okhttp/
class ContentUriRequestBody(
private val resolver: ContentResolver,
private val uri: Uri,
private val size: Long
) : RequestBody() {
override fun contentLength(): Long {
return size
}
override fun contentType(): MediaType? {
val contentType = resolver.getType(uri)
return contentType?.toMediaTypeOrNull()
}
override fun writeTo(sink: BufferedSink) {
val inputStream = resolver.openInputStream(uri) ?: throw IOException("Couldn't open content URI for reading")
inputStream.source().use { source ->
sink.writeAll(source)
}
}
}
// TODO: make this work in Android 34+
// Hack: Make end icon for drop down smaller, see https://stackoverflow.com/a/57098715/1440785
fun View.makeEndIconSmaller(resources: Resources) {
// val dimension = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30f, resources.displayMetrics)
// val endIconImageView = findViewById<ImageView>(R.id.text_input_end_icon)
// endIconImageView.minimumHeight = dimension.toInt()
// endIconImageView.minimumWidth = dimension.toInt()
// requestLayout()
}
// Shows the ripple effect on the view, if it is ripple-able, see https://stackoverflow.com/a/56314062/1440785
fun View.showRipple() {
if (background is RippleDrawable) {
background.state = intArrayOf(android.R.attr.state_pressed, android.R.attr.state_enabled)
}
}
// Hides the ripple effect on the view, if it is ripple-able, see https://stackoverflow.com/a/56314062/1440785
fun View.hideRipple() {
if (background is RippleDrawable) {
background.state = intArrayOf()
}
}
// Toggles the ripple effect on the view, if it is ripple-able
fun View.ripple(scope: CoroutineScope) {
showRipple()
scope.launch(Dispatchers.Main) {
delay(200)
hideRipple()
}
}
fun Uri.readBitmapFromUri(context: Context): Bitmap {
val resolver = context.applicationContext.contentResolver
val bitmapStream = resolver.openInputStream(this)
val bitmap = BitmapFactory.decodeStream(bitmapStream)
if (bitmap.byteCount > 100 * 1024 * 1024) {
// If the Bitmap is too large to be rendered (100 MB), it will throw a RuntimeException downstream.
// This workaround throws a catchable exception instead. See issue #474. From https://stackoverflow.com/a/53334563/1440785
throw Exception("Bitmap too large to draw on Canvas (${bitmap.byteCount} bytes)")
}
return bitmap
}
fun String.readBitmapFromUri(context: Context): Bitmap {
return this.toUri().readBitmapFromUri(context)
}
fun String.readBitmapFromUriOrNull(context: Context): Bitmap? {
return try {
this.readBitmapFromUri(context)
} catch (_: Exception) {
null
}
}
// TextWatcher that only implements the afterTextChanged method
class AfterChangedTextWatcher(val afterTextChangedFn: (s: Editable?) -> Unit) : TextWatcher {
override fun afterTextChanged(s: Editable?) {
afterTextChangedFn(s)
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
// Nothing
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
// Nothing
}
}
fun ensureSafeNewFile(dir: File, name: String): File {
val safeName = name.replace("[^-_.()\\w]+".toRegex(), "_");
val file = File(dir, safeName)
if (!file.exists()) {
return file
}
(1..1000).forEach { i ->
val newFile = File(dir, if (file.extension == "") {
"${file.nameWithoutExtension} ($i)"
} else {
"${file.nameWithoutExtension} ($i).${file.extension}"
})
if (!newFile.exists()) {
return newFile
}
}
throw Exception("Cannot find safe file")
}
fun copyToClipboard(context: Context, label: String, message: String) {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText(label, message)
clipboard.setPrimaryClip(clip)
// https://developer.android.com/develop/ui/views/touch-and-input/copy-paste#duplicate-notifications
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2) {
val copied = context.getString(R.string.common_copied_to_clipboard)
Toast.makeText(context, copied, Toast.LENGTH_LONG).show()
}
}
fun String.sha256(): String {
val md = MessageDigest.getInstance("SHA-256")
val digest = md.digest(this.toByteArray())
return digest.fold("") { str, it -> str + "%02x".format(it) }
}
fun Button.dangerButton() {
setTextAppearance(R.style.DangerText)
}
fun Long.nullIfZero(): Long? {
return if (this == 0L) return null else this
}

View file

@ -0,0 +1,76 @@
package com.lonecloud.sup.work
import android.content.Context
import androidx.core.content.FileProvider
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.lonecloud.sup.BuildConfig
import com.lonecloud.sup.db.Repository
import com.lonecloud.sup.util.Log
import com.lonecloud.sup.util.maybeFileStat
import com.lonecloud.sup.util.topicShortUrl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import androidx.core.net.toUri
/**
* Deletes notifications marked for deletion and attachments for deleted notifications.
*/
class DeleteWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) {
// IMPORTANT:
// Every time the worker is changed, the periodic work has to be REPLACEd.
// This is facilitated in the MainActivity using the VERSION below.
init {
Log.init(ctx) // Init in all entrypoints
}
override suspend fun doWork(): Result {
return withContext(Dispatchers.IO) {
try {
deleteExpiredNotifications()
} catch (e: Exception) {
Log.w(TAG, "Failed to delete expired notifications", e)
}
return@withContext Result.success()
}
}
private suspend fun deleteExpiredNotifications() {
Log.d(TAG, "Deleting expired notifications")
val repository = Repository.getInstance(applicationContext)
val subscriptions = repository.getSubscriptions()
subscriptions.forEach { subscription ->
val logId = topicShortUrl(subscription.baseUrl, subscription.topic)
val deleteAfterSeconds = if (subscription.autoDelete == Repository.AUTO_DELETE_USE_GLOBAL) {
repository.getAutoDeleteSeconds()
} else {
subscription.autoDelete
}
if (deleteAfterSeconds == Repository.AUTO_DELETE_NEVER) {
Log.d(TAG, "[$logId] Not deleting any notifications; global setting set to NEVER")
return@forEach
}
// Mark as deleted
val markDeletedOlderThanTimestamp = (System.currentTimeMillis()/1000) - deleteAfterSeconds
Log.d(TAG, "[$logId] Marking notifications older than $markDeletedOlderThanTimestamp as deleted")
repository.markAsDeletedIfOlderThan(subscription.id, markDeletedOlderThanTimestamp)
// Hard delete
val deleteOlderThanTimestamp = (System.currentTimeMillis()/1000) - HARD_DELETE_AFTER_SECONDS
Log.d(TAG, "[$logId] Hard deleting notifications older than $markDeletedOlderThanTimestamp")
repository.removeNotificationsIfOlderThan(subscription.id, deleteOlderThanTimestamp)
}
}
companion object {
const val VERSION = BuildConfig.VERSION_CODE
const val TAG = "NtfyDeleteWorker"
const val WORK_NAME_PERIODIC_ALL = "NtfyDeleteWorkerPeriodic" // Do not change
private const val ONE_DAY_SECONDS = 24 * 60 * 60L
const val HARD_DELETE_AFTER_SECONDS = 4 * 30 * ONE_DAY_SECONDS // 4 months
}
}

View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:interpolator/decelerate_cubic">
<translate
android:duration="300"
android:fromYDelta="100%"
android:toYDelta="0" />
</set>

View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:interpolator/accelerate_cubic">
<translate
android:duration="250"
android:fromYDelta="0"
android:toYDelta="100%" />
</set>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#000000"
android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M20,2L4,2c-1.1,0 -2,0.9 -2,2v18l4,-4h14c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2zM20,16L5.17,16L4,17.17L4,4h16v12zM11,5h2v6h-2zM11,13h2v2h-2z"
android:fillColor="#FF9800"/>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M15.67,4L14,4L14,2h-4v2L8.33,4C7.6,4 7,4.6 7,5.33v15.33C7,21.4 7.6,22 8.33,22h7.33c0.74,0 1.34,-0.6 1.34,-1.33L17,5.33C17,4.6 16.4,4 15.67,4zM13,18h-2v-2h2v2zM13,14h-2L11,9h2v5z"
android:fillColor="#F44336"/>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M11,21h-1l1,-7H7.5c-0.88,0 -0.33,-0.75 -0.31,-0.78C8.48,10.94 10.42,7.54 13.01,3h1l-1,7h3.51c0.4,0 0.62,0.19 0.4,0.66C12.97,17.55 11,21 11,21z"
android:fillColor="#555555"/>
</vector>

View file

@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:tint="?colorControlNormal"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12.5449,2.1992 L12.3145,2.6035C9.7352,7.1246 7.809,10.5009 6.5176,12.7832c0.0118,-0.0179 -0.0053,0.0121 -0.0254,0.043 -0.024,0.0369 -0.055,0.0842 -0.0879,0.1445 -0.0657,0.1206 -0.1489,0.2813 -0.1875,0.5273 -0.0386,0.2461 0.0075,0.6682 0.2988,0.9551 0.2913,0.2869 0.6507,0.3477 0.9844,0.3477h2.5781l-1,7h2.3867l0.2305,-0.4043c0,0 1.9682,-3.4483 5.918,-10.3379l0.0176,-0.0293L17.6445,11C17.8155,10.6348 17.9095,10.1065 17.5996,9.6816 17.2897,9.2568 16.8462,9.1992 16.5195,9.1992h-2.5859l0.998,-7zM12.959,4.707 L12.0879,10.8008h3.8301c-3.0779,5.37 -4.4616,7.7886 -4.8691,8.502l0.873,-6.1035L8.123,13.1992C9.238,11.2305 10.9448,8.2378 12.959,4.707Z"
android:fillColor="#FFFFFF"/>
</vector>

View file

@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:tint="?colorControlNormal"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M11,21h-1l1,-7H7.5c-0.88,0 -0.33,-0.75 -0.31,-0.78C8.48,10.94 10.42,7.54 13.01,3h1l-1,7h3.51c0.4,0 0.62,0.19 0.4,0.66C12.97,17.55 11,21 11,21z"
android:fillColor="@android:color/white"/>
</vector>

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2019 The Android Open Source Project
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:height="24dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0"
android:width="24dp"
tools:ignore="NewApi">
<path
android:fillColor="#888888"
android:pathData="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"/>
</vector>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<solid android:color="#338574" />
</shape>

View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M19,6.41L17.59,5 12,10.59 6.41,5 5,6.41 10.59,12 5,17.59 6.41,19 12,13.41 17.59,19 19,17.59 13.41,12z"/>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M16,1L4,1c-1.1,0 -2,0.9 -2,2v14h2L4,3h12L16,1zM19,5L8,5c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h11c1.1,0 2,-0.9 2,-2L21,7c0,-1.1 -0.9,-2 -2,-2zM19,21L8,21L8,7h11v14z"
android:fillColor="@android:color/white"/>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M3,17.25V21h3.75L17.81,9.94l-3.75,-3.75L3,17.25zM20.71,7.04c0.39,-0.39 0.39,-1.02 0,-1.41l-2.34,-2.34c-0.39,-0.39 -1.02,-0.39 -1.41,0l-1.83,1.83 3.75,3.75 1.83,-1.83z"
android:fillColor="#FFFFFF"/>
</vector>

View file

@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="20dp"
android:height="20dp"
android:viewportWidth="20"
android:viewportHeight="20"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M4,6v10c0,1.1 0.9,2 2,2h8c1.1,0 2,-0.9 2,-2L16,6L4,6zM17,3h-3l-1,-1L7,2L6,3L3,3v2h14L17,3z"/>
</vector>

View file

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2019 The Android Open Source Project
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:height="24dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0"
android:width="24dp"
tools:ignore="NewApi">
<path
android:fillColor="#888888"
android:pathData="M7 10l5 5 5-5z"/>
</vector>

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2019 The Android Open Source Project
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:height="24dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0"
android:width="24dp"
tools:ignore="NewApi">
<path
android:fillColor="#888888"
android:pathData="M7 14l5-5 5 5z"/>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM13,17h-2v-2h2v2zM13,13h-2L11,7h2v6z"
android:fillColor="#F44336"/>
</vector>

View file

@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12,8l-6,6 1.41,1.41L12,10.83l4.59,4.58L18,14z"
android:fillColor="#808080"/>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M17.6,9.48l1.84,-3.18c0.16,-0.31 0.04,-0.69 -0.26,-0.85c-0.29,-0.15 -0.65,-0.06 -0.83,0.22l-1.88,3.24c-2.86,-1.21 -6.08,-1.21 -8.94,0L5.65,5.67c-0.19,-0.29 -0.58,-0.38 -0.87,-0.2C4.5,5.65 4.41,6.01 4.56,6.3L6.4,9.48C3.3,11.25 1.28,14.44 1,18h22C22.72,14.44 20.7,11.25 17.6,9.48zM7,15.25c-0.69,0 -1.25,-0.56 -1.25,-1.25c0,-0.69 0.56,-1.25 1.25,-1.25S8.25,13.31 8.25,14C8.25,14.69 7.69,15.25 7,15.25zM17,15.25c-0.69,0 -1.25,-0.56 -1.25,-1.25c0,-0.69 0.56,-1.25 1.25,-1.25s1.25,0.56 1.25,1.25C18.25,14.69 17.69,15.25 17,15.25z"
android:fillColor="#555555"/>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12,3l0.01,10.55c-0.59,-0.34 -1.27,-0.55 -2,-0.55C7.79,13 6,14.79 6,17s1.79,4 4.01,4S14,19.21 14,17L14,7h4L18,3h-6zM10.01,19c-1.1,0 -2,-0.9 -2,-2s0.9,-2 2,-2 2,0.9 2,2 -0.9,2 -2,2z"
android:fillColor="#B300FF"/>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M8,16h8v2L8,18zM8,12h8v2L8,14zM14,2L6,2c-1.1,0 -2,0.9 -2,2v16c0,1.1 0.89,2 1.99,2L18,22c1.1,0 2,-0.9 2,-2L20,8l-6,-6zM18,20L6,20L6,4h7v5h5v11z"
android:fillColor="#00ADFF"/>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M19,5v14L5,19L5,5h14m0,-2L5,3c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2L21,5c0,-1.1 -0.9,-2 -2,-2zM14.14,11.86l-3,3.87L9,13.14 6,17h12l-3.86,-5.14z"
android:fillColor="#E30000"/>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M4,6.47L5.76,10H20v8H4V6.47M22,4h-4l2,4h-3l-2,-4h-2l2,4h-3l-2,-4H8l2,4H7L5,4H4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2V4z"
android:fillColor="#FF9800"/>
</vector>

View file

@ -0,0 +1,31 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="50dp"
android:height="50dp"
android:viewportWidth="50"
android:viewportHeight="50">
<path
android:pathData="m7.8399,6.35c-3.58,0 -6.6469,2.817 -6.6469,6.3983v0.003l0.0351,27.8668 -0.8991,6.6347 12.2261,-3.248L42.9487,44.0049c3.58,0 6.6469,-2.8208 6.6469,-6.4022v-24.8545c0,-3.5803 -3.0652,-6.3967 -6.6438,-6.3983h-0.0031zM7.8399,10.8662h35.1088,0.0031c1.2579,0.0013 2.1277,0.9164 2.1277,1.8821v24.8544c0,0.9666 -0.8714,1.8821 -2.1307,1.8821L11.8924,39.4849l-6.2114,1.8768 0.0633,-0.366 -0.0343,-28.2473c0,-0.9665 0.8706,-1.8821 2.13,-1.8821z"
android:strokeWidth="0.754022"
android:fillColor="#FFFFFFFF"
android:strokeColor="#00000000"/>
<path
android:pathData="m11.5278,32.0849l0,-3.346l7.0363,-3.721q0.3397,-0.1732 0.6551,-0.2596 0.3397,-0.1153 0.6066,-0.1732 0.2912,-0.0288 0.5823,-0.0576l0,-0.2308q-0.2912,-0.0288 -0.5823,-0.1153 -0.2669,-0.0576 -0.6066,-0.1443 -0.3154,-0.1153 -0.6551,-0.2884l-7.0363,-3.721l0,-3.3749l10.8699,5.9132l0,3.6056z"
android:strokeWidth="0.525121"
android:fillColor="#FFFFFFFF"
android:strokeColor="#00000000"/>
<path
android:pathData="m10.9661,15.6112l0,4.8516l7.3742,3.9002c0.0157,0.0077 0.0305,0.0128 0.0461,0.0204 -0.0157,0.0077 -0.0305,0.0128 -0.0461,0.0204l-7.3742,3.9002l0,4.8267l0.7961,-0.4333 11.1995,-6.0969l0,-4.463zM12.0931,17.6933 L21.8346,22.9981l0,2.7446l-9.7414,5.2999l0,-1.8679l6.6912,-3.5416 0.0084,-0.0051c0.1961,-0.0992 0.3826,-0.1724 0.5531,-0.2191l0.0127,0l0.0167,-0.0051c0.2034,-0.0691 0.3777,-0.1209 0.5279,-0.1545l1.0684,-0.1046l0,-1.4644l-0.5154,-0.0497c-0.1632,-0.0153 -0.3288,-0.0505 -0.4944,-0.0997l-0.0167,-0.0051 -0.0167,-0.0051c-0.1632,-0.0352 -0.3552,-0.0811 -0.5656,-0.1344 -0.1802,-0.0668 -0.3706,-0.1479 -0.5698,-0.2492l-0.0084,-0.0051 -6.6912,-3.5416z"
android:strokeWidth="0.525121"
android:fillColor="#FFFFFFFF"
android:strokeColor="#00000000"/>
<path
android:pathData="m26.7503,30.9206l11.6118,0l0,3.1388L26.7503,34.0594Z"
android:strokeWidth="0.525121"
android:fillColor="#FFFFFFFF"
android:strokeColor="#00000000"/>
<path
android:pathData="m26.1875,30.2775l0,0.6427 0,3.7845l12.7371,0l0,-4.4272zM27.3113,31.563l10.4896,0l0,1.8515l-10.4896,0z"
android:strokeWidth="0.525121"
android:fillColor="#FFFFFFFF"
android:strokeColor="#00000000"/>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M6,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM18,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM12,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2z"
android:fillColor="#555555"/>
</vector>

View file

@ -0,0 +1,31 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="50dp"
android:height="50dp"
android:viewportWidth="50"
android:viewportHeight="50">
<path
android:pathData="m7.8399,6.35c-3.58,0 -6.6469,2.817 -6.6469,6.3983v0.003l0.0351,27.8668 -0.8991,6.6347 12.2261,-3.248L42.9487,44.0049c3.58,0 6.6469,-2.8208 6.6469,-6.4022v-24.8545c0,-3.5803 -3.0652,-6.3967 -6.6438,-6.3983h-0.0031zM7.8399,10.8662h35.1088,0.0031c1.2579,0.0013 2.1277,0.9164 2.1277,1.8821v24.8544c0,0.9666 -0.8714,1.8821 -2.1307,1.8821L11.8924,39.4849l-6.2114,1.8768 0.0633,-0.366 -0.0343,-28.2473c0,-0.9665 0.8706,-1.8821 2.13,-1.8821z"
android:strokeWidth="0.754022"
android:fillColor="#FFFFFFFF"
android:strokeColor="#00000000"/>
<path
android:pathData="m11.5278,32.0849l0,-3.346l7.0363,-3.721q0.3397,-0.1732 0.6551,-0.2596 0.3397,-0.1153 0.6066,-0.1732 0.2912,-0.0288 0.5823,-0.0576l0,-0.2308q-0.2912,-0.0288 -0.5823,-0.1153 -0.2669,-0.0576 -0.6066,-0.1443 -0.3154,-0.1153 -0.6551,-0.2884l-7.0363,-3.721l0,-3.3749l10.8699,5.9132l0,3.6056z"
android:strokeWidth="0.525121"
android:fillColor="#FFFFFFFF"
android:strokeColor="#00000000"/>
<path
android:pathData="m10.9661,15.6112l0,4.8516l7.3742,3.9002c0.0157,0.0077 0.0305,0.0128 0.0461,0.0204 -0.0157,0.0077 -0.0305,0.0128 -0.0461,0.0204l-7.3742,3.9002l0,4.8267l0.7961,-0.4333 11.1995,-6.0969l0,-4.463zM12.0931,17.6933 L21.8346,22.9981l0,2.7446l-9.7414,5.2999l0,-1.8679l6.6912,-3.5416 0.0084,-0.0051c0.1961,-0.0992 0.3826,-0.1724 0.5531,-0.2191l0.0127,0l0.0167,-0.0051c0.2034,-0.0691 0.3777,-0.1209 0.5279,-0.1545l1.0684,-0.1046l0,-1.4644l-0.5154,-0.0497c-0.1632,-0.0153 -0.3288,-0.0505 -0.4944,-0.0997l-0.0167,-0.0051 -0.0167,-0.0051c-0.1632,-0.0352 -0.3552,-0.0811 -0.5656,-0.1344 -0.1802,-0.0668 -0.3706,-0.1479 -0.5698,-0.2492l-0.0084,-0.0051 -6.6912,-3.5416z"
android:strokeWidth="0.525121"
android:fillColor="#FFFFFFFF"
android:strokeColor="#00000000"/>
<path
android:pathData="m26.7503,30.9206l11.6118,0l0,3.1388L26.7503,34.0594Z"
android:strokeWidth="0.525121"
android:fillColor="#FFFFFFFF"
android:strokeColor="#00000000"/>
<path
android:pathData="m26.1875,30.2775l0,0.6427 0,3.7845l12.7371,0l0,-4.4272zM27.3113,31.563l10.4896,0l0,1.8515l-10.4896,0z"
android:strokeWidth="0.525121"
android:fillColor="#FFFFFFFF"
android:strokeColor="#00000000"/>
</vector>

View file

@ -0,0 +1,12 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12,2.5C11.17,2.5 10.5,3.17 10.5,4L10.5,4.6797C9.556,4.9041 8.749,5.3367 8.0859,5.9219L9.5273,7.3672C10.1748,6.8243 11.0077,6.5 12,6.5C14.49,6.5 16,8.52 16,11L16,13.8555L18,15.8613L18,11C18,7.93 16.37,5.3597 13.5,4.6797L13.5,4C13.5,3.17 12.83,2.5 12,2.5zM6.7715,7.6289C6.2688,8.6106 6,9.762 6,11L6,16L4,18L4,19L18.1172,19L16,16.8789L16,17L8,17L8,11C8,10.3476 8.1073,9.7283 8.3066,9.168L6.7715,7.6289zM10,20C10,21.1 10.9,22 12,22C13.1,22 14,21.1 14,20L10,20z"
android:fillColor="#555555"/>
<path
android:pathData="M3.543,3.3965 L2.0313,4.9043 19.5234,22.4395 21.0352,20.9316Z"
android:fillColor="#555555"/>
</vector>

View file

@ -0,0 +1,15 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12,2.5C11.17,2.5 10.5,3.17 10.5,4L10.5,4.6797C9.556,4.9041 8.749,5.3367 8.0859,5.9219L9.5273,7.3672C10.1748,6.8243 11.0077,6.5 12,6.5C14.1766,6.5 15.6028,8.0429 15.9277,10.0879A6.6092,6.6092 0,0 1,16.502 10.0371A6.6092,6.6092 0,0 1,17.9609 10.2031C17.7024,7.4927 16.1179,5.2999 13.5,4.6797L13.5,4C13.5,3.17 12.83,2.5 12,2.5zM3.543,3.3965L2.0313,4.9043L6.2266,9.1094C6.0793,9.7072 6,10.3404 6,11L6,16L4,18L4,19L10.334,19A6.6092,6.6092 0,0 1,9.9238 17L8,17L8,11C8,10.9637 8.0032,10.9287 8.0039,10.8926L10.6738,13.5684A6.6092,6.6092 0,0 1,11.9824 11.8555L3.543,3.3965z"
android:fillColor="#555555"/>
<path
android:pathData="m16.8553,10.7743c-3.3109,0 -6.002,2.6955 -6.002,6.0059 0,3.3104 2.6911,6.0078 6.002,6.0078 3.316,0 6.0117,-2.6969 6.0117,-6.0078 0,-3.3109 -2.6957,-6.0059 -6.0117,-6.0059zM16.8592,12.7861c2.2124,0 3.9941,1.7818 3.9941,3.9941 0,2.2124 -1.7818,3.9941 -3.9941,3.9941 -2.2124,0 -3.9941,-1.7818 -3.9941,-3.9941 0,-2.2124 1.7818,-3.9941 3.9941,-3.9941z"
android:fillColor="#555555"/>
<path
android:pathData="m15.6308,13.426v4.041l3.5195,2.1113 0.8887,-1.4551 -2.6719,-1.5859v-3.1113h-0.4512z"
android:fillColor="#555555"/>
</vector>

View file

@ -0,0 +1,16 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:tint="?attr/colorControlNormal"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12,2.5C11.17,2.5 10.5,3.17 10.5,4L10.5,4.6797C9.556,4.9041 8.749,5.3367 8.0859,5.9219L9.5273,7.3672C10.1748,6.8243 11.0077,6.5 12,6.5C14.1766,6.5 15.6028,8.0429 15.9277,10.0879A6.6092,6.6092 0,0 1,16.502 10.0371A6.6092,6.6092 0,0 1,17.9609 10.2031C17.7024,7.4927 16.1179,5.2999 13.5,4.6797L13.5,4C13.5,3.17 12.83,2.5 12,2.5zM3.543,3.3965L2.0313,4.9043L6.2266,9.1094C6.0793,9.7072 6,10.3404 6,11L6,16L4,18L4,19L10.334,19A6.6092,6.6092 0,0 1,9.9238 17L8,17L8,11C8,10.9637 8.0032,10.9287 8.0039,10.8926L10.6738,13.5684A6.6092,6.6092 0,0 1,11.9824 11.8555L3.543,3.3965z"
android:fillColor="#FFFFFF"/>
<path
android:pathData="m16.8553,10.7743c-3.3109,0 -6.002,2.6955 -6.002,6.0059 0,3.3104 2.6911,6.0078 6.002,6.0078 3.316,0 6.0117,-2.6969 6.0117,-6.0078 0,-3.3109 -2.6957,-6.0059 -6.0117,-6.0059zM16.8592,12.7861c2.2124,0 3.9941,1.7818 3.9941,3.9941 0,2.2124 -1.7818,3.9941 -3.9941,3.9941 -2.2124,0 -3.9941,-1.7818 -3.9941,-3.9941 0,-2.2124 1.7818,-3.9941 3.9941,-3.9941z"
android:fillColor="#FFFFFF"/>
<path
android:pathData="m15.6308,13.426v4.041l3.5195,2.1113 0.8887,-1.4551 -2.6719,-1.5859v-3.1113h-0.4512z"
android:fillColor="#FFFFFF"/>
</vector>

View file

@ -0,0 +1,13 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:tint="?attr/colorControlNormal"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12,2.5C11.17,2.5 10.5,3.17 10.5,4L10.5,4.6797C9.556,4.9041 8.749,5.3367 8.0859,5.9219L9.5273,7.3672C10.1748,6.8243 11.0077,6.5 12,6.5C14.49,6.5 16,8.52 16,11L16,13.8555L18,15.8613L18,11C18,7.93 16.37,5.3597 13.5,4.6797L13.5,4C13.5,3.17 12.83,2.5 12,2.5zM6.7715,7.6289C6.2688,8.6106 6,9.762 6,11L6,16L4,18L4,19L18.1172,19L16,16.8789L16,17L8,17L8,11C8,10.3476 8.1073,9.7283 8.3066,9.168L6.7715,7.6289zM10,20C10,21.1 10.9,22 12,22C13.1,22 14,21.1 14,20L10,20z"
android:fillColor="#FFFFFF"/>
<path
android:pathData="M3.543,3.3965 L2.0313,4.9043 19.5234,22.4395 21.0352,20.9316Z"
android:fillColor="#FFFFFF"/>
</vector>

View file

@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:tint="?attr/colorControlNormal"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.89,2 2,2zM18,16v-5c0,-3.07 -1.64,-5.64 -4.5,-6.32L13.5,4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68C7.63,5.36 6,7.92 6,11v5l-2,2v1h16v-1l-2,-2z"
android:fillColor="#FFFFFF"/>
</vector>

View file

@ -0,0 +1,26 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="m12.195,20.8283a1.2747,1.2747 0,0 0,0.6616 -0.1852l6.6466,-4.0372a1.2746,1.2746 0,0 0,0.4275 -1.7511,1.2746 1.2746,0 0,0 -1.7509,-0.4277l-5.9848,3.6353 -5.9848,-3.6353a1.2746,1.2746 0,0 0,-1.7509 0.4277,1.2746 1.2746,0 0,0 0.4275,1.7511l6.6464,4.0372a1.2747,1.2747 0,0 0,0.6618 0.1852z"
android:strokeLineJoin="round"
android:strokeWidth="0.0919748"
android:fillColor="#999999"
android:strokeLineCap="round"/>
<path
android:pathData="m12.195,15.694a1.2747,1.2747 0,0 0,0.6616 -0.1852l6.6466,-4.0372A1.2746,1.2746 0,0 0,19.9307 9.7205,1.2746 1.2746,0 0,0 18.1798,9.2928L12.195,12.9281 6.2102,9.2928a1.2746,1.2746 0,0 0,-1.7509 0.4277,1.2746 1.2746,0 0,0 0.4275,1.7511l6.6464,4.0372a1.2747,1.2747 0,0 0,0.6618 0.1852z"
android:strokeLineJoin="round"
android:strokeWidth="0.0919748"
android:fillColor="#b3b3b3"
android:strokeColor="#00000000"
android:strokeLineCap="round"/>
<path
android:pathData="m12.1168,10.4268a1.2747,1.2747 0,0 0,0.6616 -0.1852l6.6466,-4.0372a1.2746,1.2746 0,0 0,0.4275 -1.7511,1.2746 1.2746,0 0,0 -1.7509,-0.4277l-5.9848,3.6353 -5.9848,-3.6353a1.2746,1.2746 0,0 0,-1.7509 0.4277,1.2746 1.2746,0 0,0 0.4275,1.7511L11.455,10.2416a1.2747,1.2747 0,0 0,0.6618 0.1852z"
android:strokeLineJoin="round"
android:strokeWidth="0.0919748"
android:fillColor="#cccccc"
android:strokeColor="#00000000"
android:strokeLineCap="round"/>
</vector>

View file

@ -0,0 +1,19 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="m12.1727,17.7744a1.2747,1.2747 0,0 0,0.6616 -0.1852l6.6466,-4.0372a1.2746,1.2746 0,0 0,0.4275 -1.7511,1.2746 1.2746,0 0,0 -1.7509,-0.4277L12.1727,15.0085 6.1879,11.3731a1.2746,1.2746 0,0 0,-1.7509 0.4277,1.2746 1.2746,0 0,0 0.4275,1.7511l6.6464,4.0372a1.2747,1.2747 0,0 0,0.6618 0.1852z"
android:strokeLineJoin="round"
android:strokeWidth="0.0919748"
android:fillColor="#999999"
android:strokeLineCap="round"/>
<path
android:pathData="m12.1727,12.64a1.2747,1.2747 0,0 0,0.6616 -0.1852L19.4809,8.4177A1.2746,1.2746 0,0 0,19.9084 6.6666,1.2746 1.2746,0 0,0 18.1575,6.2388L12.1727,9.8742 6.1879,6.2388a1.2746,1.2746 0,0 0,-1.7509 0.4277,1.2746 1.2746,0 0,0 0.4275,1.7511l6.6464,4.0372a1.2747,1.2747 0,0 0,0.6618 0.1852z"
android:strokeLineJoin="round"
android:strokeWidth="0.0919748"
android:fillColor="#b3b3b3"
android:strokeColor="#00000000"
android:strokeLineCap="round"/>
</vector>

View file

@ -0,0 +1,13 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M4,10h16v1.5H4z"
android:fillColor="#2196F3"/>
<path
android:pathData="M4,13h16v1.5H4z"
android:fillColor="#2196F3"/>
</vector>

View file

@ -0,0 +1,20 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12.1168,6.5394A1.2747,1.2747 0,0 0,11.4552 6.7246l-6.6466,4.0372a1.2746,1.2746 0,0 0,-0.4275 1.7511,1.2746 1.2746,0 0,0 1.7509,0.4277l5.9848,-3.6353 5.9848,3.6353A1.2746,1.2746 0,0 0,19.8525 12.5129,1.2746 1.2746,0 0,0 19.425,10.7618L12.7786,6.7246A1.2747,1.2747 0,0 0,12.1168 6.5394Z"
android:strokeLineJoin="round"
android:strokeWidth="0.0919748"
android:fillColor="#c60000"
android:strokeColor="#00000000"
android:strokeLineCap="round"/>
<path
android:pathData="m12.195,11.8067a1.2747,1.2747 0,0 0,-0.6616 0.1852l-6.6466,4.0372a1.2746,1.2746 0,0 0,-0.4275 1.7511,1.2746 1.2746,0 0,0 1.7509,0.4277l5.9848,-3.6353 5.9848,3.6353a1.2746,1.2746 0,0 0,1.7509 -0.4277,1.2746 1.2746,0 0,0 -0.4275,-1.7511l-6.6464,-4.0372a1.2747,1.2747 0,0 0,-0.6618 -0.1852z"
android:strokeLineJoin="round"
android:strokeWidth="0.0919748"
android:fillColor="#de0000"
android:strokeColor="#00000000"
android:strokeLineCap="round"/>
</vector>

View file

@ -0,0 +1,26 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M12.1168,3.4051A1.2747,1.2747 0,0 0,11.4552 3.5903L4.8086,7.6275A1.2746,1.2746 0,0 0,4.381 9.3786,1.2746 1.2746,0 0,0 6.132,9.8063L12.1168,6.171 18.1016,9.8063A1.2746,1.2746 0,0 0,19.8525 9.3786,1.2746 1.2746,0 0,0 19.425,7.6275L12.7786,3.5903A1.2747,1.2747 0,0 0,12.1168 3.4051Z"
android:strokeLineJoin="round"
android:strokeWidth="0.0919748"
android:fillColor="#aa0000"
android:strokeLineCap="round"/>
<path
android:pathData="M12.1168,8.5394A1.2747,1.2747 0,0 0,11.4552 8.7246l-6.6466,4.0372a1.2746,1.2746 0,0 0,-0.4275 1.7511,1.2746 1.2746,0 0,0 1.7509,0.4277l5.9848,-3.6353 5.9848,3.6353A1.2746,1.2746 0,0 0,19.8525 14.5129,1.2746 1.2746,0 0,0 19.425,12.7618L12.7786,8.7246A1.2747,1.2747 0,0 0,12.1168 8.5394Z"
android:strokeLineJoin="round"
android:strokeWidth="0.0919748"
android:fillColor="#c60000"
android:strokeColor="#00000000"
android:strokeLineCap="round"/>
<path
android:pathData="m12.195,13.8067a1.2747,1.2747 0,0 0,-0.6616 0.1852l-6.6466,4.0372a1.2746,1.2746 0,0 0,-0.4275 1.7511,1.2746 1.2746,0 0,0 1.7509,0.4277l5.9848,-3.6353 5.9848,3.6353a1.2746,1.2746 0,0 0,1.7509 -0.4277,1.2746 1.2746,0 0,0 -0.4275,-1.7511l-6.6464,-4.0372a1.2747,1.2747 0,0 0,-0.6618 -0.1852z"
android:strokeLineJoin="round"
android:strokeWidth="0.0919748"
android:fillColor="#de0000"
android:strokeColor="#00000000"
android:strokeLineCap="round"/>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M4.01,6.03l7.51,3.22 -7.52,-1 0.01,-2.22m7.5,8.72L4,17.97v-2.22l7.51,-1M2.01,3L2,10l15,2 -15,2 0.01,7L23,12 2.01,3z"
android:fillColor="#FFFFFF"/>
</vector>

View file

@ -0,0 +1,18 @@
<vector android:height="24dp" android:viewportHeight="50"
android:viewportWidth="50" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#888888"
android:pathData="m7.8399,6.35c-3.58,0 -6.6469,2.817 -6.6469,6.3983v0.003l0.0351,27.8668 -0.8991,6.6347 12.2261,-3.248L42.9487,44.0049c3.58,0 6.6469,-2.8208 6.6469,-6.4022v-24.8545c0,-3.5803 -3.0652,-6.3967 -6.6438,-6.3983h-0.0031zM7.8399,10.8662h35.1088,0.0031c1.2579,0.0013 2.1277,0.9164 2.1277,1.8821v24.8544c0,0.9666 -0.8714,1.8821 -2.1307,1.8821L11.8924,39.4849l-6.2114,1.8768 0.0633,-0.366 -0.0343,-28.2473c0,-0.9665 0.8706,-1.8821 2.13,-1.8821z"
android:strokeColor="#00000000" android:strokeWidth="0.754022"/>
<path android:fillColor="#888888"
android:pathData="m11.5278,32.0849l0,-3.346l7.0363,-3.721q0.3397,-0.1732 0.6551,-0.2596 0.3397,-0.1153 0.6066,-0.1732 0.2912,-0.0288 0.5823,-0.0576l0,-0.2308q-0.2912,-0.0288 -0.5823,-0.1153 -0.2669,-0.0576 -0.6066,-0.1443 -0.3154,-0.1153 -0.6551,-0.2884l-7.0363,-3.721l0,-3.3749l10.8699,5.9132l0,3.6056z"
android:strokeColor="#00000000" android:strokeWidth="0.525121"/>
<path android:fillColor="#888888"
android:pathData="m10.9661,15.6112l0,4.8516l7.3742,3.9002c0.0157,0.0077 0.0305,0.0128 0.0461,0.0204 -0.0157,0.0077 -0.0305,0.0128 -0.0461,0.0204l-7.3742,3.9002l0,4.8267l0.7961,-0.4333 11.1995,-6.0969l0,-4.463zM12.0931,17.6933 L21.8346,22.9981l0,2.7446l-9.7414,5.2999l0,-1.8679l6.6912,-3.5416 0.0084,-0.0051c0.1961,-0.0992 0.3826,-0.1724 0.5531,-0.2191l0.0127,0l0.0167,-0.0051c0.2034,-0.0691 0.3777,-0.1209 0.5279,-0.1545l1.0684,-0.1046l0,-1.4644l-0.5154,-0.0497c-0.1632,-0.0153 -0.3288,-0.0505 -0.4944,-0.0997l-0.0167,-0.0051 -0.0167,-0.0051c-0.1632,-0.0352 -0.3552,-0.0811 -0.5656,-0.1344 -0.1802,-0.0668 -0.3706,-0.1479 -0.5698,-0.2492l-0.0084,-0.0051 -6.6912,-3.5416z"
android:strokeColor="#00000000" android:strokeWidth="0.525121"/>
<path android:fillColor="#888888"
android:pathData="m26.7503,30.9206l11.6118,0l0,3.1388L26.7503,34.0594Z"
android:strokeColor="#00000000" android:strokeWidth="0.525121"/>
<path android:fillColor="#888888"
android:pathData="m26.1875,30.2775l0,0.6427 0,3.7845l12.7371,0l0,-4.4272zM27.3113,31.563l10.4896,0l0,1.8515l-10.4896,0z"
android:strokeColor="#00000000" android:strokeWidth="0.525121"/>
</vector>

View file

@ -0,0 +1,18 @@
<vector android:height="48dp" android:viewportHeight="50"
android:viewportWidth="50" android:width="48dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#888888"
android:pathData="m7.8399,6.35c-3.58,0 -6.6469,2.817 -6.6469,6.3983v0.003l0.0351,27.8668 -0.8991,6.6347 12.2261,-3.248L42.9487,44.0049c3.58,0 6.6469,-2.8208 6.6469,-6.4022v-24.8545c0,-3.5803 -3.0652,-6.3967 -6.6438,-6.3983h-0.0031zM7.8399,10.8662h35.1088,0.0031c1.2579,0.0013 2.1277,0.9164 2.1277,1.8821v24.8544c0,0.9666 -0.8714,1.8821 -2.1307,1.8821L11.8924,39.4849l-6.2114,1.8768 0.0633,-0.366 -0.0343,-28.2473c0,-0.9665 0.8706,-1.8821 2.13,-1.8821z"
android:strokeColor="#00000000" android:strokeWidth="0.754022"/>
<path android:fillColor="#888888"
android:pathData="m11.5278,32.0849l0,-3.346l7.0363,-3.721q0.3397,-0.1732 0.6551,-0.2596 0.3397,-0.1153 0.6066,-0.1732 0.2912,-0.0288 0.5823,-0.0576l0,-0.2308q-0.2912,-0.0288 -0.5823,-0.1153 -0.2669,-0.0576 -0.6066,-0.1443 -0.3154,-0.1153 -0.6551,-0.2884l-7.0363,-3.721l0,-3.3749l10.8699,5.9132l0,3.6056z"
android:strokeColor="#00000000" android:strokeWidth="0.525121"/>
<path android:fillColor="#888888"
android:pathData="m10.9661,15.6112l0,4.8516l7.3742,3.9002c0.0157,0.0077 0.0305,0.0128 0.0461,0.0204 -0.0157,0.0077 -0.0305,0.0128 -0.0461,0.0204l-7.3742,3.9002l0,4.8267l0.7961,-0.4333 11.1995,-6.0969l0,-4.463zM12.0931,17.6933 L21.8346,22.9981l0,2.7446l-9.7414,5.2999l0,-1.8679l6.6912,-3.5416 0.0084,-0.0051c0.1961,-0.0992 0.3826,-0.1724 0.5531,-0.2191l0.0127,0l0.0167,-0.0051c0.2034,-0.0691 0.3777,-0.1209 0.5279,-0.1545l1.0684,-0.1046l0,-1.4644l-0.5154,-0.0497c-0.1632,-0.0153 -0.3288,-0.0505 -0.4944,-0.0997l-0.0167,-0.0051 -0.0167,-0.0051c-0.1632,-0.0352 -0.3552,-0.0811 -0.5656,-0.1344 -0.1802,-0.0668 -0.3706,-0.1479 -0.5698,-0.2492l-0.0084,-0.0051 -6.6912,-3.5416z"
android:strokeColor="#00000000" android:strokeWidth="0.525121"/>
<path android:fillColor="#888888"
android:pathData="m26.7503,30.9206l11.6118,0l0,3.1388L26.7503,34.0594Z"
android:strokeColor="#00000000" android:strokeWidth="0.525121"/>
<path android:fillColor="#888888"
android:pathData="m26.1875,30.2775l0,0.6427 0,3.7845l12.7371,0l0,-4.4272zM27.3113,31.563l10.4896,0l0,1.8515l-10.4896,0z"
android:strokeColor="#00000000" android:strokeWidth="0.525121"/>
</vector>

View file

@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FF8C00"
android:pathData="M1,21h22L12,2 1,21zM13,18h-2v-2h2v2zM13,14h-2v-4h2v4z"/>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFF"
android:pathData="M1,21h22L12,2 1,21zM13,18h-2v-2h2v2zM13,14h-2v-4h2v4z"/>
</vector>

View file

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".ui.DetailActivity"
>
<include
android:id="@+id/app_bar_drawer"
layout="@layout/app_bar_drawer"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/detail_content_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/detail_activity_background"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
style="@style/CardViewBackground"
android:id="@+id/detail_notification_list_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:visibility="gone"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@id/detail_message_bar"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/detail_notification_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:clipToPadding="false"
android:background="?android:attr/selectableItemBackground"
app:layoutManager="LinearLayoutManager"/>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/detail_no_notifications"
app:layout_constraintBottom_toTopOf="@id/detail_message_bar"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content" app:srcCompat="@drawable/ic_sms_gray_48dp"
android:id="@+id/detail_no_notifications_image"/>
<TextView
android:id="@+id/detail_no_notifications_text"
android:text="@string/detail_no_notifications_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="@style/TextAppearance.AppCompat.Medium"
android:padding="10dp" android:gravity="center_horizontal"
android:paddingStart="50dp" android:paddingEnd="50dp"/>
<TextView
android:text="@string/detail_how_to_intro"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/detail_how_to_intro"
android:layout_marginTop="20dp"
android:layout_marginStart="50dp"
android:layout_marginEnd="50dp"/>
<TextView
android:text="@string/detail_how_to_example"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/detail_how_to_example"
android:layout_marginTop="7dp"
android:layout_marginStart="50dp"
android:layout_marginEnd="50dp"/>
<TextView
android:text="@string/detail_how_to_link"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/detail_how_to_link"
android:layout_marginTop="7dp"
android:layout_marginStart="50dp"
android:layout_marginEnd="50dp"
android:linksClickable="true"
android:autoLink="web"/>
</LinearLayout>
<include
android:id="@+id/detail_message_bar"
layout="@layout/view_message_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/detail_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="24dp"
android:contentDescription="@string/detail_fab_publish_description"
android:src="@drawable/ic_create_white_24dp"
android:visibility="gone"
app:layout_anchor="@id/detail_content_layout"
app:layout_anchorGravity="bottom|end"
style="@style/FloatingActionButton"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View file

@ -1,93 +1,309 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="24dp">
android:fitsSystemWindows="true">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginBottom="32dp" />
<include
android:id="@+id/app_bar_drawer"
layout="@layout/app_bar_drawer"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/server_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Server URL"
app:layout_constraintTop_toBottomOf="@id/title"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginTop="24dp" />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="16dp"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<EditText
android:id="@+id/server_url"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="https://your-server.com"
android:inputType="textUri"
app:layout_constraintTop_toBottomOf="@id/server_label"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="8dp" />
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/BannerCardStyle"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="@+id/main_banner_battery"
android:visibility="visible"
>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/main_banner_battery_constraint" android:elevation="5dp">
<TextView
android:id="@+id/api_key_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="API Key (optional)"
app:layout_constraintTop_toBottomOf="@id/server_url"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginTop="24dp" />
<ImageView
android:layout_width="28dp"
android:layout_height="28dp" app:srcCompat="@drawable/ic_battery_alert_red_24dp"
android:id="@+id/main_banner_battery_image"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/main_banner_battery_text"
app:layout_constraintEnd_toStartOf="@id/main_banner_battery_text"
app:layout_constraintBottom_toBottomOf="@+id/main_banner_battery_text"
android:layout_marginStart="15dp"/>
<TextView
android:id="@+id/main_banner_battery_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/main_banner_battery_text"
android:textAppearance="@style/TextAppearance.AppCompat.Small"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginEnd="15dp" android:layout_marginTop="15dp"
app:layout_constraintStart_toEndOf="@+id/main_banner_battery_image"
android:layout_marginStart="10dp"/>
<EditText
android:id="@+id/api_key"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="your-api-key"
android:inputType="textPassword"
app:layout_constraintTop_toBottomOf="@id/api_key_label"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="8dp" />
<androidx.constraintlayout.helper.widget.Flow
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:constraint_referenced_ids="main_banner_battery_ask_later,main_banner_battery_dontaskagain,main_banner_battery_fix_now"
app:layout_constraintTop_toBottomOf="@id/main_banner_battery_text"
app:flow_horizontalAlign="end"
app:flow_wrapMode="chain"
app:flow_horizontalStyle="packed"
android:layout_marginEnd="15dp"
android:id="@+id/main_banner_battery_flow"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="15dp"
app:flow_horizontalBias="1"
app:flow_verticalGap="0dp" app:flow_horizontalGap="0dp"/>
<Button
android:id="@+id/save_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Save Settings"
app:layout_constraintTop_toBottomOf="@id/api_key"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="32dp" />
<com.google.android.material.button.MaterialButton
android:id="@+id/main_banner_battery_ask_later"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/main_banner_battery_button_remind_later"
tools:layout_editor_absoluteX="15dp" tools:layout_editor_absoluteY="67dp"/>
<Button
android:id="@+id/enable_listener_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Enable Notification Access"
app:layout_constraintTop_toBottomOf="@id/save_button"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="16dp" />
<com.google.android.material.button.MaterialButton
android:id="@+id/main_banner_battery_dontaskagain"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/main_banner_battery_button_dismiss"
tools:layout_editor_absoluteX="142dp" tools:layout_editor_absoluteY="71dp"/>
<com.google.android.material.button.MaterialButton
android:id="@+id/main_banner_battery_fix_now"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/main_banner_battery_button_fix_now"
tools:layout_editor_absoluteX="269dp" tools:layout_editor_absoluteY="67dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>
<TextView
android:id="@+id/info"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/info_text"
android:textSize="12sp"
android:alpha="0.7"
app:layout_constraintTop_toBottomOf="@id/enable_listener_button"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="32dp" />
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/BannerCardStyle"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/main_banner_battery"
android:id="@+id/main_banner_websocket" android:visibility="visible">
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/main_banner_websocket_constraint" android:elevation="5dp">
<ImageView
android:layout_width="28dp"
android:layout_height="28dp" app:srcCompat="@drawable/ic_announcement_orange_24dp"
android:id="@+id/main_banner_websocket_image"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/main_banner_websocket_text"
app:layout_constraintEnd_toStartOf="@id/main_banner_websocket_text"
app:layout_constraintBottom_toBottomOf="@+id/main_banner_websocket_text"
android:layout_marginStart="15dp"/>
<TextView
android:id="@+id/main_banner_websocket_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/main_banner_websocket_text"
android:textAppearance="@style/TextAppearance.AppCompat.Small"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginEnd="15dp" android:layout_marginTop="15dp"
app:layout_constraintStart_toEndOf="@+id/main_banner_websocket_image"
android:layout_marginStart="10dp"
/>
<androidx.constraintlayout.helper.widget.Flow
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:constraint_referenced_ids="main_banner_websocket_remind_later,main_banner_websocket_dontaskagain,main_banner_websocket_enable" app:layout_constraintTop_toBottomOf="@id/main_banner_websocket_text" app:flow_horizontalAlign="end" app:flow_wrapMode="chain" app:flow_horizontalStyle="packed" android:layout_marginEnd="15dp" android:id="@+id/flow" app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="15dp" app:flow_horizontalBias="1"
app:flow_verticalGap="0dp" app:flow_horizontalGap="0dp"/>
<com.google.android.material.button.MaterialButton
android:id="@+id/main_banner_websocket_remind_later"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/main_banner_websocket_button_remind_later"
tools:layout_editor_absoluteX="86dp" tools:layout_editor_absoluteY="83dp"/>
<com.google.android.material.button.MaterialButton
android:id="@+id/main_banner_websocket_dontaskagain"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/main_banner_websocket_button_dismiss"
tools:layout_editor_absoluteX="260dp" tools:layout_editor_absoluteY="83dp"/>
<com.google.android.material.button.MaterialButton
android:id="@+id/main_banner_websocket_enable"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/main_banner_websocket_button_enable_now"
tools:layout_editor_absoluteX="253dp" tools:layout_editor_absoluteY="131dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/BannerCardStyle"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/main_banner_websocket"
android:id="@+id/main_banner_websocket_reconnect" android:visibility="visible">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/main_banner_websocket_reconnect_constraint" android:elevation="5dp">
<ImageView
android:layout_width="28dp"
android:layout_height="28dp" app:srcCompat="@drawable/ic_announcement_orange_24dp"
android:id="@+id/main_banner_websocket_reconnect_image"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/main_banner_websocket_reconnect_text"
app:layout_constraintEnd_toStartOf="@id/main_banner_websocket_reconnect_text"
app:layout_constraintBottom_toBottomOf="@+id/main_banner_websocket_reconnect_text"
android:layout_marginStart="15dp"/>
<TextView
android:id="@+id/main_banner_websocket_reconnect_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/main_banner_websocket_reconnect_text"
android:textAppearance="@style/TextAppearance.AppCompat.Small"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginEnd="15dp" android:layout_marginTop="15dp"
app:layout_constraintStart_toEndOf="@+id/main_banner_websocket_reconnect_image"
android:layout_marginStart="10dp"
/>
<androidx.constraintlayout.helper.widget.Flow
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:constraint_referenced_ids="main_banner_websocket_reconnect_remind_later,main_banner_websocket_reconnect_dontaskagain,main_banner_websocket_reconnect_enable" app:layout_constraintTop_toBottomOf="@id/main_banner_websocket_reconnect_text" app:flow_horizontalAlign="end" app:flow_wrapMode="chain" app:flow_horizontalStyle="packed" android:layout_marginEnd="15dp" android:id="@+id/flow_reconnect" app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="15dp" app:flow_horizontalBias="1"
app:flow_verticalGap="0dp" app:flow_horizontalGap="0dp"/>
<com.google.android.material.button.MaterialButton
android:id="@+id/main_banner_websocket_reconnect_remind_later"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/main_banner_websocket_reconnect_button_remind_later"
tools:layout_editor_absoluteX="86dp" tools:layout_editor_absoluteY="83dp"/>
<com.google.android.material.button.MaterialButton
android:id="@+id/main_banner_websocket_reconnect_dontaskagain"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/main_banner_websocket_reconnect_button_dismiss"
tools:layout_editor_absoluteX="260dp" tools:layout_editor_absoluteY="83dp"/>
<com.google.android.material.button.MaterialButton
android:id="@+id/main_banner_websocket_reconnect_enable"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/main_banner_websocket_reconnect_button_enable_now"
tools:layout_editor_absoluteX="253dp" tools:layout_editor_absoluteY="131dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/main_subscriptions_list_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:visibility="visible"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@id/main_banner_websocket_reconnect">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/main_subscriptions_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:clipToPadding="false"
android:background="?android:attr/selectableItemBackground"
app:layoutManager="LinearLayoutManager"/>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toTopOf="@+id/fab" app:layout_constraintStart_toStartOf="parent"
android:id="@+id/main_no_subscriptions" android:visibility="gone">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content" app:srcCompat="@drawable/ic_sms_gray_48dp"
android:id="@+id/main_no_subscriptions_image"/>
<TextView
android:id="@+id/main_no_subscriptions_text"
android:text="@string/main_no_subscriptions_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="@style/TextAppearance.AppCompat.Medium"
android:padding="10dp" android:gravity="center_horizontal"
android:paddingStart="50dp" android:paddingEnd="50dp"/>
<TextView
android:text="@string/main_how_to_intro"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/main_how_to_intro"
android:layout_marginTop="20dp"
android:layout_marginStart="50dp"
android:layout_marginEnd="50dp"/>
<TextView
android:text="@string/main_how_to_link"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/main_how_to_link"
android:layout_marginTop="7dp"
android:layout_marginStart="50dp"
android:layout_marginEnd="50dp"
android:linksClickable="true"
android:autoLink="web"/>
</LinearLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="24dp"
android:contentDescription="@string/main_add_button_description"
android:src="@drawable/ic_add_black_24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
style="@style/FloatingActionButton"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.appbar.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:fitsSystemWindows="true"
app:liftOnScroll="false">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize" />
</com.google.android.material.appbar.AppBarLayout>

View file

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.button.MaterialButton
xmlns:android="http://schemas.android.com/apk/res/android"
style="?attr/borderlessButtonStyle"
android:id="@+id/button"
android:text="Button"
android:layout_margin="0dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="0dp"
android:minHeight="0dp"
android:insetBottom="0dp"
android:insetTop="0dp"
android:insetLeft="0dp"
android:insetRight="0dp"
android:paddingStart="8dp"
android:paddingEnd="8dp"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:textSize="14sp"
/>

View file

@ -0,0 +1,342 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/colorSurface"
android:fitsSystemWindows="true">
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/add_dialog_app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorSurface"
app:elevation="0dp"
app:liftOnScroll="false">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/add_dialog_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorSurface"
android:paddingStart="0dp"
android:paddingEnd="12dp"
app:navigationIcon="@drawable/ic_close_white_24dp"
app:navigationIconTint="?attr/colorOnSurface"
app:title="@string/add_dialog_title"
app:titleTextColor="?attr/colorOnSurface"
app:menu="@menu/menu_add_dialog" />
</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingHorizontal="?dialogPreferredPadding"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<ScrollView
android:id="@+id/add_dialog_subscribe_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/add_dialog_subscribe_description"
android:text="@string/add_dialog_description_below"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="4dp"
android:paddingEnd="4dp"
android:paddingTop="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_width="24dp"
android:layout_height="24dp"
android:id="@+id/add_dialog_subscribe_progress"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:indeterminate="true"
android:layout_marginTop="16dp"
android:visibility="gone"/>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/add_dialog_subscribe_topic_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/add_dialog_subscribe_description"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="10dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/add_dialog_subscribe_topic_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/add_dialog_topic_name_hint"
android:importantForAutofill="no"
android:maxLines="1"
android:inputType="text"
android:maxLength="64"/>
</com.google.android.material.textfield.TextInputLayout>
<CheckBox
android:id="@+id/add_dialog_subscribe_use_another_server_checkbox"
android:text="@string/add_dialog_use_another_server"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="-3dp"
android:layout_marginTop="-3dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/add_dialog_subscribe_topic_layout"/>
<TextView
android:id="@+id/add_dialog_subscribe_use_another_server_description"
android:text="@string/add_dialog_use_another_server_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-5dp"
android:paddingStart="4dp"
android:paddingEnd="4dp"
android:paddingTop="0dp"
android:visibility="gone"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/add_dialog_subscribe_use_another_server_checkbox" />
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.Dense.ExposedDropdownMenu"
android:id="@+id/add_dialog_subscribe_base_url_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:padding="0dp"
android:visibility="gone"
app:endIconMode="custom"
app:hintEnabled="false"
app:boxBackgroundColor="@null"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/add_dialog_subscribe_use_another_server_description">
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/add_dialog_subscribe_base_url_text"
android:hint="@string/app_base_url"
android:maxLines="1"
android:layout_marginTop="4dp"
android:layout_marginBottom="10dp"
android:inputType="textNoSuggestions"
android:paddingStart="0dp"
android:paddingEnd="0dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:layout_marginStart="4dp"
android:layout_marginEnd="4dp"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</com.google.android.material.textfield.TextInputLayout>
<LinearLayout
android:id="@+id/add_dialog_subscribe_instant_delivery_box"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-3dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/add_dialog_subscribe_base_url_layout">
<CheckBox
android:id="@+id/add_dialog_subscribe_instant_delivery_checkbox"
android:text="@string/add_dialog_instant_delivery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="-8dp"
android:layout_marginBottom="-5dp"
android:layout_marginStart="-3dp"/>
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_marginTop="3dp"
android:paddingTop="3dp"
android:id="@+id/add_dialog_subscribe_instant_image"
app:srcCompat="@drawable/ic_bolt_gray_24dp"
app:layout_constraintTop_toTopOf="@+id/main_item_text"
app:layout_constraintEnd_toStartOf="@+id/main_item_date"/>
</LinearLayout>
<TextView
android:id="@+id/add_dialog_subscribe_instant_delivery_description"
android:text="@string/add_dialog_instant_delivery_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="4dp"
android:paddingEnd="4dp"
android:paddingTop="0dp"
android:visibility="gone"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/add_dialog_subscribe_instant_delivery_box"/>
<TextView
android:id="@+id/add_dialog_subscribe_foreground_description"
android:text="@string/add_dialog_foreground_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="4dp"
android:paddingEnd="4dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/add_dialog_subscribe_instant_delivery_description"/>
<ImageView
android:id="@+id/add_dialog_subscribe_error_text_image"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginTop="1dp"
android:visibility="gone"
app:srcCompat="@drawable/ic_error_red_24dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@id/add_dialog_subscribe_error_text"/>
<TextView
android:id="@+id/add_dialog_subscribe_error_text"
android:text="Unable to resolve host example.com"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:paddingStart="4dp"
android:paddingEnd="4dp"
android:textAppearance="@style/DangerText"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/add_dialog_subscribe_foreground_description"
app:layout_constraintStart_toEndOf="@id/add_dialog_subscribe_error_text_image"
tools:visibility="gone"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/add_dialog_login_view"
android:visibility="gone">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:text="@string/add_dialog_login_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/add_dialog_login_description"
android:paddingStart="4dp"
android:paddingTop="16dp"
android:paddingEnd="4dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_width="25dp"
android:layout_height="25dp"
android:id="@+id/add_dialog_login_progress"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:indeterminate="true"
android:layout_marginTop="16dp"
android:visibility="gone"/>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/add_dialog_login_username_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/add_dialog_login_description"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="10dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/add_dialog_login_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/add_dialog_login_username_hint"
android:importantForAutofill="no"
android:maxLines="1"
android:inputType="text"
android:maxLength="64"/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/add_dialog_login_password_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/add_dialog_login_username_layout"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="10dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/add_dialog_login_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/add_dialog_login_password_hint"
android:importantForAutofill="no"
android:maxLines="1"
android:inputType="textPassword"/>
</com.google.android.material.textfield.TextInputLayout>
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:id="@+id/add_dialog_login_error_text_image"
android:visibility="gone"
app:srcCompat="@drawable/ic_error_red_24dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="@+id/add_dialog_login_error_text"
app:layout_constraintTop_toTopOf="@+id/add_dialog_login_error_text"/>
<TextView
android:id="@+id/add_dialog_login_error_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Login failed. User not authorized."
android:paddingStart="4dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/add_dialog_login_password_layout"
android:paddingEnd="4dp"
android:visibility="gone"
android:textAppearance="@style/DangerText"
app:layout_constraintStart_toEndOf="@id/add_dialog_login_error_text_image"
tools:visibility="visible"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View file

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="?android:attr/textColorAlertDialogListItem"
android:gravity="center_vertical"
android:paddingStart="7dp"
android:paddingEnd="7dp"
android:paddingTop="7dp"
android:paddingBottom="7dp"
android:ellipsize="marquee"
/>

View file

@ -0,0 +1,210 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" style="@style/CardView"
android:id="@+id/detail_item_card"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:layout_marginStart="6dp"
android:layout_marginEnd="6dp"
android:layout_marginBottom="1dp"
android:padding="3dp"
app:cardCornerRadius="3dp"
app:cardElevation="2dp"
app:cardMaxElevation="2dp"
app:cardPreventCornerOverlap="true"
app:cardUseCompatPadding="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/detail_item_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="?android:attr/selectableItemBackground"
android:focusable="true"
android:paddingBottom="6dp" android:paddingTop="6dp" android:paddingEnd="6dp">
<TextView
android:text="Sun, October 31, 2021, 10:43:12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/detail_item_date_text"
android:textAppearance="@style/TextAppearance.AppCompat.Small"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="5dp" app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="12dp"/>
<TextView
android:layout_width="10dp"
android:layout_height="10dp" android:id="@+id/detail_item_new_dot"
android:layout_gravity="center"
android:background="@drawable/ic_circle"
android:gravity="center"
app:layout_constraintTop_toTopOf="@+id/detail_item_date_text"
app:layout_constraintBottom_toBottomOf="@+id/detail_item_date_text"
android:layout_marginTop="1dp"
app:layout_constraintStart_toEndOf="@id/detail_item_priority_image"
android:layout_marginStart="5dp"/>
<ImageButton
android:layout_width="28dp"
android:layout_height="26dp" app:srcCompat="@drawable/ic_more_horiz_gray_24dp"
android:id="@+id/detail_item_menu_button"
app:layout_constraintTop_toTopOf="parent"
android:background="?android:attr/selectableItemBackground" android:paddingTop="-5dp"
app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="3dp"/>
<TextView
android:text="This is a very very very long message. It could be as long as 1024 charaters, which is a lot more than you'd think. No, really so far this message is barely 180 characters long. I can't believe how long 1024 bytes are. This is outrageous. Oh you know what, I think I won't type the whole thing. This seems a little too long for a sample text. Well, anyway, it was nice chatting. So far this message is about 400 bytes long. So maybe just double what you see and that's that."
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/detail_item_message_text"
android:textColor="?android:attr/textColorPrimary"
android:textAppearance="@style/TextAppearance.AppCompat.Medium"
android:autoLink="web|phone|email"
app:layout_constraintTop_toBottomOf="@id/detail_item_title_text"
app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="12dp"
app:layout_constraintBottom_toTopOf="@id/detail_item_attachment_image" app:layout_constraintEnd_toStartOf="@id/detail_item_icon" android:layout_marginEnd="6dp"/>
<TextView
android:text="This is an optional title. It can also be a little longer but not too long."
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/detail_item_title_text"
android:textColor="?android:attr/textColorPrimary"
android:textAppearance="@style/TextAppearance.AppCompat.Medium"
android:autoLink="web"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="12dp" android:textStyle="bold"
app:layout_constraintTop_toBottomOf="@+id/detail_item_date_text" app:layout_constraintEnd_toStartOf="@id/detail_item_icon" android:layout_marginEnd="6dp" tools:layout_constraintEnd_toStartOf="@id/detail_item_icon"/>
<ImageView
android:layout_width="16dp"
android:layout_height="16dp" app:srcCompat="@drawable/ic_priority_5_24dp"
android:id="@+id/detail_item_priority_image"
app:layout_constraintStart_toEndOf="@+id/detail_item_date_text"
app:layout_constraintTop_toTopOf="@+id/detail_item_date_text"
app:layout_constraintBottom_toBottomOf="@+id/detail_item_date_text" android:layout_marginStart="5dp"/>
<com.google.android.material.imageview.ShapeableImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content" app:srcCompat="@drawable/ic_cancel_gray_24dp"
android:id="@+id/detail_item_attachment_image" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@id/detail_item_message_text"
android:layout_marginStart="12dp" android:layout_marginEnd="6dp"
android:scaleType="centerCrop"
android:adjustViewBounds="true" android:maxHeight="150dp" android:layout_marginTop="7dp"
app:shapeAppearanceOverlay="@style/roundedCornersImageView" android:visibility="visible"
android:layout_marginBottom="3dp" app:layout_constraintBottom_toTopOf="@id/detail_item_tags_text"/>
<TextView
android:text="Tags: ssh, zfs"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/detail_item_tags_text"
android:textAppearance="@style/TextAppearance.AppCompat.Small"
app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="12dp"
app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="6dp"
app:layout_constraintTop_toBottomOf="@id/detail_item_attachment_image"
app:layout_constraintBottom_toTopOf="@id/detail_item_attachment_file_box"
app:layout_constraintHorizontal_bias="0.0" android:layout_marginTop="2dp"
/>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" app:layout_constraintTop_toBottomOf="@id/detail_item_tags_text"
android:id="@+id/detail_item_attachment_file_box" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" android:layout_marginStart="12dp" android:layout_marginEnd="6dp"
android:visibility="visible" android:layout_marginTop="2dp"
android:background="?android:attr/selectableItemBackground"
android:clickable="true" android:focusable="true" android:padding="4dp" android:paddingStart="0dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content" app:srcCompat="@drawable/ic_cancel_gray_24dp"
android:id="@+id/detail_item_attachment_file_icon" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toStartOf="@+id/detail_item_attachment_file_info" android:layout_marginEnd="5dp"
app:layout_constraintBottom_toBottomOf="parent"
/>
<TextView
android:text="attachment.jpg\n58 MB, not downloaded, expires 1/2/2022 10:30 PM"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/detail_item_attachment_file_info"
android:textColor="?android:attr/textColorPrimary"
android:textAppearance="@style/TextAppearance.AppCompat.Small"
app:layout_constraintStart_toEndOf="@+id/detail_item_attachment_file_icon"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="@+id/detail_item_attachment_file_icon"
app:layout_constraintBottom_toBottomOf="@+id/detail_item_attachment_file_icon"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/detail_item_attachment_file_box"
android:id="@+id/detail_item_actions_wrapper"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="4dp"
android:visibility="gone"
android:padding="0dp" android:layout_marginStart="4dp" android:layout_marginTop="4dp">
<com.google.android.material.button.MaterialButton
android:text="Bing it"
style="?attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/button2" tools:layout_editor_absoluteY="4dp" tools:layout_editor_absoluteX="171dp" android:textSize="14sp" tools:visibility="visible"/>
<com.google.android.material.button.MaterialButton
android:text="Google it"
style="?attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/button3" tools:visibility="visible" tools:layout_editor_absoluteY="52dp" tools:layout_editor_absoluteX="4dp" android:textSize="14sp"/>
<com.google.android.material.button.MaterialButton
android:text="DuckDuckGo it"
style="?attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/button1" tools:visibility="visible" tools:layout_editor_absoluteY="4dp" tools:layout_editor_absoluteX="4dp" android:textSize="14sp" android:layout_margin="0dp"/>
<androidx.constraintlayout.helper.widget.Flow
android:id="@+id/detail_item_actions_flow"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:flow_wrapMode="chain2"
app:flow_horizontalStyle="packed"
app:flow_verticalBias="0"
app:flow_verticalGap="0dp"
app:flow_verticalStyle="packed"
app:flow_verticalAlign="top"
app:flow_horizontalBias="0"
app:flow_horizontalGap="0dp"
app:flow_horizontalAlign="start"
app:flow_firstHorizontalBias="0"
app:flow_firstVerticalBias="0"
app:flow_firstHorizontalStyle="packed"
app:flow_firstVerticalStyle="packed"
app:flow_maxElementsWrap="3"
android:layout_margin="0dp"
android:padding="0dp"
app:constraint_referenced_ids="button1,button2,button3"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="4dp"
android:id="@+id/detail_item_padding_bottom"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/detail_item_actions_wrapper" app:layout_constraintBottom_toBottomOf="parent"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="0dp"
app:srcCompat="@drawable/ic_notification"
android:id="@+id/detail_item_icon"
android:visibility="visible"
android:maxHeight="40dp"
android:maxWidth="40dp"
android:adjustViewBounds="true"
android:scaleType="fitStart"
android:padding="0dp"
app:layout_constraintTop_toTopOf="@+id/detail_item_date_text"
app:layout_constraintBottom_toBottomOf="@+id/detail_item_message_text"
app:layout_constraintEnd_toStartOf="@id/detail_item_menu_button"
android:layout_marginEnd="6dp"/>
<androidx.constraintlayout.widget.Guideline android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/guideline2" app:layout_constraintGuide_begin="27dp" android:orientation="horizontal"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

View file

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?android:attr/selectableItemBackground"
android:orientation="horizontal" android:clickable="true"
android:focusable="true" android:paddingEnd="18dp"
android:paddingStart="18dp">
<ImageView
android:layout_width="35dp"
android:layout_height="35dp" app:srcCompat="@drawable/ic_sms_gray_24dp"
android:id="@+id/main_item_image" app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginTop="17dp" android:scaleType="fitStart"/>
<TextView
android:text="ntfy.sh/example"
android:layout_width="0dp"
android:layout_height="wrap_content" android:id="@+id/main_item_text"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@+id/main_item_status"
android:layout_marginStart="12dp" app:layout_constraintStart_toEndOf="@+id/main_item_image"
app:layout_constraintVertical_bias="0.0" android:textAppearance="@style/TextAppearance.AppCompat.Medium"
android:textColor="?android:attr/textColorPrimary" android:layout_marginTop="10dp"
app:layout_constraintEnd_toStartOf="@id/main_item_connection_error_image"/>
<TextView
android:text="89 notifications, reconnecting ... This may wrap in the case of UnifiedPush"
android:layout_width="0dp"
android:layout_height="wrap_content" android:id="@+id/main_item_status"
app:layout_constraintStart_toStartOf="@+id/main_item_text"
app:layout_constraintTop_toBottomOf="@+id/main_item_text" app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="10dp" app:layout_constrainedWidth="true"
app:layout_constraintEnd_toStartOf="@id/main_item_new" android:layout_marginEnd="10dp"/>
<ImageView
android:layout_width="20dp"
android:layout_height="24dp" app:srcCompat="@drawable/ic_warning_amber_24dp"
android:id="@+id/main_item_connection_error_image"
app:layout_constraintTop_toTopOf="@+id/main_item_text"
app:layout_constraintEnd_toStartOf="@+id/main_item_notification_disabled_until_image"
android:paddingTop="3dp" android:layout_marginEnd="3dp"
android:visibility="gone"/>
<ImageView
android:layout_width="20dp"
android:layout_height="24dp" app:srcCompat="@drawable/ic_notifications_off_time_gray_outline_24dp"
android:id="@+id/main_item_notification_disabled_until_image"
app:layout_constraintTop_toTopOf="@+id/main_item_text"
app:layout_constraintEnd_toStartOf="@+id/main_item_notification_disabled_forever_image"
android:paddingTop="3dp" android:layout_marginEnd="3dp"/>
<ImageView
android:layout_width="20dp"
android:layout_height="24dp" app:srcCompat="@drawable/ic_notifications_off_gray_outline_24dp"
android:id="@+id/main_item_notification_disabled_forever_image"
app:layout_constraintTop_toTopOf="@+id/main_item_notification_disabled_until_image"
app:layout_constraintEnd_toStartOf="@+id/main_item_instant_image" android:paddingTop="3dp"
android:layout_marginEnd="3dp"/>
<ImageView
android:layout_width="20dp"
android:layout_height="24dp" app:srcCompat="@drawable/ic_bolt_gray_24dp"
android:id="@+id/main_item_instant_image"
app:layout_constraintTop_toTopOf="@+id/main_item_notification_disabled_forever_image"
app:layout_constraintEnd_toStartOf="@+id/main_item_date" android:paddingTop="3dp"/>
<TextView
android:text="10:13"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/main_item_date"
app:layout_constraintTop_toTopOf="@+id/main_item_instant_image"
app:layout_constraintEnd_toEndOf="parent"
android:paddingTop="2dp"/>
<TextView
android:text="99+"
android:layout_width="24dp"
android:layout_height="24dp" android:id="@+id/main_item_new"
android:layout_marginTop="3dp"
android:layout_gravity="center"
android:background="@drawable/ic_circle"
android:gravity="center"
android:textColor="@android:color/white"
app:layout_constraintTop_toBottomOf="@+id/main_item_date"
app:layout_constraintEnd_toEndOf="@+id/main_item_date"
app:layout_constraintStart_toEndOf="@+id/main_item_instant_image"
android:textSize="10sp" android:textStyle="bold"/>
</androidx.constraintlayout.widget.ConstraintLayout>

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:paddingHorizontal="16dp"
android:paddingVertical="12dp"
android:minHeight="48dp">
<ImageView
android:id="@+id/priority_icon"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginEnd="12dp"
android:contentDescription="@null"
app:srcCompat="@drawable/ic_priority_3_24dp"/>
<TextView
android:id="@+id/priority_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="16sp"
android:textColor="?android:attr/textColorPrimary"/>
</LinearLayout>

View file

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/detail_activity_background"
android:paddingStart="8dp"
android:paddingEnd="8dp"
android:paddingTop="6dp"
android:paddingBottom="6dp">
<com.google.android.material.card.MaterialCardView
android:id="@+id/message_bar_card"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:cardCornerRadius="16dp"
app:cardElevation="0dp"
app:strokeWidth="0dp"
app:cardBackgroundColor="?android:attr/colorBackground"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="@id/message_bar_publish_button"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginEnd="6dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical">
<ImageButton
android:id="@+id/message_bar_expand_button"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@drawable/ic_expand_less_gray_24dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/message_bar_expand_button_description"
app:tint="?attr/colorOutline"
android:layout_marginStart="4dp"/>
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/message_bar_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="@string/message_bar_hint"
android:textColorHint="?attr/colorOutline"
android:inputType="textMultiLine|textCapSentences"
android:minHeight="48dp"
android:maxLines="4"
android:background="@null"
android:paddingStart="4dp"
android:paddingEnd="16dp"
android:paddingTop="12dp"
android:paddingBottom="12dp"
android:importantForAutofill="no"/>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/message_bar_publish_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_send_white_24dp"
android:contentDescription="@string/message_bar_publish_button_description"
android:clickable="true"
android:focusable="true"
app:fabSize="mini"
app:fabCustomSize="48dp"
app:maxImageSize="24dp"
app:tint="?attr/colorOnPrimary"
app:backgroundTint="?attr/colorPrimary"
app:rippleColor="#40FFFFFF"
app:elevation="2dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.materialswitch.MaterialSwitch xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/switchWidget"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

View file

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/add_dialog_action_button"
android:title="@string/add_dialog_button_subscribe"
android:enabled="false"
app:showAsAction="always" />
</menu>

Some files were not shown because too many files have changed in this diff Show more