Move to better solution for gateway discovery

This commit is contained in:
ProtoKai 2022-11-11 12:22:46 +00:00
parent 9830bacdb2
commit 18bbb93873

View File

@ -1,53 +1,65 @@
@file:OptIn(DelicateCoroutinesApi::class)
package org.muellerssoftware.openproximitychat.common
import org.slf4j.Logger
import org.bitlet.weupnp.GatewayDevice
import org.bitlet.weupnp.GatewayDiscover
import kotlinx.coroutines.*
object Logging {
enum class LogType {
Debug,
Info,
Error
}
object UPnPManager {
var gateway: GatewayDevice? = null
val mappedPorts = mutableMapOf<Int, Int>()
var discoveryJob: Job = Job()
var logger: Logger? = null
set(value) {
for (log in backLog) {
when (log.first) {
LogType.Debug -> value?.debug(log.second)
LogType.Info -> value?.info(log.second)
LogType.Error -> value?.error(log.second)
}
init {
runBlocking {
discoveryJob = GlobalScope.launch {
startGatewayDiscover()
}
field = value
}
var backLog = mutableListOf<Pair<LogType, String>>()
fun info(message: String) {
if (logger != null) {
logger!!.info(message)
}
else {
backLog.add(Pair(LogType.Info, message))
}
}
fun error(message: String) {
if (logger != null) {
logger!!.error(message)
suspend fun startGatewayDiscover() {
val gatewayDiscoverer = GatewayDiscover()
for (i in 0..9) {
Logging.info("Searching for UPnP gateway... (Attempt ${i + 1})")
gatewayDiscoverer.discover()
if (gatewayDiscoverer.getValidGateway() != null) {
gateway = gatewayDiscoverer.validGateway
break
}
}
if (gateway == null) {
Logging.error("No UPnP gateway found!")
}
else {
backLog.add(Pair(LogType.Error, message))
Logging.info("UPnP gateway found: ${gateway!!.friendlyName}")
val ports = mappedPorts.toMutableMap()
mappedPorts.clear()
ports.map {
mapPort(it.key, it.value)
}
}
}
fun debug(message: String) {
if (logger != null) {
logger!!.debug(message)
fun mapPort(port: Int) {
mapPort(port, port)
}
fun mapPort(internalPort: Int, externalPort: Int) {
if (gateway == null) {
mappedPorts.put(internalPort, externalPort)
}
else {
backLog.add(Pair(LogType.Debug, message))
val succeeded = gateway?.addPortMapping(externalPort, internalPort, gateway!!.localAddress.hostAddress, "UDP", "OpenProximityChat mapped port")
if (succeeded == true) {
mappedPorts.put(internalPort, externalPort)
}
}
fun unMapAll() {
mappedPorts.map {
gateway?.deletePortMapping(it.value, "UDP")
}
}
}