Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
greenart7c3 committed Mar 6, 2024
1 parent ac6e509 commit f1b33f4
Show file tree
Hide file tree
Showing 22 changed files with 92 additions and 69 deletions.
4 changes: 2 additions & 2 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@
tools:targetApi="31">

<service
android:name=".WebSocketServerService"
android:name=".service.WebSocketServerService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="remoteMessaging">
</service>

<receiver
android:name=".BootBroadcastReceiver"
android:name=".service.BootBroadcastReceiver"
android:enabled="true"
android:exported="false"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
Expand Down
67 changes: 34 additions & 33 deletions app/src/main/java/com/greenart7c3/citrine/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -30,21 +30,24 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import com.greenart7c3.citrine.service.WebSocketServerService
import com.greenart7c3.citrine.ui.dialogs.ContactsDialog
import com.greenart7c3.citrine.ui.theme.CitrineTheme
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
private val requestPermissionLauncher =
registerForActivityResult(
ActivityResultContracts.RequestPermission()
) {
val intent = Intent(this, WebSocketServerService::class.java)
startService(intent)
bindService(intent, connection, Context.BIND_AUTO_CREATE)
@OptIn(DelicateCoroutinesApi::class)
private val requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) {
GlobalScope.launch(Dispatchers.IO) {
start()
}
}

private var service: WebSocketServerService? = null
private var bound = false
Expand All @@ -64,6 +67,26 @@ class MainActivity : ComponentActivity() {
}
}

private suspend fun stop() {
isLoading.value = true
val intent = Intent(applicationContext, WebSocketServerService::class.java)
stopService(intent)
unbindService(connection)
bound = false
service = null
delay(1000)
isLoading.value = false
}

private suspend fun start() {
isLoading.value = true
val intent = Intent(applicationContext, WebSocketServerService::class.java)
startService(intent)
bindService(intent, connection, Context.BIND_AUTO_CREATE)
delay(1000)
isLoading.value = false
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

Expand Down Expand Up @@ -111,10 +134,10 @@ class MainActivity : ComponentActivity() {
if (isLoading.value) {
CircularProgressIndicator()
} else {
val isStarted = service?.webSocketServer?.server != null
val isStarted = service?.isStarted() ?: false
if (isStarted) {
Text("Relay started at")
Text("ws://localhost:${service?.webSocketServer?.port() ?: 0}")
Text("ws://localhost:${service?.port() ?: 0}")
ElevatedButton(
onClick = {
coroutineScope.launch(Dispatchers.IO) {
Expand All @@ -125,11 +148,7 @@ class MainActivity : ComponentActivity() {
}
}
) {
if (service?.webSocketServer?.server != null) {
Text("Stop")
} else {
Text("Start")
}
Text("Stop")
}
} else {
Text("Relay not running")
Expand All @@ -143,11 +162,7 @@ class MainActivity : ComponentActivity() {
}
}
) {
if (service?.webSocketServer?.server != null) {
Text("Stop")
} else {
Text("Start")
}
Text("Start")
}
}

Expand Down Expand Up @@ -187,18 +202,4 @@ class MainActivity : ComponentActivity() {
}
super.onDestroy()
}

private fun stop() {
val intent = Intent(applicationContext, WebSocketServerService::class.java)
stopService(intent)
unbindService(connection)
bound = false
service = null
}

private fun start() {
val intent = Intent(applicationContext, WebSocketServerService::class.java)
startService(intent)
bindService(intent, connection, Context.BIND_AUTO_CREATE)
}
}
2 changes: 1 addition & 1 deletion app/src/main/java/com/greenart7c3/citrine/relays/Client.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
package com.greenart7c3.citrine.relays

import android.util.Log
import com.greenart7c3.citrine.checkNotInMainThread
import com.greenart7c3.citrine.utils.checkNotInMainThread
import com.vitorpamplona.quartz.events.Event
import com.vitorpamplona.quartz.events.EventInterface
import kotlinx.coroutines.DelicateCoroutinesApi
Expand Down
4 changes: 2 additions & 2 deletions app/src/main/java/com/greenart7c3/citrine/relays/Relay.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ package com.greenart7c3.citrine.relays

