Skip to content

Commit

Permalink
Bug fix
Browse files Browse the repository at this point in the history
  • Loading branch information
dkrivoruchko committed Oct 14, 2021
1 parent efd7a84 commit fa8c1a9
Show file tree
Hide file tree
Showing 12 changed files with 79 additions and 36 deletions.
16 changes: 8 additions & 8 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -94,17 +94,17 @@ dependencies {

implementation("androidx.core:core-ktx:1.6.0")
implementation("androidx.activity:activity-ktx:1.3.1")
implementation("androidx.fragment:fragment-ktx:1.4.0-alpha09")
implementation("androidx.fragment:fragment-ktx:1.4.0-alpha10")
implementation("androidx.appcompat:appcompat:1.3.1")
implementation("androidx.constraintlayout:constraintlayout:2.1.1")
implementation("androidx.recyclerview:recyclerview:1.2.1")
implementation("com.google.android.material:material:1.4.0")
implementation("androidx.window:window:1.0.0-beta02")

implementation("androidx.navigation:navigation-fragment-ktx:2.4.0-alpha09")
implementation("androidx.navigation:navigation-ui-ktx:2.4.0-alpha09")
implementation("androidx.lifecycle:lifecycle-livedata:2.4.0-beta01")
implementation("androidx.lifecycle:lifecycle-common:2.4.0-beta01")
implementation("androidx.navigation:navigation-fragment-ktx:2.4.0-alpha10")
implementation("androidx.navigation:navigation-ui-ktx:2.4.0-alpha10")
implementation("androidx.lifecycle:lifecycle-livedata:2.4.0-rc01")
implementation("androidx.lifecycle:lifecycle-common:2.4.0-rc01")

implementation("com.afollestad.material-dialogs:core:3.3.0")
implementation("com.afollestad.material-dialogs:color:3.3.0")
Expand All @@ -125,10 +125,10 @@ dependencies {
exclude group: "androidx.fragment"
exclude group: "androidx.core"
}
firebaseImplementation("com.google.firebase:firebase-analytics:19.0.1")
firebaseImplementation("com.google.firebase:firebase-crashlytics:18.2.1")
firebaseImplementation("com.google.firebase:firebase-analytics:19.0.2")
firebaseImplementation("com.google.firebase:firebase-crashlytics:18.2.3")
firebaseImplementation("com.google.android.gms:play-services-ads:20.4.0")
firebaseImplementation("androidx.work:work-runtime:2.7.0-beta01") // Temp fix for AdMob Android 12
firebaseImplementation("androidx.work:work-runtime:2.7.0-rc01") // Temp fix for AdMob Android 12

debugImplementation("com.squareup.leakcanary:leakcanary-android:2.7")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,12 @@ class NotificationHelper(context: Context) {
)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = notificationManager.getNotificationChannel(CHANNEL_STREAM)
builder
.setSound(notificationChannel.sound)
.setPriority(notificationChannel.importance)
.setVibrate(notificationChannel.vibrationPattern)
notificationManager.getNotificationChannel(CHANNEL_STREAM)?.let { notificationChannel ->
builder
.setSound(notificationChannel.sound)
.setPriority(notificationChannel.importance)
.setVibrate(notificationChannel.vibrationPattern)
}
}

return when (notificationType) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.annotation.ColorInt
import info.dvkr.screenstream.R

class ColorCircleView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/res/values-ru/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<string name="error_title">Ошибка</string>
<string name="error_port_in_use">Порт уже используется. Выберите другой.</string>
<string name="error_invalid_media_projection">Ошибка безопасности: Недопустимая проекция медиа. Попробуйте еще раз.</string>
<string name="error_ip_address_not_found">IP адресс не найден.\nПопробуйте отключить \"Использовать только WiFi\" в настройках.</string>
<string name="error_ip_address_not_found">IP адрес не найден.\nПопробуйте отключить \"Использовать только WiFi\" в настройках.</string>
<string name="error_wrong_image_format">Система отдает изображение в неверном формате. Решения проблемы нет.</string>
<string name="error_exit">Выход</string>
<string name="app_activity_collecting_logs">Идет логирование…</string>
Expand Down
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ buildscript {
}

