Compare commits

..
15 changed files with 638 additions and 43 deletions
+2
View File
@@ -7,3 +7,5 @@ app/google-services.json:Zone.Identifier
*.iml
keystore.properties
*.jks
release-artifacts/
app/src/main/res_bak/
+20
View File
@@ -21,3 +21,23 @@ 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 dla Gitea oraz AAB dla Google Play Console, tworzy commit wersji,
tag, push i Gitea Release. Artefakty zostają również zapisane lokalnie w
`release-artifacts/<tag>/`.
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
```
+2 -2
View File
@@ -34,8 +34,8 @@ android {
applicationId = "pl.firmatpp.kierowca"
minSdk = 26
targetSdk = 35
versionCode = 105
versionName = "1.0.52"
versionCode = 107
versionName = "1.0.54"
setProperty("archivesBaseName", "pl.firmatpp.kierowca")
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
@@ -1,12 +1,23 @@
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 {
runCatching { OfflineOutboxManager(this@DriverApplication).repairGpsQueue() }
.onFailure { AppDiagnostics.reportNonFatal(it, "repair_gps_queue") }
}
}
}
@@ -3,8 +3,9 @@ package pl.firmatpp.kierowca.data.upload
import android.content.Context
import androidx.work.WorkManager
import java.io.File
import java.util.concurrent.TimeUnit
class OfflineOutboxManager(context: Context) {
class OfflineOutboxManager(private val context: Context) {
private val database = DriverDatabase.get(context)
private val workManager = WorkManager.getInstance(context)
@@ -14,6 +15,27 @@ class OfflineOutboxManager(context: Context) {
database.routeActionDao().allUnsent().size +
database.routePointDao().allUnsent().size
suspend fun repairGpsQueue() {
val retryableStatuses = setOf(
RoutePointStatus.Pending,
RoutePointStatus.Syncing,
RoutePointStatus.FailedRetryable,
)
val routeIds = database.routePointDao().allUnsent()
.filter { it.status in retryableStatuses }
.map { it.routeId }
.distinct()
routeIds.forEach { routeId ->
runCatching {
workManager.cancelUniqueWork(RoutePointWorker.uniqueWorkName(routeId))
.result
.get(5, TimeUnit.SECONDS)
}
RoutePointOutbox(context).enqueueWorker(routeId, delaySeconds = 0L)
}
}
suspend fun clearAll() {
val photos = database.photoUploadDao().allRecords()
val dispatchSheets = database.dispatchSheetUploadDao().allRecords()
@@ -37,6 +37,9 @@ interface RoutePointDao {
@Query("SELECT COUNT(*) FROM route_points WHERE status IN ('PENDING', 'SYNCING', 'FAILED_RETRYABLE')")
fun observeUnsentCount(): Flow<Int>
@Query("SELECT MIN(createdAtEpochMillis) FROM route_points WHERE status IN ('PENDING', 'SYNCING', 'FAILED_RETRYABLE')")
fun observeOldestUnsentAt(): Flow<Long?>
@Query(
"""
UPDATE route_points
@@ -54,7 +54,7 @@ class RoutePointOutbox(
workManager.enqueueUniqueWork(
RoutePointWorker.uniqueWorkName(routeId),
ExistingWorkPolicy.APPEND_OR_REPLACE,
ExistingWorkPolicy.KEEP,
request,
)
}
@@ -4,6 +4,7 @@ import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import java.util.UUID
import kotlinx.coroutines.delay
import pl.firmatpp.kierowca.data.ApiErrorKind
import pl.firmatpp.kierowca.data.ApiErrorMapper
import pl.firmatpp.kierowca.data.DriverRepository
@@ -23,31 +24,34 @@ class RoutePointWorker(
override suspend fun doWork(): Result {
if (!NetworkMonitor(applicationContext).isCurrentlyValidated()) return Result.retry()
val routeId = inputData.getString(KEY_ROUTE_ID) ?: return Result.failure()
while (!isStopped) {
val points = dao.pendingForRoute(routeId, BATCH_LIMIT)
if (points.isEmpty()) return Result.success()
val pointIds = points.map { it.clientPointId }
dao.updateStatus(pointIds, RoutePointStatus.Syncing, null, attemptIncrement = 1)
return runCatching {
val response = repository.storeRoutePoints(
val outcome = runCatching {
repository.storeRoutePoints(
routeId = routeId,
body = RoutePointBatchBody(
clientBatchId = UUID.randomUUID().toString(),
points = points.map { it.toDto() },
),
)
}
val response = outcome.getOrNull()
if (response != null) {
dao.delete(pointIds)
if (response.arrived) {
ActiveRouteTrackingService.markArrived(applicationContext, routeId)
if (response.arrived) ActiveRouteTrackingService.markArrived(applicationContext, routeId)
if (dao.pendingCount(routeId) == 0) {
delay(750L)
if (dao.pendingCount(routeId) == 0) return Result.success()
}
if (dao.pendingCount(routeId) > 0) {
RoutePointOutbox(applicationContext).enqueueWorker(routeId, delaySeconds = 1L)
continue
}
Result.success()
}.getOrElse { throwable ->
val throwable = outcome.exceptionOrNull() ?: return Result.retry()
val error = ApiErrorMapper.map(throwable)
AppDiagnostics.reportNonFatal(
throwable = throwable,
@@ -61,11 +65,18 @@ class RoutePointWorker(
"retryable" to error.retryable,
),
)
if (isInactiveRoutePointError(error.code)) {
dao.delete(pointIds)
ActiveRouteTrackingService.stop(applicationContext, routeId)
continue
}
val status = if (error.retryable) RoutePointStatus.FailedRetryable else RoutePointStatus.FailedPermanent
dao.updateStatus(pointIds, status, error.message, attemptIncrement = 0)
if (error.retryable && error.kind != ApiErrorKind.Auth) Result.retry() else Result.failure()
return if (error.retryable && error.kind != ApiErrorKind.Auth) Result.retry() else Result.failure()
}
return Result.retry()
}
private fun RoutePointEntity.toDto(): RoutePointDto =
@@ -90,3 +101,5 @@ class RoutePointWorker(
fun uniqueWorkName(routeId: String): String = "route-point-sync-$routeId"
}
}
internal fun isInactiveRoutePointError(code: String?): Boolean = code == "ROUTE_POINTS_INVALID_STATUS"
@@ -3,6 +3,7 @@ package pl.firmatpp.kierowca.sync
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import java.net.URI
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -49,7 +50,24 @@ class OkHttpLiveWebSocketFactory(
private val client: OkHttpClient,
) : LiveWebSocketFactory {
override fun newWebSocket(url: String, listener: WebSocketListener): WebSocket =
client.newWebSocket(Request.Builder().url(url).build(), listener)
client.newWebSocket(
Request.Builder()
.url(url)
.header("Origin", websocketOrigin(url))
.build(),
listener,
)
}
internal fun websocketOrigin(url: String): String =
URI(
url
.replaceFirst("wss://", "https://")
.replaceFirst("ws://", "http://")
).let { uri ->
val defaultPort = (uri.scheme == "https" && uri.port == 443) || (uri.scheme == "http" && uri.port == 80)
val port = if (uri.port > 0 && !defaultPort) ":${uri.port}" else ""
"${uri.scheme}://${uri.host}$port"
}
enum class LiveSyncConnectionState {
@@ -56,6 +56,10 @@ class ActiveRouteTrackingService : Service(), LocationListener {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_STOP -> {
val requestedRouteId = intent.getStringExtra(EXTRA_ROUTE_ID)
if (!requestedRouteId.isNullOrBlank() && routeId != requestedRouteId) {
return START_NOT_STICKY
}
stopSelf()
return START_NOT_STICKY
}
@@ -64,13 +68,25 @@ class ActiveRouteTrackingService : Service(), LocationListener {
if (!id.isNullOrBlank() && (routeId == null || id == routeId)) {
routeId = id
arrived = true
runCatching { locationManager.removeUpdates(this) }
startForegroundCompat(buildNotification())
}
return START_STICKY
return START_NOT_STICKY
}
else -> {
routeId = intent?.getStringExtra(EXTRA_ROUTE_ID) ?: routeId
driverId = intent?.getStringExtra(EXTRA_DRIVER_ID) ?: driverId
val nextRouteId = intent?.getStringExtra(EXTRA_ROUTE_ID) ?: routeId
val nextDriverId = intent?.getStringExtra(EXTRA_DRIVER_ID) ?: driverId
if (nextRouteId.isNullOrBlank() || nextDriverId.isNullOrBlank()) {
stopSelf()
return START_NOT_STICKY
}
val routeChanged = nextRouteId != routeId
routeId = nextRouteId
driverId = nextDriverId
getSharedPreferences(TRACKING_PREFERENCES, Context.MODE_PRIVATE)
.edit()
.putString(ACTIVE_ROUTE_ID, nextRouteId)
.apply()
routeLabel = intent?.getStringExtra(EXTRA_ROUTE_LABEL) ?: routeLabel
destinationLat = intent?.takeIf { it.hasExtra(EXTRA_DESTINATION_LAT) }?.getDoubleExtra(EXTRA_DESTINATION_LAT, 0.0)
?: destinationLat
@@ -80,10 +96,10 @@ class ActiveRouteTrackingService : Service(), LocationListener {
?.takeIf { it > 0.0 }
?: totalDistanceMeters
progressEnabled = intent?.getBooleanExtra(EXTRA_PROGRESS_ENABLED, true) ?: progressEnabled
arrived = false
if (routeChanged) arrived = false
startForegroundCompat(buildNotification())
requestLocationUpdates()
return START_STICKY
if (!arrived) requestLocationUpdates()
return START_NOT_STICKY
}
}
}
@@ -96,6 +112,7 @@ class ActiveRouteTrackingService : Service(), LocationListener {
if (!arrived && remaining != null && remaining <= arrivalRadiusMeters(location)) {
arrived = true
runCatching { locationManager.removeUpdates(this) }
startForegroundCompat(buildNotification())
} else {
startForegroundCompat(buildNotification())
@@ -119,14 +136,19 @@ class ActiveRouteTrackingService : Service(), LocationListener {
override fun onDestroy() {
runCatching { locationManager.removeUpdates(this) }
getSharedPreferences(TRACKING_PREFERENCES, Context.MODE_PRIVATE)
.edit()
.remove(ACTIVE_ROUTE_ID)
.apply()
scope.cancel()
super.onDestroy()
}
private fun requestLocationUpdates() {
if (!hasLocationPermission()) {
if (!hasLocationPermission() || routeId.isNullOrBlank() || driverId.isNullOrBlank()) {
return
}
runCatching { locationManager.removeUpdates(this) }
runCatching {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_INTERVAL_MS, 0f, this)
}
@@ -266,6 +288,8 @@ class ActiveRouteTrackingService : Service(), LocationListener {
private const val EXTRA_DESTINATION_LON = "destinationLon"
private const val EXTRA_TOTAL_DISTANCE_METERS = "totalDistanceMeters"
private const val EXTRA_PROGRESS_ENABLED = "progressEnabled"
private const val TRACKING_PREFERENCES = "active_route_tracking"
private const val ACTIVE_ROUTE_ID = "active_route_id"
fun start(context: Context, route: DriverRouteDto, driver: DriverDto, progressEnabled: Boolean = true) {
val intent = Intent(context, ActiveRouteTrackingService::class.java).apply {
@@ -281,12 +305,16 @@ class ActiveRouteTrackingService : Service(), LocationListener {
ContextCompat.startForegroundService(context, intent)
}
fun stop(context: Context) {
context.startService(
Intent(context, ActiveRouteTrackingService::class.java).apply {
action = ACTION_STOP
},
)
fun stop(context: Context, routeId: String? = null) {
val activeRouteId = context.getSharedPreferences(TRACKING_PREFERENCES, Context.MODE_PRIVATE)
.getString(ACTIVE_ROUTE_ID, null)
if (routeId == null || routeId == activeRouteId) {
context.stopService(Intent(context, ActiveRouteTrackingService::class.java))
context.getSharedPreferences(TRACKING_PREFERENCES, Context.MODE_PRIVATE)
.edit()
.remove(ACTIVE_ROUTE_ID)
.apply()
}
}
fun markArrived(context: Context, routeId: String) {
@@ -118,6 +118,7 @@ data class DriverUiState(
val pendingLogoutItems: Int = 0,
val pendingDispatchUploads: Int = 0,
val pendingGpsPoints: Int = 0,
val oldestPendingGpsAtEpochMillis: Long? = null,
val diagnostics: DiagnosticSnapshot? = null,
val diagnosticsLoading: Boolean = false,
val diagnosticsError: String? = null,
@@ -138,13 +139,20 @@ data class DriverUiState(
val displaySelectedRoute: DriverRouteDto?
get() = selectedRouteProjection?.route
val pendingOperationalItems: Int
private val pendingUserOperationalItems: Int
get() = queuedPhotoUploads.count { it.status != PhotoUploadStatus.Confirmed.storageValue && it.status != PhotoUploadStatus.Cancelled.storageValue } +
visibleRouteActions.count { it.status != RouteActionStatus.Confirmed } + pendingDispatchUploads + pendingGpsPoints
visibleRouteActions.count { it.status != RouteActionStatus.Confirmed } + pendingDispatchUploads
val gpsQueueNeedsAttention: Boolean
get() = isOnline && oldestPendingGpsAtEpochMillis?.let { System.currentTimeMillis() - it >= 2 * 60 * 1000L } == true
val pendingOperationalItems: Int
get() = pendingUserOperationalItems + if (!isOnline || serverConnectionState == ServerConnectionState.Degraded || gpsQueueNeedsAttention) pendingGpsPoints else 0
val operationalQueueNeedsAttention: Boolean
get() = queuedPhotoUploads.any { it.status == PhotoUploadStatus.FailedPermanent.storageValue } ||
visibleRouteActions.any { it.status == RouteActionStatus.FailedPermanent || it.status == RouteActionStatus.FailedConflict }
visibleRouteActions.any { it.status == RouteActionStatus.FailedPermanent || it.status == RouteActionStatus.FailedConflict } ||
gpsQueueNeedsAttention
}
internal fun DriverUiState.withApiError(throwable: Throwable): DriverUiState {
@@ -240,6 +248,11 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
_state.update { it.copy(pendingGpsPoints = count) }
}
}
viewModelScope.launch {
DriverDatabase.get(application).routePointDao().observeOldestUnsentAt().collect { oldest ->
_state.update { it.copy(oldestPendingGpsAtEpochMillis = oldest) }
}
}
viewModelScope.launch {
liveSyncClient.connectionState.collect { connectionState ->
DriverRuntimeSyncState.realtimeConnected = connectionState == LiveSyncConnectionState.Connected
@@ -405,6 +418,9 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
if (_state.value.isOnline && !cached.stale) registerPushTokenIfAvailable(driverId)
}
observeDispatchSheetUploads(response.dispatchSheetReminder?.workDate)
if (_state.value.isOnline && !cached.stale && settings?.selectedDate == settings?.today) {
reconcileTrackingService(response.routes.today, response.session.driver)
}
}.onFailure { throwable ->
if (generation != routesRequestGeneration) return@onFailure
reportHandledException("load_routes", throwable, mapOf("date" to date))
@@ -457,6 +473,9 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
}
observePhotoUploads(routeId)
observeRouteActions(routeId)
if (_state.value.isOnline && !cached.stale) {
reconcileTrackingServiceForRoute(response.route, _state.value.driver)
}
}
fun refreshSelectedRoute() {
@@ -484,6 +503,9 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
error = null,
)
}
if (_state.value.isOnline && !cached.stale) {
reconcileTrackingServiceForRoute(response.route, _state.value.driver)
}
}
.onFailure { throwable ->
if (generation == routeDetailRequestGeneration) _state.update { it.withApiError(throwable) }
@@ -1389,6 +1411,35 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
}
}
private fun reconcileTrackingService(routes: List<DriverRouteDto>, driver: DriverDto) {
val activeRoute = routes.firstOrNull { it.status == "W TRAKCIE" || it.trackingStatus == "active" }
if (activeRoute == null) {
ActiveRouteTrackingService.stop(getApplication())
} else {
ActiveRouteTrackingService.start(
context = getApplication(),
route = activeRoute,
driver = driver,
progressEnabled = _state.value.routeProgressNotificationEnabled,
)
}
}
private fun reconcileTrackingServiceForRoute(route: DriverRouteDto, driver: DriverDto?) {
if (route.status == "W TRAKCIE" || route.trackingStatus == "active") {
if (driver != null) {
ActiveRouteTrackingService.start(
context = getApplication(),
route = route,
driver = driver,
progressEnabled = _state.value.routeProgressNotificationEnabled,
)
}
} else {
ActiveRouteTrackingService.stop(getApplication(), route.id)
}
}
private fun observeRouteActions(routeId: String) {
routeActionsJob?.cancel()
routeActionsJob = viewModelScope.launch {
@@ -0,0 +1,18 @@
package pl.firmatpp.kierowca.data.upload
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class RoutePointWorkerRulesTest {
@Test
fun inactiveRouteConflictDiscardsObsoleteGpsPoints() {
assertTrue(isInactiveRoutePointError("ROUTE_POINTS_INVALID_STATUS"))
}
@Test
fun temporaryServerFailureDoesNotDiscardGpsPoints() {
assertFalse(isInactiveRoutePointError("SERVER_UNAVAILABLE"))
assertFalse(isInactiveRoutePointError(null))
}
}
@@ -25,6 +25,13 @@ class DriverLiveSyncClientTest {
reverbWsBaseUrl = "wss://example.test/app",
)
@Test
fun derivesBrowserCompatibleOriginFromWebSocketUrl() {
assertEquals("https://api-intranet.firmatpp.pl", websocketOrigin("wss://api-intranet.firmatpp.pl/ws/app/app-key"))
assertEquals("https://example.test:8443", websocketOrigin("wss://example.test:8443/app/app-key"))
assertEquals("http://localhost:8080", websocketOrigin("ws://localhost:8080/app/app-key"))
}
@Test
fun reconnectsWithBackoffAfterSocketFailure() = runTest {
val factory = FakeWebSocketFactory()
@@ -1,6 +1,7 @@
package pl.firmatpp.kierowca.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.IOException
@@ -130,6 +131,44 @@ class DriverUiStateTest {
assertEquals(listOf("above-first", "above-second", "span"), state.displayRoutes.map { it.id })
}
@Test
fun freshGpsPointsDoNotShowSynchronizationBannerWhenOnlineIsHealthy() {
val state = DriverUiState(
isOnline = true,
serverConnectionState = ServerConnectionState.Reachable,
pendingGpsPoints = 48,
oldestPendingGpsAtEpochMillis = System.currentTimeMillis() - 30_000L,
)
assertEquals(0, state.pendingOperationalItems)
assertFalse(state.operationalQueueNeedsAttention)
}
@Test
fun staleGpsBacklogRequiresAttentionWhenOnline() {
val state = DriverUiState(
isOnline = true,
serverConnectionState = ServerConnectionState.Reachable,
pendingGpsPoints = 48,
oldestPendingGpsAtEpochMillis = System.currentTimeMillis() - 3 * 60_000L,
)
assertEquals(48, state.pendingOperationalItems)
assertTrue(state.operationalQueueNeedsAttention)
}
@Test
fun offlineGpsPointsAreShownAsSavedLocallyNotAsFailure() {
val state = DriverUiState(
isOnline = false,
pendingGpsPoints = 48,
oldestPendingGpsAtEpochMillis = System.currentTimeMillis() - 3 * 60_000L,
)
assertEquals(48, state.pendingOperationalItems)
assertFalse(state.operationalQueueNeedsAttention)
}
private fun leaveRequest(id: String, status: String, version: Long = 1): DriverLeaveRequestDto =
DriverLeaveRequestDto(
id = id,
+363
View File
@@ -0,0 +1,363 @@
#!/usr/bin/env bash
set -Eeuo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
VERSION_FILE="$ROOT_DIR/app/build.gradle.kts"
REMOTE_NAME="${GIT_REMOTE:-origin}"
NOTES_FILE=""
SKIP_TESTS=0
REUSE_CURRENT=0
VERSION_FILE_CHANGED=0
VERSION_COMMITTED=0
VERSION_BACKUP=""
RELEASE_SUCCEEDED=0
usage() {
cat <<'EOF'
Użycie: scripts/release-android.sh [opcje]
Buduje i publikuje kolejną wersję aplikacji kierowcy:
- automatycznie zwiększa versionCode o 1 i patch versionName o 1,
- uruchamia testy jednostkowe,
- buduje podpisany APK dla Gitea Release,
- buduje podpisany AAB dla Google Play Console,
- zapisuje zmianę wersji w commicie, tworzy tag i wykonuje push,
- tworzy lub aktualizuje Gitea Release i wysyła APK oraz SHA256SUMS.
Opcje:
--notes-file PLIK Treść release notes z podanego pliku.
--skip-tests Pomiń testDebugUnitTest.
--reuse-current Nie zwiększaj wersji. Wznów publikację wersji zapisanej
obecnie w app/build.gradle.kts.
-h, --help Pokaż pomoc.
Zmienne środowiskowe:
GITEA_TOKEN Token API Gitea. Jeśli go brak, używany jest git credential helper.
GITEA_BASE_URL Nadpisuje adres Gitea, np. https://gitea.example.com.
GITEA_REPOSITORY Nadpisuje owner/repository.
GIT_REMOTE Remote Git, domyślnie origin.
Wersja początkowa jest zawsze odczytywana z app/build.gradle.kts.
Google Play Console otrzymuje plik AAB, ponieważ jest to właściwy format publikacyjny.
EOF
}
while (($# > 0)); do
case "$1" in
--notes-file)
NOTES_FILE="${2:-}"
[[ -n "$NOTES_FILE" ]] || { echo "Brak wartości dla --notes-file." >&2; exit 2; }
shift 2
;;
--skip-tests)
SKIP_TESTS=1
shift
;;
--reuse-current)
REUSE_CURRENT=1
shift
;;
-h|--help)
usage
exit 0
;;
*)
echo "Nieznana opcja: $1" >&2
usage >&2
exit 2
;;
esac
done
cd "$ROOT_DIR"
for command in git curl jq perl sha256sum jarsigner; do
command -v "$command" >/dev/null 2>&1 || {
echo "Brak wymaganego polecenia: $command" >&2
exit 1
}
done
[[ -x ./gradlew ]] || { echo "Brak wykonywalnego ./gradlew." >&2; exit 1; }
[[ -f keystore.properties ]] || { echo "Brak keystore.properties wymaganego do podpisania release." >&2; exit 1; }
[[ -f "$VERSION_FILE" ]] || { echo "Brak $VERSION_FILE." >&2; exit 1; }
branch="$(git branch --show-current)"
[[ -n "$branch" ]] || { echo "Release nie może być wykonany z detached HEAD." >&2; exit 1; }
if ! git diff --quiet || ! git diff --cached --quiet; then
echo "Repozytorium ma niezapisane zmiany śledzonych plików. Najpierw wykonaj commit." >&2
exit 1
fi
relevant_untracked="$(git status --porcelain --untracked-files=all -- app gradle scripts build.gradle.kts settings.gradle.kts gradle.properties | awk '$1 == "??" { print }')"
if [[ -n "$relevant_untracked" ]]; then
echo "Repozytorium ma nieśledzone pliki źródłowe. Najpierw zdecyduj, czy mają wejść do release:" >&2
printf '%s\n' "$relevant_untracked" >&2
exit 1
fi
git fetch --tags "$REMOTE_NAME"
remote_url="$(git remote get-url "$REMOTE_NAME")"
sanitized_remote="$(printf '%s' "$remote_url" | sed -E 's#^(https?://)[^/@]+@#\1#')"
if [[ "$sanitized_remote" =~ ^(https?)://([^/]+)/(.+)$ ]]; then
detected_protocol="${BASH_REMATCH[1]}"
detected_host="${BASH_REMATCH[2]}"
detected_repository="${BASH_REMATCH[3]%.git}"
else
detected_protocol="https"
detected_host=""
detected_repository=""
fi
gitea_base_url="${GITEA_BASE_URL:-${detected_protocol}://${detected_host}}"
gitea_repository="${GITEA_REPOSITORY:-$detected_repository}"
gitea_base_url="${gitea_base_url%/}"
[[ "$gitea_base_url" =~ ^https?://[^/]+$ ]] || { echo "Ustaw poprawne GITEA_BASE_URL." >&2; exit 1; }
[[ "$gitea_repository" =~ ^[^/]+/[^/]+$ ]] || { echo "Ustaw poprawne GITEA_REPOSITORY=owner/repository." >&2; exit 1; }
auth_args=()
if [[ -n "${GITEA_TOKEN:-}" ]]; then
auth_args=(-H "Authorization: token $GITEA_TOKEN")
else
credential="$(printf 'protocol=%s\nhost=%s\n\n' "$detected_protocol" "$detected_host" | git credential fill)"
gitea_username="$(printf '%s\n' "$credential" | sed -n 's/^username=//p')"
gitea_password="$(printf '%s\n' "$credential" | sed -n 's/^password=//p')"
[[ -n "$gitea_username" && -n "$gitea_password" ]] || {
echo "Brak danych Gitea. Ustaw GITEA_TOKEN albo skonfiguruj git credential helper." >&2
exit 1
}
auth_args=(-u "$gitea_username:$gitea_password")
fi
api_base="$gitea_base_url/api/v1/repos/$gitea_repository"
preflight_status="$(curl -sS "${auth_args[@]}" -o /dev/null -w '%{http_code}' "$api_base")"
[[ "$preflight_status" == "200" ]] || {
echo "Brak dostępu do repozytorium Gitea $gitea_repository (HTTP $preflight_status)." >&2
exit 1
}
read_version() {
local code name
code="$(sed -nE 's/^[[:space:]]*versionCode = ([0-9]+).*$/\1/p' "$VERSION_FILE" | sed -n '1p')"
name="$(sed -nE 's/^[[:space:]]*versionName = "([^"]+)".*$/\1/p' "$VERSION_FILE" | sed -n '1p')"
[[ "$code" =~ ^[0-9]+$ ]] || { echo "Nie można odczytać versionCode." >&2; return 1; }
[[ "$name" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "versionName musi mieć format major.minor.patch." >&2; return 1; }
printf '%s %s\n' "$code" "$name"
}
read -r current_code current_name < <(read_version)
if ((REUSE_CURRENT == 1)); then
next_code="$current_code"
next_name="$current_name"
else
IFS=. read -r version_major version_minor version_patch <<<"$current_name"
next_code=$((current_code + 1))
next_name="${version_major}.${version_minor}.$((version_patch + 1))"
fi
tag_name="v${next_name}-${next_code}"
artifact_dir="$ROOT_DIR/release-artifacts/$tag_name"
gitea_apk_name="TPP-Kierowca-${next_name}-${next_code}.apk"
play_aab_name="TPP-Kierowca-${next_name}-${next_code}.aab"
cleanup_on_exit() {
local exit_code=$?
if ((RELEASE_SUCCEEDED == 0 && VERSION_FILE_CHANGED == 1 && VERSION_COMMITTED == 0)) && [[ -n "$VERSION_BACKUP" && -f "$VERSION_BACKUP" ]]; then
cp "$VERSION_BACKUP" "$VERSION_FILE"
echo "Przywrócono poprzednią wersję w app/build.gradle.kts." >&2
fi
[[ -n "$VERSION_BACKUP" && -f "$VERSION_BACKUP" ]] && rm -f "$VERSION_BACKUP"
if ((RELEASE_SUCCEEDED == 0)); then
echo "Release nie został ukończony. Po usunięciu przyczyny użyj --reuse-current, jeśli commit wersji już powstał." >&2
fi
trap - EXIT INT TERM
exit "$exit_code"
}
trap cleanup_on_exit EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
if ((REUSE_CURRENT == 0)); then
if git show-ref --verify --quiet "refs/tags/$tag_name" || git ls-remote --exit-code --tags "$REMOTE_NAME" "refs/tags/$tag_name" >/dev/null 2>&1; then
echo "Tag $tag_name już istnieje. Użyj --reuse-current albo zwiększ wersję ręcznie." >&2
exit 1
fi
VERSION_BACKUP="$(mktemp)"
cp "$VERSION_FILE" "$VERSION_BACKUP"
perl -0pi -e "s/versionCode = \\d+/versionCode = $next_code/" "$VERSION_FILE"
perl -0pi -e "s/versionName = \"[^\"]+\"/versionName = \"$next_name\"/" "$VERSION_FILE"
VERSION_FILE_CHANGED=1
read -r written_code written_name < <(read_version)
[[ "$written_code" == "$next_code" && "$written_name" == "$next_name" ]] || {
echo "Nie udało się jednoznacznie zapisać nowej wersji." >&2
exit 1
}
fi
echo "Buduję TPP Kierowca $next_name ($next_code)..."
gradle_tasks=(assembleRelease bundleRelease)
if ((SKIP_TESTS == 0)); then
gradle_tasks=(testDebugUnitTest "${gradle_tasks[@]}")
fi
./gradlew "${gradle_tasks[@]}"
apk_source="$(find app/build/outputs/apk/release -maxdepth 1 -type f -name '*.apk' -print -quit)"
aab_source="$(find app/build/outputs/bundle/release -maxdepth 1 -type f -name '*.aab' -print -quit)"
[[ -n "$apk_source" && -f "$apk_source" ]] || { echo "Nie znaleziono release APK." >&2; exit 1; }
[[ -n "$aab_source" && -f "$aab_source" ]] || { echo "Nie znaleziono release AAB." >&2; exit 1; }
sdk_dir="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}"
if [[ -z "$sdk_dir" && -f local.properties ]]; then
sdk_dir="$(sed -n 's/^sdk.dir=//p' local.properties | sed -n '1p')"
fi
apksigner="$(find "$sdk_dir/build-tools" -type f -name apksigner 2>/dev/null | sort -V | tail -n 1)"
aapt="$(find "$sdk_dir/build-tools" -type f -name aapt 2>/dev/null | sort -V | tail -n 1)"
[[ -x "$apksigner" && -x "$aapt" ]] || { echo "Nie znaleziono apksigner/aapt w Android SDK." >&2; exit 1; }
"$apksigner" verify --verbose "$apk_source"
apk_badging="$("$aapt" dump badging "$apk_source" | sed -n '1p')"
[[ "$apk_badging" == *"versionCode='$next_code'"* && "$apk_badging" == *"versionName='$next_name'"* ]] || {
echo "APK ma inny numer wersji niż oczekiwany $next_name ($next_code)." >&2
exit 1
}
jarsigner -verify "$aab_source" >/dev/null
rm -rf "$artifact_dir"
mkdir -p "$artifact_dir/gitea" "$artifact_dir/google-play"
cp "$apk_source" "$artifact_dir/gitea/$gitea_apk_name"
cp "$aab_source" "$artifact_dir/google-play/$play_aab_name"
(
cd "$artifact_dir"
sha256sum "gitea/$gitea_apk_name" "google-play/$play_aab_name" > SHA256SUMS.txt
)
if ((REUSE_CURRENT == 0)); then
git add "$VERSION_FILE"
git diff --cached --check
git commit -m "chore: release android driver $next_name ($next_code)"
VERSION_COMMITTED=1
fi
git push "$REMOTE_NAME" "$branch"
if ! git show-ref --verify --quiet "refs/tags/$tag_name"; then
git tag -a "$tag_name" -m "TPP Kierowca $next_name ($next_code)"
fi
tag_commit="$(git rev-list -n 1 "$tag_name")"
head_commit="$(git rev-parse HEAD)"
[[ "$tag_commit" == "$head_commit" ]] || {
echo "Tag $tag_name nie wskazuje aktualnego commita ($head_commit)." >&2
exit 1
}
git push "$REMOTE_NAME" "$tag_name"
if [[ -n "$NOTES_FILE" ]]; then
[[ -f "$NOTES_FILE" ]] || { echo "Nie istnieje plik release notes: $NOTES_FILE" >&2; exit 1; }
release_notes="$(<"$NOTES_FILE")"
else
previous_tag="$(git tag --sort=-version:refname | grep -Fxv "$tag_name" | sed -n '1p' || true)"
if [[ -n "$previous_tag" ]]; then
changes="$(git log --format='- %s (%h)' "$previous_tag..HEAD")"
else
changes="$(git log -20 --format='- %s (%h)')"
fi
release_notes="TPP Kierowca $next_name ($next_code)
Zmiany:
${changes:-'- Wydanie techniczne.'}
Artefakt Google Play Console (AAB) znajduje się lokalnie w:
release-artifacts/$tag_name/google-play/$play_aab_name"
fi
release_response="$(mktemp)"
release_status="$(curl -sS "${auth_args[@]}" -o "$release_response" -w '%{http_code}' "$api_base/releases/tags/$tag_name")"
if [[ "$release_status" == "200" ]]; then
release_id="$(jq -r '.id' "$release_response")"
elif [[ "$release_status" == "404" ]]; then
release_payload="$(jq -n \
--arg tag "$tag_name" \
--arg target "$branch" \
--arg name "TPP Kierowca $next_name ($next_code)" \
--arg body "$release_notes" \
'{tag_name:$tag,target_commitish:$target,name:$name,body:$body,draft:false,prerelease:false}')"
release_status="$(curl -sS "${auth_args[@]}" \
-H 'Content-Type: application/json' \
-o "$release_response" \
-w '%{http_code}' \
-X POST \
-d "$release_payload" \
"$api_base/releases")"
[[ "$release_status" == "201" ]] || {
echo "Nie udało się utworzyć Gitea Release (HTTP $release_status)." >&2
jq '{message,errors}' "$release_response" >&2 || true
exit 1
}
release_id="$(jq -r '.id' "$release_response")"
else
echo "Nie udało się sprawdzić Gitea Release (HTTP $release_status)." >&2
exit 1
fi
upload_asset() {
local file_path="$1"
local asset_name="$2"
local mime_type="$3"
local assets_response existing_asset_id upload_response upload_status
assets_response="$(mktemp)"
curl -fsS "${auth_args[@]}" -o "$assets_response" "$api_base/releases/$release_id/assets"
existing_asset_id="$(jq -r --arg name "$asset_name" '.[] | select(.name == $name) | .id' "$assets_response" | sed -n '1p')"
if [[ -n "$existing_asset_id" ]]; then
curl -fsS "${auth_args[@]}" -X DELETE "$api_base/releases/$release_id/assets/$existing_asset_id" >/dev/null
fi
upload_response="$(mktemp)"
upload_status="$(curl -sS "${auth_args[@]}" \
-o "$upload_response" \
-w '%{http_code}' \
-X POST \
-F "attachment=@$file_path;type=$mime_type" \
"$api_base/releases/$release_id/assets?name=$asset_name")"
[[ "$upload_status" == "201" ]] || {
echo "Nie udało się wysłać $asset_name (HTTP $upload_status)." >&2
jq '{message,errors}' "$upload_response" >&2 || true
return 1
}
}
upload_asset "$artifact_dir/gitea/$gitea_apk_name" "$gitea_apk_name" "application/vnd.android.package-archive"
upload_asset "$artifact_dir/SHA256SUMS.txt" "SHA256SUMS.txt" "text/plain"
assets_response="$(mktemp)"
curl -fsS "${auth_args[@]}" -o "$assets_response" "$api_base/releases/$release_id/assets"
published_apk_url="$(jq -r --arg name "$gitea_apk_name" '.[] | select(.name == $name) | .browser_download_url' "$assets_response" | sed -n '1p')"
[[ -n "$published_apk_url" && "$published_apk_url" != "null" ]] || {
echo "Nie znaleziono opublikowanego APK w Gitea Release." >&2
exit 1
}
downloaded_apk="$(mktemp)"
curl -fsSL "${auth_args[@]}" -o "$downloaded_apk" "$published_apk_url"
local_apk_hash="$(sha256sum "$artifact_dir/gitea/$gitea_apk_name" | awk '{print $1}')"
published_apk_hash="$(sha256sum "$downloaded_apk" | awk '{print $1}')"
[[ "$local_apk_hash" == "$published_apk_hash" ]] || {
echo "Checksum opublikowanego APK nie zgadza się z lokalnym plikiem." >&2
exit 1
}
release_url="$gitea_base_url/$gitea_repository/releases/tag/$tag_name"
RELEASE_SUCCEEDED=1
trap - EXIT INT TERM
[[ -n "$VERSION_BACKUP" ]] && rm -f "$VERSION_BACKUP"
cat <<EOF
Release zakończony:
Wersja: $next_name ($next_code)
Tag: $tag_name
Gitea: $release_url
APK: $artifact_dir/gitea/$gitea_apk_name
Google Play: $artifact_dir/google-play/$play_aab_name
Checksumy: $artifact_dir/SHA256SUMS.txt
EOF