import android.util.Log
import com.greenart7c3.citrine.BuildConfig
import com.greenart7c3.citrine.HttpClientManager
import com.greenart7c3.citrine.checkNotInMainThread
import com.greenart7c3.citrine.utils.HttpClientManager
import com.greenart7c3.citrine.utils.checkNotInMainThread
import com.vitorpamplona.quartz.encoders.HexKey
import com.vitorpamplona.quartz.events.Event
import com.vitorpamplona.quartz.events.EventInterface
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
package com.greenart7c3.citrine.relays

import androidx.compose.runtime.Immutable
import com.greenart7c3.citrine.checkNotInMainThread
import com.greenart7c3.citrine.utils.checkNotInMainThread
import com.vitorpamplona.quartz.events.Event
import com.vitorpamplona.quartz.events.EventInterface
import kotlinx.coroutines.channels.BufferOverflow
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.greenart7c3.citrine
package com.greenart7c3.citrine.server

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.vitorpamplona.quartz.events.Event
Expand All @@ -14,6 +14,5 @@ data class CommandResult(val eventId: String, val result: Boolean, val descripti
fun ok(event: Event) = CommandResult(event.id, true)
fun duplicated(event: Event) = CommandResult(event.id, true, "duplicate:")
fun invalid(event: Event, message: String) = CommandResult(event.id, false, "invalid: $message")
fun error(event: Event, message: String) = CommandResult(event.id, false, "error: $message")
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.greenart7c3.citrine
package com.greenart7c3.citrine.server

import io.ktor.websocket.DefaultWebSocketSession
import java.util.concurrent.atomic.AtomicInteger
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
package com.greenart7c3.citrine
package com.greenart7c3.citrine.server

import android.util.Log
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.greenart7c3.citrine.BuildConfig
import com.greenart7c3.citrine.database.AppDatabase
import com.greenart7c3.citrine.database.toEventWithTags
import com.greenart7c3.citrine.utils.isEphemeral
import com.greenart7c3.citrine.utils.isParameterizedReplaceable
import com.greenart7c3.citrine.utils.shouldDelete
import com.greenart7c3.citrine.utils.shouldOverwrite
import com.vitorpamplona.quartz.events.Event
import io.ktor.http.ContentType
import io.ktor.http.HttpMethod
Expand Down Expand Up @@ -102,7 +107,12 @@ class CustomWebSocketServer(private val port: Int, private val appDatabase: AppD
val event = objectMapper.treeToValue(eventNode, Event::class.java)

if (!event.hasVerifiedSignature()) {
connection.session.send(CommandResult.invalid(event, "event signature verification failed").toJson())
connection.session.send(
CommandResult.invalid(
event,
"event signature verification failed"
).toJson()
)
return
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
package com.greenart7c3.citrine.server

data class EOSE(val subscriptionId: String) {
fun toJson(): String {
return """["EOSE","$subscriptionId"]"""
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.greenart7c3.citrine
package com.greenart7c3.citrine.server

import com.vitorpamplona.quartz.events.Event
import java.util.function.Predicate
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.greenart7c3.citrine
package com.greenart7c3.citrine.server

import com.greenart7c3.citrine.database.toEvent
import com.vitorpamplona.quartz.utils.TimeUtils
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.greenart7c3.citrine
package com.greenart7c3.citrine.server

import android.util.Log
import android.util.LruCache
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.greenart7c3.citrine
package com.greenart7c3.citrine.server

data class NoticeResult(val message: String) {
fun toJson(): String {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.greenart7c3.citrine
package com.greenart7c3.citrine.server

import EOSE
import android.util.Log
import io.ktor.websocket.send
import kotlinx.coroutines.CancellationException
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.greenart7c3.citrine
package com.greenart7c3.citrine.service

import android.content.BroadcastReceiver
import android.content.Context
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.greenart7c3.citrine
package com.greenart7c3.citrine.service

import android.annotation.SuppressLint
import android.app.Notification
Expand All @@ -18,7 +18,11 @@ import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat.getSystemService
import com.greenart7c3.citrine.MainActivity
import com.greenart7c3.citrine.R
import com.greenart7c3.citrine.database.AppDatabase
import com.greenart7c3.citrine.server.CustomWebSocketServer
import com.greenart7c3.citrine.server.EventSubscription

class WebSocketServerService : Service() {
lateinit var webSocketServer: CustomWebSocketServer
Expand Down Expand Up @@ -52,9 +56,8 @@ class WebSocketServerService : Service() {
}

// Start the WebSocket server
val port = if (BuildConfig.DEBUG) defaultPortDebug else defaultPort
webSocketServer = CustomWebSocketServer(
port,
DEFAULT_PORT,
AppDatabase.getDatabase(this@WebSocketServerService)
)
webSocketServer.start()
Expand Down Expand Up @@ -103,8 +106,15 @@ class WebSocketServerService : Service() {
return notificationBuilder.build()
}

fun isStarted(): Boolean {
return webSocketServer.server != null
}

fun port(): Int? {
return webSocketServer.port()
}

companion object {
const val defaultPort = 4869
const val defaultPortDebug = 4869
const val DEFAULT_PORT = 4869
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ import androidx.compose.ui.window.DialogProperties
import com.greenart7c3.citrine.database.AppDatabase
import com.greenart7c3.citrine.database.toEvent
import com.greenart7c3.citrine.relays.Client
import com.greenart7c3.citrine.toDateString
import com.greenart7c3.citrine.ui.CloseButton
import com.greenart7c3.citrine.utils.toDateString
import com.vitorpamplona.quartz.encoders.bechToBytes
import com.vitorpamplona.quartz.encoders.toHexKey
import com.vitorpamplona.quartz.events.ContactListEvent
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.greenart7c3.citrine
package com.greenart7c3.citrine.utils

import java.time.Instant
import java.time.LocalDateTime
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.greenart7c3.citrine
package com.greenart7c3.citrine.utils

import com.vitorpamplona.quartz.events.Event

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.greenart7c3.citrine
package com.greenart7c3.citrine.utils

import android.util.Log
import com.greenart7c3.citrine.BuildConfig
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
Expand Down Expand Up @@ -50,20 +51,20 @@ object HttpClientManager {
fun setDefaultProxy(proxy: Proxy?) {
if (internalProxy != proxy) {
Log.d("HttpClient", "Changing proxy to: ${proxy != null}")
this.internalProxy = proxy
internalProxy = proxy

// recreates singleton
this.defaultHttpClient = buildHttpClient(internalProxy, defaultTimeout)
defaultHttpClient = buildHttpClient(internalProxy, defaultTimeout)
}
}

fun setDefaultTimeout(timeout: Duration) {
Log.d("HttpClient", "Changing timeout to: $timeout")
if (this.defaultTimeout.seconds != timeout.seconds) {
this.defaultTimeout = timeout
if (defaultTimeout.seconds != timeout.seconds) {
defaultTimeout = timeout

// recreates singleton
this.defaultHttpClient = buildHttpClient(internalProxy, defaultTimeout)
defaultHttpClient = buildHttpClient(internalProxy, defaultTimeout)
}
}

Expand Down Expand Up @@ -98,8 +99,8 @@ object HttpClientManager {
}

fun getHttpClient(): OkHttpClient {
if (this.defaultHttpClient == null) {
this.defaultHttpClient = buildHttpClient(internalProxy, defaultTimeout)
if (defaultHttpClient == null) {
defaultHttpClient = buildHttpClient(internalProxy, defaultTimeout)
}
return defaultHttpClient!!
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.greenart7c3.citrine
package com.greenart7c3.citrine.utils

import android.os.Looper
import com.greenart7c3.citrine.BuildConfig

fun checkNotInMainThread() {
if (BuildConfig.DEBUG && isMainThread()) {
Expand Down
2 changes: 1 addition & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ okhttp = "5.0.0-alpha.12"
room = "2.6.1"
workRuntimeKtx = "2.9.0"
material3 = "1.2.0"
quartz = "v0.85.0"
quartz = "v0.85.3"

[libraries]
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" }
Expand Down

0 comments on commit f1b33f4

Please sign in to comment.