Skip to content

Commit

Permalink
fix test
Browse files Browse the repository at this point in the history
  • Loading branch information
storytellerF committed Feb 22, 2025
1 parent 05cb7ae commit 31dd5c2
Show file tree
Hide file tree
Showing 42 changed files with 865 additions and 665 deletions.
2 changes: 1 addition & 1 deletion backend/src/main/kotlin/com/storyteller_f/Backend.kt
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ fun readEnv(map: Map<String, String> = emptyMap()): MergedEnv {
return MergedEnv(
listOf(
map,
System.getenv(),
readFileEnv("../${BackendConfig.FLAVOR}.env"),
readFileEnv(".env"),
readResourceEnv(".env"),
System.getenv()
)
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,15 @@ class LuceneTopicSearchService(private val path: Path) : TopicSearchService {
try {
DirectoryReader.open(it).use { reader ->
val searcher = IndexSearcher(reader)
val combinedQuery = buildQuery(preTopicId, nextTopicId, word, rootType, parentType, rootIdList, parentIdList).build()
val combinedQuery = buildQuery(
preTopicId,
nextTopicId,
word,
rootType,
parentType,
rootIdList,
parentIdList
)
Napier.i {
"lucene search query $combinedQuery"
}
Expand Down Expand Up @@ -145,7 +153,7 @@ class LuceneTopicSearchService(private val path: Path) : TopicSearchService {
parent: ObjectType?,
rootIdList: List<PrimaryKey>?,
parentIdList: List<PrimaryKey>?
): BooleanQuery.Builder {
): BooleanQuery? {
val analyzer = StandardAnalyzer()
val combinedQuery = BooleanQuery
.Builder()
Expand Down Expand Up @@ -188,7 +196,7 @@ class LuceneTopicSearchService(private val path: Path) : TopicSearchService {
parentIdList?.let {
combinedQuery.add(LongPoint.newSetQuery("parentId", it), BooleanClause.Occur.MUST)
}
return combinedQuery
return combinedQuery.build()
}

private fun <R> useLucene(block: (FSDirectory) -> R): Result<R> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import io.github.aakira.napier.Napier
import kotlinx.datetime.Instant
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import org.apache.http.client.utils.URIBuilder
import org.apache.tika.Tika
import java.io.File
import java.net.URLConnection
Expand Down Expand Up @@ -61,7 +62,7 @@ class FileSystemMediaService(private val url: String, base: String) : MediaServi
if (file.exists()) {
val item = stat(it, file)
val dimension = getDimension(file, item.contentType)
MediaInfo("${url}amedia/$it", item, dimension)
MediaInfo(URIBuilder(url).setPath("amedia/$it").build().toString(), item, dimension)
} else {
null
}
Expand Down
2 changes: 1 addition & 1 deletion builtin-bot/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ plugins {
group = "com.storyteller_f.a"
version = "1.0.0"
application {
mainClass.set("com.storyteller_f.a.server.ApplicationKt")
mainClass.set("com.storyteller_f.a.built_in_bot.BuiltInBotKt")
}

dependencies {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.storyteller_f.a.built_in_bot

fun main() {
println("built in bot")
}
2 changes: 1 addition & 1 deletion cli/src/main/kotlin/com/storyteller_f/cli/CleanCommand.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class PrintCommand : Subcommand("print", "print") {
runBlocking {
val result = backend.topicSearchService.searchDocument(
10,
parentType = null to ObjectType.COMMUNITY
parentType = ObjectType.COMMUNITY
).getOrThrow()
Napier.i {
"total ${result.total} ${result.list.size}"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,9 @@ class ClientWebSocket(
}
}
}.onFailure {
Napier.e(it, tag = "pagination") {
"Exception in Client WebSocket"
Napier.e(it, tag = "ClientWebSocket") {
"Exception in startListenerWebSocket"
}
connectionHandler.data.value = null
connectionHandler.state.value = null
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -427,10 +427,16 @@ suspend fun HttpClient.upload(
suspend fun DefaultClientWebSocketSession.sendMessage(
roomInfo: RoomInfo,
input: String,
keyData: List<Pair<PrimaryKey, String>>,
keyData: List<Pair<PrimaryKey, String>>?,
topicId: PrimaryKey?,
keyState: LoadingState?,
notifyPubKeyStillLoading: () -> Unit
) {
val content = if (roomInfo.isPrivate) {
if (keyState !is LoadingState.Done || keyData == null) {
notifyPubKeyStillLoading()
return
}
val (encrypted, aes) = encrypt(input)
TopicContent.Encrypted(encrypted.toHexString(), keyData.associate {
it.first to encryptAesKey(it.second, aes).toHexString()
Expand Down
16 changes: 10 additions & 6 deletions composeApp/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -406,11 +406,15 @@ tasks.withType(KotlinCompile::class.java).configureEach {
tasks.getByName("copyNonXmlValueResourcesForCommonMain").dependsOn("exportLibraryDefinitions")

tasks.withType<Test> {
if (name == "testDebugUnitTest") {
exclude("**/device_based/*")
} else if (name == "testReleaseUnitTest") {
exclude("**/device_based/*", "**/jvm_based/*")
} else if (name == "desktopTest") {
exclude("**/device_based/*")
when (name) {
"testDebugUnitTest" -> {
exclude("**/device_based/*")
}
"testReleaseUnitTest" -> {
exclude("**/device_based/*", "**/jvm_based/*")
}
"desktopTest" -> {
exclude("**/device_based/*")
}
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
package jvm_based

actual abstract class UsingContextTest actual constructor()
actual abstract class UsingContextTest actual constructor() {
actual fun onActivity(block: () -> Unit) {
block()
}
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
package com.storyteller_f.a.app

import android.R
import android.app.Activity
import android.app.Application.ActivityLifecycleCallbacks
import android.app.NotificationManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.kdroid.composenotification.builder.AndroidChannelConfig
import com.kdroid.composenotification.builder.NotificationInitializer.notificationInitializer
Expand All @@ -22,19 +18,11 @@ import io.github.vinceglb.filekit.core.FileKit
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
bindActivity(this)
FileKit.init(this)
enableEdgeToEdge()
WindowInsetsControllerCompat(window, window.decorView).isAppearanceLightNavigationBars = false
notificationInitializer(
defaultChannelConfig = AndroidChannelConfig(
channelId = "Regular",
channelName = "Regular",
channelDescription = "Regular",
channelImportance = NotificationManager.IMPORTANCE_DEFAULT,
smallIcon = R.drawable.ic_notification_overlay
)
)

initFromContext()

setContent {
App()
}
Expand All @@ -51,3 +39,17 @@ class MainActivity : ComponentActivity() {
fun AppAndroidPreview() {
App()
}

fun ComponentActivity.initFromContext() {
bindActivity(this)
FileKit.init(this)
notificationInitializer(
defaultChannelConfig = AndroidChannelConfig(
channelId = "Regular",
channelName = "Regular",
channelDescription = "Regular",
channelImportance = NotificationManager.IMPORTANCE_DEFAULT,
smallIcon = R.drawable.ic_notification_overlay
)
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat
import com.storyteller_f.a.app.MainActivity
import androidx.lifecycle.Lifecycle
import io.github.aakira.napier.Napier
import java.lang.ref.WeakReference

Expand Down Expand Up @@ -51,14 +51,17 @@ var mainAppRef: WeakReference<ComponentActivity>? = null

fun bindActivity(activity: ComponentActivity) {
mainAppRef = WeakReference(activity)
val launcher = activity.registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
requestQueue.removeAt(0)
val currentState = activity.lifecycle.currentState
if (currentState.isAtLeast(Lifecycle.State.CREATED) && !currentState.isAtLeast(Lifecycle.State.DESTROYED)) {
val launcher = activity.registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
requestQueue.removeAt(0)
}
}
launcherRef = WeakReference(launcher)
}
launcherRef = WeakReference(launcher)
}

fun unbindActivity() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
package com.storyteller_f.a.app.utils

import androidx.activity.ComponentActivity
import androidx.lifecycle.Lifecycle
import com.storyteller_f.a.app.compontents.mainAppRef
import com.storyteller_f.a.app.initFromContext

actual val platform: Platform
get() {
val currentState = mainAppRef?.get()?.lifecycle?.currentState
val isActive = currentState?.isAtLeast(Lifecycle.State.RESUMED) == true
return Platform(true, isActive)
}

actual fun initEnvironment(context: Any) {
if (context is ComponentActivity) {
context.initFromContext()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package jvm_based

import android.content.ComponentName
import android.content.ContentProvider
import androidx.lifecycle.Lifecycle
import androidx.test.core.app.ActivityScenario
import com.storyteller_f.a.app.MainActivity
import kotbase.CouchbaseLite
import org.junit.Assume
Expand Down Expand Up @@ -53,4 +55,17 @@ actual abstract class UsingContextTest {
null
}
}

actual fun onActivity(block: () -> Unit) {
// GIVEN
val scenario = ActivityScenario.launch(MainActivity::class.java)

// WHEN
scenario.moveToState(Lifecycle.State.CREATED)

// THEN
scenario.onActivity {
block()
}
}
}
30 changes: 16 additions & 14 deletions composeApp/src/commonMain/kotlin/com/storyteller_f/a/app/App.kt
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ fun App2(navigator: NavHostController, httpUrl: String, wsServerUrl: String, con
setupRequest(httpUrl)
}
CompositionLocalProvider(LocalClient provides client) {
val ws = remeberWsClient(client, wsServerUrl, appNav)
val ws = rememberWsClient(client, wsServerUrl, appNav)
CompositionLocalProvider(LocalWsClient provides ws) {
GlobalDialog(globalDialogState)
val toasterState = rememberToasterState()
Expand All @@ -202,26 +202,28 @@ private fun buildWsListener(
) = object : ClientWsListener {
override fun onReceived(frame: RoomFrame) {
if (frame is RoomFrame.NewTopicInfo) {
val message = frame.topicInfo.content
val topicInfo = frame.topicInfo
val message = topicInfo.content
if (message is TopicContent.Plain) {
if (platform.isActive) {
if (appNav.toRoute<RoomScreen>()?.roomId != frame.topicInfo.parentId &&
appNav.toRoute<TopicScreen>()?.topicId != frame.topicInfo.parentId
val roomScreen = appNav.toRoute<RoomScreen>()
val topicScreen = appNav.toRoute<TopicScreen>()
if (roomScreen?.roomId != topicInfo.parentId &&
topicScreen?.topicId != topicInfo.parentId
) {
messageToasterState.show(message)
val nickname = topicInfo.extension?.authorInfo?.nickname
messageToasterState.show("$nickname: ${message.plain}")
}
} else if (hasPermission) {
sendTopicNotification(message)
}
}
}
}


}

@Composable
private fun remeberWsClient(
private fun rememberWsClient(
client: HttpClient,
wsServerUrl: String,
appNav: AppNav
Expand All @@ -230,7 +232,7 @@ private fun remeberWsClient(
ClientWebSocket({
client.webSocketSession(buildUrl {
takeFrom(wsServerUrl)
path("link")
appendPathSegments("link")
}.toString()) {
addRequestHeaders(LoginViewModel.session?.first)
}
Expand All @@ -248,7 +250,7 @@ private fun remeberWsClient(
Toaster(messageToasterState, alignment = Alignment.TopCenter)
val notificationProvider = getNotificationProvider()
val hasPermission by notificationProvider.hasPermissionState
val listener = remember {
val listener = remember(hasPermission) {
buildWsListener(appNav, messageToasterState, hasPermission)
}
remember.addListener(listener)
Expand Down Expand Up @@ -291,7 +293,7 @@ fun LoginCheck(content: @Composable () -> Unit) {
if (currentState is ClientSession.SignUpSuccess && user == null) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
if (tried) {
Column {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Button({
scope.launch {
signOut(client)
Expand Down Expand Up @@ -470,6 +472,7 @@ fun updateDocumentInParent(info: TopicInfo) {
}

fun updateDocument(collectionName: String, info: TopicInfo) {
assert(!info.isPrivate || info.content is TopicContent.Encrypted)
getOrCreateCollection(collectionName).save(
MutableDocument(
info.id.toString(),
Expand All @@ -488,7 +491,7 @@ val bus = MutableSharedFlow<Any>()

inline fun <reified T : Any> AppNav.toRoute(): T? {
if (!hasRoute(T::class)) return null
return currentDestination?.toRoute()
return currentDestination?.toRoute<T>()
}

interface AppNav {
Expand Down Expand Up @@ -632,6 +635,5 @@ private fun sendTopicNotification(message: TopicContent.Plain) {
)
}
) {

}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ fun SelectFile(isSignUp: Boolean) {
scope.launch {
val f = FileKit.pickFile()
if (f != null) {
startSign(String(f.readBytes()), appNav, client, isSignUp)
startSign(String(f.readBytes()).replace("\r\n", "\n"), appNav, client, isSignUp)
}
}
}) {
Expand Down
Loading

0 comments on commit 31dd5c2

Please sign in to comment.