Compare commits
101
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e9e8a75bf1 | ||
|
|
c212a6a488 | ||
|
|
08fcb25a2a | ||
|
|
b8b135ee63 | ||
|
|
6066527dc0 | ||
|
|
1f39f27618 | ||
|
|
956be6a6de | ||
|
|
90ca9775ef | ||
|
|
0e33564b95 | ||
|
|
321b260e3d | ||
|
|
be3c885988 | ||
|
|
802393962e | ||
|
|
ac31308443 | ||
|
|
af832dee93 | ||
|
|
8ca5f20a98 | ||
|
|
26b17ece26 | ||
|
|
2e7eb7e47b | ||
|
|
062415a75d | ||
|
|
ab68be4c1e | ||
|
|
513c1785ef | ||
|
|
e70a53eca7 | ||
|
|
c3004a3d2e | ||
|
|
fda4b462dc | ||
|
|
6a1a15ade9 | ||
|
|
ea44cf5d2e | ||
|
|
984feb170a | ||
|
|
5691c87e91 | ||
|
|
227e08a671 | ||
|
|
3bfb5f9788 | ||
|
|
bf1cf3865a | ||
|
|
0c3bed6213 | ||
|
|
f1cb2d618d | ||
|
|
8c9a3b5b37 | ||
|
|
de8510bc79 | ||
|
|
34d01b312e | ||
|
|
f89332b28c | ||
|
|
8f12bf32bc | ||
|
|
b9ae128842 | ||
|
|
a86dca50b8 | ||
|
|
fc49eae512 | ||
|
|
ffbae9edfd | ||
|
|
2268c64250 | ||
|
|
c954fd9bb8 | ||
|
|
b9757348f2 | ||
|
|
130f8bbecc | ||
|
|
4c00d46a14 | ||
|
|
07fc4021e1 | ||
|
|
431436d0db | ||
|
|
905711d8de | ||
|
|
7c9cb3fb0d | ||
|
|
ae0d1b2d3d | ||
|
|
c5b3c5dae9 | ||
|
|
3fa3b4eac1 | ||
|
|
197bcc6f5e | ||
|
|
f4f5cec2be | ||
|
|
5a630f8401 | ||
|
|
54a3c58a22 | ||
|
|
1c6a044c37 | ||
|
|
fcc022db64 | ||
|
|
a908a2da18 | ||
|
|
2c25647fa5 | ||
|
|
956f33140e | ||
|
|
7bba4dc878 | ||
|
|
89235fbb46 | ||
|
|
0564101e9e | ||
|
|
2baa544b32 | ||
|
|
f9c3a2e305 | ||
|
|
e49e7c358e | ||
|
|
3267fee439 | ||
|
|
8a0651e578 | ||
|
|
32d45f6430 | ||
|
|
4a06e9da8b | ||
|
|
d6b36a1d3a | ||
|
|
e811b4bc43 | ||
|
|
5d3b355163 | ||
|
|
81f3b05653 | ||
|
|
37407e2737 | ||
|
|
13159c576e | ||
|
|
1834763f19 | ||
|
|
62c0469669 | ||
|
|
3d6e1624e9 | ||
|
|
b1a34105f1 | ||
|
|
72db88b25c | ||
|
|
97f0eb56d5 | ||
|
|
c6d6392656 | ||
|
|
958fb6eaa6 | ||
|
|
2c806ef14e | ||
|
|
0bbdbdb4f1 | ||
|
|
fe2e2e589a | ||
|
|
e0115e85fc | ||
|
|
0e15d5f9a4 | ||
|
|
5555676395 | ||
|
|
ca512f5993 | ||
|
|
64d6f5a41d | ||
|
|
a3d39764e2 | ||
|
|
705b8904a4 | ||
|
|
541dda292f | ||
|
|
fa98451533 | ||
|
|
ee9d8cdbaf | ||
|
|
76326bbc27 | ||
|
|
ed02da031b |
@@ -1,4 +1,5 @@
|
||||
.gradle/
|
||||
.kotlin/
|
||||
build/
|
||||
local.properties
|
||||
app/google-services.json
|
||||
@@ -7,3 +8,7 @@ app/google-services.json:Zone.Identifier
|
||||
*.iml
|
||||
keystore.properties
|
||||
*.jks
|
||||
release-artifacts/
|
||||
app/src/main/res_bak/
|
||||
scripts/*.json
|
||||
scripts/*.json:Zone.Identifier
|
||||
|
||||
@@ -21,3 +21,65 @@ Natywna aplikacja Android Jetpack Compose dla kierowcow TPP.
|
||||
```bash
|
||||
./gradlew :app:testDebugUnitTest
|
||||
```
|
||||
|
||||
## Release Gitea i Google Play
|
||||
|
||||
Przed wydaniem zapisz wszystkie zmiany źródłowe w commicie. Następnie uruchom:
|
||||
|
||||
```bash
|
||||
./scripts/release-android.sh
|
||||
```
|
||||
|
||||
Skrypt automatycznie zwiększa `versionCode` i ostatni człon `versionName`, uruchamia testy,
|
||||
buduje podpisany APK oraz AAB, a po poprawnym buildzie pyta, czy wysłać aktualizację do
|
||||
Google Play. Po odpowiedzi „tak” publikuje AAB w skonfigurowanym teście zamkniętym i
|
||||
wysyła zmiany do weryfikacji. Następnie tworzy commit wersji, tag, push i Gitea Release.
|
||||
Artefakty zostają również zapisane lokalnie w `release-artifacts/<tag>/`.
|
||||
|
||||
Do publikacji Google Play konto serwisowe musi mieć dla aplikacji
|
||||
`pl.firmatpp.kierowca` uprawnienia „Wyświetlanie informacji o aplikacji (tylko do odczytu)”
|
||||
oraz „Publikowanie aplikacji na ścieżkach testowych”. Pobrany klucz JSON umieść
|
||||
bezpośrednio w folderze `scripts`, na przykład:
|
||||
|
||||
```text
|
||||
scripts/google-play-service-account.json
|
||||
```
|
||||
|
||||
Skrypt sam znajduje jedyny plik `scripts/*.json`, sprawdza, czy jest prawidłowym kluczem
|
||||
konta serwisowego, i używa go do autoryzacji. Pliki `scripts/*.json` są ignorowane przez
|
||||
Git i nie mogą zostać przypadkowo dodane do repozytorium. Jeśli w folderze znajduje się
|
||||
więcej niż jeden prawidłowy klucz, skrypt przerwie działanie i poprosi o pozostawienie
|
||||
jednego.
|
||||
|
||||
`GOOGLE_PLAY_TRACK` musi być identyfikatorem istniejącego testu zamkniętego. Domyślna
|
||||
wartość to `alpha`. Opcjonalnie można ustawić `GOOGLE_PLAY_PACKAGE_NAME` i
|
||||
`GOOGLE_PLAY_RELEASE_LANGUAGE` (domyślnie `pl-PL`). Zmienna
|
||||
`GOOGLE_PLAY_SERVICE_ACCOUNT_CREDENTIALS` pozostaje opcjonalnym sposobem wskazania klucza
|
||||
spoza folderu `scripts`. Skrypt nie zapisuje tokenu ani klucza w repozytorium; prywatny
|
||||
klucz tymczasowy jest usuwany po zakończeniu.
|
||||
|
||||
Przed zatwierdzeniem skrypt waliduje edycję Google Play. Commit edycji jawnie wysyła
|
||||
zmiany do weryfikacji. Jeżeli inne zmiany są już sprawdzane, skrypt nie anuluje ich —
|
||||
kończy się błędem i można go wznowić po zakończeniu poprzedniej weryfikacji.
|
||||
Jeżeli na koncie jest włączone publikowanie zarządzane, po akceptacji Google nadal trzeba
|
||||
wybrać „Opublikuj zmiany” w Play Console; bez publikowania zarządzanego zaakceptowane
|
||||
wydanie zostanie udostępnione testerom automatycznie.
|
||||
|
||||
Awaryjne wydanie wyłącznie do Gitea, bez Google Play:
|
||||
|
||||
```bash
|
||||
./scripts/release-android.sh --skip-google-play
|
||||
```
|
||||
|
||||
W środowisku bez interaktywnego terminala decyzję trzeba podać jawnie:
|
||||
|
||||
```bash
|
||||
./scripts/release-android.sh --publish-google-play
|
||||
```
|
||||
|
||||
Do autoryzacji Gitea używany jest `GITEA_TOKEN` albo dane zapisane w Git credential helper.
|
||||
Jeśli publikacja została przerwana już po utworzeniu commita wersji, można ją wznowić:
|
||||
|
||||
```bash
|
||||
./scripts/release-android.sh --reuse-current
|
||||
```
|
||||
|
||||
+11
-4
@@ -10,6 +10,7 @@ plugins {
|
||||
|
||||
if (file("google-services.json").exists()) {
|
||||
apply(plugin = "com.google.gms.google-services")
|
||||
apply(plugin = "com.google.firebase.crashlytics")
|
||||
}
|
||||
|
||||
val keystorePropertiesFile = rootProject.file("keystore.properties")
|
||||
@@ -21,7 +22,7 @@ val keystoreProperties = Properties().apply {
|
||||
|
||||
android {
|
||||
namespace = "pl.firmatpp.kierowca"
|
||||
compileSdk = 35
|
||||
compileSdk = 36
|
||||
|
||||
fun configValue(name: String, default: String): String =
|
||||
providers.gradleProperty(name)
|
||||
@@ -32,9 +33,9 @@ android {
|
||||
defaultConfig {
|
||||
applicationId = "pl.firmatpp.kierowca"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 21
|
||||
versionName = "1.0.20"
|
||||
targetSdk = 36
|
||||
versionCode = 133
|
||||
versionName = "1.0.80"
|
||||
setProperty("archivesBaseName", "pl.firmatpp.kierowca")
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
|
||||
@@ -68,6 +69,9 @@ android {
|
||||
release {
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
isMinifyEnabled = false
|
||||
ndk {
|
||||
debugSymbolLevel = "SYMBOL_TABLE"
|
||||
}
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro"
|
||||
@@ -120,11 +124,14 @@ dependencies {
|
||||
implementation(libs.compose.ui.tooling.preview)
|
||||
implementation(libs.coroutines.android)
|
||||
implementation(platform(libs.firebase.bom))
|
||||
implementation(libs.firebase.crashlytics)
|
||||
implementation(libs.firebase.messaging)
|
||||
implementation(libs.okhttp)
|
||||
implementation(libs.okhttp.logging)
|
||||
implementation(libs.play.services.auth)
|
||||
implementation(libs.play.services.auth.api.phone)
|
||||
implementation(libs.play.app.update)
|
||||
implementation(libs.play.app.update.ktx)
|
||||
implementation(libs.retrofit)
|
||||
implementation(libs.retrofit.gson)
|
||||
|
||||
|
||||
@@ -2,13 +2,28 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
|
||||
|
||||
<uses-feature
|
||||
android:name="android.hardware.camera"
|
||||
android:required="false" />
|
||||
|
||||
<queries>
|
||||
<intent>
|
||||
<action android:name="android.speech.RecognitionService" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:name=".DriverApplication"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.TppKierowca">
|
||||
@@ -38,5 +53,10 @@
|
||||
<action android:name="com.google.firebase.MESSAGING_EVENT" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<service
|
||||
android:name=".tracking.ActiveRouteTrackingService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="location" />
|
||||
</application>
|
||||
</manifest>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package pl.firmatpp.kierowca
|
||||
|
||||
import android.app.Application
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
import pl.firmatpp.kierowca.data.upload.OfflineOutboxManager
|
||||
import pl.firmatpp.kierowca.diagnostics.AppDiagnostics
|
||||
|
||||
class DriverApplication : Application() {
|
||||
private val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
AppDiagnostics.installFirebaseCrashlytics()
|
||||
AppDiagnostics.log("app_started")
|
||||
applicationScope.launch {
|
||||
val outboxManager = OfflineOutboxManager(this@DriverApplication)
|
||||
runCatching { outboxManager.repairOperationalQueues() }
|
||||
.onFailure { AppDiagnostics.reportNonFatal(it, "repair_operational_queues") }
|
||||
runCatching { outboxManager.repairGpsQueue() }
|
||||
.onFailure { AppDiagnostics.reportNonFatal(it, "repair_gps_queue") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,19 +3,88 @@ package pl.firmatpp.kierowca
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import pl.firmatpp.kierowca.ui.DriverApp
|
||||
import pl.firmatpp.kierowca.ui.DriverViewModel
|
||||
import pl.firmatpp.kierowca.ui.theme.TppKierowcaTheme
|
||||
import pl.firmatpp.kierowca.update.PlayAppUpdateState
|
||||
import pl.firmatpp.kierowca.update.PlayInAppUpdateController
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContent {
|
||||
TppKierowcaTheme {
|
||||
val viewModel: DriverViewModel = viewModel()
|
||||
DriverApp(viewModel = viewModel)
|
||||
}
|
||||
private var notificationRouteId by mutableStateOf<String?>(null)
|
||||
private var notificationRouteTarget by mutableStateOf<String?>(null)
|
||||
private var notificationLeaveRequestId by mutableStateOf<String?>(null)
|
||||
private var playAppUpdateState by mutableStateOf(PlayAppUpdateState())
|
||||
private lateinit var playInAppUpdates: PlayInAppUpdateController
|
||||
private val appUpdateLauncher = registerForActivityResult(
|
||||
ActivityResultContracts.StartIntentSenderForResult(),
|
||||
) { result ->
|
||||
if (::playInAppUpdates.isInitialized) {
|
||||
playInAppUpdates.onUpdateFlowResult(result.resultCode)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
notificationRouteId = intent.getStringExtra(EXTRA_ROUTE_ID)
|
||||
notificationRouteTarget = intent.getStringExtra(EXTRA_ROUTE_TARGET)
|
||||
notificationLeaveRequestId = intent.getStringExtra(EXTRA_LEAVE_REQUEST_ID)
|
||||
playInAppUpdates = PlayInAppUpdateController(
|
||||
activity = this,
|
||||
launcher = appUpdateLauncher,
|
||||
onStateChanged = { playAppUpdateState = it },
|
||||
)
|
||||
setContent {
|
||||
val viewModel: DriverViewModel = viewModel()
|
||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||
|
||||
TppKierowcaTheme(themeMode = state.themeMode) {
|
||||
DriverApp(
|
||||
viewModel = viewModel,
|
||||
initialRouteId = notificationRouteId,
|
||||
initialRouteTarget = notificationRouteTarget,
|
||||
initialLeaveRequestId = notificationLeaveRequestId,
|
||||
playAppUpdateState = playAppUpdateState,
|
||||
onStartAppUpdate = playInAppUpdates::startUpdate,
|
||||
onCompleteAppUpdate = playInAppUpdates::completeDownloadedUpdate,
|
||||
)
|
||||
}
|
||||
}
|
||||
playInAppUpdates.checkForUpdate()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (::playInAppUpdates.isInitialized) {
|
||||
playInAppUpdates.checkForUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
if (::playInAppUpdates.isInitialized) {
|
||||
playInAppUpdates.dispose()
|
||||
}
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: android.content.Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
notificationRouteId = intent.getStringExtra(EXTRA_ROUTE_ID)
|
||||
notificationRouteTarget = intent.getStringExtra(EXTRA_ROUTE_TARGET)
|
||||
notificationLeaveRequestId = intent.getStringExtra(EXTRA_LEAVE_REQUEST_ID)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_ROUTE_ID = "pl.firmatpp.kierowca.EXTRA_ROUTE_ID"
|
||||
const val EXTRA_ROUTE_TARGET = "pl.firmatpp.kierowca.EXTRA_ROUTE_TARGET"
|
||||
const val EXTRA_LEAVE_REQUEST_ID = "pl.firmatpp.kierowca.EXTRA_LEAVE_REQUEST_ID"
|
||||
const val ROUTE_TARGET_DETAIL = "detail"
|
||||
const val ROUTE_TARGET_FINISH = "finish"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package pl.firmatpp.kierowca.data
|
||||
|
||||
import java.io.IOException
|
||||
import java.net.UnknownHostException
|
||||
import kotlin.coroutines.cancellation.CancellationException
|
||||
import retrofit2.HttpException
|
||||
|
||||
enum class ApiErrorKind {
|
||||
@@ -20,11 +22,17 @@ data class ApiError(
|
||||
val retryable: Boolean,
|
||||
val code: String? = null,
|
||||
val statusCode: Int? = null,
|
||||
val responseBody: String? = null,
|
||||
)
|
||||
|
||||
object ApiErrorMapper {
|
||||
fun map(throwable: Throwable): ApiError =
|
||||
when (throwable) {
|
||||
is UnknownHostException -> ApiError(
|
||||
kind = ApiErrorKind.Network,
|
||||
message = "Brak internetu lub połączenia z serwerem. Sprawdź zasięg i spróbuj ponownie.",
|
||||
retryable = true,
|
||||
)
|
||||
is IOException -> ApiError(
|
||||
kind = ApiErrorKind.Network,
|
||||
message = "Nie udało się połączyć z serwerem. Operacja nie została potwierdzona.",
|
||||
@@ -38,8 +46,14 @@ object ApiErrorMapper {
|
||||
)
|
||||
}
|
||||
|
||||
fun shouldReportNonFatal(throwable: Throwable): Boolean =
|
||||
map(throwable).kind != ApiErrorKind.Network
|
||||
|
||||
fun mapHttpStatus(statusCode: Int, body: String?): ApiError {
|
||||
val code = body?.let { """"code"\s*:\s*"([^"]+)"""".toRegex().find(it)?.groupValues?.getOrNull(1) }
|
||||
val code = body?.let {
|
||||
""""code"\s*:\s*"([^"]+)"""".toRegex().find(it)?.groupValues?.getOrNull(1)
|
||||
?: """"reason"\s*:\s*"([^"]+)"""".toRegex().find(it)?.groupValues?.getOrNull(1)
|
||||
}
|
||||
val message = body?.let { """"message"\s*:\s*"([^"]+)"""".toRegex().find(it)?.groupValues?.getOrNull(1) }
|
||||
val retryable = body?.let { """"retryable"\s*:\s*(true|false)""".toRegex().find(it)?.groupValues?.getOrNull(1)?.toBooleanStrictOrNull() }
|
||||
|
||||
@@ -48,10 +62,17 @@ object ApiErrorMapper {
|
||||
code = code,
|
||||
message = message,
|
||||
retryable = retryable,
|
||||
responseBody = body,
|
||||
)
|
||||
}
|
||||
|
||||
fun mapProblem(statusCode: Int, code: String?, message: String?, retryable: Boolean?): ApiError {
|
||||
fun mapProblem(
|
||||
statusCode: Int,
|
||||
code: String?,
|
||||
message: String?,
|
||||
retryable: Boolean?,
|
||||
responseBody: String? = null,
|
||||
): ApiError {
|
||||
val kind = when (statusCode) {
|
||||
401 -> ApiErrorKind.Auth
|
||||
403 -> ApiErrorKind.Forbidden
|
||||
@@ -63,15 +84,20 @@ object ApiErrorMapper {
|
||||
}
|
||||
val defaultRetryable = statusCode == 429 || statusCode in 500..599
|
||||
val resolvedRetryable = retryable ?: defaultRetryable
|
||||
val resolvedMessage = message?.takeIf { it.isNotBlank() } ?: when (kind) {
|
||||
ApiErrorKind.Auth -> "Sesja wygasła. Zaloguj się ponownie."
|
||||
ApiErrorKind.Forbidden -> "Brak uprawnień do tej operacji."
|
||||
ApiErrorKind.Validation -> "Serwer odrzucił operację. Nie została zapisana."
|
||||
ApiErrorKind.Conflict -> "Operacja jest w konflikcie z aktualnym stanem danych."
|
||||
ApiErrorKind.RateLimited -> "Za dużo prób. Aplikacja spróbuje ponownie później."
|
||||
ApiErrorKind.Server -> "Serwer nie potwierdził operacji. Aplikacja spróbuje ponownie."
|
||||
ApiErrorKind.Network -> "Nie udało się połączyć z serwerem. Operacja nie została potwierdzona."
|
||||
ApiErrorKind.Unknown -> "Wystąpił błąd. Operacja nie została potwierdzona."
|
||||
val resolvedMessage = when {
|
||||
code == "INVALID_OTP" -> "Kod jest nieprawidłowy lub wygasł. Użyj kodu z najnowszego SMS-a."
|
||||
kind == ApiErrorKind.RateLimited -> "Za dużo prób. Odczekaj chwilę i spróbuj ponownie."
|
||||
!message.isNullOrBlank() -> message
|
||||
else -> when (kind) {
|
||||
ApiErrorKind.Auth -> "Sesja wygasła. Zaloguj się ponownie."
|
||||
ApiErrorKind.Forbidden -> "Brak uprawnień do tej operacji."
|
||||
ApiErrorKind.Validation -> "Serwer odrzucił operację. Nie została zapisana."
|
||||
ApiErrorKind.Conflict -> "Operacja jest w konflikcie z aktualnym stanem danych."
|
||||
ApiErrorKind.RateLimited -> "Za dużo prób. Odczekaj chwilę i spróbuj ponownie."
|
||||
ApiErrorKind.Server -> "Serwer nie potwierdził operacji. Aplikacja spróbuje ponownie."
|
||||
ApiErrorKind.Network -> "Nie udało się połączyć z serwerem. Operacja nie została potwierdzona."
|
||||
ApiErrorKind.Unknown -> "Wystąpił błąd. Operacja nie została potwierdzona."
|
||||
}
|
||||
}
|
||||
|
||||
return ApiError(
|
||||
@@ -80,11 +106,20 @@ object ApiErrorMapper {
|
||||
retryable = resolvedRetryable,
|
||||
code = code,
|
||||
statusCode = statusCode,
|
||||
responseBody = responseBody,
|
||||
)
|
||||
}
|
||||
|
||||
private fun mapHttpException(exception: HttpException): ApiError {
|
||||
val body = runCatching { exception.response()?.errorBody()?.string() }.getOrNull()
|
||||
val body = runCatching {
|
||||
val source = exception.response()?.errorBody()?.source() ?: return@runCatching null
|
||||
source.request(Long.MAX_VALUE)
|
||||
source.buffer.clone().readUtf8()
|
||||
}.getOrNull()
|
||||
return mapHttpStatus(exception.code(), body)
|
||||
}
|
||||
}
|
||||
|
||||
fun Throwable.rethrowIfCancellation() {
|
||||
if (this is CancellationException) throw this
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package pl.firmatpp.kierowca.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import pl.firmatpp.kierowca.ui.theme.AppThemeMode
|
||||
|
||||
private val Context.driverAppPreferencesDataStore by preferencesDataStore(name = "driver_app_preferences")
|
||||
|
||||
class AppPreferencesStore(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
) {
|
||||
constructor(context: Context) : this(context.driverAppPreferencesDataStore)
|
||||
|
||||
private val themeModeKey = stringPreferencesKey("theme_mode")
|
||||
private val routeProgressNotificationEnabledKey = booleanPreferencesKey("route_progress_notification_enabled")
|
||||
private val routeLocationEnabledKey = booleanPreferencesKey("route_location_enabled")
|
||||
|
||||
val themeMode: Flow<AppThemeMode> = dataStore.data
|
||||
.map { preferences -> AppThemeMode.fromStoredValue(preferences[themeModeKey]) }
|
||||
|
||||
val routeProgressNotificationEnabled: Flow<Boolean> = dataStore.data
|
||||
.map { preferences -> preferences[routeProgressNotificationEnabledKey] ?: true }
|
||||
|
||||
val routeLocationEnabled: Flow<Boolean> = dataStore.data
|
||||
.map { preferences -> preferences[routeLocationEnabledKey] ?: false }
|
||||
|
||||
suspend fun setThemeMode(themeMode: AppThemeMode) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[themeModeKey] = themeMode.storedValue
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setRouteProgressNotificationEnabled(enabled: Boolean) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[routeProgressNotificationEnabledKey] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setRouteLocationEnabled(enabled: Boolean) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[routeLocationEnabledKey] = enabled
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,17 +22,6 @@ class DeviceInfoProvider(
|
||||
androidVersion = Build.VERSION.RELEASE,
|
||||
sdkInt = Build.VERSION.SDK_INT,
|
||||
appVersion = BuildConfig.VERSION_NAME,
|
||||
serialNumber = readSerialNumber(),
|
||||
serialNumber = null,
|
||||
)
|
||||
|
||||
private fun readSerialNumber(): String? =
|
||||
runCatching {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
Build.getSerial()
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
Build.SERIAL
|
||||
}
|
||||
}.getOrNull()
|
||||
?.takeUnless { it.isBlank() || it.equals(Build.UNKNOWN, ignoreCase = true) }
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package pl.firmatpp.kierowca.data
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.OpenableColumns
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import java.util.UUID
|
||||
@@ -12,16 +13,35 @@ import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import pl.firmatpp.kierowca.data.api.ApiFactory
|
||||
import pl.firmatpp.kierowca.data.api.MobileDriverApi
|
||||
import pl.firmatpp.kierowca.data.model.BootstrapResponse
|
||||
import pl.firmatpp.kierowca.data.model.AcknowledgeTachographReminderBody
|
||||
import pl.firmatpp.kierowca.data.model.BroadcastAuthBody
|
||||
import pl.firmatpp.kierowca.data.model.BroadcastAuthResponse
|
||||
import pl.firmatpp.kierowca.data.model.CancelLeaveRequestBody
|
||||
import pl.firmatpp.kierowca.data.model.DispatchSheetUploadResponse
|
||||
import pl.firmatpp.kierowca.data.model.CreateLeaveRequestBody
|
||||
import pl.firmatpp.kierowca.data.model.DriverDto
|
||||
import pl.firmatpp.kierowca.data.model.DriverLeaveCalendarEntryDto
|
||||
import pl.firmatpp.kierowca.data.model.DriverLeaveDocumentDto
|
||||
import pl.firmatpp.kierowca.data.model.DriverLeaveForecastDto
|
||||
import pl.firmatpp.kierowca.data.model.DriverLeaveRequestDto
|
||||
import pl.firmatpp.kierowca.data.model.DriverLeaveSummaryDto
|
||||
import pl.firmatpp.kierowca.data.model.FinishRouteBody
|
||||
import pl.firmatpp.kierowca.data.model.LeaveForecastBody
|
||||
import pl.firmatpp.kierowca.data.model.NotificationPreferencesBody
|
||||
import pl.firmatpp.kierowca.data.model.NotificationPreferencesDto
|
||||
import pl.firmatpp.kierowca.data.model.OtpResponse
|
||||
import pl.firmatpp.kierowca.data.model.PhotoUploadResponse
|
||||
import pl.firmatpp.kierowca.data.model.PushTokenBody
|
||||
import pl.firmatpp.kierowca.data.model.RealtimeStatusBody
|
||||
import pl.firmatpp.kierowca.data.model.RequestOtpBody
|
||||
import pl.firmatpp.kierowca.data.model.RoutePointBatchBody
|
||||
import pl.firmatpp.kierowca.data.model.RoutePointsResponse
|
||||
import pl.firmatpp.kierowca.data.model.RouteResponse
|
||||
import pl.firmatpp.kierowca.data.model.StartRouteBody
|
||||
import pl.firmatpp.kierowca.data.model.SyncStateResponse
|
||||
import pl.firmatpp.kierowca.data.model.TachographReminderDto
|
||||
import pl.firmatpp.kierowca.data.model.VerifyOtpBody
|
||||
import pl.firmatpp.kierowca.data.upload.DispatchSheetUploadEntity
|
||||
import pl.firmatpp.kierowca.data.upload.PhotoUploadEntity
|
||||
|
||||
class DriverRepository(
|
||||
@@ -43,9 +63,120 @@ class DriverRepository(
|
||||
suspend fun bootstrap(date: String? = null): BootstrapResponse =
|
||||
api.bootstrap(authHeader(requireToken()), date)
|
||||
|
||||
suspend fun acknowledgeTachographReminder(taskIds: List<String>): TachographReminderDto =
|
||||
api.acknowledgeTachographReminder(
|
||||
authHeader(requireToken()),
|
||||
AcknowledgeTachographReminderBody(taskIds),
|
||||
).tachographReminder
|
||||
|
||||
suspend fun route(routeId: String): RouteResponse =
|
||||
api.route(authHeader(requireToken()), routeId)
|
||||
|
||||
suspend fun leaveRequests(): List<DriverLeaveRequestDto> =
|
||||
api.leaveRequests(authHeader(requireToken())).data
|
||||
|
||||
suspend fun leaveSummary(): DriverLeaveSummaryDto =
|
||||
api.leaveSummary(authHeader(requireToken())).data
|
||||
|
||||
suspend fun leaveForecast(
|
||||
dateFrom: String,
|
||||
dateTo: String,
|
||||
type: String,
|
||||
requestMode: String,
|
||||
requestedQuantity: Int?,
|
||||
details: Map<String, String>,
|
||||
): DriverLeaveForecastDto =
|
||||
api.leaveForecast(
|
||||
authHeader(requireToken()),
|
||||
LeaveForecastBody(type, dateFrom, dateTo, requestMode, requestedQuantity, details),
|
||||
).data
|
||||
|
||||
suspend fun leaveCalendar(from: String, to: String): List<DriverLeaveCalendarEntryDto> =
|
||||
api.leaveCalendar(authHeader(requireToken()), from, to).data
|
||||
|
||||
suspend fun leaveRequest(id: String): DriverLeaveRequestDto =
|
||||
api.leaveRequest(authHeader(requireToken()), id).data
|
||||
|
||||
suspend fun createLeaveRequest(
|
||||
dateFrom: String,
|
||||
dateTo: String,
|
||||
type: String,
|
||||
requestMode: String,
|
||||
requestedQuantity: Int?,
|
||||
details: Map<String, String>,
|
||||
idempotencyKey: String,
|
||||
note: String?,
|
||||
): DriverLeaveRequestDto =
|
||||
api.createLeaveRequest(
|
||||
authHeader(requireToken()),
|
||||
CreateLeaveRequestBody(
|
||||
dateFrom = dateFrom,
|
||||
dateTo = dateTo,
|
||||
type = type,
|
||||
requestMode = requestMode,
|
||||
requestedQuantity = requestedQuantity,
|
||||
details = details,
|
||||
idempotencyKey = idempotencyKey,
|
||||
note = note,
|
||||
),
|
||||
).data
|
||||
|
||||
suspend fun cancelLeaveRequest(id: String, expectedVersion: Long, comment: String? = null): DriverLeaveRequestDto =
|
||||
api.cancelLeaveRequest(authHeader(requireToken()), id, CancelLeaveRequestBody(comment, expectedVersion)).data
|
||||
|
||||
suspend fun leaveDocuments(id: String): List<DriverLeaveDocumentDto> =
|
||||
api.leaveDocuments(authHeader(requireToken()), id).data
|
||||
|
||||
suspend fun uploadLeaveDocument(id: String, documentType: String, uri: Uri): DriverLeaveDocumentDto {
|
||||
val resolver = context.contentResolver
|
||||
val mimeType = resolver.getType(uri) ?: "application/octet-stream"
|
||||
val fileMetadata = resolver.query(
|
||||
uri,
|
||||
arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE),
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
)?.use { cursor ->
|
||||
if (!cursor.moveToFirst()) {
|
||||
null
|
||||
} else {
|
||||
cursor.getString(0) to cursor.getLong(1)
|
||||
}
|
||||
}
|
||||
if ((fileMetadata?.second ?: 0L) > 20L * 1024L * 1024L) {
|
||||
error("Dokument jest za duży. Maksymalny rozmiar pliku to 20 MB.")
|
||||
}
|
||||
val bytes = resolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
?: error("Nie można odczytać wybranego dokumentu.")
|
||||
val originalName = fileMetadata?.first
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?: "dokument"
|
||||
val body = bytes.toRequestBody(mimeType.toMediaTypeOrNull())
|
||||
val file = MultipartBody.Part.createFormData("file", originalName, body)
|
||||
|
||||
return api.uploadLeaveDocument(
|
||||
authHeader(requireToken()),
|
||||
id,
|
||||
file,
|
||||
documentType.toPlainTextBody(),
|
||||
).data
|
||||
}
|
||||
|
||||
suspend fun completeRoute(routeId: String) =
|
||||
api.completeRoute(authHeader(requireToken()), routeId)
|
||||
|
||||
suspend fun startRoute(routeId: String, body: StartRouteBody) =
|
||||
api.startRoute(authHeader(requireToken()), routeId, body)
|
||||
|
||||
suspend fun finishRoute(routeId: String, body: FinishRouteBody) =
|
||||
api.finishRoute(authHeader(requireToken()), routeId, body)
|
||||
|
||||
suspend fun storeRoutePoints(routeId: String, body: RoutePointBatchBody): RoutePointsResponse =
|
||||
api.storeRoutePoints(authHeader(requireToken()), routeId, body)
|
||||
|
||||
suspend fun updateNotificationPreferences(notifyNewRoutes: Boolean): NotificationPreferencesDto =
|
||||
api.updateNotificationPreferences(authHeader(requireToken()), NotificationPreferencesBody(notifyNewRoutes))
|
||||
|
||||
suspend fun syncState(date: String?, routeId: String? = null): SyncStateResponse =
|
||||
api.syncState(authHeader(requireToken()), date, routeId)
|
||||
|
||||
@@ -56,6 +187,10 @@ class DriverRepository(
|
||||
api.storePushToken(authHeader(requireToken()), PushTokenBody(token))
|
||||
}
|
||||
|
||||
suspend fun storeRealtimeStatus(status: String, socketId: String? = null, error: String? = null) {
|
||||
api.storeRealtimeStatus(authHeader(requireToken()), RealtimeStatusBody(status, socketId, error))
|
||||
}
|
||||
|
||||
suspend fun deletePushToken() {
|
||||
val token = tokenStore.read() ?: return
|
||||
runCatching { api.deletePushToken(authHeader(token)) }
|
||||
@@ -65,7 +200,11 @@ class DriverRepository(
|
||||
routeId: String,
|
||||
uri: Uri,
|
||||
source: String,
|
||||
stage: String = "other",
|
||||
metadata: PhotoUploadMetadata = PhotoUploadMetadata(),
|
||||
workflowVersion: String? = null,
|
||||
workflowStepId: String? = null,
|
||||
workflowDocumentId: String? = null,
|
||||
): PhotoUploadResponse {
|
||||
val resolver = context.contentResolver
|
||||
val mimeType = resolver.getType(uri) ?: "image/jpeg"
|
||||
@@ -85,6 +224,10 @@ class DriverRepository(
|
||||
clientRequestId.toPlainTextBody(),
|
||||
contentSha256.toPlainTextBody(),
|
||||
sourceBody,
|
||||
stage.toPlainTextBody(),
|
||||
workflowVersion?.toPlainTextBody(),
|
||||
workflowStepId?.toPlainTextBody(),
|
||||
workflowDocumentId?.toPlainTextBody(),
|
||||
metadataParts["takenAt"],
|
||||
metadataParts["latitude"],
|
||||
metadataParts["longitude"],
|
||||
@@ -111,6 +254,10 @@ class DriverRepository(
|
||||
upload.clientRequestId.toPlainTextBody(),
|
||||
upload.contentSha256.toPlainTextBody(),
|
||||
upload.source.toPlainTextBody(),
|
||||
upload.stage.toPlainTextBody(),
|
||||
upload.workflowVersion?.toPlainTextBody(),
|
||||
upload.workflowStepId?.toPlainTextBody(),
|
||||
upload.workflowDocumentId?.toPlainTextBody(),
|
||||
metadataParts["takenAt"],
|
||||
metadataParts["latitude"],
|
||||
metadataParts["longitude"],
|
||||
@@ -118,13 +265,39 @@ class DriverRepository(
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun uploadQueuedDispatchSheetPhoto(upload: DispatchSheetUploadEntity): DispatchSheetUploadResponse {
|
||||
val file = File(upload.localPath)
|
||||
val body = file.readBytes().toRequestBody(upload.mimeType.toMediaTypeOrNull())
|
||||
val photo = MultipartBody.Part.createFormData("photo", file.name, body)
|
||||
val metadataParts = PhotoUploadMetadata(
|
||||
takenAt = upload.takenAt,
|
||||
latitude = upload.latitude,
|
||||
longitude = upload.longitude,
|
||||
locationAccuracyMeters = upload.locationAccuracyMeters,
|
||||
).toMultipartTextParts()
|
||||
|
||||
return api.uploadDispatchSheetPhoto(
|
||||
authHeader(requireToken()),
|
||||
upload.clientRequestId,
|
||||
photo,
|
||||
upload.clientRequestId.toPlainTextBody(),
|
||||
upload.contentSha256.toPlainTextBody(),
|
||||
upload.source.toPlainTextBody(),
|
||||
metadataParts["takenAt"],
|
||||
metadataParts["latitude"],
|
||||
metadataParts["longitude"],
|
||||
metadataParts["locationAccuracyMeters"],
|
||||
upload.replacePhotoId?.toPlainTextBody(),
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun deletePhoto(photoId: String) {
|
||||
api.deletePhoto(authHeader(requireToken()), photoId)
|
||||
}
|
||||
|
||||
suspend fun logout() {
|
||||
suspend fun logout(notifyServer: Boolean = true) {
|
||||
val token = tokenStore.read()
|
||||
if (token != null) {
|
||||
if (token != null && notifyServer) {
|
||||
runCatching { api.deletePushToken(authHeader(token)) }
|
||||
runCatching { api.logout(authHeader(token)) }
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package pl.firmatpp.kierowca.data
|
||||
|
||||
import java.io.Serializable
|
||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
@@ -9,7 +10,7 @@ data class PhotoUploadMetadata(
|
||||
val latitude: Double? = null,
|
||||
val longitude: Double? = null,
|
||||
val locationAccuracyMeters: Double? = null,
|
||||
)
|
||||
) : Serializable
|
||||
|
||||
fun PhotoUploadMetadata.toMultipartTextParts(): Map<String, RequestBody> = buildMap {
|
||||
takenAt?.let { put("takenAt", it.toPlainTextBody()) }
|
||||