Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,45 @@
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTask"
android:theme="@style/Theme.ParcelTracker.Starting">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

<!-- Share target: lets users share a tracking URL (e.g. from a browser
or email app) directly into the Add Parcel form. -->
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>

<!-- App Links for known courier tracking domains. Deliberately NOT
autoVerify="true": we don't own these third-party domains and
can't host assetlinks.json on them, so Digital Asset Links
verification would just fail. A plain VIEW + BROWSABLE + DEFAULT
filter is what lets users manually opt in via
Settings > Apps > Deliveries > Open by default > Add link. -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="my.dhlparcel.nl" />
<data android:scheme="https" android:host="www.ups.com" />
<data android:scheme="https" android:host="gls-group.eu" />
<data android:scheme="https" android:host="gls-group.com" />
<data android:scheme="https" android:host="www.gls-info.nl" />
<data android:scheme="https" android:host="inpost.pl" />
<data android:scheme="https" android:host="www.inpost.pl" />
<data android:scheme="https" android:host="jouw.postnl.nl" />
<data android:scheme="https" android:host="emonitoring.poczta-polska.pl" />
</intent-filter>
</activity>

<activity android:name=".LogcatDumperActivity"
android:theme="@style/Theme.ParcelTracker">
</activity>
</application>
</manifest>
</manifest>
112 changes: 87 additions & 25 deletions app/src/main/java/dev/itsvic/parceltracker/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableIntState
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
Expand All @@ -50,8 +51,11 @@ import dev.itsvic.parceltracker.api.APIKeyMissingException
import dev.itsvic.parceltracker.api.Parcel as APIParcel
import dev.itsvic.parceltracker.api.ParcelHistoryItem
import dev.itsvic.parceltracker.api.ParcelNonExistentException
import dev.itsvic.parceltracker.api.Service
import dev.itsvic.parceltracker.api.Status
import dev.itsvic.parceltracker.api.getParcel
import dev.itsvic.parceltracker.api.parseSharedText
import dev.itsvic.parceltracker.api.parseTrackingUrl
import dev.itsvic.parceltracker.db.Parcel
import dev.itsvic.parceltracker.db.ParcelStatus
import dev.itsvic.parceltracker.db.ParcelWithStatus
Expand All @@ -78,25 +82,55 @@ class MainActivity : ComponentActivity() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) handleNotificationPermissionStuff()

parcelToOpen = mutableIntStateOf(intent.getIntExtra("openParcel", -1))
addParcelIntent = mutableStateOf(resolveAddParcelIntent(intent))

setContent {
val parcelToOpen by parcelToOpen
val addParcelIntent by addParcelIntent

ParcelTrackerTheme {
Box(modifier = Modifier.background(color = MaterialTheme.colorScheme.background)) {
ParcelAppNavigation(parcelToOpen)
ParcelAppNavigation(parcelToOpen, addParcelIntent)
}
}
}
}

companion object {
lateinit var parcelToOpen: MutableIntState
lateinit var addParcelIntent: MutableState<AddParcelPage?>

// Resolves a share (ACTION_SEND) or deep link (ACTION_VIEW) intent into
// an AddParcelPage prefill, if any. Returns null for intents that aren't
// asking to add a parcel at all (e.g. the initial MAIN/LAUNCHER intent).
private fun resolveAddParcelIntent(intent: Intent): AddParcelPage? {
return when (intent.action) {
Intent.ACTION_SEND -> {
if (intent.type != "text/plain") null
else {
val text = intent.getStringExtra(Intent.EXTRA_TEXT)
val match = text?.let { parseSharedText(it) }
AddParcelPage(match?.service, match?.trackingId, match?.postalCode)
}
}
Intent.ACTION_VIEW -> {
val data = intent.data
if (data == null) null
else {
val match = parseTrackingUrl(data.toString())
AddParcelPage(match?.service, match?.trackingId, match?.postalCode)
}
}
else -> null
}
}
}

override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
parcelToOpen.intValue = intent.getIntExtra("openParcel", -1)
resolveAddParcelIntent(intent)?.let { addParcelIntent.value = it }
}

