Skip to content

Commit

Permalink
fix: refresh token correctly
Browse files Browse the repository at this point in the history
[release: 1.2.1]
  • Loading branch information
Zxilly committed Oct 14, 2022
1 parent d538744 commit c34bfe6
Show file tree
Hide file tree
Showing 8 changed files with 75 additions and 49 deletions.
1 change: 1 addition & 0 deletions app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
-keep class dev.zxilly.notify.sdk.** {*;}
-keep class dev.zxilly.notify.sdk.entity.** {*;}
-keep class top.learningman.push.** {*;}

-dontwarn com.caverock.androidsvg.SVG
Expand Down
1 change: 1 addition & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
android:name=".service.ReceiverService"
android:enabled="true"
android:exported="true"
android:process=":push"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/kotlin/top/learningman/push/Constant.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package top.learningman.push

object Constant {
private val ENDPOINT_LIST = arrayOf("push.learningman.top", "192.168.1.103:14444")
private val ENDPOINT_LIST = arrayOf("push.learningman.top", "192.168.0.108:14444")
private const val ENDPOINT_INDEX = 0

private val HOST:String
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class MainActivity : AppCompatActivity() {
Log.d("MainActivity", "Setting Activity Result ${it.resultCode}")
if ((it.resultCode and SettingsActivity.UPDATE_CHANNEL) == SettingsActivity.UPDATE_CHANNEL) {
Log.d("MainActivity", "Update Channel")
val channel = AutoChannel.getInstance(context = this, nocache = true)
channel = AutoChannel.getInstance(context = this, nocache = true)
channel.init(context = this)
} else if ((it.resultCode and SettingsActivity.UPDATE_USERNAME) == SettingsActivity.UPDATE_USERNAME) {
Log.d("MainActivity", "Update User")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import com.google.android.material.color.DynamicColors
import com.microsoft.appcenter.AppCenter
import com.microsoft.appcenter.analytics.Analytics
import com.microsoft.appcenter.crashes.Crashes
import top.learningman.push.BuildConfig
import top.learningman.push.Constant
import top.learningman.push.checkerInit
import top.learningman.push.data.Repo
Expand All @@ -25,10 +24,6 @@ class MainApplication : Application() {
Crashes::class.java
)

if (BuildConfig.DEBUG){
Crashes.getInstance().isInstanceEnabled = false
}

DynamicColors.applyToActivitiesIfAvailable(this)

checkerInit(this)
Expand Down
1 change: 1 addition & 0 deletions app/src/main/kotlin/top/learningman/push/provider/FCM.kt
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ object FCM : Channel {
APIUtils.register(userID, token, NotifyChannel.FCM, deviceID)
.onSuccess {
Toast.makeText(context, "FCM 注册成功", Toast.LENGTH_LONG).show()
Log.i("FCM", "FCM 注册成功")
}
.onFailure {
Toast.makeText(context, "FCM 注册失败", Toast.LENGTH_LONG).show()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.work.*
import com.microsoft.appcenter.crashes.Crashes
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import top.learningman.push.BuildConfig
Expand Down Expand Up @@ -46,10 +48,12 @@ object WebSocket : Channel {
val deviceID = Repo.getInstance(context).getDeviceID()
APIUtils.register(userID, "ws", NotifyChannel.WebSocket, deviceID)
.onSuccess {
Log.d("WebSocket", "WebSocket 注册成功")
Toast.makeText(context, "WebSocket 注册成功", Toast.LENGTH_LONG).show()
Log.i("WebSocket", "WebSocket 注册成功")
}
.onFailure {
Log.e("WebSocket", "WebSocket 注册失败", it)
Crashes.trackError(it)
}
}
}
Expand Down
106 changes: 65 additions & 41 deletions app/src/main/kotlin/top/learningman/push/service/ReceiverService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,15 @@ class ReceiverService : NotificationListenerService() {
override fun onCreate() {
super.onCreate()
manager = WebsocketSessionManager(this)
Log.d(TAG, "ReceiverService $id create")
Log.i(TAG, "ReceiverService $id create")

services.add(id)
if (services.size > 1) {
Log.e(TAG, "ReceiverService $id create more than once")
for (service in services) {
Log.e(TAG, "ReceiverService $service exists")
}
}
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Expand All @@ -69,42 +77,40 @@ class ReceiverService : NotificationListenerService() {
return START_STICKY
}

override fun onTaskRemoved(rootIntent: Intent) {
val restartServiceIntent = Intent(applicationContext, ReceiverService::class.java).also {
it.setPackage(packageName)
}
val restartServicePendingIntent: PendingIntent = PendingIntent.getService(
this,
1,
restartServiceIntent,
PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
)
applicationContext.getSystemService(Context.ALARM_SERVICE)
val alarmService =
applicationContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent
)
}
// override fun onTaskRemoved(rootIntent: Intent) {
// val restartServiceIntent = Intent(applicationContext, ReceiverService::class.java).also {
// it.setPackage(packageName)
// }
// val restartServicePendingIntent: PendingIntent = PendingIntent.getService(
// this,
// 1,
// restartServiceIntent,
// PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
// )
// applicationContext.getSystemService(Context.ALARM_SERVICE)
// val alarmService =
// applicationContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager
// alarmService.set(
// AlarmManager.ELAPSED_REALTIME,
// SystemClock.elapsedRealtime() + 1000,
// restartServicePendingIntent
// )
// }

override fun onListenerDisconnected() {
super.onListenerDisconnected()
Log.d(TAG, "onListenerDisconnected")
if (!BuildConfig.DEBUG) {
requestRebind(
ComponentName(
applicationContext,
NotificationListenerService::class.java
)
Log.d(TAG, "onListenerDisconnected in $id")
requestRebind(
ComponentName(
applicationContext,
NotificationListenerService::class.java
)
}
)
manager.tryResume()
}

override fun onListenerConnected() {
super.onListenerConnected()
manager.tryResume()
Log.d(TAG, "onListenerConnected")
}

Expand All @@ -113,15 +119,25 @@ class ReceiverService : NotificationListenerService() {
manager.stop()
// Maybe useless but just in case
manager.cancel()

Log.i(TAG, "ReceiverService $id destroyed")

services.remove(id)
if (services.size > 0) {
Log.e(TAG, "ReceiverService $id destroy but still exists")
for (service in services) {
Log.e(TAG, "ReceiverService $service exists")
}
}
}

@OptIn(DelicateCoroutinesApi::class)
private class WebsocketSessionManager(private val context: Context) :
private class WebsocketSessionManager(private val service: ReceiverService) :
CoroutineScope by CoroutineScope(context = newSingleThreadContext("WebsocketSessionManager")) {

private var job: Job? = null
private var jobLock = Mutex()
private val repo by lazy { Repo.getInstance(context) }
private val repo by lazy { Repo.getInstance(service) }
private var currentUserID = repo.getUser()
private val client by lazy {
HttpClient(OkHttp) {
Expand All @@ -130,7 +146,7 @@ class ReceiverService : NotificationListenerService() {
}
}
private val connectivityManager by lazy {
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
service.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
}

private var status = AtomicInteger(Status.WAIT_START)
Expand Down Expand Up @@ -159,7 +175,7 @@ class ReceiverService : NotificationListenerService() {
}
}

private val netWorkCallback = object : ConnectivityManager.NetworkCallback(){
private val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: android.net.Network) {
super.onAvailable(network)
if (status.compareAndSet(Status.NETWORK_LOST, Status.WAIT_RECONNECT)) {
Expand All @@ -184,31 +200,37 @@ class ReceiverService : NotificationListenerService() {
}

init {
connectivityManager.registerDefaultNetworkCallback(netWorkCallback)
connectivityManager.registerDefaultNetworkCallback(networkCallback)
}

fun stop() {
status.set(Status.STOP)
runBlocking {
tryCancelJob()
}
connectivityManager.unregisterNetworkCallback(netWorkCallback)
connectivityManager.unregisterNetworkCallback(networkCallback)
}

suspend fun tryCancelJob() {
jobLock.lock()
try {
job?.cancelAndJoin()
job = null
if(job != null) {
job?.cancelAndJoin()
job = null
Log.i(TAG, "job cancelled in ${service.id}")
}
} catch (e: Throwable) {
Log.e(TAG, "tryCancelJob: ", e)
} finally {
jobLock.unlock()
}
}

private fun diagnose() {
private fun diagnose(msg: String = "") {
Log.d(TAG, "current thread ${Thread.currentThread().id}")
if (msg.isNotEmpty()) {
Log.d(TAG, msg)
}
}

fun tryResume() {
Expand Down Expand Up @@ -333,7 +355,7 @@ class ReceiverService : NotificationListenerService() {
}
}
if (job?.isActive == true) {
Log.i(TAG, "job is active, start websocket success")
Log.i(TAG, "job is active, start websocket success in ${service.id}")
} else {
Log.e(TAG, "job is not active, start websocket failed")
}
Expand Down Expand Up @@ -363,7 +385,7 @@ class ReceiverService : NotificationListenerService() {
}.fold({
Log.d(TAG, "prepare to send notification")
val notificationMessage = it.toMessage()
notifyMessage(notificationMessage, from = (context as ReceiverService).id)
notifyMessage(notificationMessage, from = (service as ReceiverService).id)
repo.setLastMessageTime(notificationMessage.createdAt)
}, {
Log.e(TAG, "Error parsing message", it)
Expand All @@ -378,7 +400,7 @@ class ReceiverService : NotificationListenerService() {

private fun notifyMessage(message: Message, from: String = "anonymous") {
Log.d(TAG, "notifyMessage: $message from $from")
Utils.notifyMessage(context, message)
Utils.notifyMessage(service, message)
}
}

Expand All @@ -391,5 +413,7 @@ class ReceiverService : NotificationListenerService() {
const val TAG = "ReceiverService"

const val INTENT_USERID_KEY = "nextUserID"

var services = mutableListOf<String>()
}
}

0 comments on commit c34bfe6

Please sign in to comment.