diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 03efc1a15..6dbfeaf9b 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -4,6 +4,7 @@ import com.github.spotbugs.snom.SpotBugsTask plugins { id("com.android.application") id("com.github.spotbugs") + id("org.jetbrains.kotlin.android") } spotbugs { @@ -62,8 +63,8 @@ android { // Flag to enable support for the new language APIs isCoreLibraryDesugaringEnabled = true - sourceCompatibility = JavaVersion.VERSION_11 - targetCompatibility = JavaVersion.VERSION_11 + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 } sourceSets { @@ -84,6 +85,9 @@ android { lint { lintConfig = file("lint.xml") } + kotlinOptions { + jvmTarget = "17" + } } dependencies { @@ -91,18 +95,17 @@ dependencies { // AndroidX implementation("androidx.appcompat:appcompat:1.7.0") implementation("androidx.constraintlayout:constraintlayout:2.1.4") + implementation("androidx.core:core-ktx:1.13.1") + implementation("androidx.core:core-splashscreen:1.0.1") implementation("androidx.exifinterface:exifinterface:1.3.7") implementation("androidx.palette:palette:1.0.0") implementation("androidx.preference:preference:1.2.1") implementation("com.google.android.material:material:1.12.0") - implementation("com.github.yalantis:ucrop:2.2.9") coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.2") - // Splash Screen - implementation("androidx.core:core-splashscreen:1.0.1") - // Third-party implementation("com.journeyapps:zxing-android-embedded:4.3.0@aar") + implementation("com.github.yalantis:ucrop:2.2.9") implementation("com.google.zxing:core:3.5.3") implementation("org.apache.commons:commons-csv:1.9.0") implementation("com.jaredrummler:colorpicker:1.1.0") diff --git a/app/src/main/java/protect/card_locker/LoyaltyCard.java b/app/src/main/java/protect/card_locker/LoyaltyCard.java index d4e3bf531..2b77ea498 100644 --- a/app/src/main/java/protect/card_locker/LoyaltyCard.java +++ b/app/src/main/java/protect/card_locker/LoyaltyCard.java @@ -11,8 +11,6 @@ import java.math.BigDecimal; import java.util.Currency; import java.util.Date; -import java.util.HashMap; -import java.util.Map; import java.util.Objects; public class LoyaltyCard implements Parcelable { diff --git a/app/src/main/java/protect/card_locker/PkpassParser.kt b/app/src/main/java/protect/card_locker/PkpassParser.kt new file mode 100644 index 000000000..92d9a5559 --- /dev/null +++ b/app/src/main/java/protect/card_locker/PkpassParser.kt @@ -0,0 +1,393 @@ +package protect.card_locker + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Color +import android.net.Uri +import android.util.ArrayMap +import android.util.Log +import com.google.zxing.BarcodeFormat +import net.lingala.zip4j.io.inputstream.ZipInputStream +import net.lingala.zip4j.model.LocalFileHeader +import org.json.JSONException +import org.json.JSONObject +import java.io.FileNotFoundException +import java.io.IOException +import java.math.BigDecimal +import java.text.DateFormat +import java.text.ParseException +import java.time.ZonedDateTime +import java.time.format.DateTimeParseException +import java.util.Currency +import java.util.Date + +class PkpassParser(context: Context, uri: Uri?) { + private var mContext = context + + private var translations: ArrayMap> = ArrayMap() + + private var passContent: JSONObject? = null + + private var store: String? = null + private var note: String? = null + private var validFrom: Date? = null + private var expiry: Date? = null + private val balance: BigDecimal = BigDecimal(0) + private val balanceType: Currency? = null + private var cardId: String? = null + private var barcodeId: String? = null + private var barcodeType: CatimaBarcode? = null + private var headerColor: Int? = null + private val starStatus = 0 + private val lastUsed: Long = 0 + private val zoomLevel = DBHelper.DEFAULT_ZOOM_LEVEL + private var archiveStatus = 0 + + var image: Bitmap? = null + private set + private var logoSize = 0 + + init { + if (passContent != null) { + throw IllegalStateException("Pkpass instance already initialized!") + } + + mContext = context + + Log.i(TAG, "Received Pkpass file") + if (uri == null) { + Log.e(TAG, "Uri did not contain any data") + throw IOException(context.getString(R.string.errorReadingFile)) + } + + try { + mContext.contentResolver.openInputStream(uri).use { inputStream -> + ZipInputStream(inputStream).use { zipInputStream -> + var localFileHeader: LocalFileHeader + while ((zipInputStream.nextEntry.also { localFileHeader = it }) != null) { + // Ignore directories + if (localFileHeader.isDirectory) continue + + // We assume there are three options, as per spec: + // language.lproj/pass.strings + // file.extension + // More directories are ignored + val filenameParts = localFileHeader.fileName.split('/') + if (filenameParts.size > 2) { + continue + } else if (filenameParts.size == 2) { + // Doesn't seem like a language directory, ignore + if (!filenameParts[0].endsWith(".lproj")) continue + + val locale = filenameParts[0].removeSuffix(".lproj") + + translations[locale] = parseLanguageStrings(ZipUtils.read(zipInputStream)) + } + + // Not a language, parse as normal files + when (localFileHeader.fileName) { + "logo.png" -> loadImageIfBiggerSize(1, zipInputStream) + "logo@2x.png" -> loadImageIfBiggerSize(2, zipInputStream) + "logo@3x.png" -> loadImageIfBiggerSize(3, zipInputStream) + "pass.json" -> passContent = ZipUtils.readJSON(zipInputStream) // Parse this last, so we're sure we have all language info + } + } + + checkNotNull(passContent) { "File lacks pass.json" } + } + } + } catch (e: FileNotFoundException) { + throw IOException(mContext.getString(R.string.errorReadingFile)) + } catch (e: Exception) { + throw e + } + } + + fun listLocales(): List { + return translations.keys.toList() + } + + fun toLoyaltyCard(locale: String?): LoyaltyCard { + parsePassJSON(checkNotNull(passContent) { "Pkpass instance not yet initialized!" }, locale) + + return LoyaltyCard( + -1, + store, + note, + validFrom, + expiry, + balance, + balanceType, + cardId, + barcodeId, + barcodeType, + headerColor, + starStatus, + lastUsed, + zoomLevel, + archiveStatus + ) + } + + private fun getTranslation(string: String, locale: String?): String { + if (locale == null) { + return string + } + + val localeStrings = translations[locale] + + return localeStrings?.get(string) ?: string + } + + private fun loadImageIfBiggerSize(fileLogoSize: Int, zipInputStream: ZipInputStream) { + if (logoSize < fileLogoSize) { + image = ZipUtils.readImage(zipInputStream) + logoSize = fileLogoSize + } + } + + private fun parseDateTime(dateTime: String): Date { + return Date.from(ZonedDateTime.parse(dateTime).toInstant()) + } + + private fun parseLanguageStrings(data: String): Map { + val output = ArrayMap() + + // Translations look like this: + // "key_name" = "Translated value"; + // + // However, "Translated value" may be multiple lines and may contain " (however, it'll be escaped) + var translationLine = StringBuilder() + + for (line in data.lines()) { + translationLine.append(line) + + // Make sure we don't have a false ending (this is the escaped double quote: \";) + if (!line.endsWith("\\\";") and line.endsWith("\";")) { + // We reached a translation ending, time to parse it + + // 1. Split into key and value + // 2. Remove cruft of each + // 3. Clean up escape sequences + val keyValue = translationLine.toString().split("=", ignoreCase = false, limit = 2) + val key = keyValue[0].trim().removePrefix("\"").removeSuffix("\"") + val value = keyValue[1].trim().removePrefix("\"").removeSuffix("\";").replace("\\", "") + + output[key] = value + + translationLine = StringBuilder() + } else { + translationLine.append("\n") + } + } + + return output + } + + private fun parsePassJSON(jsonObject: JSONObject, locale: String?) { + if (jsonObject.getInt("formatVersion") != 1) { + throw IllegalArgumentException(mContext.getString(R.string.unsupportedFile)) + } + + // Prefer logoText for store, it's generally shorter + try { + store = jsonObject.getString("logoText") + } catch (ignored: JSONException) {} + + if (store.isNullOrEmpty()) { + store = jsonObject.getString("organizationName") + } + + val noteText = StringBuilder() + noteText.append(getTranslation(jsonObject.getString("description"), locale)) + + try { + validFrom = parseDateTime(jsonObject.getString("relevantDate")) + } catch (ignored: JSONException) {} + + try { + expiry = parseDateTime(jsonObject.getString("expirationDate")) + } catch (ignored: JSONException) {} + + try { + headerColor = Color.parseColor(jsonObject.getString("backgroundColor")) + } catch (ignored: JSONException) { + } catch (ignored: ParseException) {} + + var pkPassHasBarcodes = false + var validBarcodeFound = false + + // Create a list of possible barcodes + val barcodes = ArrayList() + + // Append the non-deprecated entries + try { + val foundInBarcodesField = jsonObject.getJSONArray("barcodes") + + for (i in 0 until foundInBarcodesField.length()) { + barcodes.add(foundInBarcodesField.getJSONObject(i)) + } + } catch (ignored: JSONException) {} + + // Append the deprecated entry if it exists + try { + barcodes.add(jsonObject.getJSONObject("barcode")) + } catch (ignored: JSONException) {} + + for (barcode in barcodes) { + pkPassHasBarcodes = true + + try { + parsePassJSONBarcodeField(barcode) + + validBarcodeFound = true + break + } catch (ignored: IllegalArgumentException) {} + } + + if (pkPassHasBarcodes && !validBarcodeFound) { + throw FormatException(mContext.getString(R.string.errorReadingFile)) + } + + // An used card being "archived" probably is the most sensible way to map "voided" + archiveStatus = try { + if (jsonObject.getBoolean("voided")) 1 else 0 + } catch (ignored: JSONException) { + 0 + } + + // Append type-specific info to the pass + noteText.append("\n\n") + + // Find the relevant pass type and parse it + var hasPassData = false + for (passType in listOf("boardingPass", "coupon", "eventTicket", "generic")) { + try { + noteText.append( + parsePassJSONPassFields( + jsonObject.getJSONObject(passType), + locale + ) + ) + + hasPassData = true + + break + } catch (ignored: JSONException) {} + } + + // Failed to parse anything, error out + if (!hasPassData) { + throw FormatException(mContext.getString(R.string.errorReadingFile)) + } + + note = noteText.toString() + } + + /* Return success or failure */ + private fun parsePassJSONBarcodeField(barcodeInfo: JSONObject) { + val format = barcodeInfo.getString("format") + + // We only need to check these 4 formats as no other options are valid in the PkPass spec + barcodeType = when(format) { + "PKBarcodeFormatQR" -> CatimaBarcode.fromBarcode(BarcodeFormat.QR_CODE) + "PKBarcodeFormatPDF417" -> CatimaBarcode.fromBarcode(BarcodeFormat.PDF_417) + "PKBarcodeFormatAztec" -> CatimaBarcode.fromBarcode(BarcodeFormat.AZTEC) + "PKBarcodeFormatCode128" -> CatimaBarcode.fromBarcode(BarcodeFormat.CODE_128) + else -> throw IllegalArgumentException("No valid barcode type") + } + + // FIXME: We probably need to do something with the messageEncoding field + try { + cardId = barcodeInfo.getString("altText") + barcodeId = barcodeInfo.getString("message") + } catch (ignored: JSONException) { + cardId = barcodeInfo.getString("message") + barcodeId = null + } + } + + private fun parsePassJSONPassFields(fieldsParent: JSONObject, locale: String?): String { + // These fields contain a lot of info on where we're supposed to display them, but Catima doesn't really have anything for that + // So for now, throw them all into the description field in a logical order + val noteContents: MutableList = ArrayList() + + // Collect all the groups of fields that exist + for (fieldType in listOf("headerFields", "primaryFields", "secondaryFields", "auxiliaryFields", "backFields")) { + val content = StringBuilder() + + try { + val fieldArray = fieldsParent.getJSONArray(fieldType) + for (i in 0 until fieldArray.length()) { + val entry = fieldArray.getJSONObject(i) + + content.append(parsePassJSONPassField(entry, locale)) + + // If this is not the last part, add spacing on the end + if (i < (fieldArray.length() - 1)) { + content.append("\n") + } + } + } catch (ignore: JSONException) { + } catch (ignore: ParseException) { + } + + if (content.isNotEmpty()) { + noteContents.add(content.toString()) + } + } + + // Merge all field groups together, one paragraph for field group + val output = StringBuilder() + + for (i in 0 until noteContents.size) { + output.append(noteContents[i]) + + // If this is not the last part, add newlines to separate + if (i < (noteContents.size - 1)) { + output.append("\n\n") + } + } + + return output.toString() + } + + private fun parsePassJSONPassField(field: JSONObject, locale: String?): String { + // Value may be a localizable string, a date or a number. So let's try to parse it as a date first + + var value = getTranslation(field.getString("value"), locale) + try { + value = DateFormat.getDateTimeInstance().format(parseDateTime(value)) + } catch (ignored: DateTimeParseException) { + // It's fine if it's not a date + } + + // FIXME: Use the Android thing for formatted strings here + if (field.has("currencyCode")) { + val valueCurrency = Currency.getInstance(field.getString("currencyCode")) + + value = Utils.formatBalance( + mContext, + Utils.parseBalance(value, valueCurrency), + valueCurrency + ) + } else if (field.has("numberStyle")) { + if (field.getString("numberStyle") == "PKNumberStylePercent") { + // FIXME: Android formatting string + value = "${value}%" + } + } + + val label = getTranslation(field.getString("label"), locale) + + if (label.isNotEmpty()) { + return "$label: $value" + } + + return value + } + + companion object { + private const val TAG = "Catima" + } +} diff --git a/app/src/main/java/protect/card_locker/Utils.java b/app/src/main/java/protect/card_locker/Utils.java index 116f60add..135936b28 100644 --- a/app/src/main/java/protect/card_locker/Utils.java +++ b/app/src/main/java/protect/card_locker/Utils.java @@ -869,7 +869,7 @@ public static int resolveBackgroundColor(AppCompatActivity activity) { return typedValue.data; } - public static int getHeaderColorFromImage(Bitmap image, int fallback) { + public static int getHeaderColorFromImage(@Nullable Bitmap image, int fallback) { if (image == null) { return fallback; } diff --git a/app/src/main/java/protect/card_locker/ZipUtils.java b/app/src/main/java/protect/card_locker/ZipUtils.java index c0c30bd1d..158223dd9 100644 --- a/app/src/main/java/protect/card_locker/ZipUtils.java +++ b/app/src/main/java/protect/card_locker/ZipUtils.java @@ -23,7 +23,7 @@ public static JSONObject readJSON(ZipInputStream zipInputStream) throws IOExcept return new JSONObject(read(zipInputStream)); } - private static String read(ZipInputStream zipInputStream) throws IOException { + public static String read(ZipInputStream zipInputStream) throws IOException { StringBuilder stringBuilder = new StringBuilder(); Reader reader = new BufferedReader(new InputStreamReader(zipInputStream, StandardCharsets.UTF_8)); int c; diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 6d6be18a5..40fe12c91 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -343,4 +343,6 @@ Export cancelled Use front image Use back image + Select a Passbook file (.pkpass) + This file is not supported diff --git a/app/src/test/java/protect/card_locker/PkpassTest.kt b/app/src/test/java/protect/card_locker/PkpassTest.kt new file mode 100644 index 000000000..bcadd84c4 --- /dev/null +++ b/app/src/test/java/protect/card_locker/PkpassTest.kt @@ -0,0 +1,238 @@ +package protect.card_locker + +import android.content.Context +import android.graphics.BitmapFactory +import android.graphics.Color +import android.net.Uri +import androidx.test.core.app.ApplicationProvider +import com.google.zxing.BarcodeFormat +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.shadows.ShadowContentResolver +import org.robolectric.shadows.ShadowLog +import java.math.BigDecimal +import java.util.Date + +@RunWith(RobolectricTestRunner::class) +class PkpassTest { + @Before + fun setUp() { + ShadowLog.stream = System.out + } + + @Test + fun testEurowingsPass() { + // Prepare + val context: Context = ApplicationProvider.getApplicationContext() + val pkpass = "pkpass/Eurowings/Eurowings.pkpass" + val image = "pkpass/Eurowings/logo@2x.png" + + val pkpassUri = Uri.parse(pkpass) + val imageUri = Uri.parse(image) + ShadowContentResolver().registerInputStream(pkpassUri, javaClass.getResourceAsStream(pkpass)) + ShadowContentResolver().registerInputStream(imageUri, javaClass.getResourceAsStream(image)) + + val parser = PkpassParser(context, pkpassUri) + val imageBitmap = BitmapFactory.decodeStream(context.contentResolver.openInputStream(imageUri)) + + // Confirm this does not have languages + Assert.assertEquals(listOf("de", "en"), parser.listLocales()) + + // Confirm correct parsing (en) + var parsedCard = parser.toLoyaltyCard("de") + + Assert.assertEquals(-1, parsedCard.id) + Assert.assertEquals("EUROWINGS", parsedCard.store) + Assert.assertEquals("Eurowings Boarding Pass\n" + + "\n" + + "Gate: B61\n" + + "Sitz: 12D\n" + + "\n" + + "Cologne-Bonn: CGN\n" + + "Dubrovnik: DBV\n" + + "\n" + + "Name: John Doe\n" + + "Status: -\n" + + "Gruppe: GROUP 1\n" + + "Tarif: SMART\n" + + "\n" + + "Flug: EW 954\n" + + "Datum: 08/09/2019\n" + + "Boarding: 05:00\n" + + "Gate Schließt: 05:15\n" + + "\n" + + "Eurowings wünscht Ihnen einen angenehmen Flug.\n" + + "\n" + + "Wir bitten Sie, sich zur angegeben Boarding Zeit am Gate einzufinden.\n" + + "Buchungscode: JBZPPP\n" + + "Sequenz: 73\n" + + "Hinweis: Bitte beachten Sie, dass obwohl Ihr Flug verspätet sein mag, Sie dennoch wie geplant pünktlich am Check-in und am Abfluggate erscheinen müssen.\n" + + "\n" + + "Kostenlose Mitnahme eines Handgepäckstücks (8 Kg, 55 x 40 x 23cm).\n" + + "Mitnahme von Flüssigkeiten im Handgepäck: Neben den sonstigen Beschränkungen für das Handgepäck ist für alle Abflüge innerhalb der Europäischen Union sowie vielen weiteren Ländern (u.a. Schweiz, Russland, Island, Kroatien, Israel, Ägypten, Marokko, Tunesien, Norwegen) die Mitnahme von vor der Fluggastkontrolle erworbenen bzw. mitgebrachten Flüssigkeiten und Gels nur noch eingeschränkt erlaubt:\n" + + "\n" + + "- Sämtliche Flüssigkeiten (wie Kosmetik- und Toilettenartikel, Gels, Pasten, Cremes, Lotionen, Gemische aus flüssigen und festen Stoffen, Parfums, Behälter unter Druck, Dosen, Wasserflaschen etc.) sowie wachs- oder gelartige Stoffe dürfen nur noch in Behältnissen bis zu 100 ml bzw. 100 g mit an Bord genommen werden.\n" + + "\n" + + "- Diese Flüssigkeiten bzw. Stoffe müssen in einem transparenten, wiederverschließbaren Plastikbeutel (max. 1 kg Inhalt) vollständig geschlossen, verpackt sein.\n" + + "\n" + + "- Diese Beutel müssen Fluggäste selbst vor dem Abflug erwerben. Sie sind in vielen Supermärkten z. B. als Gefrierbeutel erhältlich. Es besteht zurzeit keine Möglichkeit, entsprechende Plastikbeutel am Eurowings Check-In zu erwerben bzw. auszugeben.\n" + + "\n" + + "- Verschreibungspflichtige Medikamente sowie Babynahrung dürfen weiterhin im Handgepäck transportiert werden. Der Fluggast muss nachweisen, dass die Medikamente und Babynahrung während des Fluges benötigt werden.\n" + + "\n" + + "- Produkte und Beutel, die nicht den Maßgaben entsprechen oder die nur mit Gummiband oder ähnlichem verschlossen sind, müssen leider abgegeben werden.\n" + + "\n" + + "Flüssigkeiten und Gels, die Sie nicht zwingend während Ihres Aufenthalts an Bord benötigen, sollten zur raschen Fluggastabfertigung nach Möglichkeit im aufzugebenden Gepäck untergebracht werden.\n" + + "\n" + + "Selbstverständlich ist die Mitnahme von allen Flüssigkeiten/Gels/Getränken aus Travel-Value oder Duty Free-Shops, die nach der Fluggastkontrolle erworben werden, weiterhin erlaubt.\n" + + "\n" + + "Eurowings übernimmt keine Haftung für Gegenstände, die der Fluggast nicht im Handgepäck mitführen darf und deshalb aus Sicherheitsgründen an der Fluggastkontrolle abgeben muss.\n" + + "Kontakt: Sie erreichen das deutsche Call Center unter der Telefonnummer\n" + + "\n" + + "0180 6 320 320 ( 0:00 Uhr - 24:00 Uhr )\n" + + "\n" + + "(0,20 € pro Anruf aus dem Festnetz der Deutschen Telekom - Mobilfunk maximal 0,60 € pro Anruf).", parsedCard.note) + Assert.assertEquals(Date(1567911600000), parsedCard.validFrom) + Assert.assertEquals(null, parsedCard.expiry) + Assert.assertEquals(BigDecimal(0), parsedCard.balance) + Assert.assertEquals(null, parsedCard.balanceType) + Assert.assertEquals("M1DOE/JOHN JBZPPP CGNDBVEW 0954 251A012D0073 148>5181W 9250BEW 00000000000002A0000000000000 0 N", parsedCard.cardId) + Assert.assertEquals(null, parsedCard.barcodeId) + Assert.assertEquals(BarcodeFormat.AZTEC, parsedCard.barcodeType!!.format()) + Assert.assertEquals(Color.parseColor("#FFFFFF"), parsedCard.headerColor) + Assert.assertEquals(0, parsedCard.starStatus) + Assert.assertEquals(0, parsedCard.archiveStatus) + Assert.assertEquals(0, parsedCard.lastUsed) + Assert.assertEquals(DBHelper.DEFAULT_ZOOM_LEVEL, parsedCard.zoomLevel) + + // Confirm correct image is used + Assert.assertTrue(imageBitmap.sameAs(parser.image)) + + // Confirm correct parsing (en) + parsedCard = parser.toLoyaltyCard("en") + + Assert.assertEquals(-1, parsedCard.id) + Assert.assertEquals("EUROWINGS", parsedCard.store) + Assert.assertEquals("Eurowings Boarding Pass\n" + + "\n" + + "Gate: B61\n" + + "Seat: 12D\n" + + "\n" + + "Cologne-Bonn: CGN\n" + + "Dubrovnik: DBV\n" + + "\n" + + "Name: John Doe\n" + + "Status: -\n" + + "Group: GROUP 1\n" + + "Fare: SMART\n" + + "\n" + + "Flight: EW 954\n" + + "Date: 08/09/2019\n" + + "Boarding: 05:00\n" + + "Gate closure: 05:15\n" + + "\n" + + "Eurowings wishes you a pleasant flight .\n" + + "\n" + + "We kindly ask you to be present at your departure gate on time.\n" + + "Booking code: JBZPPP\n" + + "Sequence: 73\n" + + "Notice: Please note that although your flight may be delayed, you will still need to check in and go to your departure gate on time as scheduled.\n" + + "\n" + + "Carry on one item of hand luggage (8 kg, 55 x 40 x 23 cm) for free.\n" + + "Carrying liquids in hand luggage: In addition to other restrictions on hand luggage, there are still restrictions on liquids and gels brought by the passenger or purchased before the security control on all departures within the European Union, as well as to many other countries (including Switzerland, Russia, Iceland, Croatia, Israel, Egypt, Morocco, Tunisia and Norway):\n" + + "\n" + + "- All liquids (such as toiletries and cosmetics, gels, pastes, creams, lotions, mixtures of liquids and solids, perfumes, pressurised containers, cans, water bottles etc) as well as wax and gel-like substances may only be carried on board in amounts less than 100ml or 100g.\n" + + "\n" + + "- These liquids or substances must be packed in closed containers in a transparent, re-sealable plastic bag (max. contents 1 kg).\n" + + "\n" + + "- It is the passenger’s responsibility to purchase this bag before departure. They are available in many supermarkets, e.g. as freezer bags. It is currently not possible for passengers to obtain or purchase the required bags from Eurowings check-in.\n" + + "\n" + + "- Prescription medicines and baby food may still be carried in hand baggage. The passenger must prove that such medicines and/or baby food are needed during the flight.\n" + + "\n" + + "- Products and bags which do not meet the requirements or are only sealed with a rubber band or similar will unfortunately have to be surrendered by passengers\n" + + "\n" + + "In order to pass through the airport as quickly as possible, you are strongly advised to pack any liquids or gels which are not essential for your journey on board the aircraft in your checked baggage if possible.\n" + + "\n" + + "As a matter of course, liquids from the Travel Value / Duty Free shops which have been purchased after you have passed through security are still allowed on board.\n" + + "\n" + + "Eurowings shall not be liable for any items which passengers are prohibited from carrying in their hand baggage for security reasons and are required to surrender at the security checkpoint.\n" + + "Contact: https://mobile.eurowings.com/booking/StaticContactInfo.aspx?culture=en-GB&back=home", parsedCard.note) + Assert.assertEquals(Date(1567911600000), parsedCard.validFrom) + Assert.assertEquals(null, parsedCard.expiry) + Assert.assertEquals(BigDecimal(0), parsedCard.balance) + Assert.assertEquals(null, parsedCard.balanceType) + Assert.assertEquals("M1DOE/JOHN JBZPPP CGNDBVEW 0954 251A012D0073 148>5181W 9250BEW 00000000000002A0000000000000 0 N", parsedCard.cardId) + Assert.assertEquals(null, parsedCard.barcodeId) + Assert.assertEquals(BarcodeFormat.AZTEC, parsedCard.barcodeType!!.format()) + Assert.assertEquals(Color.parseColor("#FFFFFF"), parsedCard.headerColor) + Assert.assertEquals(0, parsedCard.starStatus) + Assert.assertEquals(0, parsedCard.archiveStatus) + Assert.assertEquals(0, parsedCard.lastUsed) + Assert.assertEquals(DBHelper.DEFAULT_ZOOM_LEVEL, parsedCard.zoomLevel) + + // Confirm correct image is used + Assert.assertTrue(imageBitmap.sameAs(parser.image)) + } + + @Test + fun testDCBPkPass() { + // Prepare + val context: Context = ApplicationProvider.getApplicationContext() + val pkpass = "pkpass/DCBLN24/DCBLN24-QLUKT-1-passbook.pkpass" + val image = "pkpass/DCBLN24/logo.png" + + val pkpassUri = Uri.parse(pkpass) + val imageUri = Uri.parse(image) + ShadowContentResolver().registerInputStream(pkpassUri, javaClass.getResourceAsStream(pkpass)) + ShadowContentResolver().registerInputStream(imageUri, javaClass.getResourceAsStream(image)) + + val parser = PkpassParser(context, pkpassUri) + val imageBitmap = BitmapFactory.decodeStream(context.contentResolver.openInputStream(imageUri)) + + // Confirm this does not have languages + Assert.assertEquals(listOf(), parser.listLocales()) + + // Confirm correct parsing + val parsedCard = parser.toLoyaltyCard(null) + + Assert.assertEquals(-1, parsedCard.id) + Assert.assertEquals("droidcon Berlin 2024", parsedCard.store) + Assert.assertEquals("Ticket for droidcon Berlin 2024 (Speaker)\n" + + "\n" + + "Admission time: 2024-07-03 08:00\n" + + "\n" + + "Event: droidcon Berlin 2024\n" + + "\n" + + "Product: Speaker\n" + + "\n" + + "Attendee name: Sylvia van Os\n" + + "From: 2024-07-03 08:00\n" + + "To: 2024-07-05 18:30\n" + + "\n" + + "Admission time: 2024-07-03 08:00\n" + + "Attendee name: Sylvia van Os\n" + + "Ordered by: REDACTED@example.com\n" + + "Organizer: droidcon\n" + + "Organizer contact: global@droidcon.de\n" + + "Order code: REDACTED\n" + + "Purchase date: 2024-06-06 07:26\n" + + "Website: https://pretix.eu/droidcon/dcbln24/", parsedCard.note) + Assert.assertEquals(null, parsedCard.validFrom) + Assert.assertEquals(null, parsedCard.expiry) + Assert.assertEquals(BigDecimal(0), parsedCard.balance) + Assert.assertEquals(null, parsedCard.balanceType) + Assert.assertEquals("ca4phaix1ahkahD2eiVi5iepahxa6rei", parsedCard.cardId) + Assert.assertEquals("ca4phaix1ahkahD2eiVi5iepahxa6rei", parsedCard.barcodeId) + Assert.assertEquals(BarcodeFormat.QR_CODE, parsedCard.barcodeType!!.format()) + Assert.assertEquals(Color.parseColor("#0014e6"), parsedCard.headerColor) + Assert.assertEquals(0, parsedCard.starStatus) + Assert.assertEquals( 0, parsedCard.archiveStatus) + Assert.assertEquals(0, parsedCard.lastUsed) + Assert.assertEquals(DBHelper.DEFAULT_ZOOM_LEVEL, parsedCard.zoomLevel) + + // Confirm correct image is used + Assert.assertTrue(imageBitmap.sameAs(parser.image)) + } +} diff --git a/app/src/test/res/protect/card_locker/pkpass/DCBLN24/DCBLN24-QLUKT-1-passbook.pkpass b/app/src/test/res/protect/card_locker/pkpass/DCBLN24/DCBLN24-QLUKT-1-passbook.pkpass new file mode 100644 index 000000000..b6d4b08f5 Binary files /dev/null and b/app/src/test/res/protect/card_locker/pkpass/DCBLN24/DCBLN24-QLUKT-1-passbook.pkpass differ diff --git a/app/src/test/res/protect/card_locker/pkpass/DCBLN24/logo.png b/app/src/test/res/protect/card_locker/pkpass/DCBLN24/logo.png new file mode 100644 index 000000000..362d1990a Binary files /dev/null and b/app/src/test/res/protect/card_locker/pkpass/DCBLN24/logo.png differ diff --git a/app/src/test/res/protect/card_locker/pkpass/Eurowings/Eurowings.pkpass b/app/src/test/res/protect/card_locker/pkpass/Eurowings/Eurowings.pkpass new file mode 100644 index 000000000..f2265f66e Binary files /dev/null and b/app/src/test/res/protect/card_locker/pkpass/Eurowings/Eurowings.pkpass differ diff --git a/app/src/test/res/protect/card_locker/pkpass/Eurowings/logo@2x.png b/app/src/test/res/protect/card_locker/pkpass/Eurowings/logo@2x.png new file mode 100644 index 000000000..ba1a78ff5 Binary files /dev/null and b/app/src/test/res/protect/card_locker/pkpass/Eurowings/logo@2x.png differ diff --git a/build.gradle.kts b/build.gradle.kts index eb3416d99..6b6232e05 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -3,6 +3,7 @@ plugins { id("com.android.application") version "8.6.1" apply false id("com.github.spotbugs") version "5.1.4" apply false + id("org.jetbrains.kotlin.android") version "2.0.0" apply false } allprojects {