dependencies {
classpath("com.android.tools.build:gradle:7.0.2")
classpath("com.android.tools.build:gradle:7.0.3")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31")
classpath("com.google.gms:google-services:4.3.10")
classpath("com.google.firebase:firebase-crashlytics-gradle:2.7.1")
Expand Down
2 changes: 1 addition & 1 deletion data/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ dependencies {
implementation("androidx.core:core:1.6.0")
implementation("androidx.window:window:1.0.0-beta02")

implementation("io.ktor:ktor-server-cio:1.6.3")
implementation("io.ktor:ktor-server-cio:1.6.4")

implementation("com.github.iamironz:binaryprefs:1.0.1")
implementation('com.elvishew:xlog:1.11.0')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ internal class HttpServer(
val coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable ->
XLog.e(getLog("onCoroutineException", throwable.toString()))
sendEvent(Event.Error(FatalError.HttpServerException))
ktorServer?.stop(250, 250)
ktorServer?.stop(0, 250)
ktorServer = null
}
val coroutineScope = CoroutineScope(Job() + Dispatchers.Default + coroutineExceptionHandler)
Expand Down Expand Up @@ -133,7 +133,7 @@ internal class HttpServer(
} finally {
exception?.let {
sendEvent(Event.Error(it))
ktorServer?.stop(250, 250)
ktorServer?.stop(0, 250)
ktorServer = null
}
}
Expand All @@ -145,7 +145,7 @@ internal class HttpServer(
return CompletableDeferred<Unit>().apply Deferred@{
ktorServer?.apply {
stopDeferred.set(this@Deferred)
stop(250, 250)
stop(0, 250)
ktorServer = null
} ?: complete(Unit)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ import info.dvkr.screenstream.data.other.randomString
import io.ktor.application.*
import io.ktor.features.*
import io.ktor.http.*
import io.ktor.http.cio.*
import io.ktor.http.content.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.cio.*
import io.ktor.util.*
import io.ktor.utils.io.*
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.cancel
Expand All @@ -21,6 +23,7 @@ import java.util.*
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.atomic.AtomicReference

@OptIn(InternalAPI::class)
internal fun Application.appModule(
httpServerFiles: HttpServerFiles,
clientData: ClientData,
Expand Down Expand Up @@ -52,11 +55,11 @@ internal fun Application.appModule(
}

environment.monitor.subscribe(ApplicationStarted) {
XLog.i(getLog("monitor", "ApplicationStarted: ${hashCode()}"))
XLog.i(getLog("monitor", "KtorApplicationStarted: ${hashCode()}"))
}

environment.monitor.subscribe(ApplicationStopped) {
XLog.i(getLog("monitor", "ApplicationStopped: ${hashCode()}"))
XLog.i(getLog("monitor", "KtorApplicationStopped: ${hashCode()}"))
it.environment.parentCoroutineContext.cancel()
clientData.clearStatistics()
stopDeferred.getAndSet(null)?.complete(Unit)
Expand All @@ -75,8 +78,9 @@ internal fun Application.appModule(
call.respondRedirect(HttpServerFiles.PIN_REQUEST_ADDRESS)
}
exception<Throwable> { cause ->
XLog.e(getLog("exception<Throwable>"))
XLog.e(getLog("exception"), cause)
val headers = CIOHeadersResearch.getHeadersAsString(call.request.headers as CIOHeaders)
XLog.e(this@appModule.getLog("exception<Throwable>", headers))
XLog.e(this@appModule.getLog("exception"), cause)
sendEvent(HttpServer.Event.Error(FatalError.HttpServerException))
call.respond(HttpStatusCode.InternalServerError)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,11 +164,11 @@ class AppStateMachineImpl(
settingsReadOnly.registerChangeListener(settingsListener)
broadcastHelper.startListening(
onScreenOff = { sendEvent(InternalEvent.ScreenOff) },
onConnectionChanged = { sendEvent(InternalEvent.RestartServer(RestartReason.ConnectionChanged(""))) }
onConnectionChanged = { sendEvent(InternalEvent.RestartServer(RestartReason.ConnectionChanged("BroadcastHelper"))) }
)

connectivityHelper.startListening {
sendEvent(InternalEvent.RestartServer(RestartReason.ConnectionChanged("")))
connectivityHelper.startListening(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.ConnectionChanged("ConnectivityHelper")))
}

coroutineScope.launch(CoroutineName("AppStateMachineImpl.httpServer.eventSharedFlow")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import android.net.Network
import android.os.Build
import com.elvishew.xlog.XLog
import info.dvkr.screenstream.data.other.getLog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*

internal sealed class ConnectivityHelper {
companion object {
Expand All @@ -18,9 +22,10 @@ internal sealed class ConnectivityHelper {
}
}

protected lateinit var onConnectionChanged: () -> Unit
protected val connectionChangEventFlow =
MutableSharedFlow<Network>(extraBufferCapacity = 64, onBufferOverflow = BufferOverflow.DROP_OLDEST)

abstract fun startListening(onConnectionChanged: () -> Unit)
abstract fun startListening(coroutineScope: CoroutineScope, onConnectionChanged: () -> Unit)
abstract fun stopListening()

@TargetApi(Build.VERSION_CODES.N)
Expand All @@ -31,19 +36,30 @@ internal sealed class ConnectivityHelper {
private val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
XLog.d(this@NougatConnectivityHelper.getLog("onAvailable", "Network: $network"))
if (::onConnectionChanged.isInitialized) onConnectionChanged.invoke()
connectionChangEventFlow.tryEmit(network)
}

override fun onLost(network: Network) {
XLog.d(this@NougatConnectivityHelper.getLog("onLost", "Network: $network"))
if (::onConnectionChanged.isInitialized) onConnectionChanged.invoke()
connectionChangEventFlow.tryEmit(network)
}
}

override fun startListening(onConnectionChanged: () -> Unit) {
this.onConnectionChanged = onConnectionChanged
override fun startListening(coroutineScope: CoroutineScope, onConnectionChanged: () -> Unit) {
XLog.d(this@NougatConnectivityHelper.getLog("startListening"))

connectionChangEventFlow.conflate()
.onStart {
XLog.d(this@NougatConnectivityHelper.getLog("startListening", "onStart"))
onConnectionChanged.invoke()
}
.onEach {
XLog.d(this@NougatConnectivityHelper.getLog("onEach", "Network: $it"))
onConnectionChanged.invoke()
delay(250)
}.shareIn(coroutineScope, SharingStarted.Eagerly)

connectivityManager.registerDefaultNetworkCallback(networkCallback)
onConnectionChanged.invoke()
}

override fun stopListening() {
Expand All @@ -53,7 +69,7 @@ internal sealed class ConnectivityHelper {

@Suppress("Deprecation")
private class EmptyConnectivityHelper : ConnectivityHelper() {
override fun startListening(onConnectionChanged: () -> Unit) {
override fun startListening(coroutineScope: CoroutineScope, onConnectionChanged: () -> Unit) {
XLog.d(this@EmptyConnectivityHelper.getLog("startListening", "Trigger on start address discovery"))
onConnectionChanged.invoke()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class NetworkHelper(context: Context) {
private fun getNetworkInterfacesWithFallBack(): Enumeration<NetworkInterface> {
try {
return NetworkInterface.getNetworkInterfaces()
} catch (ex: SocketException) {
} catch (ex: Exception) {
XLog.w(getLog("getNetworkInterfacesWithFallBack.getNetworkInterfaces", ex.toString()))
}

Expand Down
23 changes: 23 additions & 0 deletions data/src/main/kotlin/io/ktor/server/cio/CIOHeadersResearch.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package io.ktor.server.cio;

import java.lang.reflect.Field;

import io.ktor.http.cio.CIOHeaders;
import io.ktor.http.cio.HttpHeadersMap;
import io.ktor.http.cio.internals.CharArrayBuilder;

public class CIOHeadersResearch {
public static String getHeadersAsString(CIOHeaders headers) {
try {
Field privateHeadersField = CIOHeaders.class.getDeclaredField("headers");
privateHeadersField.setAccessible(true);
HttpHeadersMap headersMap = (HttpHeadersMap) privateHeadersField.get(headers);
Field privateBuilderField = HttpHeadersMap.class.getDeclaredField("builder");
privateBuilderField.setAccessible(true);
CharArrayBuilder charArrayBuilder = (CharArrayBuilder) privateBuilderField.get(headersMap);
return charArrayBuilder.toString();
} catch (Throwable ignore) {
}
return null;
}
}

0 comments on commit fa8c1a9

Please sign in to comment.