ntfy-android/app/src/main/java/io/heckel/ntfy/ui/MainActivity.kt

712 lines
31 KiB
Kotlin
Raw Normal View History

2021-10-28 16:04:14 +13:00
package io.heckel.ntfy.ui
import android.Manifest
2021-11-04 05:48:13 +13:00
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.app.AlertDialog
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.PackageManager
2021-10-28 16:04:14 +13:00
import android.net.Uri
2022-01-19 10:49:00 +13:00
import android.os.Build
import android.os.Bundle
2022-01-19 10:49:00 +13:00
import android.provider.Settings
2022-06-20 06:19:27 +12:00
import android.text.method.LinkMovementMethod
2022-01-17 18:19:05 +13:00
import android.view.ActionMode
import android.view.Menu
import android.view.MenuItem
import android.view.View
2022-01-19 10:49:00 +13:00
import android.widget.Button
2022-06-20 06:19:27 +12:00
import android.widget.TextView
2021-11-08 07:29:19 +13:00
import android.widget.Toast
import androidx.activity.viewModels
2021-10-26 07:24:44 +13:00
import androidx.appcompat.app.AppCompatActivity
2022-01-20 15:05:41 +13:00
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.app.ActivityCompat
2021-11-04 05:48:13 +13:00
import androidx.core.content.ContextCompat
2021-11-08 07:29:19 +13:00
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
2021-11-15 08:20:30 +13:00
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.work.*
import com.google.android.material.floatingactionbutton.FloatingActionButton
2022-01-20 17:40:03 +13:00
import io.heckel.ntfy.BuildConfig
2021-10-31 13:16:12 +13:00
import io.heckel.ntfy.R
2021-10-30 14:13:58 +13:00
import io.heckel.ntfy.app.Application
2022-01-19 10:49:00 +13:00
import io.heckel.ntfy.db.Repository
2022-01-19 08:28:48 +13:00
import io.heckel.ntfy.db.Subscription
2021-11-25 10:12:51 +13:00
import io.heckel.ntfy.firebase.FirebaseMessenger
2022-01-17 18:19:05 +13:00
import io.heckel.ntfy.msg.ApiService
import io.heckel.ntfy.msg.DownloadManager
import io.heckel.ntfy.msg.DownloadType
2022-01-17 18:19:05 +13:00
import io.heckel.ntfy.msg.NotificationDispatcher
import io.heckel.ntfy.service.SubscriberService
import io.heckel.ntfy.service.SubscriberServiceManager
2022-01-19 10:49:00 +13:00
import io.heckel.ntfy.util.*
import io.heckel.ntfy.work.DeleteWorker
2022-01-17 18:19:05 +13:00
import io.heckel.ntfy.work.PollWorker
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
2021-11-01 08:19:25 +13:00
import java.util.*
import java.util.concurrent.TimeUnit
2021-10-31 13:16:12 +13:00
import kotlin.random.Random
2021-11-23 09:45:43 +13:00
class MainActivity : AppCompatActivity(), ActionMode.Callback, AddFragment.SubscribeListener, NotificationFragment.NotificationSettingsListener {
2021-11-01 08:19:25 +13:00
private val viewModel by viewModels<SubscriptionsViewModel> {
2021-10-30 14:13:58 +13:00
SubscriptionsViewModelFactory((application as Application).repository)
}
2021-11-08 07:29:19 +13:00
private val repository by lazy { (application as Application).repository }
private val api = ApiService()
2021-11-25 10:12:51 +13:00
private val messenger = FirebaseMessenger()
2021-11-23 09:45:43 +13:00
// UI elements
private lateinit var menu: Menu
2021-11-04 05:48:13 +13:00
private lateinit var mainList: RecyclerView
2021-11-15 08:20:30 +13:00
private lateinit var mainListContainer: SwipeRefreshLayout
2021-11-04 05:48:13 +13:00
private lateinit var adapter: MainAdapter
private lateinit var fab: FloatingActionButton
2021-11-23 09:45:43 +13:00
// Other stuff
2021-11-04 05:48:13 +13:00
private var actionMode: ActionMode? = null
private var workManager: WorkManager? = null // Context-dependent
2021-12-30 08:33:17 +13:00
private var dispatcher: NotificationDispatcher? = null // Context-dependent
private var appBaseUrl: String? = null // Context-dependent
2021-10-30 14:13:58 +13:00
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
2021-11-23 09:45:43 +13:00
setContentView(R.layout.activity_main)
Log.init(this) // Init logs in all entry points
Log.d(TAG, "Create $this")
2021-11-08 07:29:19 +13:00
// Dependencies that depend on Context
workManager = WorkManager.getInstance(this)
dispatcher = NotificationDispatcher(this, repository)
appBaseUrl = getString(R.string.app_base_url)
2021-11-08 07:29:19 +13:00
2021-10-29 04:45:34 +13:00
// Action bar
title = getString(R.string.main_action_bar_title)
// Floating action button ("+")
2021-11-04 05:48:13 +13:00
fab = findViewById(R.id.fab)
fab.setOnClickListener {
2021-10-30 14:13:58 +13:00
onSubscribeButtonClick()
}
2021-11-15 10:48:50 +13:00
// Swipe to refresh
mainListContainer = findViewById(R.id.main_subscriptions_list_container)
2021-11-15 08:20:30 +13:00
mainListContainer.setOnRefreshListener { refreshAllSubscriptions() }
mainListContainer.setColorSchemeResources(Colors.refreshProgressIndicator)
2021-11-15 08:20:30 +13:00
2021-11-01 08:19:25 +13:00
// Update main list based on viewModel (& its datasource/livedata)
2021-11-02 03:49:52 +13:00
val noEntries: View = findViewById(R.id.main_no_subscriptions)
2021-11-04 05:48:13 +13:00
val onSubscriptionClick = { s: Subscription -> onSubscriptionItemClick(s) }
val onSubscriptionLongClick = { s: Subscription -> onSubscriptionItemLongClick(s) }
mainList = findViewById(R.id.main_subscriptions_list)
adapter = MainAdapter(repository, onSubscriptionClick, onSubscriptionLongClick)
2021-10-29 04:45:34 +13:00
mainList.adapter = adapter
2021-11-01 08:19:25 +13:00
viewModel.list().observe(this) {
it?.let { subscriptions ->
// Update main list
adapter.submitList(subscriptions as MutableList<Subscription>)
2021-10-29 04:45:34 +13:00
if (it.isEmpty()) {
2021-11-15 08:20:30 +13:00
mainListContainer.visibility = View.GONE
2021-11-02 03:49:52 +13:00
noEntries.visibility = View.VISIBLE
2021-10-29 04:45:34 +13:00
} else {
2021-11-15 08:20:30 +13:00
mainListContainer.visibility = View.VISIBLE
2021-11-02 03:49:52 +13:00
noEntries.visibility = View.GONE
2021-10-29 04:45:34 +13:00
}
// 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)
}
2022-06-20 06:19:27 +12:00
// Update banner + WebSocket banner
showHideBatteryBanner(subscriptions)
2022-06-20 06:19:27 +12:00
showHideWebSocketBanner(subscriptions)
}
2021-10-26 06:45:56 +13:00
}
2022-03-15 10:10:44 +13:00
// Add scrub terms to log (in case it gets exported) // FIXME this should be in Log.getFormatted
repository.getUsersLiveData().observe(this) {
it?.let { users ->
users.forEach { u ->
Log.addScrubTerm(shortUrl(u.baseUrl), Log.TermType.Domain)
Log.addScrubTerm(u.username, Log.TermType.Username)
Log.addScrubTerm(u.password, Log.TermType.Password)
}
}
}
// 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)
}
}
2021-12-30 11:48:06 +13:00
// React to changes in instant delivery setting
viewModel.listIdsWithInstantStatus().observe(this) {
2021-12-31 14:00:08 +13:00
SubscriberServiceManager.refresh(this)
2021-11-14 13:26:37 +13:00
}
2022-01-19 10:49:00 +13:00
// Battery banner
2022-01-19 13:10:34 +13:00
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 {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val intent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)
startActivity(intent)
2022-01-19 10:49:00 +13:00
}
}
2022-06-20 06:19:27 +12:00
// WebSocket banner
val wsBanner = findViewById<View>(R.id.main_banner_websocket) // Banner visibility is toggled in onResume()
val wsText = findViewById<TextView>(R.id.main_banner_websocket_text)
val wsDismissButton = findViewById<Button>(R.id.main_banner_websocket_dontaskagain)
val wsRemindButton = findViewById<Button>(R.id.main_banner_websocket_remind_later)
val wsEnableButton = findViewById<Button>(R.id.main_banner_websocket_enable)
wsText.movementMethod = LinkMovementMethod.getInstance() // Make links clickable
wsDismissButton.setOnClickListener {
wsBanner.visibility = View.GONE
repository.setWebSocketRemindTime(Repository.WEBSOCKET_REMIND_TIME_NEVER)
2022-03-17 15:41:27 +13:00
}
2022-06-20 06:19:27 +12:00
wsRemindButton.setOnClickListener {
wsBanner.visibility = View.GONE
repository.setWebSocketRemindTime(System.currentTimeMillis() + ONE_DAY_MILLIS)
2022-03-17 15:41:27 +13:00
}
2022-06-20 06:19:27 +12:00
wsEnableButton.setOnClickListener {
repository.setConnectionProtocol(Repository.CONNECTION_PROTOCOL_WS)
SubscriberServiceManager(this).restart()
wsBanner.visibility = View.GONE
2022-03-17 15:41:27 +13:00
}
2021-11-30 08:06:08 +13:00
// Create notification channels right away, so we can configure them immediately after installing the app
dispatcher?.init()
2021-11-30 08:06:08 +13:00
2021-12-14 14:54:36 +13:00
// Subscribe to control Firebase channel (so we can re-start the foreground service if it dies)
2021-12-14 15:10:48 +13:00
messenger.subscribe(ApiService.CONTROL_TOPIC)
2021-12-14 14:54:36 +13:00
2022-01-20 15:05:41 +13:00
// Darrkkkk mode
AppCompatDelegate.setDefaultNightMode(repository.getDarkMode())
2021-11-14 13:26:37 +13:00
// Background things
schedulePeriodicPollWorker()
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()
redrawList()
}
2022-01-19 13:10:34 +13:00
private fun showHideBatteryBanner(subscriptions: List<Subscription>) {
val hasInstantSubscriptions = subscriptions.count { it.instant } > 0
2022-01-19 13:10:34 +13:00
val batteryRemindTimeReached = repository.getBatteryOptimizationsRemindTime() < System.currentTimeMillis()
val ignoringOptimizations = isIgnoringBatteryOptimizations(this@MainActivity)
val showBanner = hasInstantSubscriptions && batteryRemindTimeReached && !ignoringOptimizations
2022-01-19 13:10:34 +13:00
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); instant subscriptions = $hasInstantSubscriptions; remind time reached = $batteryRemindTimeReached; banner = $showBanner")
2021-11-14 13:26:37 +13:00
}
2022-06-20 06:19:27 +12:00
private fun showHideWebSocketBanner(subscriptions: List<Subscription>) {
val hasSelfHostedSubscriptions = subscriptions.count { it.baseUrl != appBaseUrl } > 0
2022-03-17 15:41:27 +13:00
val usingWebSockets = repository.getConnectionProtocol() == Repository.CONNECTION_PROTOCOL_WS
2022-06-20 06:19:27 +12:00
val wsRemindTimeReached = repository.getWebSocketRemindTime() < System.currentTimeMillis()
val showBanner = hasSelfHostedSubscriptions && wsRemindTimeReached && !usingWebSockets
val wsBanner = findViewById<View>(R.id.main_banner_websocket)
wsBanner.visibility = if (showBanner) View.VISIBLE else View.GONE
2022-03-17 15:41:27 +13:00
}
private fun schedulePeriodicPollWorker() {
2021-12-14 14:54:36 +13:00
val workerVersion = repository.getPollWorkerVersion()
val workPolicy = if (workerVersion == PollWorker.VERSION) {
Log.d(TAG, "Poll worker version matches: choosing KEEP as existing work policy")
ExistingPeriodicWorkPolicy.KEEP
} else {
Log.d(TAG, "Poll worker version DOES NOT MATCH: choosing REPLACE as existing work policy")
2021-11-23 09:45:43 +13:00
repository.setPollWorkerVersion(PollWorker.VERSION)
ExistingPeriodicWorkPolicy.REPLACE
}
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val work = PeriodicWorkRequestBuilder<PollWorker>(POLL_WORKER_INTERVAL_MINUTES, TimeUnit.MINUTES)
.setConstraints(constraints)
.addTag(PollWorker.TAG)
.addTag(PollWorker.WORK_NAME_PERIODIC_ALL)
.build()
Log.d(TAG, "Poll worker: Scheduling period work every $POLL_WORKER_INTERVAL_MINUTES minutes")
workManager!!.enqueueUniquePeriodicWork(PollWorker.WORK_NAME_PERIODIC_ALL, workPolicy, work)
2021-10-26 14:14:09 +13:00
}
2021-10-26 13:25:54 +13:00
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() {
2021-12-14 14:54:36 +13:00
val workerVersion = repository.getAutoRestartWorkerVersion()
val workPolicy = if (workerVersion == SubscriberService.SERVICE_START_WORKER_VERSION) {
Log.d(TAG, "ServiceStartWorker version matches: choosing KEEP as existing work policy")
2021-12-14 14:54:36 +13:00
ExistingPeriodicWorkPolicy.KEEP
} else {
Log.d(TAG, "ServiceStartWorker version DOES NOT MATCH: choosing REPLACE as existing work policy")
repository.setAutoRestartWorkerVersion(SubscriberService.SERVICE_START_WORKER_VERSION)
2021-12-14 14:54:36 +13:00
ExistingPeriodicWorkPolicy.REPLACE
}
val work = PeriodicWorkRequestBuilder<SubscriberServiceManager.ServiceStartWorker>(SERVICE_START_WORKER_INTERVAL_MINUTES, TimeUnit.MINUTES)
2021-12-14 14:54:36 +13:00
.addTag(SubscriberService.TAG)
.addTag(SubscriberService.SERVICE_START_WORKER_WORK_NAME_PERIODIC)
2021-12-14 14:54:36 +13:00
.build()
Log.d(TAG, "ServiceStartWorker: Scheduling period work every $SERVICE_START_WORKER_INTERVAL_MINUTES minutes")
workManager?.enqueueUniquePeriodicWork(SubscriberService.SERVICE_START_WORKER_WORK_NAME_PERIODIC, workPolicy, work)
2021-12-14 14:54:36 +13:00
}
2021-10-28 16:04:14 +13:00
override fun onCreateOptionsMenu(menu: Menu): Boolean {
2021-11-23 09:45:43 +13:00
menuInflater.inflate(R.menu.menu_main_action_bar, menu)
this.menu = menu
showHideNotificationMenuItems()
checkSubscriptionsMuted() // This is done here, because then we know that we've initialized the menu
2021-10-28 16:04:14 +13:00
return true
}
private fun checkSubscriptionsMuted(delayMillis: Long = 0L) {
2021-11-23 09:45:43 +13:00
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()
}
2021-11-23 09:45:43 +13:00
// 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
2021-11-23 09:45:43 +13:00
}
}
if (rerenderList) {
redrawList()
2021-11-23 09:45:43 +13:00
}
}
}
private fun showHideNotificationMenuItems() {
if (!this::menu.isInitialized) {
return
}
2021-11-23 09:45:43 +13:00
val mutedUntilSeconds = repository.getGlobalMutedUntil()
runOnUiThread {
2022-01-20 17:40:03 +13:00
// Show/hide in-app rate widget
val rateAppItem = menu.findItem(R.id.main_menu_rate)
rateAppItem.isVisible = BuildConfig.RATE_APP_AVAILABLE
// Pause notification icons
2021-11-23 09:45:43 +13:00
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)
}
}
}
2021-10-28 16:04:14 +13:00
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
2021-11-23 09:45:43 +13:00
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
}
2021-12-31 13:34:25 +13:00
R.id.main_menu_settings -> {
startActivity(Intent(this, SettingsActivity::class.java))
true
}
2022-01-20 17:40:03 +13:00
R.id.main_menu_report_bug -> {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.main_menu_report_bug_url))))
true
}
R.id.main_menu_rate -> {
try {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$packageName")))
} catch (e: ActivityNotFoundException) {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$packageName")))
}
2021-10-28 16:04:14 +13:00
true
}
2022-11-27 14:57:37 +13:00
R.id.main_menu_donate -> {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.main_menu_donate_url))))
true
}
2022-01-20 17:40:03 +13:00
R.id.main_menu_docs -> {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.main_menu_docs_url))))
2021-10-28 16:04:14 +13:00
true
}
else -> super.onOptionsItemSelected(item)
}
}
2021-11-23 09:45:43 +13:00
private fun onNotificationSettingsClick(enable: Boolean) {
if (!enable) {
Log.d(TAG, "Showing global notification settings dialog")
val notificationFragment = NotificationFragment()
notificationFragment.show(supportFragmentManager, NotificationFragment.TAG)
} else {
Log.d(TAG, "Re-enabling global notifications")
2022-01-20 15:05:41 +13:00
onNotificationMutedUntilChanged(Repository.MUTED_UNTIL_SHOW_ALL)
2021-11-23 09:45:43 +13:00
}
}
override fun onNotificationMutedUntilChanged(mutedUntilTimestamp: Long) {
repository.setGlobalMutedUntil(mutedUntilTimestamp)
showHideNotificationMenuItems()
runOnUiThread {
redrawList() // Update the "muted until" icons
2021-11-23 09:45:43 +13:00
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()
}
}
}
}
2021-10-30 14:13:58 +13:00
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)")
2021-11-02 02:57:05 +13:00
2021-11-08 07:29:19 +13:00
// Add subscription to database
2021-11-04 05:48:13 +13:00
val subscription = Subscription(
2022-06-20 06:45:01 +12:00
id = randomSubscriptionId(),
2021-11-04 05:48:13 +13:00
baseUrl = baseUrl,
topic = topic,
2021-11-14 13:26:37 +13:00
instant = instant,
dedicatedChannels = false,
2021-11-22 08:54:13 +13:00
mutedUntil = 0,
2022-05-06 08:56:06 +12:00
minPriority = Repository.MIN_PRIORITY_USE_GLOBAL,
autoDelete = Repository.AUTO_DELETE_USE_GLOBAL,
insistent = Repository.INSISTENT_MAX_PRIORITY_USE_GLOBAL,
2022-06-19 13:01:05 +12:00
lastNotificationId = null,
2022-05-07 13:03:15 +12:00
icon = null,
2021-12-31 02:23:47 +13:00
upAppId = null,
upConnectorToken = null,
displayName = null,
totalCount = 0,
newCount = 0,
2021-11-04 05:48:13 +13:00
lastActive = Date().time/1000
)
2021-11-01 08:19:25 +13:00
viewModel.add(subscription)
2021-11-08 07:29:19 +13:00
// Subscribe to Firebase topic if ntfy.sh (even if instant, just to be sure!)
if (baseUrl == appBaseUrl) {
Log.d(TAG, "Subscribing to Firebase topic $topic")
2021-11-25 10:12:51 +13:00
messenger.subscribe(topic)
2021-11-14 13:26:37 +13:00
}
2021-11-06 13:25:02 +13:00
2021-11-08 07:29:19 +13:00
// Fetch cached messages
lifecycleScope.launch(Dispatchers.IO) {
try {
val user = repository.getUser(subscription.baseUrl) // May be null
val notifications = api.poll(subscription.id, subscription.baseUrl, subscription.topic, user)
notifications.forEach { notification ->
repository.addNotification(notification)
if (notification.icon != null) {
DownloadManager.enqueue(this@MainActivity, notification.id, userAction = false, DownloadType.ICON)
}
}
} catch (e: Exception) {
Log.e(TAG, "Unable to fetch notifications: ${e.message}", e)
2021-11-08 07:29:19 +13:00
}
}
2021-11-03 14:43:31 +13:00
2021-11-08 07:29:19 +13:00
// Switch to detail view after adding it
onSubscriptionItemClick(subscription)
}
2021-10-26 13:25:54 +13:00
2021-11-01 08:19:25 +13:00
private fun onSubscriptionItemClick(subscription: Subscription) {
2021-11-04 05:48:13 +13:00
if (actionMode != null) {
handleActionModeClick(subscription)
} else if (subscription.upAppId != null) { // UnifiedPush
2022-07-02 15:30:30 +12:00
startDetailSettingsView(subscription)
2021-11-04 05:48:13 +13:00
} else {
startDetailView(subscription)
}
}
private fun onSubscriptionItemLongClick(subscription: Subscription) {
if (actionMode == null) {
beginActionMode(subscription)
}
}
private fun refreshAllSubscriptions() {
2021-11-11 15:16:00 +13:00
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 ->
2022-06-20 06:45:01 +12:00
Log.d(TAG, "subscription: ${subscription}")
try {
val user = repository.getUser(subscription.baseUrl) // May be null
2022-06-19 13:01:05 +12:00
val notifications = api.poll(subscription.id, subscription.baseUrl, subscription.topic, user, subscription.lastNotificationId)
val newNotifications = repository.onlyNewNotifications(subscription.id, notifications)
newNotifications.forEach { notification ->
newNotificationsCount++
2021-11-23 09:45:43 +13:00
val notificationWithId = notification.copy(notificationId = Random.nextInt())
if (repository.addNotification(notificationWithId)) {
dispatcher?.dispatch(subscription, notificationWithId)
}
2021-11-11 15:16:00 +13:00
}
} catch (e: Exception) {
val topic = displayName(subscription)
if (errorMessage == "") errorMessage = "$topic: ${e.message}"
errors++
2021-11-11 15:16:00 +13:00
}
}
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")
2021-11-11 15:16:00 +13:00
}
}
2021-11-04 05:48:13 +13:00
private fun startDetailView(subscription: Subscription) {
2021-11-02 02:57:05 +13:00
Log.d(TAG, "Entering detail view for subscription $subscription")
2021-11-01 08:19:25 +13:00
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(subscription))
2021-11-14 13:26:37 +13:00
intent.putExtra(EXTRA_SUBSCRIPTION_INSTANT, subscription.instant)
2021-11-23 09:45:43 +13:00
intent.putExtra(EXTRA_SUBSCRIPTION_MUTED_UNTIL, subscription.mutedUntil)
startActivity(intent)
2021-10-27 05:23:41 +13:00
}
2021-10-27 06:46:49 +13:00
2022-07-02 15:30:30 +12:00
private fun startDetailSettingsView(subscription: Subscription) {
Log.d(TAG, "Opening subscription settings for ${topicShortUrl(subscription.baseUrl, subscription.topic)}")
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(subscription))
startActivity(intent)
}
2021-11-04 05:48:13 +13:00
private fun handleActionModeClick(subscription: Subscription) {
adapter.toggleSelection(subscription.id)
if (adapter.selected.size == 0) {
finishActionMode()
} else {
actionMode!!.title = adapter.selected.size.toString()
}
}
override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
this.actionMode = mode
if (mode != null) {
2021-11-23 09:45:43 +13:00
mode.menuInflater.inflate(R.menu.menu_main_action_mode, menu)
2021-11-04 05:48:13 +13:00
mode.title = "1" // One item selected
}
return true
}
override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
return false
}
override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean {
return when (item?.itemId) {
2021-11-04 06:56:08 +13:00
R.id.main_action_mode_delete -> {
2021-11-04 05:48:13 +13:00
onMultiDeleteClick()
true
}
else -> false
}
}
private fun onMultiDeleteClick() {
Log.d(DetailActivity.TAG, "Showing multi-delete dialog for selected items")
val builder = AlertDialog.Builder(this)
val dialog = builder
2021-11-04 05:48:13 +13:00
.setMessage(R.string.main_action_mode_delete_dialog_message)
.setPositiveButton(R.string.main_action_mode_delete_dialog_permanently_delete) { _, _ ->
2021-12-31 02:23:47 +13:00
adapter.selected.map { subscriptionId -> viewModel.remove(this, subscriptionId) }
2021-11-04 05:48:13 +13:00
finishActionMode()
}
.setNegativeButton(R.string.main_action_mode_delete_dialog_cancel) { _, _ ->
finishActionMode()
}
.create()
dialog.setOnShowListener {
dialog
.getButton(AlertDialog.BUTTON_POSITIVE)
2022-12-07 10:17:05 +13:00
.dangerButton(this)
}
dialog.show()
2021-11-04 05:48:13 +13:00
}
override fun onDestroyActionMode(mode: ActionMode?) {
endActionModeAndRedraw()
}
private fun beginActionMode(subscription: Subscription) {
actionMode = startActionMode(this)
adapter.toggleSelection(subscription.id)
2021-11-04 05:48:13 +13:00
// 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
}
})
// Fade status bar color
val fromColor = ContextCompat.getColor(this, Colors.statusBarNormal(this))
val toColor = ContextCompat.getColor(this, Colors.statusBarActionMode(this))
2021-11-04 06:56:08 +13:00
fadeStatusBarColor(window, fromColor, toColor)
2021-11-04 05:48:13 +13:00
}
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
}
})
// Fade status bar color
val fromColor = ContextCompat.getColor(this, Colors.statusBarActionMode(this))
val toColor = ContextCompat.getColor(this, Colors.statusBarNormal(this))
2021-11-04 06:56:08 +13:00
fadeStatusBarColor(window, fromColor, toColor)
2021-11-04 05:48:13 +13:00
}
private fun redrawList() {
if (!this::mainList.isInitialized) {
return
}
adapter.notifyItemRangeChanged(0, adapter.currentList.size)
2021-11-04 05:48:13 +13:00
}
2021-10-30 14:13:58 +13:00
companion object {
const val TAG = "NtfyMainActivity"
2021-11-01 08:19:25 +13:00
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"
2021-11-14 13:26:37 +13:00
const val EXTRA_SUBSCRIPTION_INSTANT = "subscriptionInstant"
2021-11-23 09:45:43 +13:00
const val EXTRA_SUBSCRIPTION_MUTED_UNTIL = "subscriptionMutedUntil"
2021-11-04 05:48:13 +13:00
const val ANIMATION_DURATION = 80L
2022-01-19 10:49:00 +13:00
const val ONE_DAY_MILLIS = 86400000L
2021-12-14 14:54:36 +13:00
// As per documentation: The minimum repeat interval that can be defined is 15 minutes
2021-12-14 14:54:36 +13:00
// (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
2021-10-27 06:46:49 +13:00
}
}