Change default server port from 3000 to 8080
Updates the default PORT across backend, Dockerfile, README docs, the Android client's fallback URLs/placeholders, and the frontend dev proxy. Touched files also pick up line-ending normalization (CRLF->LF) with no other content changes. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
84a32fe6b4
commit
f84907eb9b
11 files changed
+1042
-1042
No files matched your search
@@ -42,8 +42,8 @@ The app includes a Settings screen where you can configure the server URL:
|
|||||||
3. Tap "Save"
|
3. Tap "Save"
|
||||||
|
|
||||||
**Default URLs:**
|
**Default URLs:**
|
||||||
- Android Emulator: `http://10.0.2.2:3000/api/`
|
- Android Emulator: `http://10.0.2.2:8080/api/`
|
||||||
- Physical Device: `http://YOUR_COMPUTER_IP:3000/api/` (replace YOUR_COMPUTER_IP with your actual IP address)
|
- Physical Device: `http://YOUR_COMPUTER_IP:8080/api/` (replace YOUR_COMPUTER_IP with your actual IP address)
|
||||||
|
|
||||||
**Note:** Make sure to include `/api/` at the end of the URL.
|
**Note:** Make sure to include `/api/` at the end of the URL.
|
||||||
|
|
||||||
|
|||||||
@@ -1,146 +1,146 @@
|
|||||||
package com.collabtable.app.data.api
|
package com.collabtable.app.data.api
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import com.collabtable.app.data.preferences.PreferencesManager
|
import com.collabtable.app.data.preferences.PreferencesManager
|
||||||
import com.collabtable.app.utils.Logger
|
import com.collabtable.app.utils.Logger
|
||||||
import okhttp3.Interceptor
|
import okhttp3.Interceptor
|
||||||
import okhttp3.OkHttpClient
|
import okhttp3.OkHttpClient
|
||||||
import okhttp3.logging.HttpLoggingInterceptor
|
import okhttp3.logging.HttpLoggingInterceptor
|
||||||
import retrofit2.Retrofit
|
import retrofit2.Retrofit
|
||||||
import retrofit2.converter.gson.GsonConverterFactory
|
import retrofit2.converter.gson.GsonConverterFactory
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
object ApiClient {
|
object ApiClient {
|
||||||
private var baseUrl: String = "http://10.0.2.2:3000/api/" // Default for Android emulator
|
private var baseUrl: String = "http://10.0.2.2:8080/api/" // Default for Android emulator
|
||||||
private var retrofit: Retrofit? = null
|
private var retrofit: Retrofit? = null
|
||||||
private var context: Context? = null
|
private var context: Context? = null
|
||||||
|
|
||||||
private val loggingInterceptor =
|
private val loggingInterceptor =
|
||||||
HttpLoggingInterceptor().apply {
|
HttpLoggingInterceptor().apply {
|
||||||
level = HttpLoggingInterceptor.Level.BODY
|
level = HttpLoggingInterceptor.Level.BODY
|
||||||
}
|
}
|
||||||
|
|
||||||
private val authInterceptor =
|
private val authInterceptor =
|
||||||
Interceptor { chain ->
|
Interceptor { chain ->
|
||||||
val request = chain.request()
|
val request = chain.request()
|
||||||
val apiToken =
|
val apiToken =
|
||||||
context?.let {
|
context?.let {
|
||||||
PreferencesManager.getInstance(it).getApiToken()?.trim()
|
PreferencesManager.getInstance(it).getApiToken()?.trim()
|
||||||
}
|
}
|
||||||
|
|
||||||
val newRequest =
|
val newRequest =
|
||||||
if (!apiToken.isNullOrBlank() && apiToken != "\$apiToken") {
|
if (!apiToken.isNullOrBlank() && apiToken != "\$apiToken") {
|
||||||
request
|
request
|
||||||
.newBuilder()
|
.newBuilder()
|
||||||
.header("Authorization", "Bearer $apiToken")
|
.header("Authorization", "Bearer $apiToken")
|
||||||
.build()
|
.build()
|
||||||
} else {
|
} else {
|
||||||
request
|
request
|
||||||
}
|
}
|
||||||
|
|
||||||
chain.proceed(newRequest)
|
chain.proceed(newRequest)
|
||||||
}
|
}
|
||||||
|
|
||||||
private val deviceIdInterceptor =
|
private val deviceIdInterceptor =
|
||||||
Interceptor { chain ->
|
Interceptor { chain ->
|
||||||
val request = chain.request()
|
val request = chain.request()
|
||||||
val devId = context?.let { PreferencesManager.getInstance(it).getDeviceId() }
|
val devId = context?.let { PreferencesManager.getInstance(it).getDeviceId() }
|
||||||
val newReq =
|
val newReq =
|
||||||
if (!devId.isNullOrBlank()) request.newBuilder().header("x-device-id", devId).build() else request
|
if (!devId.isNullOrBlank()) request.newBuilder().header("x-device-id", devId).build() else request
|
||||||
chain.proceed(newReq)
|
chain.proceed(newReq)
|
||||||
}
|
}
|
||||||
|
|
||||||
private val okHttpClient =
|
private val okHttpClient =
|
||||||
OkHttpClient
|
OkHttpClient
|
||||||
.Builder()
|
.Builder()
|
||||||
.addInterceptor(authInterceptor)
|
.addInterceptor(authInterceptor)
|
||||||
.addInterceptor(deviceIdInterceptor)
|
.addInterceptor(deviceIdInterceptor)
|
||||||
.addInterceptor(loggingInterceptor)
|
.addInterceptor(loggingInterceptor)
|
||||||
.connectTimeout(30, TimeUnit.SECONDS)
|
.connectTimeout(30, TimeUnit.SECONDS)
|
||||||
.readTimeout(30, TimeUnit.SECONDS)
|
.readTimeout(30, TimeUnit.SECONDS)
|
||||||
.writeTimeout(30, TimeUnit.SECONDS)
|
.writeTimeout(30, TimeUnit.SECONDS)
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
private fun buildRetrofit(): Retrofit =
|
private fun buildRetrofit(): Retrofit =
|
||||||
Retrofit
|
Retrofit
|
||||||
.Builder()
|
.Builder()
|
||||||
.baseUrl(baseUrl)
|
.baseUrl(baseUrl)
|
||||||
.client(okHttpClient)
|
.client(okHttpClient)
|
||||||
.addConverterFactory(GsonConverterFactory.create())
|
.addConverterFactory(GsonConverterFactory.create())
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
private fun isEmulator(): Boolean {
|
private fun isEmulator(): Boolean {
|
||||||
val fingerprint = Build.FINGERPRINT.lowercase()
|
val fingerprint = Build.FINGERPRINT.lowercase()
|
||||||
val model = Build.MODEL.lowercase()
|
val model = Build.MODEL.lowercase()
|
||||||
val brand = Build.BRAND.lowercase()
|
val brand = Build.BRAND.lowercase()
|
||||||
val device = Build.DEVICE.lowercase()
|
val device = Build.DEVICE.lowercase()
|
||||||
val product = Build.PRODUCT.lowercase()
|
val product = Build.PRODUCT.lowercase()
|
||||||
return fingerprint.contains("generic") ||
|
return fingerprint.contains("generic") ||
|
||||||
fingerprint.contains("emulator") ||
|
fingerprint.contains("emulator") ||
|
||||||
model.contains("google_sdk") ||
|
model.contains("google_sdk") ||
|
||||||
model.contains("emulator") ||
|
model.contains("emulator") ||
|
||||||
model.contains("android sdk built for") ||
|
model.contains("android sdk built for") ||
|
||||||
brand.startsWith("generic") ||
|
brand.startsWith("generic") ||
|
||||||
device.startsWith("generic") ||
|
device.startsWith("generic") ||
|
||||||
product.contains("sdk")
|
product.contains("sdk")
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun ensureTrailingSlash(url: String): String = if (url.endsWith("/")) url else "$url/"
|
private fun ensureTrailingSlash(url: String): String = if (url.endsWith("/")) url else "$url/"
|
||||||
|
|
||||||
private fun normalizeForAndroidEmulator(rawUrl: String): String {
|
private fun normalizeForAndroidEmulator(rawUrl: String): String {
|
||||||
// Remap common hostnames that are unreachable from the Android emulator to host loopback
|
// Remap common hostnames that are unreachable from the Android emulator to host loopback
|
||||||
// - localhost / 127.0.0.1 / host.docker.internal -> 10.0.2.2 (emulator-only)
|
// - localhost / 127.0.0.1 / host.docker.internal -> 10.0.2.2 (emulator-only)
|
||||||
// Leave other hosts unchanged.
|
// Leave other hosts unchanged.
|
||||||
if (!isEmulator()) return ensureTrailingSlash(rawUrl)
|
if (!isEmulator()) return ensureTrailingSlash(rawUrl)
|
||||||
return try {
|
return try {
|
||||||
val uri = Uri.parse(rawUrl)
|
val uri = Uri.parse(rawUrl)
|
||||||
val host = uri.host?.lowercase()
|
val host = uri.host?.lowercase()
|
||||||
val needsRemap = host == "localhost" || host == "127.0.0.1" || host == "host.docker.internal"
|
val needsRemap = host == "localhost" || host == "127.0.0.1" || host == "host.docker.internal"
|
||||||
if (needsRemap) {
|
if (needsRemap) {
|
||||||
val scheme = uri.scheme ?: "http"
|
val scheme = uri.scheme ?: "http"
|
||||||
val portPart = if (uri.port != -1) ":${uri.port}" else ""
|
val portPart = if (uri.port != -1) ":${uri.port}" else ""
|
||||||
val pathPart = uri.encodedPath ?: "/"
|
val pathPart = uri.encodedPath ?: "/"
|
||||||
val queryPart = if (uri.encodedQuery != null) "?${uri.encodedQuery}" else ""
|
val queryPart = if (uri.encodedQuery != null) "?${uri.encodedQuery}" else ""
|
||||||
val remapped = "$scheme://10.0.2.2$portPart$pathPart$queryPart"
|
val remapped = "$scheme://10.0.2.2$portPart$pathPart$queryPart"
|
||||||
ensureTrailingSlash(if (remapped.contains("/api")) remapped else remapped.trimEnd('/') + "/api/")
|
ensureTrailingSlash(if (remapped.contains("/api")) remapped else remapped.trimEnd('/') + "/api/")
|
||||||
} else {
|
} else {
|
||||||
// Ensure /api/ suffix present
|
// Ensure /api/ suffix present
|
||||||
val ensuredApi = if (rawUrl.contains("/api")) rawUrl else rawUrl.trimEnd('/') + "/api/"
|
val ensuredApi = if (rawUrl.contains("/api")) rawUrl else rawUrl.trimEnd('/') + "/api/"
|
||||||
ensureTrailingSlash(ensuredApi)
|
ensureTrailingSlash(ensuredApi)
|
||||||
}
|
}
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
Logger.w("HTTP", "Failed to normalize API URL '$rawUrl': ${error.message}")
|
Logger.w("HTTP", "Failed to normalize API URL '$rawUrl': ${error.message}")
|
||||||
ensureTrailingSlash(rawUrl)
|
ensureTrailingSlash(rawUrl)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun initialize(context: Context) {
|
fun initialize(context: Context) {
|
||||||
this.context = context.applicationContext
|
this.context = context.applicationContext
|
||||||
val prefs = PreferencesManager.getInstance(context)
|
val prefs = PreferencesManager.getInstance(context)
|
||||||
baseUrl = normalizeForAndroidEmulator(prefs.getServerUrl())
|
baseUrl = normalizeForAndroidEmulator(prefs.getServerUrl())
|
||||||
try {
|
try {
|
||||||
Logger.i("HTTP", "API base URL initialized to $baseUrl")
|
Logger.i("HTTP", "API base URL initialized to $baseUrl")
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
}
|
}
|
||||||
retrofit = buildRetrofit()
|
retrofit = buildRetrofit()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setBaseUrl(url: String) {
|
fun setBaseUrl(url: String) {
|
||||||
baseUrl = normalizeForAndroidEmulator(url)
|
baseUrl = normalizeForAndroidEmulator(url)
|
||||||
try {
|
try {
|
||||||
Logger.i("HTTP", "API base URL set to $baseUrl")
|
Logger.i("HTTP", "API base URL set to $baseUrl")
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
}
|
}
|
||||||
retrofit = buildRetrofit()
|
retrofit = buildRetrofit()
|
||||||
}
|
}
|
||||||
|
|
||||||
val api: CollabTableApi
|
val api: CollabTableApi
|
||||||
get() {
|
get() {
|
||||||
if (retrofit == null) {
|
if (retrofit == null) {
|
||||||
retrofit = buildRetrofit()
|
retrofit = buildRetrofit()
|
||||||
}
|
}
|
||||||
return retrofit!!.create(CollabTableApi::class.java)
|
return retrofit!!.create(CollabTableApi::class.java)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+320
-320
@@ -1,320 +1,320 @@
|
|||||||
package com.collabtable.app.data.preferences
|
package com.collabtable.app.data.preferences
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.SharedPreferences
|
import android.content.SharedPreferences
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
|
|
||||||
class PreferencesManager(
|
class PreferencesManager(
|
||||||
context: Context,
|
context: Context,
|
||||||
) {
|
) {
|
||||||
private val prefs: SharedPreferences =
|
private val prefs: SharedPreferences =
|
||||||
context.getSharedPreferences("collab_table_prefs", Context.MODE_PRIVATE)
|
context.getSharedPreferences("collab_table_prefs", Context.MODE_PRIVATE)
|
||||||
|
|
||||||
private val _serverUrl = MutableStateFlow(getServerUrl())
|
private val _serverUrl = MutableStateFlow(getServerUrl())
|
||||||
val serverUrl: StateFlow<String> = _serverUrl.asStateFlow()
|
val serverUrl: StateFlow<String> = _serverUrl.asStateFlow()
|
||||||
|
|
||||||
private val _isFirstRunFlow = MutableStateFlow(isFirstRun())
|
private val _isFirstRunFlow = MutableStateFlow(isFirstRun())
|
||||||
val isFirstRunFlow: StateFlow<Boolean> = _isFirstRunFlow.asStateFlow()
|
val isFirstRunFlow: StateFlow<Boolean> = _isFirstRunFlow.asStateFlow()
|
||||||
|
|
||||||
private val _themeMode = MutableStateFlow(getThemeMode())
|
private val _themeMode = MutableStateFlow(getThemeMode())
|
||||||
val themeMode: StateFlow<String> = _themeMode.asStateFlow()
|
val themeMode: StateFlow<String> = _themeMode.asStateFlow()
|
||||||
|
|
||||||
private val _dynamicColor = MutableStateFlow(isDynamicColorEnabled())
|
private val _dynamicColor = MutableStateFlow(isDynamicColorEnabled())
|
||||||
val dynamicColor: StateFlow<Boolean> = _dynamicColor.asStateFlow()
|
val dynamicColor: StateFlow<Boolean> = _dynamicColor.asStateFlow()
|
||||||
|
|
||||||
private val _amoledDark = MutableStateFlow(isAmoledDarkEnabled())
|
private val _amoledDark = MutableStateFlow(isAmoledDarkEnabled())
|
||||||
val amoledDark: StateFlow<Boolean> = _amoledDark.asStateFlow()
|
val amoledDark: StateFlow<Boolean> = _amoledDark.asStateFlow()
|
||||||
|
|
||||||
private val _sortOrder = MutableStateFlow(getSortOrder())
|
private val _sortOrder = MutableStateFlow(getSortOrder())
|
||||||
val sortOrder: StateFlow<String> = _sortOrder.asStateFlow()
|
val sortOrder: StateFlow<String> = _sortOrder.asStateFlow()
|
||||||
|
|
||||||
// Sync polling interval in milliseconds (configurable)
|
// Sync polling interval in milliseconds (configurable)
|
||||||
private val _syncPollIntervalMs = MutableStateFlow(getSyncPollIntervalMs())
|
private val _syncPollIntervalMs = MutableStateFlow(getSyncPollIntervalMs())
|
||||||
val syncPollIntervalMs: StateFlow<Long> = _syncPollIntervalMs.asStateFlow()
|
val syncPollIntervalMs: StateFlow<Long> = _syncPollIntervalMs.asStateFlow()
|
||||||
|
|
||||||
// Notification preferences (per list event type)
|
// Notification preferences (per list event type)
|
||||||
private val _notifyListAdded = MutableStateFlow(isNotifyListAddedEnabled())
|
private val _notifyListAdded = MutableStateFlow(isNotifyListAddedEnabled())
|
||||||
val notifyListAdded: StateFlow<Boolean> = _notifyListAdded.asStateFlow()
|
val notifyListAdded: StateFlow<Boolean> = _notifyListAdded.asStateFlow()
|
||||||
|
|
||||||
private val _notifyListEdited = MutableStateFlow(isNotifyListEditedEnabled())
|
private val _notifyListEdited = MutableStateFlow(isNotifyListEditedEnabled())
|
||||||
val notifyListEdited: StateFlow<Boolean> = _notifyListEdited.asStateFlow()
|
val notifyListEdited: StateFlow<Boolean> = _notifyListEdited.asStateFlow()
|
||||||
|
|
||||||
private val _notifyListRemoved = MutableStateFlow(isNotifyListRemovedEnabled())
|
private val _notifyListRemoved = MutableStateFlow(isNotifyListRemovedEnabled())
|
||||||
val notifyListRemoved: StateFlow<Boolean> = _notifyListRemoved.asStateFlow()
|
val notifyListRemoved: StateFlow<Boolean> = _notifyListRemoved.asStateFlow()
|
||||||
|
|
||||||
private val _notifyListContentUpdated = MutableStateFlow(isNotifyListContentUpdatedEnabled())
|
private val _notifyListContentUpdated = MutableStateFlow(isNotifyListContentUpdatedEnabled())
|
||||||
val notifyListContentUpdated: StateFlow<Boolean> = _notifyListContentUpdated.asStateFlow()
|
val notifyListContentUpdated: StateFlow<Boolean> = _notifyListContentUpdated.asStateFlow()
|
||||||
|
|
||||||
fun getServerUrl(): String = prefs.getString(KEY_SERVER_URL, DEFAULT_SERVER_URL) ?: DEFAULT_SERVER_URL
|
fun getServerUrl(): String = prefs.getString(KEY_SERVER_URL, DEFAULT_SERVER_URL) ?: DEFAULT_SERVER_URL
|
||||||
|
|
||||||
fun setServerUrl(url: String) {
|
fun setServerUrl(url: String) {
|
||||||
val raw = url.trim()
|
val raw = url.trim()
|
||||||
if (raw.isBlank()) {
|
if (raw.isBlank()) {
|
||||||
// Remove the key entirely to fall back to default URL on reads
|
// Remove the key entirely to fall back to default URL on reads
|
||||||
prefs.edit().remove(KEY_SERVER_URL).apply()
|
prefs.edit().remove(KEY_SERVER_URL).apply()
|
||||||
_serverUrl.value = getServerUrl()
|
_serverUrl.value = getServerUrl()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
val cleanUrl = raw.let { if (it.endsWith("/")) it else "$it/" }
|
val cleanUrl = raw.let { if (it.endsWith("/")) it else "$it/" }
|
||||||
prefs.edit().putString(KEY_SERVER_URL, cleanUrl).apply()
|
prefs.edit().putString(KEY_SERVER_URL, cleanUrl).apply()
|
||||||
_serverUrl.value = cleanUrl
|
_serverUrl.value = cleanUrl
|
||||||
}
|
}
|
||||||
|
|
||||||
fun isFirstRun(): Boolean = prefs.getBoolean(KEY_FIRST_RUN, true)
|
fun isFirstRun(): Boolean = prefs.getBoolean(KEY_FIRST_RUN, true)
|
||||||
|
|
||||||
fun setIsFirstRun(isFirstRun: Boolean) {
|
fun setIsFirstRun(isFirstRun: Boolean) {
|
||||||
prefs.edit().putBoolean(KEY_FIRST_RUN, isFirstRun).apply()
|
prefs.edit().putBoolean(KEY_FIRST_RUN, isFirstRun).apply()
|
||||||
_isFirstRunFlow.value = isFirstRun
|
_isFirstRunFlow.value = isFirstRun
|
||||||
}
|
}
|
||||||
|
|
||||||
fun getApiToken(): String? = prefs.getString(KEY_API_TOKEN, null)
|
fun getApiToken(): String? = prefs.getString(KEY_API_TOKEN, null)
|
||||||
|
|
||||||
fun setApiToken(apiToken: String) {
|
fun setApiToken(apiToken: String) {
|
||||||
if (apiToken.isBlank()) {
|
if (apiToken.isBlank()) {
|
||||||
prefs.edit().remove(KEY_API_TOKEN).apply()
|
prefs.edit().remove(KEY_API_TOKEN).apply()
|
||||||
} else {
|
} else {
|
||||||
prefs.edit().putString(KEY_API_TOKEN, apiToken).apply()
|
prefs.edit().putString(KEY_API_TOKEN, apiToken).apply()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear sync-related state so the next sync starts from scratch
|
// Clear sync-related state so the next sync starts from scratch
|
||||||
fun clearSyncState() {
|
fun clearSyncState() {
|
||||||
prefs.edit().remove(KEY_LAST_SYNC_TIMESTAMP).apply()
|
prefs.edit().remove(KEY_LAST_SYNC_TIMESTAMP).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun clearServerSettings() {
|
fun clearServerSettings() {
|
||||||
prefs
|
prefs
|
||||||
.edit()
|
.edit()
|
||||||
.remove(KEY_SERVER_URL)
|
.remove(KEY_SERVER_URL)
|
||||||
.remove(KEY_API_TOKEN)
|
.remove(KEY_API_TOKEN)
|
||||||
.remove(KEY_LAST_SYNC_TIMESTAMP)
|
.remove(KEY_LAST_SYNC_TIMESTAMP)
|
||||||
.apply()
|
.apply()
|
||||||
_serverUrl.value = getServerUrl()
|
_serverUrl.value = getServerUrl()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Theme settings
|
// Theme settings
|
||||||
fun getThemeMode(): String = prefs.getString(KEY_THEME_MODE, THEME_MODE_SYSTEM) ?: THEME_MODE_SYSTEM
|
fun getThemeMode(): String = prefs.getString(KEY_THEME_MODE, THEME_MODE_SYSTEM) ?: THEME_MODE_SYSTEM
|
||||||
|
|
||||||
fun setThemeMode(mode: String) {
|
fun setThemeMode(mode: String) {
|
||||||
val normalized =
|
val normalized =
|
||||||
when (mode.lowercase()) {
|
when (mode.lowercase()) {
|
||||||
THEME_MODE_LIGHT, THEME_MODE_DARK, THEME_MODE_SYSTEM -> mode.lowercase()
|
THEME_MODE_LIGHT, THEME_MODE_DARK, THEME_MODE_SYSTEM -> mode.lowercase()
|
||||||
else -> THEME_MODE_SYSTEM
|
else -> THEME_MODE_SYSTEM
|
||||||
}
|
}
|
||||||
prefs.edit().putString(KEY_THEME_MODE, normalized).apply()
|
prefs.edit().putString(KEY_THEME_MODE, normalized).apply()
|
||||||
_themeMode.value = normalized
|
_themeMode.value = normalized
|
||||||
}
|
}
|
||||||
|
|
||||||
fun isDynamicColorEnabled(): Boolean = prefs.getBoolean(KEY_DYNAMIC_COLOR, true)
|
fun isDynamicColorEnabled(): Boolean = prefs.getBoolean(KEY_DYNAMIC_COLOR, true)
|
||||||
|
|
||||||
fun setDynamicColorEnabled(enabled: Boolean) {
|
fun setDynamicColorEnabled(enabled: Boolean) {
|
||||||
prefs.edit().putBoolean(KEY_DYNAMIC_COLOR, enabled).apply()
|
prefs.edit().putBoolean(KEY_DYNAMIC_COLOR, enabled).apply()
|
||||||
_dynamicColor.value = enabled
|
_dynamicColor.value = enabled
|
||||||
}
|
}
|
||||||
|
|
||||||
fun isAmoledDarkEnabled(): Boolean = prefs.getBoolean(KEY_AMOLED_DARK, false)
|
fun isAmoledDarkEnabled(): Boolean = prefs.getBoolean(KEY_AMOLED_DARK, false)
|
||||||
|
|
||||||
fun setAmoledDarkEnabled(enabled: Boolean) {
|
fun setAmoledDarkEnabled(enabled: Boolean) {
|
||||||
prefs.edit().putBoolean(KEY_AMOLED_DARK, enabled).apply()
|
prefs.edit().putBoolean(KEY_AMOLED_DARK, enabled).apply()
|
||||||
_amoledDark.value = enabled
|
_amoledDark.value = enabled
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sorting preferences for tables overview
|
// Sorting preferences for tables overview
|
||||||
fun getSortOrder(): String = prefs.getString(KEY_SORT_ORDER, SORT_UPDATED_DESC) ?: SORT_UPDATED_DESC
|
fun getSortOrder(): String = prefs.getString(KEY_SORT_ORDER, SORT_UPDATED_DESC) ?: SORT_UPDATED_DESC
|
||||||
|
|
||||||
fun setSortOrder(order: String) {
|
fun setSortOrder(order: String) {
|
||||||
val normalized =
|
val normalized =
|
||||||
when (order) {
|
when (order) {
|
||||||
SORT_UPDATED_DESC, SORT_UPDATED_ASC, SORT_NAME_ASC, SORT_NAME_DESC -> order
|
SORT_UPDATED_DESC, SORT_UPDATED_ASC, SORT_NAME_ASC, SORT_NAME_DESC -> order
|
||||||
else -> SORT_UPDATED_DESC
|
else -> SORT_UPDATED_DESC
|
||||||
}
|
}
|
||||||
prefs.edit().putString(KEY_SORT_ORDER, normalized).apply()
|
prefs.edit().putString(KEY_SORT_ORDER, normalized).apply()
|
||||||
_sortOrder.value = normalized
|
_sortOrder.value = normalized
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sync interval: read/write with sensible bounds to avoid too-aggressive polling
|
// Sync interval: read/write with sensible bounds to avoid too-aggressive polling
|
||||||
fun getSyncPollIntervalMs(): Long {
|
fun getSyncPollIntervalMs(): Long {
|
||||||
val raw = prefs.getLong(KEY_SYNC_POLL_INTERVAL_MS, DEFAULT_SYNC_POLL_INTERVAL_MS)
|
val raw = prefs.getLong(KEY_SYNC_POLL_INTERVAL_MS, DEFAULT_SYNC_POLL_INTERVAL_MS)
|
||||||
return raw.coerceIn(MIN_SYNC_POLL_INTERVAL_MS, MAX_SYNC_POLL_INTERVAL_MS)
|
return raw.coerceIn(MIN_SYNC_POLL_INTERVAL_MS, MAX_SYNC_POLL_INTERVAL_MS)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setSyncPollIntervalMs(ms: Long) {
|
fun setSyncPollIntervalMs(ms: Long) {
|
||||||
val clamped = ms.coerceIn(MIN_SYNC_POLL_INTERVAL_MS, MAX_SYNC_POLL_INTERVAL_MS)
|
val clamped = ms.coerceIn(MIN_SYNC_POLL_INTERVAL_MS, MAX_SYNC_POLL_INTERVAL_MS)
|
||||||
prefs.edit().putLong(KEY_SYNC_POLL_INTERVAL_MS, clamped).apply()
|
prefs.edit().putLong(KEY_SYNC_POLL_INTERVAL_MS, clamped).apply()
|
||||||
_syncPollIntervalMs.value = clamped
|
_syncPollIntervalMs.value = clamped
|
||||||
}
|
}
|
||||||
|
|
||||||
// Last time we checked lists for background notifications
|
// Last time we checked lists for background notifications
|
||||||
fun getLastListNotifyCheckTimestamp(): Long = prefs.getLong(KEY_LAST_LIST_NOTIFY_CHECK_TS, 0L)
|
fun getLastListNotifyCheckTimestamp(): Long = prefs.getLong(KEY_LAST_LIST_NOTIFY_CHECK_TS, 0L)
|
||||||
|
|
||||||
fun setLastListNotifyCheckTimestamp(ts: Long) {
|
fun setLastListNotifyCheckTimestamp(ts: Long) {
|
||||||
prefs.edit().putLong(KEY_LAST_LIST_NOTIFY_CHECK_TS, ts).apply()
|
prefs.edit().putLong(KEY_LAST_LIST_NOTIFY_CHECK_TS, ts).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Notification settings accessors
|
// Notification settings accessors
|
||||||
private fun isNotifyListAddedEnabled(): Boolean = prefs.getBoolean(KEY_NOTIFY_LIST_ADDED, true)
|
private fun isNotifyListAddedEnabled(): Boolean = prefs.getBoolean(KEY_NOTIFY_LIST_ADDED, true)
|
||||||
|
|
||||||
fun setNotifyListAddedEnabled(enabled: Boolean) {
|
fun setNotifyListAddedEnabled(enabled: Boolean) {
|
||||||
prefs.edit().putBoolean(KEY_NOTIFY_LIST_ADDED, enabled).apply()
|
prefs.edit().putBoolean(KEY_NOTIFY_LIST_ADDED, enabled).apply()
|
||||||
_notifyListAdded.value = enabled
|
_notifyListAdded.value = enabled
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun isNotifyListEditedEnabled(): Boolean = prefs.getBoolean(KEY_NOTIFY_LIST_EDITED, true)
|
private fun isNotifyListEditedEnabled(): Boolean = prefs.getBoolean(KEY_NOTIFY_LIST_EDITED, true)
|
||||||
|
|
||||||
fun setNotifyListEditedEnabled(enabled: Boolean) {
|
fun setNotifyListEditedEnabled(enabled: Boolean) {
|
||||||
prefs.edit().putBoolean(KEY_NOTIFY_LIST_EDITED, enabled).apply()
|
prefs.edit().putBoolean(KEY_NOTIFY_LIST_EDITED, enabled).apply()
|
||||||
_notifyListEdited.value = enabled
|
_notifyListEdited.value = enabled
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun isNotifyListRemovedEnabled(): Boolean = prefs.getBoolean(KEY_NOTIFY_LIST_REMOVED, true)
|
private fun isNotifyListRemovedEnabled(): Boolean = prefs.getBoolean(KEY_NOTIFY_LIST_REMOVED, true)
|
||||||
|
|
||||||
fun setNotifyListRemovedEnabled(enabled: Boolean) {
|
fun setNotifyListRemovedEnabled(enabled: Boolean) {
|
||||||
prefs.edit().putBoolean(KEY_NOTIFY_LIST_REMOVED, enabled).apply()
|
prefs.edit().putBoolean(KEY_NOTIFY_LIST_REMOVED, enabled).apply()
|
||||||
_notifyListRemoved.value = enabled
|
_notifyListRemoved.value = enabled
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun isNotifyListContentUpdatedEnabled(): Boolean = prefs.getBoolean(KEY_NOTIFY_LIST_CONTENT_UPDATED, true)
|
private fun isNotifyListContentUpdatedEnabled(): Boolean = prefs.getBoolean(KEY_NOTIFY_LIST_CONTENT_UPDATED, true)
|
||||||
|
|
||||||
fun setNotifyListContentUpdatedEnabled(enabled: Boolean) {
|
fun setNotifyListContentUpdatedEnabled(enabled: Boolean) {
|
||||||
prefs.edit().putBoolean(KEY_NOTIFY_LIST_CONTENT_UPDATED, enabled).apply()
|
prefs.edit().putBoolean(KEY_NOTIFY_LIST_CONTENT_UPDATED, enabled).apply()
|
||||||
_notifyListContentUpdated.value = enabled
|
_notifyListContentUpdated.value = enabled
|
||||||
}
|
}
|
||||||
|
|
||||||
fun hasPromptedNotifications(): Boolean = prefs.getBoolean(KEY_HAS_PROMPTED_NOTIFICATIONS, false)
|
fun hasPromptedNotifications(): Boolean = prefs.getBoolean(KEY_HAS_PROMPTED_NOTIFICATIONS, false)
|
||||||
|
|
||||||
fun setHasPromptedNotifications(prompted: Boolean) {
|
fun setHasPromptedNotifications(prompted: Boolean) {
|
||||||
prefs.edit().putBoolean(KEY_HAS_PROMPTED_NOTIFICATIONS, prompted).apply()
|
prefs.edit().putBoolean(KEY_HAS_PROMPTED_NOTIFICATIONS, prompted).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Persist per-list column widths (fieldId -> widthDp)
|
// Persist per-list column widths (fieldId -> widthDp)
|
||||||
// Stored as a JSON object string in SharedPreferences under key: COLUMN_WIDTHS_PREFIX + listId
|
// Stored as a JSON object string in SharedPreferences under key: COLUMN_WIDTHS_PREFIX + listId
|
||||||
fun getColumnWidths(listId: String): Map<String, Float> {
|
fun getColumnWidths(listId: String): Map<String, Float> {
|
||||||
val key = COLUMN_WIDTHS_PREFIX + listId
|
val key = COLUMN_WIDTHS_PREFIX + listId
|
||||||
val raw = prefs.getString(key, null) ?: return emptyMap()
|
val raw = prefs.getString(key, null) ?: return emptyMap()
|
||||||
return runCatching {
|
return runCatching {
|
||||||
val json = JSONObject(raw)
|
val json = JSONObject(raw)
|
||||||
val map = mutableMapOf<String, Float>()
|
val map = mutableMapOf<String, Float>()
|
||||||
val it = json.keys()
|
val it = json.keys()
|
||||||
while (it.hasNext()) {
|
while (it.hasNext()) {
|
||||||
val fieldId = it.next()
|
val fieldId = it.next()
|
||||||
val width = json.optDouble(fieldId, Double.NaN)
|
val width = json.optDouble(fieldId, Double.NaN)
|
||||||
if (!width.isNaN()) {
|
if (!width.isNaN()) {
|
||||||
map[fieldId] = width.toFloat()
|
map[fieldId] = width.toFloat()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
map
|
map
|
||||||
}.getOrDefault(emptyMap())
|
}.getOrDefault(emptyMap())
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setColumnWidths(
|
fun setColumnWidths(
|
||||||
listId: String,
|
listId: String,
|
||||||
widthsDp: Map<String, Float>,
|
widthsDp: Map<String, Float>,
|
||||||
) {
|
) {
|
||||||
val key = COLUMN_WIDTHS_PREFIX + listId
|
val key = COLUMN_WIDTHS_PREFIX + listId
|
||||||
val json = JSONObject()
|
val json = JSONObject()
|
||||||
widthsDp.forEach { (fieldId, width) ->
|
widthsDp.forEach { (fieldId, width) ->
|
||||||
// Persist as double for precision, value is in dp units
|
// Persist as double for precision, value is in dp units
|
||||||
json.put(fieldId, width.toDouble())
|
json.put(fieldId, width.toDouble())
|
||||||
}
|
}
|
||||||
prefs.edit().putString(key, json.toString()).apply()
|
prefs.edit().putString(key, json.toString()).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Persist per-list column alignments (fieldId -> alignment: "start" | "center" | "end")
|
// Persist per-list column alignments (fieldId -> alignment: "start" | "center" | "end")
|
||||||
// Stored as a JSON object string under key: COLUMN_ALIGN_PREFIX + listId
|
// Stored as a JSON object string under key: COLUMN_ALIGN_PREFIX + listId
|
||||||
fun getColumnAlignments(listId: String): Map<String, String> {
|
fun getColumnAlignments(listId: String): Map<String, String> {
|
||||||
val key = COLUMN_ALIGN_PREFIX + listId
|
val key = COLUMN_ALIGN_PREFIX + listId
|
||||||
val raw = prefs.getString(key, null) ?: return emptyMap()
|
val raw = prefs.getString(key, null) ?: return emptyMap()
|
||||||
return runCatching {
|
return runCatching {
|
||||||
val json = JSONObject(raw)
|
val json = JSONObject(raw)
|
||||||
val map = mutableMapOf<String, String>()
|
val map = mutableMapOf<String, String>()
|
||||||
val it = json.keys()
|
val it = json.keys()
|
||||||
while (it.hasNext()) {
|
while (it.hasNext()) {
|
||||||
val fieldId = it.next()
|
val fieldId = it.next()
|
||||||
val align = json.optString(fieldId, "start")
|
val align = json.optString(fieldId, "start")
|
||||||
val normalized =
|
val normalized =
|
||||||
when (align.lowercase()) {
|
when (align.lowercase()) {
|
||||||
"center" -> "center"
|
"center" -> "center"
|
||||||
"end", "right" -> "end"
|
"end", "right" -> "end"
|
||||||
else -> "start"
|
else -> "start"
|
||||||
}
|
}
|
||||||
map[fieldId] = normalized
|
map[fieldId] = normalized
|
||||||
}
|
}
|
||||||
map
|
map
|
||||||
}.getOrDefault(emptyMap())
|
}.getOrDefault(emptyMap())
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setColumnAlignments(
|
fun setColumnAlignments(
|
||||||
listId: String,
|
listId: String,
|
||||||
alignments: Map<String, String>,
|
alignments: Map<String, String>,
|
||||||
) {
|
) {
|
||||||
val key = COLUMN_ALIGN_PREFIX + listId
|
val key = COLUMN_ALIGN_PREFIX + listId
|
||||||
val json = JSONObject()
|
val json = JSONObject()
|
||||||
alignments.forEach { (fieldId, alignment) ->
|
alignments.forEach { (fieldId, alignment) ->
|
||||||
val normalized =
|
val normalized =
|
||||||
when (alignment.lowercase()) {
|
when (alignment.lowercase()) {
|
||||||
"center" -> "center"
|
"center" -> "center"
|
||||||
"end", "right" -> "end"
|
"end", "right" -> "end"
|
||||||
else -> "start"
|
else -> "start"
|
||||||
}
|
}
|
||||||
json.put(fieldId, normalized)
|
json.put(fieldId, normalized)
|
||||||
}
|
}
|
||||||
prefs.edit().putString(key, json.toString()).apply()
|
prefs.edit().putString(key, json.toString()).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate and cache a stable device id (UUID) for this install
|
// Generate and cache a stable device id (UUID) for this install
|
||||||
fun getDeviceId(): String {
|
fun getDeviceId(): String {
|
||||||
val existing = prefs.getString(KEY_DEVICE_ID, null)
|
val existing = prefs.getString(KEY_DEVICE_ID, null)
|
||||||
if (!existing.isNullOrBlank()) return existing
|
if (!existing.isNullOrBlank()) return existing
|
||||||
val id =
|
val id =
|
||||||
java.util.UUID
|
java.util.UUID
|
||||||
.randomUUID()
|
.randomUUID()
|
||||||
.toString()
|
.toString()
|
||||||
prefs.edit().putString(KEY_DEVICE_ID, id).apply()
|
prefs.edit().putString(KEY_DEVICE_ID, id).apply()
|
||||||
return id
|
return id
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private const val KEY_SERVER_URL = "server_url"
|
private const val KEY_SERVER_URL = "server_url"
|
||||||
private const val KEY_DEVICE_ID = "device_id"
|
private const val KEY_DEVICE_ID = "device_id"
|
||||||
private const val KEY_FIRST_RUN = "first_run"
|
private const val KEY_FIRST_RUN = "first_run"
|
||||||
private const val KEY_API_TOKEN = "api_token"
|
private const val KEY_API_TOKEN = "api_token"
|
||||||
private const val KEY_LAST_SYNC_TIMESTAMP = "last_sync_timestamp"
|
private const val KEY_LAST_SYNC_TIMESTAMP = "last_sync_timestamp"
|
||||||
private const val KEY_THEME_MODE = "theme_mode" // system|light|dark
|
private const val KEY_THEME_MODE = "theme_mode" // system|light|dark
|
||||||
private const val KEY_DYNAMIC_COLOR = "dynamic_color"
|
private const val KEY_DYNAMIC_COLOR = "dynamic_color"
|
||||||
private const val KEY_AMOLED_DARK = "amoled_dark"
|
private const val KEY_AMOLED_DARK = "amoled_dark"
|
||||||
private const val KEY_SORT_ORDER = "sort_order"
|
private const val KEY_SORT_ORDER = "sort_order"
|
||||||
private const val KEY_SYNC_POLL_INTERVAL_MS = "sync_poll_interval_ms"
|
private const val KEY_SYNC_POLL_INTERVAL_MS = "sync_poll_interval_ms"
|
||||||
private const val KEY_NOTIFY_LIST_ADDED = "notify_list_added"
|
private const val KEY_NOTIFY_LIST_ADDED = "notify_list_added"
|
||||||
private const val KEY_NOTIFY_LIST_EDITED = "notify_list_edited"
|
private const val KEY_NOTIFY_LIST_EDITED = "notify_list_edited"
|
||||||
private const val KEY_NOTIFY_LIST_REMOVED = "notify_list_removed"
|
private const val KEY_NOTIFY_LIST_REMOVED = "notify_list_removed"
|
||||||
private const val KEY_NOTIFY_LIST_CONTENT_UPDATED = "notify_list_content_updated"
|
private const val KEY_NOTIFY_LIST_CONTENT_UPDATED = "notify_list_content_updated"
|
||||||
private const val KEY_LAST_LIST_NOTIFY_CHECK_TS = "last_list_notify_check_ts"
|
private const val KEY_LAST_LIST_NOTIFY_CHECK_TS = "last_list_notify_check_ts"
|
||||||
private const val KEY_HAS_PROMPTED_NOTIFICATIONS = "has_prompted_notifications"
|
private const val KEY_HAS_PROMPTED_NOTIFICATIONS = "has_prompted_notifications"
|
||||||
private const val COLUMN_WIDTHS_PREFIX = "column_widths_" // + listId
|
private const val COLUMN_WIDTHS_PREFIX = "column_widths_" // + listId
|
||||||
private const val COLUMN_ALIGN_PREFIX = "column_align_" // + listId
|
private const val COLUMN_ALIGN_PREFIX = "column_align_" // + listId
|
||||||
private const val DEFAULT_SERVER_URL = "http://10.0.2.2:3000/api/"
|
private const val DEFAULT_SERVER_URL = "http://10.0.2.2:8080/api/"
|
||||||
private const val DEFAULT_SYNC_POLL_INTERVAL_MS = 250L
|
private const val DEFAULT_SYNC_POLL_INTERVAL_MS = 250L
|
||||||
private const val MIN_SYNC_POLL_INTERVAL_MS = 250L
|
private const val MIN_SYNC_POLL_INTERVAL_MS = 250L
|
||||||
private const val MAX_SYNC_POLL_INTERVAL_MS = 600_000L // 10 minutes
|
private const val MAX_SYNC_POLL_INTERVAL_MS = 600_000L // 10 minutes
|
||||||
const val THEME_MODE_SYSTEM = "system"
|
const val THEME_MODE_SYSTEM = "system"
|
||||||
const val THEME_MODE_LIGHT = "light"
|
const val THEME_MODE_LIGHT = "light"
|
||||||
const val THEME_MODE_DARK = "dark"
|
const val THEME_MODE_DARK = "dark"
|
||||||
|
|
||||||
// Sort orders
|
// Sort orders
|
||||||
const val SORT_UPDATED_DESC = "updated_desc" // Newest first (default)
|
const val SORT_UPDATED_DESC = "updated_desc" // Newest first (default)
|
||||||
const val SORT_UPDATED_ASC = "updated_asc" // Oldest first
|
const val SORT_UPDATED_ASC = "updated_asc" // Oldest first
|
||||||
const val SORT_NAME_ASC = "name_asc" // A-Z
|
const val SORT_NAME_ASC = "name_asc" // A-Z
|
||||||
const val SORT_NAME_DESC = "name_desc" // Z-A
|
const val SORT_NAME_DESC = "name_desc" // Z-A
|
||||||
|
|
||||||
@Volatile
|
@Volatile
|
||||||
private var instance: PreferencesManager? = null
|
private var instance: PreferencesManager? = null
|
||||||
|
|
||||||
fun getInstance(context: Context): PreferencesManager =
|
fun getInstance(context: Context): PreferencesManager =
|
||||||
instance ?: synchronized(this) {
|
instance ?: synchronized(this) {
|
||||||
instance ?: PreferencesManager(context.applicationContext).also { instance = it }
|
instance ?: PreferencesManager(context.applicationContext).also { instance = it }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+256
-256
@@ -1,256 +1,256 @@
|
|||||||
package com.collabtable.app.ui.screens
|
package com.collabtable.app.ui.screens
|
||||||
|
|
||||||
import android.Manifest
|
import android.Manifest
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.Spacer
|
import androidx.compose.foundation.layout.Spacer
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.height
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.text.KeyboardOptions
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.CheckCircle
|
import androidx.compose.material.icons.filled.CheckCircle
|
||||||
import androidx.compose.material.icons.filled.Error
|
import androidx.compose.material.icons.filled.Error
|
||||||
import androidx.compose.material.icons.filled.Visibility
|
import androidx.compose.material.icons.filled.Visibility
|
||||||
import androidx.compose.material.icons.filled.VisibilityOff
|
import androidx.compose.material.icons.filled.VisibilityOff
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.CenterAlignedTopAppBar
|
import androidx.compose.material3.CenterAlignedTopAppBar
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TopAppBarDefaults
|
import androidx.compose.material3.TopAppBarDefaults
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.collectAsState
|
import androidx.compose.runtime.collectAsState
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.text.input.KeyboardType
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
import androidx.compose.ui.text.input.VisualTransformation
|
import androidx.compose.ui.text.input.VisualTransformation
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
import com.collabtable.app.data.preferences.PreferencesManager
|
import com.collabtable.app.data.preferences.PreferencesManager
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun ServerSetupScreen(onSetupComplete: () -> Unit) {
|
fun ServerSetupScreen(onSetupComplete: () -> Unit) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val preferencesManager = remember { PreferencesManager.getInstance(context) }
|
val preferencesManager = remember { PreferencesManager.getInstance(context) }
|
||||||
val viewModel = remember { ServerSetupViewModel(preferencesManager) }
|
val viewModel = remember { ServerSetupViewModel(preferencesManager) }
|
||||||
|
|
||||||
var serverUrl by remember { mutableStateOf("") }
|
var serverUrl by remember { mutableStateOf("") }
|
||||||
var apiToken by remember { mutableStateOf("") }
|
var apiToken by remember { mutableStateOf("") }
|
||||||
var tokenVisible by remember { mutableStateOf(false) }
|
var tokenVisible by remember { mutableStateOf(false) }
|
||||||
val isValidating by viewModel.isValidating.collectAsState()
|
val isValidating by viewModel.isValidating.collectAsState()
|
||||||
val validationResult by viewModel.validationResult.collectAsState()
|
val validationResult by viewModel.validationResult.collectAsState()
|
||||||
val validationError by viewModel.validationError.collectAsState()
|
val validationError by viewModel.validationError.collectAsState()
|
||||||
|
|
||||||
var completed by remember { mutableStateOf(false) }
|
var completed by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
fun finishOnce() {
|
fun finishOnce() {
|
||||||
if (!completed) {
|
if (!completed) {
|
||||||
completed = true
|
completed = true
|
||||||
preferencesManager.setHasPromptedNotifications(true)
|
preferencesManager.setHasPromptedNotifications(true)
|
||||||
onSetupComplete()
|
onSetupComplete()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val permissionLauncher =
|
val permissionLauncher =
|
||||||
rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||||
// If granted, enable all; else disable all
|
// If granted, enable all; else disable all
|
||||||
preferencesManager.setNotifyListAddedEnabled(granted)
|
preferencesManager.setNotifyListAddedEnabled(granted)
|
||||||
preferencesManager.setNotifyListEditedEnabled(granted)
|
preferencesManager.setNotifyListEditedEnabled(granted)
|
||||||
preferencesManager.setNotifyListRemovedEnabled(granted)
|
preferencesManager.setNotifyListRemovedEnabled(granted)
|
||||||
// Also set content-updated preference consistently
|
// Also set content-updated preference consistently
|
||||||
try {
|
try {
|
||||||
preferencesManager.setNotifyListContentUpdatedEnabled(granted)
|
preferencesManager.setNotifyListContentUpdatedEnabled(granted)
|
||||||
} catch (_: Throwable) {
|
} catch (_: Throwable) {
|
||||||
// Older builds may not have this preference; ignore
|
// Older builds may not have this preference; ignore
|
||||||
}
|
}
|
||||||
finishOnce()
|
finishOnce()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun startCompletionFlow() {
|
fun startCompletionFlow() {
|
||||||
if (completed) return
|
if (completed) return
|
||||||
|
|
||||||
// On Android 13+ prompt for notifications; otherwise default to enabled
|
// On Android 13+ prompt for notifications; otherwise default to enabled
|
||||||
if (Build.VERSION.SDK_INT >= 33) {
|
if (Build.VERSION.SDK_INT >= 33) {
|
||||||
val granted =
|
val granted =
|
||||||
ContextCompat.checkSelfPermission(
|
ContextCompat.checkSelfPermission(
|
||||||
context,
|
context,
|
||||||
Manifest.permission.POST_NOTIFICATIONS,
|
Manifest.permission.POST_NOTIFICATIONS,
|
||||||
) == PackageManager.PERMISSION_GRANTED
|
) == PackageManager.PERMISSION_GRANTED
|
||||||
if (granted) {
|
if (granted) {
|
||||||
preferencesManager.setNotifyListAddedEnabled(true)
|
preferencesManager.setNotifyListAddedEnabled(true)
|
||||||
preferencesManager.setNotifyListEditedEnabled(true)
|
preferencesManager.setNotifyListEditedEnabled(true)
|
||||||
preferencesManager.setNotifyListRemovedEnabled(true)
|
preferencesManager.setNotifyListRemovedEnabled(true)
|
||||||
try {
|
try {
|
||||||
preferencesManager.setNotifyListContentUpdatedEnabled(true)
|
preferencesManager.setNotifyListContentUpdatedEnabled(true)
|
||||||
} catch (_: Throwable) {
|
} catch (_: Throwable) {
|
||||||
}
|
}
|
||||||
finishOnce()
|
finishOnce()
|
||||||
} else {
|
} else {
|
||||||
// Request permission; callback will complete
|
// Request permission; callback will complete
|
||||||
permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
preferencesManager.setNotifyListAddedEnabled(true)
|
preferencesManager.setNotifyListAddedEnabled(true)
|
||||||
preferencesManager.setNotifyListEditedEnabled(true)
|
preferencesManager.setNotifyListEditedEnabled(true)
|
||||||
preferencesManager.setNotifyListRemovedEnabled(true)
|
preferencesManager.setNotifyListRemovedEnabled(true)
|
||||||
try {
|
try {
|
||||||
preferencesManager.setNotifyListContentUpdatedEnabled(true)
|
preferencesManager.setNotifyListContentUpdatedEnabled(true)
|
||||||
} catch (_: Throwable) {
|
} catch (_: Throwable) {
|
||||||
}
|
}
|
||||||
finishOnce()
|
finishOnce()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
LaunchedEffect(validationResult) {
|
LaunchedEffect(validationResult) {
|
||||||
if (validationResult == true && !completed) {
|
if (validationResult == true && !completed) {
|
||||||
startCompletionFlow()
|
startCompletionFlow()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
topBar = {
|
topBar = {
|
||||||
CenterAlignedTopAppBar(
|
CenterAlignedTopAppBar(
|
||||||
title = { Text("Server Setup") },
|
title = { Text("Server Setup") },
|
||||||
colors =
|
colors =
|
||||||
TopAppBarDefaults.centerAlignedTopAppBarColors(
|
TopAppBarDefaults.centerAlignedTopAppBarColors(
|
||||||
containerColor = MaterialTheme.colorScheme.primaryContainer,
|
containerColor = MaterialTheme.colorScheme.primaryContainer,
|
||||||
titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
|
titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
) { padding ->
|
) { padding ->
|
||||||
Column(
|
Column(
|
||||||
modifier =
|
modifier =
|
||||||
Modifier
|
Modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.padding(padding)
|
.padding(padding)
|
||||||
.padding(16.dp),
|
.padding(16.dp),
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
) {
|
) {
|
||||||
Spacer(modifier = Modifier.height(4.dp))
|
Spacer(modifier = Modifier.height(4.dp))
|
||||||
|
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = serverUrl,
|
value = serverUrl,
|
||||||
onValueChange = {
|
onValueChange = {
|
||||||
serverUrl = it
|
serverUrl = it
|
||||||
viewModel.clearValidationState()
|
viewModel.clearValidationState()
|
||||||
},
|
},
|
||||||
label = { Text("Server Hostname") },
|
label = { Text("Server Hostname") },
|
||||||
placeholder = { Text("example.com or 10.0.2.2:3000") },
|
placeholder = { Text("example.com or 10.0.2.2:8080") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
enabled = !isValidating,
|
enabled = !isValidating,
|
||||||
isError = validationError != null,
|
isError = validationError != null,
|
||||||
supportingText = {
|
supportingText = {
|
||||||
when {
|
when {
|
||||||
validationError != null ->
|
validationError != null ->
|
||||||
Text(
|
Text(
|
||||||
text = validationError ?: "",
|
text = validationError ?: "",
|
||||||
color = MaterialTheme.colorScheme.error,
|
color = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
else -> Text("Server address (e.g. 192.168.1.5:3000)")
|
else -> Text("Server address (e.g. 192.168.1.5:8080)")
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
trailingIcon = {
|
trailingIcon = {
|
||||||
when {
|
when {
|
||||||
isValidating ->
|
isValidating ->
|
||||||
CircularProgressIndicator(
|
CircularProgressIndicator(
|
||||||
modifier = Modifier.size(24.dp),
|
modifier = Modifier.size(24.dp),
|
||||||
strokeWidth = 2.dp,
|
strokeWidth = 2.dp,
|
||||||
)
|
)
|
||||||
validationResult == true ->
|
validationResult == true ->
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Default.CheckCircle,
|
Icons.Default.CheckCircle,
|
||||||
contentDescription = "Valid",
|
contentDescription = "Valid",
|
||||||
tint = MaterialTheme.colorScheme.primary,
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
)
|
)
|
||||||
validationError != null ->
|
validationError != null ->
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Default.Error,
|
Icons.Default.Error,
|
||||||
contentDescription = "Error",
|
contentDescription = "Error",
|
||||||
tint = MaterialTheme.colorScheme.error,
|
tint = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = apiToken,
|
value = apiToken,
|
||||||
onValueChange = {
|
onValueChange = {
|
||||||
apiToken = it
|
apiToken = it
|
||||||
viewModel.clearValidationState()
|
viewModel.clearValidationState()
|
||||||
},
|
},
|
||||||
label = { Text("API Token") },
|
label = { Text("API Token") },
|
||||||
placeholder = { Text("Paste API token") },
|
placeholder = { Text("Paste API token") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
enabled = !isValidating,
|
enabled = !isValidating,
|
||||||
visualTransformation = if (tokenVisible) VisualTransformation.None else PasswordVisualTransformation(),
|
visualTransformation = if (tokenVisible) VisualTransformation.None else PasswordVisualTransformation(),
|
||||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
|
||||||
trailingIcon = {
|
trailingIcon = {
|
||||||
IconButton(onClick = { tokenVisible = !tokenVisible }) {
|
IconButton(onClick = { tokenVisible = !tokenVisible }) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = if (tokenVisible) Icons.Default.Visibility else Icons.Default.VisibilityOff,
|
imageVector = if (tokenVisible) Icons.Default.Visibility else Icons.Default.VisibilityOff,
|
||||||
contentDescription = if (tokenVisible) "Hide token" else "Show token",
|
contentDescription = if (tokenVisible) "Hide token" else "Show token",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
supportingText = { Text("Generated from the server dashboard's Settings page") },
|
supportingText = { Text("Generated from the server dashboard's Settings page") },
|
||||||
)
|
)
|
||||||
|
|
||||||
Button(
|
Button(
|
||||||
onClick = {
|
onClick = {
|
||||||
if (validationResult == true) {
|
if (validationResult == true) {
|
||||||
startCompletionFlow()
|
startCompletionFlow()
|
||||||
} else {
|
} else {
|
||||||
viewModel.validateAndSaveServerUrl(serverUrl.trim(), apiToken.trim())
|
viewModel.validateAndSaveServerUrl(serverUrl.trim(), apiToken.trim())
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
enabled = (serverUrl.isNotBlank() && apiToken.isNotBlank() && !isValidating) || validationResult == true,
|
enabled = (serverUrl.isNotBlank() && apiToken.isNotBlank() && !isValidating) || validationResult == true,
|
||||||
) {
|
) {
|
||||||
if (isValidating) {
|
if (isValidating) {
|
||||||
CircularProgressIndicator(
|
CircularProgressIndicator(
|
||||||
modifier = Modifier.size(16.dp),
|
modifier = Modifier.size(16.dp),
|
||||||
color = MaterialTheme.colorScheme.onPrimary,
|
color = MaterialTheme.colorScheme.onPrimary,
|
||||||
strokeWidth = 2.dp,
|
strokeWidth = 2.dp,
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
Text("Validating...")
|
Text("Validating...")
|
||||||
} else if (validationResult == true) {
|
} else if (validationResult == true) {
|
||||||
Text("Continue")
|
Text("Continue")
|
||||||
} else {
|
} else {
|
||||||
Text("Connect")
|
Text("Connect")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Text(
|
Text(
|
||||||
text = "Tip: Emulator host 10.0.2.2:3000 · Physical device uses your PC IP",
|
text = "Tip: Emulator host 10.0.2.2:8080 · Physical device uses your PC IP",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
textAlign = TextAlign.Center,
|
textAlign = TextAlign.Center,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+264
-264
@@ -1,264 +1,264 @@
|
|||||||
@file:Suppress("SwallowedException")
|
@file:Suppress("SwallowedException")
|
||||||
|
|
||||||
package com.collabtable.app.ui.screens
|
package com.collabtable.app.ui.screens
|
||||||
|
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.NetworkOnMainThreadException
|
import android.os.NetworkOnMainThreadException
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.collabtable.app.data.api.ApiClient
|
import com.collabtable.app.data.api.ApiClient
|
||||||
import com.collabtable.app.data.preferences.PreferencesManager
|
import com.collabtable.app.data.preferences.PreferencesManager
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import okhttp3.OkHttpClient
|
import okhttp3.OkHttpClient
|
||||||
import okhttp3.Request
|
import okhttp3.Request
|
||||||
import java.io.IOException
|
import java.io.IOException
|
||||||
import java.net.ConnectException
|
import java.net.ConnectException
|
||||||
import java.net.SocketTimeoutException
|
import java.net.SocketTimeoutException
|
||||||
import java.net.UnknownHostException
|
import java.net.UnknownHostException
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
class ServerSetupViewModel(
|
class ServerSetupViewModel(
|
||||||
private val preferencesManager: PreferencesManager,
|
private val preferencesManager: PreferencesManager,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
private val _isValidating = MutableStateFlow(false)
|
private val _isValidating = MutableStateFlow(false)
|
||||||
val isValidating: StateFlow<Boolean> = _isValidating.asStateFlow()
|
val isValidating: StateFlow<Boolean> = _isValidating.asStateFlow()
|
||||||
|
|
||||||
private val _validationResult = MutableStateFlow<Boolean?>(null)
|
private val _validationResult = MutableStateFlow<Boolean?>(null)
|
||||||
val validationResult: StateFlow<Boolean?> = _validationResult.asStateFlow()
|
val validationResult: StateFlow<Boolean?> = _validationResult.asStateFlow()
|
||||||
|
|
||||||
private val _validationError = MutableStateFlow<String?>(null)
|
private val _validationError = MutableStateFlow<String?>(null)
|
||||||
val validationError: StateFlow<String?> = _validationError.asStateFlow()
|
val validationError: StateFlow<String?> = _validationError.asStateFlow()
|
||||||
|
|
||||||
private val okHttpClient =
|
private val okHttpClient =
|
||||||
OkHttpClient
|
OkHttpClient
|
||||||
.Builder()
|
.Builder()
|
||||||
.connectTimeout(10, TimeUnit.SECONDS)
|
.connectTimeout(10, TimeUnit.SECONDS)
|
||||||
.readTimeout(10, TimeUnit.SECONDS)
|
.readTimeout(10, TimeUnit.SECONDS)
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
fun validateAndSaveServerUrl(
|
fun validateAndSaveServerUrl(
|
||||||
url: String,
|
url: String,
|
||||||
apiToken: String,
|
apiToken: String,
|
||||||
) {
|
) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
_isValidating.value = true
|
_isValidating.value = true
|
||||||
_validationError.value = null
|
_validationError.value = null
|
||||||
_validationResult.value = null
|
_validationResult.value = null
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Normalize URL - add protocol if missing
|
// Normalize URL - add protocol if missing
|
||||||
var normalizedUrl = url.trim()
|
var normalizedUrl = url.trim()
|
||||||
|
|
||||||
// Check if URL has a protocol
|
// Check if URL has a protocol
|
||||||
val hasProtocol = normalizedUrl.startsWith("http://") || normalizedUrl.startsWith("https://")
|
val hasProtocol = normalizedUrl.startsWith("http://") || normalizedUrl.startsWith("https://")
|
||||||
val hasPort = normalizedUrl.contains(":")
|
val hasPort = normalizedUrl.contains(":")
|
||||||
|
|
||||||
// Add http:// if no protocol specified
|
// Add http:// if no protocol specified
|
||||||
if (!hasProtocol) {
|
if (!hasProtocol) {
|
||||||
normalizedUrl = "http://$normalizedUrl"
|
normalizedUrl = "http://$normalizedUrl"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add default port if no port specified
|
// Add default port if no port specified
|
||||||
if (!hasPort || normalizedUrl.matches(Regex("^https?://.+$")) && !normalizedUrl.substringAfter("://").contains(":")) {
|
if (!hasPort || normalizedUrl.matches(Regex("^https?://.+$")) && !normalizedUrl.substringAfter("://").contains(":")) {
|
||||||
// Extract protocol and host
|
// Extract protocol and host
|
||||||
val protocol = if (normalizedUrl.startsWith("https://")) "https" else "http"
|
val protocol = if (normalizedUrl.startsWith("https://")) "https" else "http"
|
||||||
val hostAndPath = normalizedUrl.substringAfter("://")
|
val hostAndPath = normalizedUrl.substringAfter("://")
|
||||||
val host = if (hostAndPath.contains("/")) hostAndPath.substringBefore("/") else hostAndPath
|
val host = if (hostAndPath.contains("/")) hostAndPath.substringBefore("/") else hostAndPath
|
||||||
val path = if (hostAndPath.contains("/")) "/" + hostAndPath.substringAfter("/") else ""
|
val path = if (hostAndPath.contains("/")) "/" + hostAndPath.substringAfter("/") else ""
|
||||||
|
|
||||||
// Add default port based on protocol
|
// Add default port based on protocol
|
||||||
val defaultPort = if (protocol == "https") "443" else "80"
|
val defaultPort = if (protocol == "https") "443" else "80"
|
||||||
normalizedUrl = "$protocol://$host:$defaultPort$path"
|
normalizedUrl = "$protocol://$host:$defaultPort$path"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove trailing slash if present for consistent handling
|
// Remove trailing slash if present for consistent handling
|
||||||
normalizedUrl = normalizedUrl.trimEnd('/')
|
normalizedUrl = normalizedUrl.trimEnd('/')
|
||||||
|
|
||||||
// Add /api/ if not present
|
// Add /api/ if not present
|
||||||
if (!normalizedUrl.contains("/api")) {
|
if (!normalizedUrl.contains("/api")) {
|
||||||
normalizedUrl = "$normalizedUrl/api"
|
normalizedUrl = "$normalizedUrl/api"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure it ends with /
|
// Ensure it ends with /
|
||||||
normalizedUrl = if (normalizedUrl.endsWith("/")) normalizedUrl else "$normalizedUrl/"
|
normalizedUrl = if (normalizedUrl.endsWith("/")) normalizedUrl else "$normalizedUrl/"
|
||||||
|
|
||||||
// Validate API token is not empty (trim leading/trailing spaces) and not a placeholder
|
// Validate API token is not empty (trim leading/trailing spaces) and not a placeholder
|
||||||
val trimmedToken = apiToken.trim()
|
val trimmedToken = apiToken.trim()
|
||||||
if (trimmedToken.isBlank()) {
|
if (trimmedToken.isBlank()) {
|
||||||
_validationError.value = "API token cannot be empty"
|
_validationError.value = "API token cannot be empty"
|
||||||
_isValidating.value = false
|
_isValidating.value = false
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
if (trimmedToken == "\$apiToken") {
|
if (trimmedToken == "\$apiToken") {
|
||||||
_validationError.value = "Enter the actual API token, not the placeholder $apiToken"
|
_validationError.value = "Enter the actual API token, not the placeholder $apiToken"
|
||||||
_isValidating.value = false
|
_isValidating.value = false
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
|
|
||||||
// On physical devices, block local-only hosts that won't resolve
|
// On physical devices, block local-only hosts that won't resolve
|
||||||
val isEmulator =
|
val isEmulator =
|
||||||
run {
|
run {
|
||||||
val fp = Build.FINGERPRINT.lowercase()
|
val fp = Build.FINGERPRINT.lowercase()
|
||||||
val model = Build.MODEL.lowercase()
|
val model = Build.MODEL.lowercase()
|
||||||
val brand = Build.BRAND.lowercase()
|
val brand = Build.BRAND.lowercase()
|
||||||
val device = Build.DEVICE.lowercase()
|
val device = Build.DEVICE.lowercase()
|
||||||
val product = Build.PRODUCT.lowercase()
|
val product = Build.PRODUCT.lowercase()
|
||||||
fp.contains("generic") ||
|
fp.contains("generic") ||
|
||||||
fp.contains("emulator") ||
|
fp.contains("emulator") ||
|
||||||
model.contains("google_sdk") ||
|
model.contains("google_sdk") ||
|
||||||
model.contains("emulator") ||
|
model.contains("emulator") ||
|
||||||
model.contains("android sdk built for") ||
|
model.contains("android sdk built for") ||
|
||||||
brand.startsWith("generic") ||
|
brand.startsWith("generic") ||
|
||||||
device.startsWith("generic") ||
|
device.startsWith("generic") ||
|
||||||
product.contains("sdk")
|
product.contains("sdk")
|
||||||
}
|
}
|
||||||
val host =
|
val host =
|
||||||
try {
|
try {
|
||||||
Uri.parse(normalizedUrl).host?.lowercase()
|
Uri.parse(normalizedUrl).host?.lowercase()
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
val localOnlyHosts = setOf("localhost", "127.0.0.1", "host.docker.internal", "10.0.2.2")
|
val localOnlyHosts = setOf("localhost", "127.0.0.1", "host.docker.internal", "10.0.2.2")
|
||||||
if (!isEmulator && host != null && host in localOnlyHosts) {
|
if (!isEmulator && host != null && host in localOnlyHosts) {
|
||||||
_validationError.value = "On a physical device, use your computer's LAN IP (e.g., 192.168.x.x:3000) instead of '$host'."
|
_validationError.value = "On a physical device, use your computer's LAN IP (e.g., 192.168.x.x:8080) instead of '$host'."
|
||||||
_isValidating.value = false
|
_isValidating.value = false
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try to reach the health endpoint (no auth required)
|
// Try to reach the health endpoint (no auth required)
|
||||||
val healthUrl = normalizedUrl.replace("/api/", "/health")
|
val healthUrl = normalizedUrl.replace("/api/", "/health")
|
||||||
val healthRequest =
|
val healthRequest =
|
||||||
Request
|
Request
|
||||||
.Builder()
|
.Builder()
|
||||||
.url(healthUrl)
|
.url(healthUrl)
|
||||||
.get()
|
.get()
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Execute network call on IO dispatcher
|
// Execute network call on IO dispatcher
|
||||||
val healthResponse =
|
val healthResponse =
|
||||||
withContext(Dispatchers.IO) {
|
withContext(Dispatchers.IO) {
|
||||||
okHttpClient.newCall(healthRequest).execute()
|
okHttpClient.newCall(healthRequest).execute()
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!healthResponse.isSuccessful) {
|
if (!healthResponse.isSuccessful) {
|
||||||
val errorMessage =
|
val errorMessage =
|
||||||
when (healthResponse.code) {
|
when (healthResponse.code) {
|
||||||
404 -> "Health endpoint not found. Check server URL."
|
404 -> "Health endpoint not found. Check server URL."
|
||||||
500 -> "Server internal error. Check server logs."
|
500 -> "Server internal error. Check server logs."
|
||||||
503 -> "Service unavailable. Server may be starting up."
|
503 -> "Service unavailable. Server may be starting up."
|
||||||
else -> "Server returned HTTP ${healthResponse.code}"
|
else -> "Server returned HTTP ${healthResponse.code}"
|
||||||
}
|
}
|
||||||
healthResponse.close()
|
healthResponse.close()
|
||||||
_validationError.value = errorMessage
|
_validationError.value = errorMessage
|
||||||
_isValidating.value = false
|
_isValidating.value = false
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
healthResponse.close()
|
healthResponse.close()
|
||||||
|
|
||||||
// Try to upgrade to HTTPS if currently using HTTP
|
// Try to upgrade to HTTPS if currently using HTTP
|
||||||
var finalUrl = normalizedUrl
|
var finalUrl = normalizedUrl
|
||||||
if (normalizedUrl.startsWith("http://")) {
|
if (normalizedUrl.startsWith("http://")) {
|
||||||
// Replace http:// with https:// and change port 80 to 443
|
// Replace http:// with https:// and change port 80 to 443
|
||||||
var httpsUrl = normalizedUrl.replace("http://", "https://")
|
var httpsUrl = normalizedUrl.replace("http://", "https://")
|
||||||
if (httpsUrl.contains(":80/")) {
|
if (httpsUrl.contains(":80/")) {
|
||||||
httpsUrl = httpsUrl.replace(":80/", ":443/")
|
httpsUrl = httpsUrl.replace(":80/", ":443/")
|
||||||
}
|
}
|
||||||
|
|
||||||
val httpsHealthUrl = httpsUrl.replace("/api/", "/health")
|
val httpsHealthUrl = httpsUrl.replace("/api/", "/health")
|
||||||
val httpsHealthRequest =
|
val httpsHealthRequest =
|
||||||
Request
|
Request
|
||||||
.Builder()
|
.Builder()
|
||||||
.url(httpsHealthUrl)
|
.url(httpsHealthUrl)
|
||||||
.get()
|
.get()
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Execute HTTPS check on IO dispatcher
|
// Execute HTTPS check on IO dispatcher
|
||||||
val httpsResponse =
|
val httpsResponse =
|
||||||
withContext(Dispatchers.IO) {
|
withContext(Dispatchers.IO) {
|
||||||
okHttpClient.newCall(httpsHealthRequest).execute()
|
okHttpClient.newCall(httpsHealthRequest).execute()
|
||||||
}
|
}
|
||||||
if (httpsResponse.isSuccessful) {
|
if (httpsResponse.isSuccessful) {
|
||||||
// HTTPS works! Upgrade to it
|
// HTTPS works! Upgrade to it
|
||||||
finalUrl = httpsUrl
|
finalUrl = httpsUrl
|
||||||
}
|
}
|
||||||
httpsResponse.close()
|
httpsResponse.close()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
// HTTPS doesn't work, stick with HTTP
|
// HTTPS doesn't work, stick with HTTP
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Now validate the API token by making an authenticated request
|
// Now validate the API token by making an authenticated request
|
||||||
val testUrl = "${finalUrl}lists"
|
val testUrl = "${finalUrl}lists"
|
||||||
val authRequest =
|
val authRequest =
|
||||||
Request
|
Request
|
||||||
.Builder()
|
.Builder()
|
||||||
.url(testUrl)
|
.url(testUrl)
|
||||||
.header("Authorization", "Bearer $trimmedToken")
|
.header("Authorization", "Bearer $trimmedToken")
|
||||||
.get()
|
.get()
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
// Execute auth check on IO dispatcher
|
// Execute auth check on IO dispatcher
|
||||||
val authResponse =
|
val authResponse =
|
||||||
withContext(Dispatchers.IO) {
|
withContext(Dispatchers.IO) {
|
||||||
okHttpClient.newCall(authRequest).execute()
|
okHttpClient.newCall(authRequest).execute()
|
||||||
}
|
}
|
||||||
|
|
||||||
if (authResponse.isSuccessful) {
|
if (authResponse.isSuccessful) {
|
||||||
// Token is valid, save both URL and API token
|
// Token is valid, save both URL and API token
|
||||||
preferencesManager.setServerUrl(finalUrl)
|
preferencesManager.setServerUrl(finalUrl)
|
||||||
preferencesManager.setApiToken(trimmedToken)
|
preferencesManager.setApiToken(trimmedToken)
|
||||||
// Reset sync baseline for a fresh initial sync on new server
|
// Reset sync baseline for a fresh initial sync on new server
|
||||||
preferencesManager.clearSyncState()
|
preferencesManager.clearSyncState()
|
||||||
preferencesManager.setIsFirstRun(false)
|
preferencesManager.setIsFirstRun(false)
|
||||||
ApiClient.setBaseUrl(finalUrl)
|
ApiClient.setBaseUrl(finalUrl)
|
||||||
_validationResult.value = true
|
_validationResult.value = true
|
||||||
} else if (authResponse.code == 401) {
|
} else if (authResponse.code == 401) {
|
||||||
_validationError.value = "Invalid API token. Please check and try again."
|
_validationError.value = "Invalid API token. Please check and try again."
|
||||||
} else {
|
} else {
|
||||||
val errorMessage =
|
val errorMessage =
|
||||||
when (authResponse.code) {
|
when (authResponse.code) {
|
||||||
403 -> "Access forbidden. Check server configuration."
|
403 -> "Access forbidden. Check server configuration."
|
||||||
404 -> "API endpoint not found. Check URL path."
|
404 -> "API endpoint not found. Check URL path."
|
||||||
500 -> "Server error. Check server logs."
|
500 -> "Server error. Check server logs."
|
||||||
503 -> "Service unavailable. Try again later."
|
503 -> "Service unavailable. Try again later."
|
||||||
else -> "Server returned HTTP ${authResponse.code}"
|
else -> "Server returned HTTP ${authResponse.code}"
|
||||||
}
|
}
|
||||||
_validationError.value = errorMessage
|
_validationError.value = errorMessage
|
||||||
}
|
}
|
||||||
authResponse.close()
|
authResponse.close()
|
||||||
} catch (e: NetworkOnMainThreadException) {
|
} catch (e: NetworkOnMainThreadException) {
|
||||||
_validationError.value = "Network operation attempted on main thread. This is a developer error - please report this bug."
|
_validationError.value = "Network operation attempted on main thread. This is a developer error - please report this bug."
|
||||||
} catch (e: UnknownHostException) {
|
} catch (e: UnknownHostException) {
|
||||||
_validationError.value = "Cannot resolve hostname. Check URL spelling and network connection."
|
_validationError.value = "Cannot resolve hostname. Check URL spelling and network connection."
|
||||||
} catch (e: ConnectException) {
|
} catch (e: ConnectException) {
|
||||||
_validationError.value = "Cannot connect to server. Check if server is running and URL is correct."
|
_validationError.value = "Cannot connect to server. Check if server is running and URL is correct."
|
||||||
} catch (e: SocketTimeoutException) {
|
} catch (e: SocketTimeoutException) {
|
||||||
_validationError.value = "Connection timeout after 10 seconds. Server may be offline or unreachable."
|
_validationError.value = "Connection timeout after 10 seconds. Server may be offline or unreachable."
|
||||||
} catch (e: IOException) {
|
} catch (e: IOException) {
|
||||||
_validationError.value = "Network error: ${e.message ?: "Unable to communicate with server"}"
|
_validationError.value = "Network error: ${e.message ?: "Unable to communicate with server"}"
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_validationError.value = "Unexpected error: ${e.javaClass.simpleName} - ${e.message ?: "Unknown cause"}"
|
_validationError.value = "Unexpected error: ${e.javaClass.simpleName} - ${e.message ?: "Unknown cause"}"
|
||||||
}
|
}
|
||||||
} catch (e: IllegalArgumentException) {
|
} catch (e: IllegalArgumentException) {
|
||||||
_validationError.value = "Invalid URL format: ${e.message ?: "Malformed URL"}"
|
_validationError.value = "Invalid URL format: ${e.message ?: "Malformed URL"}"
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_validationError.value = "Configuration error: ${e.javaClass.simpleName} - ${e.message ?: "Unable to process URL"}"
|
_validationError.value = "Configuration error: ${e.javaClass.simpleName} - ${e.message ?: "Unable to process URL"}"
|
||||||
} finally {
|
} finally {
|
||||||
_isValidating.value = false
|
_isValidating.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun clearValidationState() {
|
fun clearValidationState() {
|
||||||
_validationResult.value = null
|
_validationResult.value = null
|
||||||
_validationError.value = null
|
_validationError.value = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -40,7 +40,7 @@ The device-sync API token (generated from the dashboard's Settings page, used by
|
|||||||
|----------|----------|---------|--------------|
|
|----------|----------|---------|--------------|
|
||||||
| `DATABASE_URL` | Yes | — | PostgreSQL connection string (bring your own instance) |
|
| `DATABASE_URL` | Yes | — | PostgreSQL connection string (bring your own instance) |
|
||||||
| `AUTHGUARD_URL` | No | unset (auth disabled) | Base URL of the AuthGuard identity service. Leaving it unset disables authentication entirely rather than falling back to local auth. |
|
| `AUTHGUARD_URL` | No | unset (auth disabled) | Base URL of the AuthGuard identity service. Leaving it unset disables authentication entirely rather than falling back to local auth. |
|
||||||
| `PORT` | No | `3000` | HTTP listen port |
|
| `PORT` | No | `8080` | HTTP listen port |
|
||||||
| `APP_VERSION` | No | `dev` | Version label shown on the dashboard's About page |
|
| `APP_VERSION` | No | `dev` | Version label shown on the dashboard's About page |
|
||||||
| `COOKIE_SECURE` | No | `false` | Set `true` once served over HTTPS, to mark cookies `Secure` |
|
| `COOKIE_SECURE` | No | `false` | Set `true` once served over HTTPS, to mark cookies `Secure` |
|
||||||
| `DB_INIT_RETRY_INTERVAL_MS` | No | `5000` | Delay between database-connection retry attempts at startup |
|
| `DB_INIT_RETRY_INTERVAL_MS` | No | `5000` | Delay between database-connection retry attempts at startup |
|
||||||
@@ -60,13 +60,13 @@ docker build -t collabtable:local -f docker/Dockerfile .
|
|||||||
docker run -d \
|
docker run -d \
|
||||||
--name collabtable \
|
--name collabtable \
|
||||||
--restart unless-stopped \
|
--restart unless-stopped \
|
||||||
-p 3000:3000 \
|
-p 8080:8080 \
|
||||||
-e DATABASE_URL="postgresql://user:password@host:5432/collabtable" \
|
-e DATABASE_URL="postgresql://user:password@host:5432/collabtable" \
|
||||||
-e AUTHGUARD_URL="https://auth.example.com" \
|
-e AUTHGUARD_URL="https://auth.example.com" \
|
||||||
collabtable:local
|
collabtable:local
|
||||||
```
|
```
|
||||||
|
|
||||||
Open **http://\<host\>:3000**, complete setup (this registers the first account against AuthGuard), then generate a device-sync API token from the dashboard's Settings page for the Android app.
|
Open **http://\<host\>:8080**, complete setup (this registers the first account against AuthGuard), then generate a device-sync API token from the dashboard's Settings page for the Android app.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -100,7 +100,7 @@ Other frontend scripts: `npm run build`, `npm run format`.
|
|||||||
|
|
||||||
### Android
|
### Android
|
||||||
|
|
||||||
Open `CollabTableAndroid` in Android Studio, let Gradle sync, and run on an emulator or device. In the app's Settings, point it at the backend (`http://10.0.2.2:3000/api/` for an emulator) with the API token generated from the dashboard.
|
Open `CollabTableAndroid` in Android Studio, let Gradle sync, and run on an emulator or device. In the app's Settings, point it at the backend (`http://10.0.2.2:8080/api/` for an emulator) with the API token generated from the dashboard.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
#################################################################
|
#################################################################
|
||||||
# Server
|
# Server
|
||||||
#################################################################
|
#################################################################
|
||||||
PORT=3000
|
PORT=8080
|
||||||
APP_VERSION=dev
|
APP_VERSION=dev
|
||||||
|
|
||||||
# Set to "true" once served over HTTPS - marks the admin session cookie Secure.
|
# Set to "true" once served over HTTPS - marks the admin session cookie Secure.
|
||||||
|
|||||||
+3
-3
@@ -21,14 +21,14 @@ Svelte dashboard and the Android synchronization API from one container.
|
|||||||
cd ..
|
cd ..
|
||||||
docker build -f docker/Dockerfile -t collabtable-server .
|
docker build -f docker/Dockerfile -t collabtable-server .
|
||||||
docker run -d --name collabtable-server --restart unless-stopped \
|
docker run -d --name collabtable-server --restart unless-stopped \
|
||||||
-p 3000:3000 \
|
-p 8080:8080 \
|
||||||
-e DATABASE_URL=postgres://user:password@host:5432/collabtable \
|
-e DATABASE_URL=postgres://user:password@host:5432/collabtable \
|
||||||
-e AUTHGUARD_URL=https://auth.example.com \
|
-e AUTHGUARD_URL=https://auth.example.com \
|
||||||
-e COOKIE_SECURE=false \
|
-e COOKIE_SECURE=false \
|
||||||
collabtable-server
|
collabtable-server
|
||||||
```
|
```
|
||||||
|
|
||||||
Open `http://localhost:3000` to create the first account. Generate an API token from
|
Open `http://localhost:8080` to create the first account. Generate an API token from
|
||||||
the dashboard's Settings menu and enter it in the Android app.
|
the dashboard's Settings menu and enter it in the Android app.
|
||||||
|
|
||||||
## Local development
|
## Local development
|
||||||
@@ -108,7 +108,7 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate
|
|||||||
|
|
||||||
## Environment variables
|
## Environment variables
|
||||||
|
|
||||||
- `PORT` — HTTP port, default `3000`
|
- `PORT` — HTTP port, default `8080`
|
||||||
- `APP_VERSION` — optional version displayed in the dashboard, default `dev`
|
- `APP_VERSION` — optional version displayed in the dashboard, default `dev`
|
||||||
- `COOKIE_SECURE` — set to `true` when served over HTTPS
|
- `COOKIE_SECURE` — set to `true` when served over HTTPS
|
||||||
- `DATABASE_URL` — PostgreSQL connection string, required
|
- `DATABASE_URL` — PostgreSQL connection string, required
|
||||||
|
|||||||
+1
-1
@@ -33,7 +33,7 @@ type Server struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
port := envOrDefault("PORT", "3000")
|
port := envOrDefault("PORT", "8080")
|
||||||
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||||
if connectionString == "" {
|
if connectionString == "" {
|
||||||
fmt.Fprintln(os.Stderr, "DATABASE_URL environment variable is required")
|
fmt.Fprintln(os.Stderr, "DATABASE_URL environment variable is required")
|
||||||
|
|||||||
+2
-2
@@ -42,7 +42,7 @@ FROM scratch
|
|||||||
COPY --from=builder /app/server /server
|
COPY --from=builder /app/server /server
|
||||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||||
USER 65534:65534
|
USER 65534:65534
|
||||||
EXPOSE 3000
|
EXPOSE 8080
|
||||||
VOLUME ["/data"]
|
VOLUME ["/data"]
|
||||||
ENV PORT=3000
|
ENV PORT=8080
|
||||||
ENTRYPOINT ["/server"]
|
ENTRYPOINT ["/server"]
|
||||||
+43
-43
@@ -1,43 +1,43 @@
|
|||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import tailwindcss from '@tailwindcss/vite';
|
import tailwindcss from '@tailwindcss/vite';
|
||||||
import { sveltekit } from '@sveltejs/kit/vite';
|
import { sveltekit } from '@sveltejs/kit/vite';
|
||||||
import { defineConfig } from 'vite';
|
import { defineConfig } from 'vite';
|
||||||
|
|
||||||
// Real installed frontend dependency versions for the About page, resolved from
|
// Real installed frontend dependency versions for the About page, resolved from
|
||||||
// node_modules (not the package.json semver range) so it can't drift from what's bundled.
|
// node_modules (not the package.json semver range) so it can't drift from what's bundled.
|
||||||
const FRONTEND_TECH_STACK_PACKAGES = [
|
const FRONTEND_TECH_STACK_PACKAGES = [
|
||||||
{ name: 'Svelte', pkg: 'svelte' },
|
{ name: 'Svelte', pkg: 'svelte' },
|
||||||
{ name: 'SvelteKit', pkg: '@sveltejs/kit' },
|
{ name: 'SvelteKit', pkg: '@sveltejs/kit' },
|
||||||
{ name: 'TanStack Query', pkg: '@tanstack/svelte-query' },
|
{ name: 'TanStack Query', pkg: '@tanstack/svelte-query' },
|
||||||
{ name: 'Tailwind CSS', pkg: 'tailwindcss' },
|
{ name: 'Tailwind CSS', pkg: 'tailwindcss' },
|
||||||
{ name: 'Vite', pkg: 'vite' },
|
{ name: 'Vite', pkg: 'vite' },
|
||||||
];
|
];
|
||||||
|
|
||||||
function readInstalledVersion(pkg) {
|
function readInstalledVersion(pkg) {
|
||||||
try {
|
try {
|
||||||
const pkgJsonPath = path.resolve(import.meta.dirname, 'node_modules', pkg, 'package.json');
|
const pkgJsonPath = path.resolve(import.meta.dirname, 'node_modules', pkg, 'package.json');
|
||||||
return JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8')).version ?? null;
|
return JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8')).version ?? null;
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const frontendTechStack = FRONTEND_TECH_STACK_PACKAGES.flatMap(({ name, pkg }) => {
|
const frontendTechStack = FRONTEND_TECH_STACK_PACKAGES.flatMap(({ name, pkg }) => {
|
||||||
const version = readInstalledVersion(pkg);
|
const version = readInstalledVersion(pkg);
|
||||||
return version ? [{ name, version }] : [];
|
return version ? [{ name, version }] : [];
|
||||||
});
|
});
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [tailwindcss(), sveltekit()],
|
plugins: [tailwindcss(), sveltekit()],
|
||||||
define: {
|
define: {
|
||||||
__FRONTEND_TECH_STACK__: JSON.stringify(frontendTechStack),
|
__FRONTEND_TECH_STACK__: JSON.stringify(frontendTechStack),
|
||||||
},
|
},
|
||||||
server: {
|
server: {
|
||||||
port: 5173,
|
port: 5173,
|
||||||
proxy: {
|
proxy: {
|
||||||
'/web': 'http://localhost:3000',
|
'/web': 'http://localhost:8080',
|
||||||
'/health': 'http://localhost:3000',
|
'/health': 'http://localhost:8080',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user