@RequiresApi(Build.VERSION_CODES.TIRAMISU)
Expand Down Expand Up @@ -133,12 +167,17 @@ class MainActivity : ComponentActivity() {

@Serializable data class ParcelPage(val parcelDbId: Int)

@Serializable object AddParcelPage
@Serializable
data class AddParcelPage(
val prefillService: Service? = null,
val prefillTrackingId: String? = null,
val prefillPostalCode: String? = null,
)

@Serializable data class EditParcelPage(val parcelDbId: Int)

@Composable
fun ParcelAppNavigation(parcelToOpen: Int) {
fun ParcelAppNavigation(parcelToOpen: Int, addParcelIntent: AddParcelPage?) {
val db = ParcelApplication.db
val navController = rememberNavController()
val scope = rememberCoroutineScope()
Expand All @@ -153,6 +192,13 @@ fun ParcelAppNavigation(parcelToOpen: Int) {
}
}

LaunchedEffect(addParcelIntent) {
if (addParcelIntent != null) {
navController.navigate(route = addParcelIntent) { popUpTo(HomePage) }
MainActivity.addParcelIntent.value = null
}
}

val animDuration = 300

NavHost(
Expand All @@ -162,15 +208,17 @@ fun ParcelAppNavigation(parcelToOpen: Int) {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Start,
animationSpec = tween(animDuration),
initialOffset = { it / 4 }) + fadeIn(tween(animDuration))
initialOffset = { it / 4 },
) + fadeIn(tween(animDuration))
},
exitTransition = { fadeOut(tween(animDuration)) + scaleOut(tween(500), 0.9f) },
popEnterTransition = { fadeIn(tween(animDuration)) + scaleIn(tween(500), 0.9f) },
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Start,
animationSpec = tween(animDuration),
targetOffset = { -it / 4 }) + fadeOut(tween(animDuration))
targetOffset = { -it / 4 },
) + fadeOut(tween(animDuration))
},
) {
composable<HomePage> {
Expand All @@ -180,7 +228,7 @@ fun ParcelAppNavigation(parcelToOpen: Int) {

HomeView(
parcels = parcels,
onNavigateToAddParcel = { navController.navigate(route = AddParcelPage) },
onNavigateToAddParcel = { navController.navigate(route = AddParcelPage()) },
onNavigateToParcel = { navController.navigate(route = ParcelPage(it.id)) },
onNavigateToSettings = { navController.navigate(route = SettingsPage) },
)
Expand Down Expand Up @@ -210,24 +258,24 @@ fun ParcelAppNavigation(parcelToOpen: Int) {
return APIParcel(
dbParcel.parcelId,
listOf(ParcelHistoryItem(description, LocalDateTime.now(), "")),
status)
status,
)
}

launch(Dispatchers.IO) {
try {
apiParcel =
context.getParcel(dbParcel.parcelId, dbParcel.postalCode, dbParcel.service)
context.getParcel(
dbParcel.parcelId,
dbParcel.postalCode,
dbParcel.service,
)

if (!demoMode) {
// update parcel status
val zone = ZoneId.systemDefault()
val lastChange = apiParcel!!.history.first().time.atZone(zone).toInstant()
val status =
ParcelStatus(
dbParcel.id,
apiParcel!!.currentStatus,
lastChange,
)
val status = ParcelStatus(dbParcel.id, apiParcel!!.currentStatus, lastChange)
if (parcelWithStatus.status == null) {
db.parcelStatusDao().insert(status)
} else {
Expand All @@ -244,14 +292,21 @@ fun ParcelAppNavigation(parcelToOpen: Int) {
} catch (e: JsonDataException) {
Log.w(
"MainActivity",
"Unexpected JSON response that could not be converted: ${e.message}")
"Unexpected JSON response that could not be converted: ${e.message}",
)
apiParcel =
apiParcelError(jsonConversionError.format(e.message), Status.NetworkFailure)
apiParcelError(
jsonConversionError.format(e.message),
Status.NetworkFailure,
)
} catch (e: Exception) {
// catchall to avoid crashes
Log.e("MainActivity", "Unexpected error", e)
apiParcel =
apiParcelError(unexpectedErrorDetail.format(e.message), Status.NetworkFailure)
apiParcelError(
unexpectedErrorDetail.format(e.message),
Status.NetworkFailure,
)
}
}
}
Expand All @@ -265,16 +320,18 @@ fun ParcelAppNavigation(parcelToOpen: Int) {
history =
dbHistory.map { item ->
ParcelHistoryItem(item.description, item.time, item.location)
})
},
)
}

if (apiParcel == null && dbParcel?.isArchived == false || dbParcel == null)
Box(
modifier =
Modifier.background(color = MaterialTheme.colorScheme.background).fillMaxSize(),
contentAlignment = Alignment.Center) {
CircularProgressIndicator()
}
contentAlignment = Alignment.Center,
) {
CircularProgressIndicator()
}
else
ParcelView(
if (dbParcel.isArchived) fakeApiParcel!! else apiParcel!!,
Expand Down Expand Up @@ -327,9 +384,13 @@ fun ParcelAppNavigation(parcelToOpen: Int) {
)
}

