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