composable<AddParcelPage> {
composable<AddParcelPage> { backStackEntry ->
val route: AddParcelPage = backStackEntry.toRoute()
AddEditParcelView(
null,
prefillService = route.prefillService ?: Service.UNDEFINED,
prefillTrackingId = route.prefillTrackingId ?: "",
prefillPostalCode = route.prefillPostalCode ?: "",
onBackPressed = { navController.popBackStack() },
onCompleted = {
if (demoMode) {
Expand Down Expand Up @@ -357,9 +418,10 @@ fun ParcelAppNavigation(parcelToOpen: Int) {
return@composable Box(
modifier =
Modifier.background(color = MaterialTheme.colorScheme.background).fillMaxSize(),
contentAlignment = Alignment.Center) {
CircularProgressIndicator()
}
contentAlignment = Alignment.Center,
) {
CircularProgressIndicator()
}

AddEditParcelView(
parcel,
Expand Down
14 changes: 14 additions & 0 deletions app/src/main/java/dev/itsvic/parceltracker/api/Core.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ import dev.itsvic.parceltracker.R
import java.time.Instant
import java.time.LocalDateTime
import java.util.TimeZone
import kotlinx.serialization.Serializable
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.converter.moshi.MoshiConverterFactory

@Serializable
enum class Service {
UNDEFINED,
EXAMPLE,
Expand Down Expand Up @@ -203,8 +205,20 @@ interface DeliveryService {
fun acceptsFormat(trackingId: String): Boolean {
return false
}

// List of patterns that match this provider's public tracking-page URLs.
// See TrackingUrlPattern for matching semantics.
val trackingUrlPatterns: List<TrackingUrlPattern>
get() = emptyList()
}

// A pattern matching a provider's public tracking-page URLs. urlRegex's first
// capture group must be the tracking ID; postalCodeRegex, if given, has its own
// first capture group as the postal code. Both are matched independently with
// Regex.find() (not matchEntire) against the full URL string, so patterns don't
// need to anchor the whole string or assume query-param ordering.
data class TrackingUrlPattern(val urlRegex: Regex, val postalCodeRegex: Regex? = null)

class ParcelNonExistentException : Exception("Parcel does not exist in delivery service API")

class APIKeyMissingException :
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ object DhlDeliveryService : DeliveryService {
override val requiresApiKey: Boolean = true
override val apiKeyPreference: Preferences.Key<String>? = DHL_API_KEY

// Confirmed: verified against real link
// The main dhl.com tracker's own URL format is unconfirmed, so it's not included here.
override val trackingUrlPatterns: List<TrackingUrlPattern> =
listOf(
TrackingUrlPattern(
"""https?://my\.dhlparcel\.nl/go-track-trace\?\S*pid=([A-Za-z0-9]+)"""
.toRegex(RegexOption.IGNORE_CASE)))

override fun acceptsFormat(trackingId: String): Boolean {
val dhlParcelFormat = """^(?:JJD|JVGL|3S|JV|JD)\d*$""".toRegex()
return digits11Format.accepts(trackingId) ||
Expand All @@ -35,7 +43,7 @@ object DhlDeliveryService : DeliveryService {
override suspend fun getParcel(
context: Context,
trackingId: String,
postalCode: String?
postalCode: String?,
): Parcel {
val key = context.dataStore.data.first()[apiKeyPreference!!]
if (key.isNullOrEmpty()) {
Expand Down Expand Up @@ -85,7 +93,8 @@ object DhlDeliveryService : DeliveryService {
if (it.location == null) "Unknown location"
else if (it.location.address.postalCode != null)
"${it.location.address.postalCode} ${it.location.address.addressLocality}"
else it.location.address.addressLocality)
else it.location.address.addressLocality,
)
}

return Parcel(shipment.id, history, status)
Expand All @@ -104,14 +113,12 @@ object DhlDeliveryService : DeliveryService {
@GET("track/shipments")
suspend fun getShipments(
@Header("DHL-API-Key") apiKey: String,
@Query("trackingNumber") id: String
@Query("trackingNumber") id: String,
): ShipmentsResponse
}

@JsonClass(generateAdapter = true)
internal data class ShipmentsResponse(
val shipments: List<Shipment>,
)
internal data class ShipmentsResponse(val shipments: List<Shipment>)

@JsonClass(generateAdapter = true)
internal data class Shipment(
Expand All @@ -130,14 +137,8 @@ object DhlDeliveryService : DeliveryService {
val timestamp: String,
)

@JsonClass(generateAdapter = true)
internal data class EventLocation(
val address: Address,
)
@JsonClass(generateAdapter = true) internal data class EventLocation(val address: Address)

@JsonClass(generateAdapter = true)
internal data class Address(
val addressLocality: String,
val postalCode: String?,
)
internal data class Address(val addressLocality: String, val postalCode: String?)
}
Loading
Loading