diff --git a/.forgejo/workflows/build-debug.yml b/.forgejo/workflows/build-debug.yml
index 0818b8b..1dcc692 100644
--- a/.forgejo/workflows/build-debug.yml
+++ b/.forgejo/workflows/build-debug.yml
@@ -1,7 +1,7 @@
on:
push:
branches:
- - '*'
+ - 'master'
jobs:
build-debug:
@@ -33,23 +33,13 @@ jobs:
uses: https://gitea.angry.im/actions/setup-android@v3
- name: Build Debug APKs
- run: ./gradlew --no-daemon assembleDebug :app:assembleDebugMagiskModuleDir
+ run: ./gradlew --no-daemon assembleDebug
- - name: Copy Artifacts
- run: |
- find . -name 'app*-debug.apk' -exec cp {} . \;
- cp -r app/build/magisk/debug ./magisk-debug
-
- - name: Upload APK Artifacts
+ - name: Upload Artifacts
uses: https://gitea.angry.im/actions/upload-artifact@v3
with:
name: Debug APKs
compression-level: 0
- path: app*-debug.apk
-
- - name: Upload Magisk Artifacts
- uses: https://gitea.angry.im/actions/upload-artifact@v3
- with:
- name: magisk-debug
- compression-level: 0
- path: magisk-debug
+ path: |
+ app-unpriv/build/outputs/apk/debug/app-unpriv-debug.apk
+ app/build/outputs/apk/debug/app-debug.apk
diff --git a/.gitignore b/.gitignore
index 1aa6f8a..2b15a47 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,11 +1,20 @@
-/.gradle
-/captures
-
-# Configuration files
-
-/keystore.properties
+*.iml
+.gradle
/local.properties
-
-# macOS
-
+/keystore.properties
+/.idea/caches
+/.idea/libraries
+/.idea/modules.xml
+/.idea/workspace.xml
+/.idea/navEditor.xml
+/.idea/assetWizardSettings.xml
+/.idea/deploymentTargetDropDown.xml
.DS_Store
+/build
+/captures
+.externalNativeBuild
+.cxx
+local.properties
+/libs/**/build
+/buildSrc/build
+/app-deps/libs
\ No newline at end of file
diff --git a/.gitmodules b/.gitmodules
index 863f185..f888959 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -1,3 +1,3 @@
[submodule "libs/lpac-jni/src/main/jni/lpac"]
path = libs/lpac-jni/src/main/jni/lpac
- url = https://github.com/estkme-group/lpac.git
+ url = https://github.com/estkme/lpac
diff --git a/.idea/.gitignore b/.idea/.gitignore
index d2293f6..26d3352 100644
--- a/.idea/.gitignore
+++ b/.idea/.gitignore
@@ -1,7 +1,3 @@
-*
-!/codeStyles/Project.xml
-!/codeStyles/codeStyleConfig.xml
-!/vcs.xml
-!/kotlinc.xml
-!/compiler.xml
-!/migrations.xml
+# Default ignored files
+/shelf/
+/workspace.xml
diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml
index 7643783..4bec4ea 100644
--- a/.idea/codeStyles/Project.xml
+++ b/.idea/codeStyles/Project.xml
@@ -1,8 +1,5 @@
-
-
-
@@ -116,8 +113,5 @@
-
-
-
\ No newline at end of file
diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml
index 6e6eec1..a55e7a1 100644
--- a/.idea/codeStyles/codeStyleConfig.xml
+++ b/.idea/codeStyles/codeStyleConfig.xml
@@ -1,6 +1,5 @@
-
\ No newline at end of file
diff --git a/.idea/compiler.xml b/.idea/compiler.xml
index 1c5ab05..61f4db4 100644
--- a/.idea/compiler.xml
+++ b/.idea/compiler.xml
@@ -1,6 +1,16 @@
-
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/gradle.xml b/.idea/gradle.xml
new file mode 100644
index 0000000..163d6b4
--- /dev/null
+++ b/.idea/gradle.xml
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml
index 148fdd2..e805548 100644
--- a/.idea/kotlinc.xml
+++ b/.idea/kotlinc.xml
@@ -1,6 +1,6 @@
-
+
\ No newline at end of file
diff --git a/.idea/migrations.xml b/.idea/migrations.xml
deleted file mode 100644
index f8051a6..0000000
--- a/.idea/migrations.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
new file mode 100644
index 0000000..a1f9d9f
--- /dev/null
+++ b/.idea/misc.xml
@@ -0,0 +1,25 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Android.mk b/Android.mk
new file mode 100644
index 0000000..e69de29
diff --git a/README.md b/README.md
index 80ab300..5616a32 100644
--- a/README.md
+++ b/README.md
@@ -2,46 +2,20 @@
A fully free and open-source Local Profile Assistant implementation for Android devices.
-There are two variants of this project, OpenEUICC and EasyEUICC:
+There are two variants of this project:
-| | OpenEUICC | EasyEUICC |
-| :---------------------------- | :-----------------------------: | :-----------------: |
-| Privileged | Must be installed as system app | No |
-| Internal eSIM | Supported | Unsupported |
-| External eSIM [^1] | Supported | Supported |
-| USB Readers | Supported | Supported |
-| Requires allowlisting by eSIM | No | Yes -- except USB |
-| System Integration | Partial [^2] | No |
-| Minimum Android Version | Android 11 or higher | Android 9 or higher |
+- OpenEUICC: The full-fledged privileged variant.
+ - Due to its privilege requirement, OpenEUICC must be placed inside `/system/priv-app` and be signed with the platform certificate.
+ - The preferred way to including OpenEUICC in a system image is to [build it along with AOSP](#building-aosp).
+- EasyEUICC: Unprivileged version that can run as a user app.
+ - This version supports two modes of operation:
+ 1. Inserted, removable eSIMs: Due to obvious security requirements, EasyEUICC is only able to access eSIM chips whose [ARF/ARA](https://source.android.com/docs/core/connect/uicc#arf) contains the hash of EasyEUICC's signing certificate.
+ 2. USB CCID Card Readers: Only `T=0` readers that use the standard [USB CCID protocol](https://en.wikipedia.org/wiki/CCID_(protocol)) are supported. In this mode, EasyEUICC can access any eSIM chip loaded in the card reader regardless of their ARF/ARA, as long as they implement the [SGP.22 standard](https://www.gsma.com/solutions-and-impact/technologies/esim/wp-content/uploads/2021/07/SGP.22-v2.3.pdf).
+ - Prebuilt release-mode EasyEUICC apks can be downloaded [here](https://gitea.angry.im/PeterCxy/OpenEUICC/releases)
+ - For removable eSIM chip vendors: to have your chip supported by official builds of EasyEUICC when inserted, include the ARA-M hash `2A2FA878BC7C3354C2CF82935A5945A3EDAE4AFA`
-[^1]: Also known as "Removable eSIM"
-[^2]: Carrier Partner API unimplemented yet
-
-Some side notes:
-
-1. When privileged, OpenEUICC supports any eUICC chip that implements the [SGP.22] standard, internal or external.
- However, there is **no guarantee** that external (removable) eSIMs actually follow the standard.
- Please **DO NOT** submit bug reports for non-functioning removable eSIMs.
- They are **NOT** officially supported unless they also support / are supported by EasyEUICC, the unprivileged variant.
-2. Both variants support accessing eUICC chips through USB CCID readers,
- regardless of whether the chip contains the correct ARA-M hash to allow for unprivileged access.
- However, only `T=0` readers that use the standard [USB CCID protocol][usb-ccid] are supported.
-3. Prebuilt release-mode EasyEUICC apks can be downloaded [here][releases].
- For OpenEUICC, no official release is currently provided and only debug mode APKs and Magisk modules can be found in the [CI page][actions].
-4. For removable eSIM chip vendors: to have your chip supported by official builds of EasyEUICC when inserted,
- include the ARA-M hash `2A2FA878BC7C3354C2CF82935A5945A3EDAE4AFA`.
-
-[sgp.22]: https://www.gsma.com/solutions-and-impact/technologies/esim/gsma_resources/sgp-22-v2-2-2/ "SGP.22 v2.2.2"
-[usb-ccid]: https://en.wikipedia.org/wiki/CCID_%28protocol%29 "USB CCID Protocol"
-[releases]: https://gitea.angry.im/PeterCxy/OpenEUICC/releases "EasyEUICC Releases"
-[actions]: https://gitea.angry.im/PeterCxy/OpenEUICC/actions "OpenEUICC Actions"
-
-**This project is Free Software licensed under GNU GPL v3, WITHOUT the "or later" clause.**
-Any modification and derivative work **MUST** be released under the SAME license, which means, at the very least, that the source code **MUST** be available upon request.
-
-**If you are releasing a modification of this app, you are kindly asked to make changes to at least the app name and package name.**
-
-# Building (Gradle)
+Building (Gradle)
+===
Make sure you have all submodules cloned and updated by running
@@ -74,7 +48,8 @@ For EasyEUICC:
./gradlew :app-unpriv:assembleRelease
```
-# Building (AOSP)
+Building (AOSP)
+===
There are two ways to include OpenEUICC in your AOSP-based system image:
@@ -84,22 +59,25 @@ There are two ways to include OpenEUICC in your AOSP-based system image:
- Compilation of this project is **only** tested against the latest AOSP release version. The app itself should be compatible with older AOSP versions, but the source may not compile against an older AOSP source tree.
2. If compilation against AOSP source tree is not possible, consider [building with gradle](#building-gradle) and import the apk as a prebuilt.
- No official `Android.bp` is provided for this case but it should be straightforward to write.
- - You might want to include [`privapp_whitelist_im.angry.openeuicc.xml`] as well.
+ - You might want to include `privapp_whitelist_im.angry.openeuicc.xml` as well.
-[`privapp_whitelist_im.angry.openeuicc.xml`]: privapp_whitelist_im.angry.openeuicc.xml "OpenEUICC Privapp Whitelist"
+FAQs
+===
-# FAQs
+- Q: Do you provide prebuilt binaries for OpenEUICC?
+- A: Debug-mode APKs are available continuously as an artifact of the [Actions](https://gitea.angry.im/PeterCxy/OpenEUICC/actions) CI used by this project. However, these debug-mode APKs are **not** intended for inclusion inside system images, nor are they supported by the developer in any sense. If you are a custom ROM developer, either include the entire OpenEUICC repository in your AOSP source tree, or generate an APK using `gradle` and import that as a prebuilt system app. Note that you might want `privapp_whitelist_im.angry.openeuicc.xml` as well.
-- Q: Do you provide prebuilt binaries for OpenEUICC? \
- A: Debug-mode APKs and Magisk modules are available continuously as an artifact of the [Actions] CI used by this project. However, these debug-mode APKs are **not** intended for inclusion inside system images, nor are they supported by the developer in any sense. If you are a custom ROM developer, either include the entire OpenEUICC repository in your AOSP source tree, or generate an APK using `gradle` and import that as a prebuilt system app. Note that you might want [`privapp_whitelist_im.angry.openeuicc.xml`] as well.
+- Q: AOSP's Settings app seems to be confused by OpenEUICC (for example, disabling / enabling profiles from the Networks page do not work properly)
+- A: When your device has internal eSIM chip(s) __and__ you have inserted a removable eSIM chip, the Settings app can misbehave since it was never designed for this scenario. __Please prefer using OpenEUICC's own management interface whenever possible.__ In the future, there might be an option to exclude removable SIMs from being reported to the Android system.
-- Q: Can EasyEUICC manage my phone's internal eSIM? \
- A: No. For EasyEUICC to work, the eSIM chip MUST proactively grant access via its ARA-M field.
+- Q: Can EasyEUICC manage my phone's internal eSIM?
+- A: No. For EasyEUICC to work, the eSIM chip MUST proactively grant access via its ARA-M field.
-- Q: Removable eSIMs? Are they a joke? \
- A: No, even though the name "removable embedded SIM" can sound like an oxymoron. In fact, there can be many advantages to these chips compared to fully embedded ones. For example, the ability to transfer eSIM profiles without carrier support or approval, or the ability to use eSIM on devices that do not and may never get the support, such as Wi-Fi hotspots.
+- Q: Removable eSIMs? Are they a joke?
+- A: No, even though the name "removable embedded SIM" can sound like an oxymoron. In fact, there can be many advantages to these chips compared to fully embedded ones. For example, the ability to transfer eSIM profiles without carrier support or approval, or the ability to use eSIM on devices that do not and may never get the support, such as Wi-Fi hotspots.
-# Copyright
+Copyright
+===
Everything except `libs/lpac-jni` and `art/`:
@@ -139,4 +117,4 @@ License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
```
-`art/`: Courtesy of [Aikoyori](https://github.com/Aikoyori), CC NC-SA 4.0.
+`art/`: Courtesy of [Aikoyori](https://github.com/Aikoyori), CC NC-SA 4.0.
\ No newline at end of file
diff --git a/app-common/build.gradle.kts b/app-common/build.gradle.kts
index d74fcec..5af1799 100644
--- a/app-common/build.gradle.kts
+++ b/app-common/build.gradle.kts
@@ -5,7 +5,7 @@ plugins {
android {
namespace = "im.angry.openeuicc.common"
- compileSdk = 35
+ compileSdk = 34
defaultConfig {
minSdk = 28
diff --git a/app-common/src/main/AndroidManifest.xml b/app-common/src/main/AndroidManifest.xml
index 44c82c0..8163299 100644
--- a/app-common/src/main/AndroidManifest.xml
+++ b/app-common/src/main/AndroidManifest.xml
@@ -3,15 +3,10 @@
xmlns:android="http://schemas.android.com/apk/res/android"
package="im.angry.openeuicc.common">
-
-
-
-
+
@@ -21,41 +16,14 @@
android:label="@string/profile_notifications" />
+ android:name="im.angry.openeuicc.ui.DirectProfileDownloadActivity"
+ android:label="@string/profile_download"
+ android:theme="@style/Theme.AppCompat.Translucent" />
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app-common/src/main/java/im/angry/openeuicc/core/ApduInterfaceAtrProvider.kt b/app-common/src/main/java/im/angry/openeuicc/core/ApduInterfaceAtrProvider.kt
deleted file mode 100644
index c3646d2..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/core/ApduInterfaceAtrProvider.kt
+++ /dev/null
@@ -1,5 +0,0 @@
-package im.angry.openeuicc.core
-
-interface ApduInterfaceAtrProvider {
- val atr: ByteArray?
-}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelFactory.kt b/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelFactory.kt
index 78a8c3f..e653a07 100644
--- a/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelFactory.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelFactory.kt
@@ -1,86 +1,59 @@
package im.angry.openeuicc.core
import android.content.Context
+import android.hardware.usb.UsbDevice
+import android.hardware.usb.UsbInterface
+import android.hardware.usb.UsbManager
import android.se.omapi.SEService
import android.util.Log
-import im.angry.openeuicc.common.R
import im.angry.openeuicc.core.usb.UsbApduInterface
-import im.angry.openeuicc.core.usb.UsbCcidContext
+import im.angry.openeuicc.core.usb.getIoEndpoints
import im.angry.openeuicc.util.*
import java.lang.IllegalArgumentException
open class DefaultEuiccChannelFactory(protected val context: Context) : EuiccChannelFactory {
private var seService: SEService? = null
+ private val usbManager by lazy {
+ context.getSystemService(Context.USB_SERVICE) as UsbManager
+ }
+
private suspend fun ensureSEService() {
if (seService == null || !seService!!.isConnected) {
seService = connectSEService(context)
}
}
- override suspend fun tryOpenEuiccChannel(
- port: UiccPortInfoCompat,
- isdrAid: ByteArray
- ): EuiccChannel? = try {
+ override suspend fun tryOpenEuiccChannel(port: UiccPortInfoCompat): EuiccChannel? {
if (port.portIndex != 0) {
- Log.w(
- DefaultEuiccChannelManager.TAG,
- "OMAPI channel attempted on non-zero portId, this may or may not work."
- )
+ Log.w(DefaultEuiccChannelManager.TAG, "OMAPI channel attempted on non-zero portId, this may or may not work.")
}
ensureSEService()
- Log.i(
- DefaultEuiccChannelManager.TAG,
- "Trying OMAPI for physical slot ${port.card.physicalSlotIndex}"
- )
- EuiccChannelImpl(
- context.getString(R.string.channel_type_omapi),
- port,
- intrinsicChannelName = null,
- OmapiApduInterface(
- seService!!,
- port,
- context.preferenceRepository.verboseLoggingFlow
- ),
- isdrAid,
- context.preferenceRepository.verboseLoggingFlow,
- context.preferenceRepository.ignoreTLSCertificateFlow,
- context.preferenceRepository.es10xMssFlow,
- )
- } catch (_: IllegalArgumentException) {
- // Failed
- Log.w(
- DefaultEuiccChannelManager.TAG,
- "OMAPI APDU interface unavailable for physical slot ${port.card.physicalSlotIndex} with ISD-R AID: ${isdrAid.encodeHex()}."
- )
- null
+ Log.i(DefaultEuiccChannelManager.TAG, "Trying OMAPI for physical slot ${port.card.physicalSlotIndex}")
+ try {
+ return EuiccChannel(port, OmapiApduInterface(seService!!, port))
+ } catch (e: IllegalArgumentException) {
+ // Failed
+ Log.w(
+ DefaultEuiccChannelManager.TAG,
+ "OMAPI APDU interface unavailable for physical slot ${port.card.physicalSlotIndex}."
+ )
+ }
+
+ return null
}
- override fun tryOpenUsbEuiccChannel(
- ccidCtx: UsbCcidContext,
- isdrAid: ByteArray
- ): EuiccChannel? = try {
- EuiccChannelImpl(
- context.getString(R.string.channel_type_usb),
+ override fun tryOpenUsbEuiccChannel(usbDevice: UsbDevice, usbInterface: UsbInterface): EuiccChannel? {
+ val (bulkIn, bulkOut) = usbInterface.getIoEndpoints()
+ if (bulkIn == null || bulkOut == null) return null
+ val conn = usbManager.openDevice(usbDevice) ?: return null
+ if (!conn.claimInterface(usbInterface, true)) return null
+ return EuiccChannel(
FakeUiccPortInfoCompat(FakeUiccCardInfoCompat(EuiccChannelManager.USB_CHANNEL_ID)),
- intrinsicChannelName = ccidCtx.productName,
- UsbApduInterface(
- ccidCtx
- ),
- isdrAid,
- context.preferenceRepository.verboseLoggingFlow,
- context.preferenceRepository.ignoreTLSCertificateFlow,
- context.preferenceRepository.es10xMssFlow,
+ UsbApduInterface(conn, bulkIn, bulkOut)
)
- } catch (_: IllegalArgumentException) {
- // Failed
- Log.w(
- DefaultEuiccChannelManager.TAG,
- "USB APDU interface unavailable for ISD-R AID: ${isdrAid.encodeHex()}."
- )
- null
}
override fun cleanup() {
diff --git a/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt b/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt
index 6b336cd..b943820 100644
--- a/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt
@@ -5,18 +5,12 @@ import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.telephony.SubscriptionManager
import android.util.Log
-import im.angry.openeuicc.core.usb.UsbCcidContext
-import im.angry.openeuicc.core.usb.smartCard
-import im.angry.openeuicc.core.usb.interfaces
+import im.angry.openeuicc.core.usb.getSmartCardInterface
import im.angry.openeuicc.di.AppContainer
import im.angry.openeuicc.util.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.flow.flow
-import kotlinx.coroutines.flow.flowOn
-import kotlinx.coroutines.flow.merge
+import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
@@ -51,24 +45,6 @@ open class DefaultEuiccChannelManager(
protected open val uiccCards: Collection
get() = (0.. EuiccChannel?): EuiccChannel? {
- val isdrAidList =
- parseIsdrAidList(appContainer.preferenceRepository.isdrAidListFlow.first())
-
- return isdrAidList.firstNotNullOfOrNull {
- Log.i(TAG, "Opening channel, trying ISDR AID ${it.encodeHex()}")
-
- openFn(it)?.let { channel ->
- if (channel.valid) {
- channel
- } else {
- channel.close()
- null
- }
- }
- }
- }
-
private suspend fun tryOpenEuiccChannel(port: UiccPortInfoCompat): EuiccChannel? {
lock.withLock {
if (port.card.physicalSlotIndex == EuiccChannelManager.USB_CHANNEL_ID) {
@@ -96,10 +72,9 @@ open class DefaultEuiccChannelManager(
return null
}
- val channel =
- tryOpenChannelFirstValidAid { euiccChannelFactory.tryOpenEuiccChannel(port, it) }
+ val channel = euiccChannelFactory.tryOpenEuiccChannel(port) ?: return null
- if (channel != null) {
+ if (channel.valid) {
channelCache.add(channel)
return channel
} else {
@@ -107,29 +82,50 @@ open class DefaultEuiccChannelManager(
TAG,
"Was able to open channel for logical slot ${port.logicalSlotIndex}, but the channel is invalid (cannot get eID or profiles without errors). This slot might be broken, aborting."
)
+ channel.close()
return null
}
}
}
- protected suspend fun findEuiccChannelByLogicalSlot(logicalSlotId: Int): EuiccChannel? =
- withContext(Dispatchers.IO) {
- if (logicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
- return@withContext usbChannel
- }
+ override fun findEuiccChannelBySlotBlocking(logicalSlotId: Int): EuiccChannel? =
+ runBlocking {
+ withContext(Dispatchers.IO) {
+ if (logicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
+ return@withContext usbChannel
+ }
- for (card in uiccCards) {
- for (port in card.ports) {
- if (port.logicalSlotIndex == logicalSlotId) {
- return@withContext tryOpenEuiccChannel(port)
+ for (card in uiccCards) {
+ for (port in card.ports) {
+ if (port.logicalSlotIndex == logicalSlotId) {
+ return@withContext tryOpenEuiccChannel(port)
+ }
}
}
- }
- null
+ null
+ }
}
- private suspend fun findAllEuiccChannelsByPhysicalSlot(physicalSlotId: Int): List? {
+ override fun findEuiccChannelByPhysicalSlotBlocking(physicalSlotId: Int): EuiccChannel? =
+ runBlocking {
+ withContext(Dispatchers.IO) {
+ if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
+ return@withContext usbChannel
+ }
+
+ for (card in uiccCards) {
+ if (card.physicalSlotIndex != physicalSlotId) continue
+ for (port in card.ports) {
+ tryOpenEuiccChannel(port)?.let { return@withContext it }
+ }
+ }
+
+ null
+ }
+ }
+
+ override suspend fun findAllEuiccChannelsByPhysicalSlot(physicalSlotId: Int): List? {
if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
return usbChannel?.let { listOf(it) }
}
@@ -142,7 +138,12 @@ open class DefaultEuiccChannelManager(
return null
}
- private suspend fun findEuiccChannelByPort(physicalSlotId: Int, portId: Int): EuiccChannel? =
+ override fun findAllEuiccChannelsByPhysicalSlotBlocking(physicalSlotId: Int): List? =
+ runBlocking {
+ findAllEuiccChannelsByPhysicalSlot(physicalSlotId)
+ }
+
+ override suspend fun findEuiccChannelByPort(physicalSlotId: Int, portId: Int): EuiccChannel? =
withContext(Dispatchers.IO) {
if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
return@withContext usbChannel
@@ -153,155 +154,72 @@ open class DefaultEuiccChannelManager(
}
}
- override suspend fun findFirstAvailablePort(physicalSlotId: Int): Int =
- withContext(Dispatchers.IO) {
- if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
- return@withContext 0
- }
-
- findAllEuiccChannelsByPhysicalSlot(physicalSlotId)?.getOrNull(0)?.portId ?: -1
+ override fun findEuiccChannelByPortBlocking(physicalSlotId: Int, portId: Int): EuiccChannel? =
+ runBlocking {
+ findEuiccChannelByPort(physicalSlotId, portId)
}
- override suspend fun findAvailablePorts(physicalSlotId: Int): List =
- withContext(Dispatchers.IO) {
- if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
- return@withContext listOf(0)
- }
-
- findAllEuiccChannelsByPhysicalSlot(physicalSlotId)?.map { it.portId } ?: listOf()
- }
-
- override suspend fun withEuiccChannel(
- physicalSlotId: Int,
- portId: Int,
- fn: suspend (EuiccChannel) -> R
- ): R {
- val channel = findEuiccChannelByPort(physicalSlotId, portId)
- ?: throw EuiccChannelManager.EuiccChannelNotFoundException()
- val wrapper = EuiccChannelWrapper(channel)
- try {
- return withContext(Dispatchers.IO) {
- fn(wrapper)
- }
- } finally {
- wrapper.invalidateWrapper()
- }
- }
-
- override suspend fun withEuiccChannel(
- logicalSlotId: Int,
- fn: suspend (EuiccChannel) -> R
- ): R {
- val channel = findEuiccChannelByLogicalSlot(logicalSlotId)
- ?: throw EuiccChannelManager.EuiccChannelNotFoundException()
- val wrapper = EuiccChannelWrapper(channel)
- try {
- return withContext(Dispatchers.IO) {
- fn(wrapper)
- }
- } finally {
- wrapper.invalidateWrapper()
- }
- }
-
override suspend fun waitForReconnect(physicalSlotId: Int, portId: Int, timeoutMillis: Long) {
- if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
- usbChannel?.close()
- usbChannel = null
- } else {
- // If there is already a valid channel, we close it proactively
- // Sometimes the current channel can linger on for a bit even after it should have become invalid
- channelCache.find { it.slotId == physicalSlotId && it.portId == portId }?.apply {
- if (valid) close()
- }
+ if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) return
+
+ // If there is already a valid channel, we close it proactively
+ // Sometimes the current channel can linger on for a bit even after it should have become invalid
+ channelCache.find { it.slotId == physicalSlotId && it.portId == portId }?.apply {
+ if (valid) close()
}
withTimeout(timeoutMillis) {
while (true) {
try {
- val channel = if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
- // tryOpenUsbEuiccChannel() will always try to reopen the channel, even if
- // a USB channel already exists
- tryOpenUsbEuiccChannel()
- usbChannel!!
- } else {
- // tryOpenEuiccChannel() will automatically dispose of invalid channels
- // and recreate when needed
- findEuiccChannelByPort(physicalSlotId, portId)!!
- }
+ // tryOpenEuiccChannel() will automatically dispose of invalid channels
+ // and recreate when needed
+ val channel = findEuiccChannelByPortBlocking(physicalSlotId, portId)!!
check(channel.valid) { "Invalid channel" }
break
} catch (e: Exception) {
- Log.d(
- TAG,
- "Slot $physicalSlotId port $portId reconnect failure, retrying in 1000 ms"
- )
+ Log.d(TAG, "Slot $physicalSlotId port $portId reconnect failure, retrying in 1000 ms")
}
delay(1000)
}
}
}
- override fun flowInternalEuiccPorts(): Flow> = flow {
- uiccCards.forEach { info ->
- info.ports.forEach { port ->
- tryOpenEuiccChannel(port)?.also {
- Log.d(
- TAG,
- "Found eUICC on slot ${info.physicalSlotIndex} port ${port.portIndex}"
- )
-
- emit(Pair(info.physicalSlotIndex, port.portIndex))
+ override suspend fun enumerateEuiccChannels(): List =
+ withContext(Dispatchers.IO) {
+ uiccCards.flatMap { info ->
+ info.ports.mapNotNull { port ->
+ tryOpenEuiccChannel(port)?.also {
+ Log.d(
+ TAG,
+ "Found eUICC on slot ${info.physicalSlotIndex} port ${port.portIndex}"
+ )
+ }
}
}
}
- }.flowOn(Dispatchers.IO)
- override fun flowAllOpenEuiccPorts(): Flow> =
- merge(flowInternalEuiccPorts(), flow {
- if (tryOpenUsbEuiccChannel().second) {
- emit(Pair(EuiccChannelManager.USB_CHANNEL_ID, 0))
- }
- })
-
- override suspend fun tryOpenUsbEuiccChannel(): Pair =
+ override suspend fun enumerateUsbEuiccChannel(): Pair =
withContext(Dispatchers.IO) {
usbManager.deviceList.values.forEach { device ->
Log.i(TAG, "Scanning USB device ${device.deviceId}:${device.vendorId}")
- val iface = device.interfaces.smartCard ?: return@forEach
+ val iface = device.getSmartCardInterface() ?: return@forEach
// If we don't have permission, tell UI code that we found a candidate device, but we
// need permission to be able to do anything with it
- if (!usbManager.hasPermission(device)) return@withContext Pair(device, false)
- Log.i(
- TAG,
- "Found CCID interface on ${device.deviceId}:${device.vendorId}, and has permission; trying to open channel"
- )
-
- val ccidCtx = UsbCcidContext.createFromUsbDevice(context, device, iface) ?: return@forEach
-
+ if (!usbManager.hasPermission(device)) return@withContext Pair(device, null)
+ Log.i(TAG, "Found CCID interface on ${device.deviceId}:${device.vendorId}, and has permission; trying to open channel")
try {
- val channel = tryOpenChannelFirstValidAid {
- euiccChannelFactory.tryOpenUsbEuiccChannel(ccidCtx, it)
- }
+ val channel = euiccChannelFactory.tryOpenUsbEuiccChannel(device, iface)
if (channel != null && channel.lpa.valid) {
- ccidCtx.allowDisconnect = true
usbChannel = channel
- return@withContext Pair(device, true)
+ return@withContext Pair(device, channel)
}
} catch (e: Exception) {
// Ignored -- skip forward
e.printStackTrace()
}
-
- ccidCtx.allowDisconnect = true
- ccidCtx.disconnect()
-
- Log.i(
- TAG,
- "No valid eUICC channel found on USB device ${device.deviceId}:${device.vendorId}"
- )
+ Log.i(TAG, "No valid eUICC channel found on USB device ${device.deviceId}:${device.vendorId}")
}
- return@withContext Pair(null, false)
+ return@withContext Pair(null, null)
}
override fun invalidate() {
diff --git a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannel.kt b/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannel.kt
index b20932f..35cf0ad 100644
--- a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannel.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannel.kt
@@ -3,41 +3,21 @@ package im.angry.openeuicc.core
import im.angry.openeuicc.util.*
import net.typeblog.lpac_jni.ApduInterface
import net.typeblog.lpac_jni.LocalProfileAssistant
+import net.typeblog.lpac_jni.impl.HttpInterfaceImpl
+import net.typeblog.lpac_jni.impl.LocalProfileAssistantImpl
-interface EuiccChannel {
- val type: String
+class EuiccChannel(
+ val port: UiccPortInfoCompat,
+ apduInterface: ApduInterface,
+) {
+ val slotId = port.card.physicalSlotIndex // PHYSICAL slot
+ val logicalSlotId = port.logicalSlotIndex
+ val portId = port.portIndex
- val port: UiccPortInfoCompat
-
- val slotId: Int // PHYSICAL slot
- val logicalSlotId: Int
- val portId: Int
-
- val lpa: LocalProfileAssistant
+ val lpa: LocalProfileAssistant = LocalProfileAssistantImpl(apduInterface, HttpInterfaceImpl())
val valid: Boolean
+ get() = lpa.valid
- /**
- * Answer to Reset (ATR) value of the underlying interface, if any
- */
- val atr: ByteArray?
-
- /**
- * Intrinsic name of this channel. For device-internal SIM slots,
- * this should be null; for USB readers, this should be the name of
- * the reader device.
- */
- val intrinsicChannelName: String?
-
- /**
- * The underlying APDU interface for this channel
- */
- val apduInterface: ApduInterface
-
- /**
- * The AID of the ISD-R channel currently in use
- */
- val isdrAid: ByteArray
-
- fun close()
-}
\ No newline at end of file
+ fun close() = lpa.close()
+}
diff --git a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelFactory.kt b/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelFactory.kt
index ba587a6..fb5d95d 100644
--- a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelFactory.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelFactory.kt
@@ -1,17 +1,15 @@
package im.angry.openeuicc.core
-import im.angry.openeuicc.core.usb.UsbCcidContext
+import android.hardware.usb.UsbDevice
+import android.hardware.usb.UsbInterface
import im.angry.openeuicc.util.*
// This class is here instead of inside DI because it contains a bit more logic than just
// "dumb" dependency injection.
interface EuiccChannelFactory {
- suspend fun tryOpenEuiccChannel(port: UiccPortInfoCompat, isdrAid: ByteArray): EuiccChannel?
+ suspend fun tryOpenEuiccChannel(port: UiccPortInfoCompat): EuiccChannel?
- fun tryOpenUsbEuiccChannel(
- ccidCtx: UsbCcidContext,
- isdrAid: ByteArray
- ): EuiccChannel?
+ fun tryOpenUsbEuiccChannel(usbDevice: UsbDevice, usbInterface: UsbInterface): EuiccChannel?
/**
* Release all resources used by this EuiccChannelFactory
diff --git a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelImpl.kt b/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelImpl.kt
deleted file mode 100644
index eaec522..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelImpl.kt
+++ /dev/null
@@ -1,42 +0,0 @@
-package im.angry.openeuicc.core
-
-import im.angry.openeuicc.util.UiccPortInfoCompat
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.runBlocking
-import net.typeblog.lpac_jni.ApduInterface
-import net.typeblog.lpac_jni.LocalProfileAssistant
-import net.typeblog.lpac_jni.impl.HttpInterfaceImpl
-import net.typeblog.lpac_jni.impl.LocalProfileAssistantImpl
-
-class EuiccChannelImpl(
- override val type: String,
- override val port: UiccPortInfoCompat,
- override val intrinsicChannelName: String?,
- override val apduInterface: ApduInterface,
- override val isdrAid: ByteArray,
- verboseLoggingFlow: Flow,
- ignoreTLSCertificateFlow: Flow,
- es10xMssFlow: Flow,
-) : EuiccChannel {
- override val slotId = port.card.physicalSlotIndex
- override val logicalSlotId = port.logicalSlotIndex
- override val portId = port.portIndex
-
- override val lpa: LocalProfileAssistant =
- LocalProfileAssistantImpl(
- isdrAid,
- apduInterface,
- HttpInterfaceImpl(verboseLoggingFlow, ignoreTLSCertificateFlow),
- ).also {
- it.setEs10xMss(runBlocking { es10xMssFlow.first().toByte() })
- }
-
- override val atr: ByteArray?
- get() = (apduInterface as? ApduInterfaceAtrProvider)?.atr
-
- override val valid: Boolean
- get() = lpa.valid
-
- override fun close() = lpa.close()
-}
diff --git a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelManager.kt b/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelManager.kt
index 17f3130..b21ccf6 100644
--- a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelManager.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelManager.kt
@@ -1,7 +1,6 @@
package im.angry.openeuicc.core
import android.hardware.usb.UsbDevice
-import kotlinx.coroutines.flow.Flow
/**
* EuiccChannelManager holds references to, and manages the lifecycles of, individual
@@ -19,35 +18,19 @@ interface EuiccChannelManager {
}
/**
- * Scan all possible _device internal_ sources for EuiccChannels, as a flow, return their physical
- * (slotId, portId) and have all scanned channels cached; these channels will remain open
- * for the entire lifetime of this EuiccChannelManager object, unless disconnected externally
- * or invalidate()'d.
- *
- * To obtain a temporary reference to a EuiccChannel, use `withEuiccChannel()`.
+ * Scan all possible _device internal_ sources for EuiccChannels, return them and have all
+ * scanned channels cached; these channels will remain open for the entire lifetime of
+ * this EuiccChannelManager object, unless disconnected externally or invalidate()'d
*/
- fun flowInternalEuiccPorts(): Flow>
-
- /**
- * Same as flowInternalEuiccPorts(), except that this includes non-device internal eUICC chips
- * as well. Namely, this includes the USB reader.
- *
- * Non-internal readers will only be included if they have been opened properly, i.e. with permissions
- * granted by the user.
- */
- fun flowAllOpenEuiccPorts(): Flow>
+ suspend fun enumerateEuiccChannels(): List
/**
* Scan all possible USB devices for CCID readers that may contain eUICC cards.
* If found, try to open it for access, and add it to the internal EuiccChannel cache
* as a "port" with id 99. When user interaction is required to obtain permission
- * to interact with the device, the second return value will be false.
- *
- * Returns (usbDevice, canOpen). canOpen is false if either (1) no usb reader is found;
- * or (2) usb reader is found, but user interaction is required for access;
- * or (3) usb reader is found, but we are unable to open ISD-R.
+ * to interact with the device, the second return value (EuiccChannel) will be null.
*/
- suspend fun tryOpenUsbEuiccChannel(): Pair
+ suspend fun enumerateUsbEuiccChannel(): Pair
/**
* Wait for a slot + port to reconnect (i.e. become valid again)
@@ -57,40 +40,29 @@ interface EuiccChannelManager {
suspend fun waitForReconnect(physicalSlotId: Int, portId: Int, timeoutMillis: Long = 1000)
/**
- * Returns the first mapped & available port ID for a physical slot, or -1 if
- * not found.
+ * Returns the EuiccChannel corresponding to a **logical** slot
*/
- suspend fun findFirstAvailablePort(physicalSlotId: Int): Int
+ fun findEuiccChannelBySlotBlocking(logicalSlotId: Int): EuiccChannel?
/**
- * Returns all mapped & available port IDs for a physical slot.
+ * Returns the first EuiccChannel corresponding to a **physical** slot
+ * If the physical slot supports MEP and has multiple ports, it is undefined
+ * which of the two channels will be returned.
*/
- suspend fun findAvailablePorts(physicalSlotId: Int): List
-
- class EuiccChannelNotFoundException: Exception("EuiccChannel not found")
+ fun findEuiccChannelByPhysicalSlotBlocking(physicalSlotId: Int): EuiccChannel?
/**
- * Find a EuiccChannel by its slot and port, then run a callback with a reference to it.
- * The reference is not supposed to be held outside of the callback. This is enforced via
- * a wrapper object.
- *
- * The callback is run on Dispatchers.IO by default.
- *
- * If a channel for that slot / port is not found, EuiccChannelNotFoundException is thrown
+ * Returns all EuiccChannels corresponding to a **physical** slot
+ * Multiple channels are possible in the case of MEP
*/
- suspend fun withEuiccChannel(
- physicalSlotId: Int,
- portId: Int,
- fn: suspend (EuiccChannel) -> R
- ): R
+ suspend fun findAllEuiccChannelsByPhysicalSlot(physicalSlotId: Int): List?
+ fun findAllEuiccChannelsByPhysicalSlotBlocking(physicalSlotId: Int): List?
/**
- * Same as withEuiccChannel(Int, Int, (EuiccChannel) -> R) but instead uses logical slot ID
+ * Returns the EuiccChannel corresponding to a **physical** slot and a port ID
*/
- suspend fun withEuiccChannel(
- logicalSlotId: Int,
- fn: suspend (EuiccChannel) -> R
- ): R
+ suspend fun findEuiccChannelByPort(physicalSlotId: Int, portId: Int): EuiccChannel?
+ fun findEuiccChannelByPortBlocking(physicalSlotId: Int, portId: Int): EuiccChannel?
/**
* Invalidate all EuiccChannels previously cached by this Manager
@@ -102,7 +74,7 @@ interface EuiccChannelManager {
* This is only expected to be implemented when the application is privileged
* TODO: Remove this from the common interface
*/
- suspend fun notifyEuiccProfilesChanged(logicalSlotId: Int) {
+ fun notifyEuiccProfilesChanged(logicalSlotId: Int) {
// no-op by default
}
}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelWrapper.kt b/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelWrapper.kt
deleted file mode 100644
index 361a943..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelWrapper.kt
+++ /dev/null
@@ -1,53 +0,0 @@
-package im.angry.openeuicc.core
-
-import im.angry.openeuicc.util.*
-import net.typeblog.lpac_jni.ApduInterface
-import net.typeblog.lpac_jni.LocalProfileAssistant
-
-class EuiccChannelWrapper(orig: EuiccChannel) : EuiccChannel {
- private var _inner: EuiccChannel? = orig
-
- private val channel: EuiccChannel
- get() {
- if (_inner == null) {
- throw IllegalStateException("This wrapper has been invalidated")
- }
-
- return _inner!!
- }
-
- override val type: String
- get() = channel.type
- override val port: UiccPortInfoCompat
- get() = channel.port
- override val slotId: Int
- get() = channel.slotId
- override val logicalSlotId: Int
- get() = channel.logicalSlotId
- override val portId: Int
- get() = channel.portId
- private val lpaDelegate = lazy {
- LocalProfileAssistantWrapper(channel.lpa)
- }
- override val lpa: LocalProfileAssistant by lpaDelegate
- override val valid: Boolean
- get() = channel.valid
- override val intrinsicChannelName: String?
- get() = channel.intrinsicChannelName
- override val apduInterface: ApduInterface
- get() = channel.apduInterface
- override val atr: ByteArray?
- get() = channel.atr
- override val isdrAid: ByteArray
- get() = channel.isdrAid
-
- override fun close() = channel.close()
-
- fun invalidateWrapper() {
- _inner = null
-
- if (lpaDelegate.isInitialized()) {
- (lpa as LocalProfileAssistantWrapper).invalidateWrapper()
- }
- }
-}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/core/LocalProfileAssistantWrapper.kt b/app-common/src/main/java/im/angry/openeuicc/core/LocalProfileAssistantWrapper.kt
deleted file mode 100644
index b715ca0..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/core/LocalProfileAssistantWrapper.kt
+++ /dev/null
@@ -1,66 +0,0 @@
-package im.angry.openeuicc.core
-
-import net.typeblog.lpac_jni.EuiccInfo2
-import net.typeblog.lpac_jni.LocalProfileAssistant
-import net.typeblog.lpac_jni.LocalProfileInfo
-import net.typeblog.lpac_jni.LocalProfileNotification
-import net.typeblog.lpac_jni.ProfileDownloadCallback
-
-class LocalProfileAssistantWrapper(orig: LocalProfileAssistant) :
- LocalProfileAssistant {
- private var _inner: LocalProfileAssistant? = orig
-
- private val lpa: LocalProfileAssistant
- get() {
- if (_inner == null) {
- throw IllegalStateException("This wrapper has been invalidated")
- }
-
- return _inner!!
- }
-
- override val valid: Boolean
- get() = lpa.valid
- override val profiles: List
- get() = lpa.profiles
- override val notifications: List
- get() = lpa.notifications
- override val eID: String
- get() = lpa.eID
- override val euiccInfo2: EuiccInfo2?
- get() = lpa.euiccInfo2
-
- override fun setEs10xMss(mss: Byte) = lpa.setEs10xMss(mss)
-
- override fun enableProfile(iccid: String, refresh: Boolean): Boolean =
- lpa.enableProfile(iccid, refresh)
-
- override fun disableProfile(iccid: String, refresh: Boolean): Boolean =
- lpa.disableProfile(iccid, refresh)
-
- override fun deleteProfile(iccid: String): Boolean = lpa.deleteProfile(iccid)
-
- override fun downloadProfile(
- smdp: String,
- matchingId: String?,
- imei: String?,
- confirmationCode: String?,
- callback: ProfileDownloadCallback
- ) = lpa.downloadProfile(smdp, matchingId, imei, confirmationCode, callback)
-
- override fun deleteNotification(seqNumber: Long): Boolean = lpa.deleteNotification(seqNumber)
-
- override fun handleNotification(seqNumber: Long): Boolean = lpa.handleNotification(seqNumber)
-
- override fun euiccMemoryReset() = lpa.euiccMemoryReset()
-
- override fun setNickname(iccid: String, nickname: String) {
- lpa.setNickname(iccid, nickname)
- }
-
- override fun close() = lpa.close()
-
- fun invalidateWrapper() {
- _inner = null
- }
-}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/core/OmapiApduInterface.kt b/app-common/src/main/java/im/angry/openeuicc/core/OmapiApduInterface.kt
index f918494..227977c 100644
--- a/app-common/src/main/java/im/angry/openeuicc/core/OmapiApduInterface.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/core/OmapiApduInterface.kt
@@ -3,33 +3,19 @@ package im.angry.openeuicc.core
import android.se.omapi.Channel
import android.se.omapi.SEService
import android.se.omapi.Session
-import android.util.Log
import im.angry.openeuicc.util.*
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.runBlocking
import net.typeblog.lpac_jni.ApduInterface
-import java.util.concurrent.atomic.AtomicInteger
class OmapiApduInterface(
private val service: SEService,
- private val port: UiccPortInfoCompat,
- private val verboseLoggingFlow: Flow
-): ApduInterface, ApduInterfaceAtrProvider {
- companion object {
- const val TAG = "OmapiApduInterface"
- }
-
+ private val port: UiccPortInfoCompat
+): ApduInterface {
private lateinit var session: Session
- private val index = AtomicInteger(0)
- private val channels = mutableMapOf()
+ private lateinit var lastChannel: Channel
override val valid: Boolean
get() = service.isConnected && (this::session.isInitialized && !session.isClosed)
- override val atr: ByteArray?
- get() = session.atr
-
override fun connect() {
session = service.getUiccReaderCompat(port.logicalSlotIndex + 1).openSession()
}
@@ -39,48 +25,26 @@ class OmapiApduInterface(
}
override fun logicalChannelOpen(aid: ByteArray): Int {
- val channel = session.openLogicalChannel(aid)
- check(channel != null) { "Failed to open logical channel (${aid.encodeHex()})" }
- val handle = index.incrementAndGet()
- synchronized(channels) { channels[handle] = channel }
- return handle
+ check(!this::lastChannel.isInitialized) {
+ "Can only open one channel"
+ }
+ lastChannel = session.openLogicalChannel(aid)!!;
+ return 1;
}
override fun logicalChannelClose(handle: Int) {
- val channel = channels[handle]
- check(channel != null) { "Invalid logical channel handle $handle" }
- if (channel.isOpen) channel.close()
- synchronized(channels) { channels.remove(handle) }
+ check(handle == 1 && !this::lastChannel.isInitialized) {
+ "Unknown channel"
+ }
+ lastChannel.close()
}
- override fun transmit(handle: Int, tx: ByteArray): ByteArray {
- val channel = channels[handle]
- check(channel != null) { "Invalid logical channel handle $handle" }
-
- if (runBlocking { verboseLoggingFlow.first() }) {
- Log.d(TAG, "OMAPI APDU: ${tx.encodeHex()}")
+ override fun transmit(tx: ByteArray): ByteArray {
+ check(this::lastChannel.isInitialized) {
+ "Unknown channel"
}
- try {
- for (i in 0..10) {
- val res = channel.transmit(tx)
- if (runBlocking { verboseLoggingFlow.first() }) {
- Log.d(TAG, "OMAPI APDU response: ${res.encodeHex()}")
- }
-
- if (res.size == 2 && res[0] == 0x66.toByte() && res[1] == 0x01.toByte()) {
- Log.d(TAG, "Received checksum error 0x6601, retrying (count = $i)")
- continue
- }
-
- return res
- }
-
- throw RuntimeException("Retransmit attempts exhausted; this was likely caused by checksum errors")
- } catch (e: Exception) {
- Log.e(TAG, "OMAPI APDU exception")
- e.printStackTrace()
- throw e
- }
+ return lastChannel.transmit(tx)
}
+
}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbApduInterface.kt b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbApduInterface.kt
index 4a4ccb9..fb93ff6 100644
--- a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbApduInterface.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbApduInterface.kt
@@ -1,41 +1,49 @@
package im.angry.openeuicc.core.usb
+import android.hardware.usb.UsbDeviceConnection
+import android.hardware.usb.UsbEndpoint
import android.util.Log
-import im.angry.openeuicc.core.ApduInterfaceAtrProvider
import im.angry.openeuicc.util.*
import net.typeblog.lpac_jni.ApduInterface
class UsbApduInterface(
- private val ccidCtx: UsbCcidContext
-) : ApduInterface, ApduInterfaceAtrProvider {
+ private val conn: UsbDeviceConnection,
+ private val bulkIn: UsbEndpoint,
+ private val bulkOut: UsbEndpoint
+): ApduInterface {
companion object {
private const val TAG = "UsbApduInterface"
}
- override val atr: ByteArray?
- get() = ccidCtx.atr
+ private lateinit var ccidDescription: UsbCcidDescription
+ private lateinit var transceiver: UsbCcidTransceiver
- override val valid: Boolean
- get() = channels.isNotEmpty()
-
- private var channels = mutableSetOf()
+ private var channelId = -1
override fun connect() {
- ccidCtx.connect()
+ ccidDescription = UsbCcidDescription.fromRawDescriptors(conn.rawDescriptors)!!
- // Send Terminal Capabilities
- // Specs: ETSI TS 102 221 v15.0.0 - 11.1.19 TERMINAL CAPABILITY
- val terminalCapabilities = buildCmd(
- 0x80.toByte(), 0xaa.toByte(), 0x00, 0x00,
- "A9088100820101830107".decodeHex(),
- le = null,
- )
- transmitApduByChannel(terminalCapabilities, 0)
+ if (!ccidDescription.hasT0Protocol) {
+ throw IllegalArgumentException("Unsupported card reader; T=0 support is required")
+ }
+
+ transceiver = UsbCcidTransceiver(conn, bulkIn, bulkOut, ccidDescription)
+
+ try {
+ transceiver.iccPowerOn()
+ } catch (e: Exception) {
+ e.printStackTrace()
+ throw e
+ }
}
- override fun disconnect() = ccidCtx.disconnect()
+ override fun disconnect() {
+ conn.close()
+ }
override fun logicalChannelOpen(aid: ByteArray): Int {
+ check(channelId == -1) { "Logical channel already opened" }
+
// OPEN LOGICAL CHANNEL
val req = manageChannelCmd(true, 0)
@@ -51,7 +59,7 @@ class UsbApduInterface(
return -1
}
- val channelId = resp[0].toInt()
+ channelId = resp[0].toInt()
Log.d(TAG, "channelId = $channelId")
// Then, select AID
@@ -63,32 +71,32 @@ class UsbApduInterface(
return -1
}
- channels.add(channelId)
-
return channelId
}
override fun logicalChannelClose(handle: Int) {
- check(channels.contains(handle)) {
- "Invalid logical channel handle $handle"
- }
+ check(handle == channelId) { "Logical channel ID mismatch" }
+ check(channelId != -1) { "Logical channel is not opened" }
+
// CLOSE LOGICAL CHANNEL
- val req = manageChannelCmd(false, handle.toByte())
- val resp = transmitApduByChannel(req, handle.toByte())
+ val req = manageChannelCmd(false, channelId.toByte())
+ val resp = transmitApduByChannel(req, channelId.toByte())
if (!isSuccessResponse(resp)) {
Log.d(TAG, "CLOSE LOGICAL CHANNEL failed: ${resp.encodeHex()}")
}
- channels.remove(handle)
+
+ channelId = -1
}
- override fun transmit(handle: Int, tx: ByteArray): ByteArray {
- check(channels.contains(handle)) {
- "Invalid logical channel handle $handle"
- }
- return transmitApduByChannel(tx, handle.toByte())
+ override fun transmit(tx: ByteArray): ByteArray {
+ check(channelId != -1) { "Logical channel is not opened" }
+ return transmitApduByChannel(tx, channelId.toByte())
}
+ override val valid: Boolean
+ get() = channelId != -1
+
private fun isSuccessResponse(resp: ByteArray): Boolean =
resp.size >= 2 && resp[resp.size - 2] == 0x90.toByte() && resp[resp.size - 1] == 0x00.toByte()
@@ -122,7 +130,7 @@ class UsbApduInterface(
// OR the channel mask into the CLA byte
realTx[0] = ((realTx[0].toInt() and 0xFC) or channel.toInt()).toByte()
- var resp = ccidCtx.transceiver.sendXfrBlock(realTx).data!!
+ var resp = transceiver.sendXfrBlock(realTx).data!!
if (resp.size < 2) throw RuntimeException("APDU response smaller than 2 (sw1 + sw2)!")
@@ -133,7 +141,7 @@ class UsbApduInterface(
// 0x6C = wrong le
// so we fix the le field here
realTx[realTx.size - 1] = resp[resp.size - 1]
- resp = ccidCtx.transceiver.sendXfrBlock(realTx).data!!
+ resp = transceiver.sendXfrBlock(realTx).data!!
} else if (sw1 == 0x61) {
// 0x61 = X bytes available
// continue reading by GET RESPONSE
@@ -143,7 +151,7 @@ class UsbApduInterface(
realTx[0], 0xC0.toByte(), 0x00, 0x00, sw2.toByte()
)
- val tmp = ccidCtx.transceiver.sendXfrBlock(getResponseCmd).data!!
+ val tmp = transceiver.sendXfrBlock(getResponseCmd).data!!
resp = resp.sliceArray(0 until (resp.size - 2)) + tmp
diff --git a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidContext.kt b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidContext.kt
deleted file mode 100644
index caf69e7..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidContext.kt
+++ /dev/null
@@ -1,87 +0,0 @@
-package im.angry.openeuicc.core.usb
-
-import android.content.Context
-import android.hardware.usb.UsbDevice
-import android.hardware.usb.UsbDeviceConnection
-import android.hardware.usb.UsbEndpoint
-import android.hardware.usb.UsbInterface
-import android.hardware.usb.UsbManager
-import im.angry.openeuicc.util.preferenceRepository
-import kotlinx.coroutines.flow.Flow
-
-/**
- * A wrapper over an usb device + interface, manages the lifecycle independent
- * of the APDU interface exposed to lpac-jni.
- *
- * This allows us to try multiple AIDs on each interface without opening / closing
- * the USB connection numerous times.
- */
-class UsbCcidContext private constructor(
- private val conn: UsbDeviceConnection,
- private val bulkIn: UsbEndpoint,
- private val bulkOut: UsbEndpoint,
- val productName: String,
- val verboseLoggingFlow: Flow
-) {
- companion object {
- fun createFromUsbDevice(
- context: Context,
- usbDevice: UsbDevice,
- usbInterface: UsbInterface
- ): UsbCcidContext? = runCatching {
- val (bulkIn, bulkOut) = usbInterface.endpoints.bulkPair
- if (bulkIn == null || bulkOut == null) return@runCatching null
- val conn = context.getSystemService(UsbManager::class.java).openDevice(usbDevice)
- ?: return@runCatching null
- if (!conn.claimInterface(usbInterface, true)) return@runCatching null
- UsbCcidContext(
- conn,
- bulkIn,
- bulkOut,
- usbDevice.productName ?: "USB",
- context.preferenceRepository.verboseLoggingFlow
- )
- }.getOrNull()
- }
-
- /**
- * When set to false (the default), the disconnect() method does nothing.
- * This allows the separation of device disconnection from lpac-jni's APDU interface.
- */
- var allowDisconnect = false
- private var initialized = false
- lateinit var transceiver: UsbCcidTransceiver
- var atr: ByteArray? = null
-
- fun connect() {
- if (initialized) {
- return
- }
-
- val ccidDescription = UsbCcidDescription.fromRawDescriptors(conn.rawDescriptors)!!
-
- if (!ccidDescription.hasT0Protocol) {
- throw IllegalArgumentException("Unsupported card reader; T=0 support is required")
- }
-
- transceiver = UsbCcidTransceiver(conn, bulkIn, bulkOut, ccidDescription, verboseLoggingFlow)
-
- try {
- // 6.1.1.1 PC_to_RDR_IccPowerOn (Page 20 of 40)
- // https://www.usb.org/sites/default/files/DWG_Smart-Card_USB-ICC_ICCD_rev10.pdf
- atr = transceiver.iccPowerOn().data
- } catch (e: Exception) {
- e.printStackTrace()
- throw e
- }
-
- initialized = true
- }
-
- fun disconnect() {
- if (initialized && allowDisconnect) {
- conn.close()
- atr = null
- }
- }
-}
diff --git a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidDescription.kt b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidDescription.kt
index bc32fb6..5123d53 100644
--- a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidDescription.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidDescription.kt
@@ -20,12 +20,12 @@ data class UsbCcidDescription(
private const val FEATURE_EXCHANGE_LEVEL_TPDU = 0x10000
private const val FEATURE_EXCHANGE_LEVEL_SHORT_APDU = 0x20000
- private const val FEATURE_EXCHANGE_LEVEL_EXTENDED_APDU = 0x40000
+ private const val FEATURE_EXCHAGE_LEVEL_EXTENDED_APDU = 0x40000
// bVoltageSupport Masks
- private const val VOLTAGE_5V0: Byte = 1
- private const val VOLTAGE_3V0: Byte = 2
- private const val VOLTAGE_1V8: Byte = 4
+ private const val VOLTAGE_5V: Byte = 1
+ private const val VOLTAGE_3V: Byte = 2
+ private const val VOLTAGE_1_8V: Byte = 4
private const val SLOT_OFFSET = 4
private const val FEATURES_OFFSET = 40
@@ -71,24 +71,31 @@ data class UsbCcidDescription(
}
enum class Voltage(powerOnValue: Int, mask: Int) {
- // @formatter:off
- AUTO(0, 0),
- V50(1, VOLTAGE_5V0.toInt()),
- V30(2, VOLTAGE_3V0.toInt()),
- V18(3, VOLTAGE_1V8.toInt());
- // @formatter:on
+ AUTO(0, 0), _5V(1, VOLTAGE_5V.toInt()), _3V(2, VOLTAGE_3V.toInt()), _1_8V(
+ 3,
+ VOLTAGE_1_8V.toInt()
+ );
val mask = powerOnValue.toByte()
val powerOnValue = mask.toByte()
}
- private fun hasFeature(feature: Int) = (dwFeatures and feature) != 0
+ private fun hasFeature(feature: Int): Boolean =
+ (dwFeatures and feature) != 0
- val voltages: List
- get() {
- if (hasFeature(FEATURE_AUTOMATIC_VOLTAGE)) return listOf(Voltage.AUTO)
- return Voltage.entries.filter { (it.mask.toInt() and bVoltageSupport.toInt()) != 0 }
- }
+ val voltages: Array
+ get() =
+ if (hasFeature(FEATURE_AUTOMATIC_VOLTAGE)) {
+ arrayOf(Voltage.AUTO)
+ } else {
+ Voltage.values().mapNotNull {
+ if ((it.mask.toInt() and bVoltageSupport.toInt()) != 0) {
+ it
+ } else {
+ null
+ }
+ }.toTypedArray()
+ }
val hasAutomaticPps: Boolean
get() = hasFeature(FEATURE_AUTOMATIC_PPS)
diff --git a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidTransceiver.kt b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidTransceiver.kt
index 9155721..09d324b 100644
--- a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidTransceiver.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidTransceiver.kt
@@ -5,9 +5,6 @@ import android.hardware.usb.UsbEndpoint
import android.os.SystemClock
import android.util.Log
import im.angry.openeuicc.util.*
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.runBlocking
import java.nio.ByteBuffer
import java.nio.ByteOrder
@@ -21,8 +18,7 @@ class UsbCcidTransceiver(
private val usbConnection: UsbDeviceConnection,
private val usbBulkIn: UsbEndpoint,
private val usbBulkOut: UsbEndpoint,
- private val usbCcidDescription: UsbCcidDescription,
- private val verboseLoggingFlow: Flow
+ private val usbCcidDescription: UsbCcidDescription
) {
companion object {
private const val TAG = "UsbCcidTransceiver"
@@ -95,7 +91,6 @@ class UsbCcidTransceiver(
data class UsbCcidErrorException(val msg: String, val errorResponse: CcidDataBlock) :
Exception(msg)
- @Suppress("ArrayInDataClass")
data class CcidDataBlock(
val dwLength: Int,
val bSlot: Byte,
@@ -183,27 +178,30 @@ class UsbCcidTransceiver(
readBytes = usbConnection.bulkTransfer(
usbBulkIn, inputBuffer, inputBuffer.size, DEVICE_COMMUNICATE_TIMEOUT_MILLIS
)
- if (runBlocking { verboseLoggingFlow.first() }) {
- Log.d(TAG, "Received $readBytes bytes: ${inputBuffer.encodeHex()}")
- }
+ Log.d(TAG, "Received " + readBytes + " bytes: " + inputBuffer.encodeHex())
} while (readBytes <= 0 && attempts-- > 0)
if (readBytes < CCID_HEADER_LENGTH) {
throw UsbTransportException("USB-CCID error - failed to receive CCID header")
}
if (inputBuffer[0] != MESSAGE_TYPE_RDR_TO_PC_DATA_BLOCK.toByte()) {
- throw UsbTransportException(buildString {
- append("USB-CCID error - bad CCID header")
- append(", type ")
- append("%d (expected %d)".format(inputBuffer[0], MESSAGE_TYPE_RDR_TO_PC_DATA_BLOCK))
- if (expectedSequenceNumber != inputBuffer[6]) {
- append(", sequence number ")
- append("%d (expected %d)".format(inputBuffer[6], expectedSequenceNumber))
- }
- })
+ if (expectedSequenceNumber != inputBuffer[6]) {
+ throw UsbTransportException(
+ ((("USB-CCID error - bad CCID header, type " + inputBuffer[0]) + " (expected " +
+ MESSAGE_TYPE_RDR_TO_PC_DATA_BLOCK) + "), sequence number " + inputBuffer[6]
+ ) + " (expected " +
+ expectedSequenceNumber + ")"
+ )
+ }
+ throw UsbTransportException(
+ "USB-CCID error - bad CCID header type " + inputBuffer[0]
+ )
}
var result = CcidDataBlock.parseHeaderFromBytes(inputBuffer)
if (expectedSequenceNumber != result.bSeq) {
- throw UsbTransportException("USB-CCID error - expected sequence number $expectedSequenceNumber, got $result")
+ throw UsbTransportException(
+ ("USB-CCID error - expected sequence number " +
+ expectedSequenceNumber + ", got " + result)
+ )
}
val dataBuffer = ByteArray(result.dwLength)
@@ -214,7 +212,9 @@ class UsbCcidTransceiver(
usbBulkIn, inputBuffer, inputBuffer.size, DEVICE_COMMUNICATE_TIMEOUT_MILLIS
)
if (readBytes < 0) {
- throw UsbTransportException("USB error - failed reading response data! Header: $result")
+ throw UsbTransportException(
+ "USB error - failed reading response data! Header: $result"
+ )
}
System.arraycopy(inputBuffer, 0, dataBuffer, bufferedBytes, readBytes)
bufferedBytes += readBytes
@@ -279,7 +279,7 @@ class UsbCcidTransceiver(
}
val ccidDataBlock = receiveDataBlock(sequenceNumber)
val elapsedTime = SystemClock.elapsedRealtime() - startTime
- Log.d(TAG, "USB XferBlock call took ${elapsedTime}ms")
+ Log.d(TAG, "USB XferBlock call took " + elapsedTime + "ms")
return ccidDataBlock
}
@@ -287,13 +287,13 @@ class UsbCcidTransceiver(
val startTime = SystemClock.elapsedRealtime()
skipAvailableInput()
var response: CcidDataBlock? = null
- for (voltage in usbCcidDescription.voltages) {
- Log.v(TAG, "CCID: attempting to power on with voltage $voltage")
+ for (v in usbCcidDescription.voltages) {
+ Log.v(TAG, "CCID: attempting to power on with voltage $v")
response = try {
- iccPowerOnVoltage(voltage.powerOnValue)
+ iccPowerOnVoltage(v.powerOnValue)
} catch (e: UsbCcidErrorException) {
if (e.errorResponse.bError.toInt() == 7) { // Power select error
- Log.v(TAG, "CCID: failed to power on with voltage $voltage")
+ Log.v(TAG, "CCID: failed to power on with voltage $v")
iccPowerOff()
Log.v(TAG, "CCID: powered off")
continue
@@ -308,11 +308,8 @@ class UsbCcidTransceiver(
val elapsedTime = SystemClock.elapsedRealtime() - startTime
Log.d(
TAG,
- buildString {
- append("Usb transport connected")
- append(", took ", elapsedTime, "ms")
- append(", ATR=", response.data?.encodeHex())
- }
+ "Usb transport connected, took " + elapsedTime + "ms, ATR=" +
+ response.data?.encodeHex()
)
return response
}
diff --git a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidUtils.kt b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidUtils.kt
index 877c7fd..edca7a0 100644
--- a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidUtils.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidUtils.kt
@@ -6,22 +6,31 @@ import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbInterface
-class UsbTransportException(message: String) : Exception(message)
+class UsbTransportException(msg: String) : Exception(msg)
-val UsbDevice.interfaces: Iterable
- get() = (0 until interfaceCount).map(::getInterface)
-
-val Iterable.smartCard: UsbInterface?
- get() = find { it.interfaceClass == UsbConstants.USB_CLASS_CSCID }
-
-val UsbInterface.endpoints: Iterable
- get() = (0 until endpointCount).map(::getEndpoint)
-
-val Iterable.bulkPair: Pair
- get() {
- val endpoints = filter { it.type == UsbConstants.USB_ENDPOINT_XFER_BULK }
- return Pair(
- endpoints.find { it.direction == UsbConstants.USB_DIR_IN },
- endpoints.find { it.direction == UsbConstants.USB_DIR_OUT },
- )
+fun UsbInterface.getIoEndpoints(): Pair {
+ var bulkIn: UsbEndpoint? = null
+ var bulkOut: UsbEndpoint? = null
+ for (i in 0 until endpointCount) {
+ val endpoint = getEndpoint(i)
+ if (endpoint.type != UsbConstants.USB_ENDPOINT_XFER_BULK) {
+ continue
+ }
+ if (endpoint.direction == UsbConstants.USB_DIR_IN) {
+ bulkIn = endpoint
+ } else if (endpoint.direction == UsbConstants.USB_DIR_OUT) {
+ bulkOut = endpoint
+ }
}
+ return Pair(bulkIn, bulkOut)
+}
+
+fun UsbDevice.getSmartCardInterface(): UsbInterface? {
+ for (i in 0 until interfaceCount) {
+ val anInterface = getInterface(i)
+ if (anInterface.interfaceClass == UsbConstants.USB_CLASS_CSCID) {
+ return anInterface
+ }
+ }
+ return null
+}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/di/AppContainer.kt b/app-common/src/main/java/im/angry/openeuicc/di/AppContainer.kt
index cae7e2e..4b3c3cd 100644
--- a/app-common/src/main/java/im/angry/openeuicc/di/AppContainer.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/di/AppContainer.kt
@@ -15,5 +15,4 @@ interface AppContainer {
val preferenceRepository: PreferenceRepository
val uiComponentFactory: UiComponentFactory
val euiccChannelFactory: EuiccChannelFactory
- val customizableTextProvider: CustomizableTextProvider
}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/di/CustomizableTextProvider.kt b/app-common/src/main/java/im/angry/openeuicc/di/CustomizableTextProvider.kt
deleted file mode 100644
index 2c86273..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/di/CustomizableTextProvider.kt
+++ /dev/null
@@ -1,20 +0,0 @@
-package im.angry.openeuicc.di
-
-interface CustomizableTextProvider {
- /**
- * Explanation string for when no eUICC is found on the device.
- * This could be different depending on whether the app is privileged or not.
- */
- val noEuiccExplanation: String
-
- /**
- * Shown when we timed out switching between profiles.
- */
- val profileSwitchingTimeoutMessage: String
-
- /**
- * Format the name of a logical slot; internal only -- not intended for
- * other channels such as USB.
- */
- fun formatInternalChannelName(logicalSlotId: Int): String
-}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/di/DefaultAppContainer.kt b/app-common/src/main/java/im/angry/openeuicc/di/DefaultAppContainer.kt
index 9b70099..93fd8b8 100644
--- a/app-common/src/main/java/im/angry/openeuicc/di/DefaultAppContainer.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/di/DefaultAppContainer.kt
@@ -38,8 +38,4 @@ open class DefaultAppContainer(context: Context) : AppContainer {
override val euiccChannelFactory by lazy {
DefaultEuiccChannelFactory(context)
}
-
- override val customizableTextProvider by lazy {
- DefaultCustomizableTextProvider(context)
- }
}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/di/DefaultCustomizableTextProvider.kt b/app-common/src/main/java/im/angry/openeuicc/di/DefaultCustomizableTextProvider.kt
deleted file mode 100644
index 76227fd..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/di/DefaultCustomizableTextProvider.kt
+++ /dev/null
@@ -1,15 +0,0 @@
-package im.angry.openeuicc.di
-
-import android.content.Context
-import im.angry.openeuicc.common.R
-
-open class DefaultCustomizableTextProvider(private val context: Context) : CustomizableTextProvider {
- override val noEuiccExplanation: String
- get() = context.getString(R.string.no_euicc)
-
- override val profileSwitchingTimeoutMessage: String
- get() = context.getString(R.string.profile_switch_timeout)
-
- override fun formatInternalChannelName(logicalSlotId: Int): String =
- context.getString(R.string.channel_name_format, logicalSlotId)
-}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/di/DefaultUiComponentFactory.kt b/app-common/src/main/java/im/angry/openeuicc/di/DefaultUiComponentFactory.kt
index 52a501a..32550d6 100644
--- a/app-common/src/main/java/im/angry/openeuicc/di/DefaultUiComponentFactory.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/di/DefaultUiComponentFactory.kt
@@ -1,16 +1,13 @@
package im.angry.openeuicc.di
import androidx.fragment.app.Fragment
-import androidx.preference.PreferenceFragmentCompat
+import im.angry.openeuicc.core.EuiccChannel
import im.angry.openeuicc.ui.EuiccManagementFragment
import im.angry.openeuicc.ui.NoEuiccPlaceholderFragment
-import im.angry.openeuicc.ui.SettingsFragment
open class DefaultUiComponentFactory : UiComponentFactory {
- override fun createEuiccManagementFragment(slotId: Int, portId: Int): EuiccManagementFragment =
- EuiccManagementFragment.newInstance(slotId, portId)
+ override fun createEuiccManagementFragment(channel: EuiccChannel): EuiccManagementFragment =
+ EuiccManagementFragment.newInstance(channel.slotId, channel.portId)
override fun createNoEuiccPlaceholderFragment(): Fragment = NoEuiccPlaceholderFragment()
-
- override fun createSettingsFragment(): Fragment = SettingsFragment()
}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/di/UiComponentFactory.kt b/app-common/src/main/java/im/angry/openeuicc/di/UiComponentFactory.kt
index 2c3c72b..4e09a70 100644
--- a/app-common/src/main/java/im/angry/openeuicc/di/UiComponentFactory.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/di/UiComponentFactory.kt
@@ -1,11 +1,10 @@
package im.angry.openeuicc.di
import androidx.fragment.app.Fragment
-import androidx.preference.PreferenceFragmentCompat
+import im.angry.openeuicc.core.EuiccChannel
import im.angry.openeuicc.ui.EuiccManagementFragment
interface UiComponentFactory {
- fun createEuiccManagementFragment(slotId: Int, portId: Int): EuiccManagementFragment
+ fun createEuiccManagementFragment(channel: EuiccChannel): EuiccManagementFragment
fun createNoEuiccPlaceholderFragment(): Fragment
- fun createSettingsFragment(): Fragment
}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/service/EuiccChannelManagerService.kt b/app-common/src/main/java/im/angry/openeuicc/service/EuiccChannelManagerService.kt
index 4744321..75c58db 100644
--- a/app-common/src/main/java/im/angry/openeuicc/service/EuiccChannelManagerService.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/service/EuiccChannelManagerService.kt
@@ -1,42 +1,11 @@
package im.angry.openeuicc.service
+import android.app.Service
import android.content.Intent
-import android.content.pm.PackageManager
import android.os.Binder
import android.os.IBinder
-import android.os.PowerManager
-import android.util.Log
-import androidx.core.app.NotificationChannelCompat
-import androidx.core.app.NotificationCompat
-import androidx.core.app.NotificationManagerCompat
-import androidx.lifecycle.LifecycleService
-import androidx.lifecycle.lifecycleScope
-import im.angry.openeuicc.common.R
import im.angry.openeuicc.core.EuiccChannelManager
import im.angry.openeuicc.util.*
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.NonCancellable
-import kotlinx.coroutines.channels.BufferOverflow
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.MutableSharedFlow
-import kotlinx.coroutines.flow.MutableStateFlow
-import kotlinx.coroutines.flow.SharedFlow
-import kotlinx.coroutines.flow.asSharedFlow
-import kotlinx.coroutines.flow.collect
-import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.flow.flow
-import kotlinx.coroutines.flow.last
-import kotlinx.coroutines.flow.onCompletion
-import kotlinx.coroutines.flow.onEach
-import kotlinx.coroutines.flow.takeWhile
-import kotlinx.coroutines.flow.transformWhile
-import kotlinx.coroutines.isActive
-import kotlinx.coroutines.launch
-import kotlinx.coroutines.withContext
-import kotlinx.coroutines.withTimeoutOrNull
-import kotlinx.coroutines.yield
-import net.typeblog.lpac_jni.ProfileDownloadCallback
/**
* An Android Service wrapper for EuiccChannelManager.
@@ -48,41 +17,8 @@ import net.typeblog.lpac_jni.ProfileDownloadCallback
* instance of EuiccChannelManager. UI components can keep being bound to this service for
* their entire lifecycles, since the whole purpose of them is to expose the current state
* to the user.
- *
- * Additionally, this service is also responsible for long-running "foreground" tasks that
- * are not suitable to be managed by UI components. This includes profile downloading, etc.
- * When a UI component needs to run one of these tasks, they have to bind to this service
- * and call one of the `launch*` methods, which will run the task inside this service's
- * lifecycle context and return a Flow instance for the UI component to subscribe to its
- * progress.
*/
-class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
- companion object {
- private const val TAG = "EuiccChannelManagerService"
- private const val CHANNEL_ID = "tasks"
- private const val FOREGROUND_ID = 1000
- private const val TASK_FAILURE_ID = 1000
-
- /**
- * Utility function to wait for a foreground task to be done, return its
- * error if any, or null on success.
- */
- suspend fun Flow.waitDone(): Throwable? =
- (this.last() as ForegroundTaskState.Done).error
-
- /**
- * Apply transform to a ForegroundTaskState flow so that it completes when a Done is seen.
- *
- * This must be applied each time a flow is returned for subscription purposes. If applied
- * beforehand, we lose the ability to subscribe multiple times.
- */
- private fun Flow.applyCompletionTransform() =
- transformWhile {
- emit(it)
- it !is ForegroundTaskState.Done
- }
- }
-
+class EuiccChannelManagerService : Service(), OpenEuiccContextMarker {
inner class LocalBinder : Binder() {
val service = this@EuiccChannelManagerService
}
@@ -92,436 +28,14 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
}
val euiccChannelManager: EuiccChannelManager by euiccChannelManagerDelegate
- private val wakeLock: PowerManager.WakeLock by lazy {
- (getSystemService(POWER_SERVICE) as PowerManager).run {
- newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this::class.simpleName)
- }
- }
-
- /**
- * The state of a "foreground" task (named so due to the need to startForeground())
- */
- sealed interface ForegroundTaskState {
- data object Idle : ForegroundTaskState
- data class InProgress(val progress: Int) : ForegroundTaskState
- data class Done(val error: Throwable?) : ForegroundTaskState
- }
-
- /**
- * This flow emits whenever the service has had a start command, from startService()
- * The service self-starts when foreground is required, because other components
- * only bind to this service and do not start it per-se.
- */
- private val foregroundStarted: MutableSharedFlow = MutableSharedFlow()
-
- /**
- * This flow is used to emit progress updates when a foreground task is running.
- */
- private val foregroundTaskState: MutableStateFlow =
- MutableStateFlow(ForegroundTaskState.Idle)
-
- /**
- * A simple wrapper over a flow with taskId added.
- *
- * taskID is the exact millisecond-precision timestamp when the task is launched.
- */
- class ForegroundTaskSubscriberFlow(val taskId: Long, inner: Flow) :
- Flow by inner
-
- /**
- * A cache of subscribers to 5 recently-launched foreground tasks, identified by ID
- *
- * Only one can be run at the same time, but those that are done will be kept in this
- * map for a little while -- because UI components may be stopped and recreated while
- * tasks are running. Having this buffer allows the components to re-subscribe even if
- * the task completes while they are being recreated.
- */
- private val foregroundTaskSubscribers: MutableMap> =
- mutableMapOf()
-
- override fun onBind(intent: Intent): IBinder {
- super.onBind(intent)
- return LocalBinder()
- }
+ override fun onBind(intent: Intent?): IBinder = LocalBinder()
override fun onDestroy() {
super.onDestroy()
+ // This is the whole reason of the existence of this service:
+ // we can clean up opened channels when no one is using them
if (euiccChannelManagerDelegate.isInitialized()) {
euiccChannelManager.invalidate()
}
}
-
- override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
- return super.onStartCommand(intent, flags, startId).also {
- lifecycleScope.launch {
- foregroundStarted.emit(Unit)
- }
- }
- }
-
- private fun ensureForegroundTaskNotificationChannel() {
- val nm = NotificationManagerCompat.from(this)
- if (nm.getNotificationChannelCompat(CHANNEL_ID) == null) {
- val channel =
- NotificationChannelCompat.Builder(
- CHANNEL_ID,
- NotificationManagerCompat.IMPORTANCE_LOW
- )
- .setName(getString(R.string.task_notification))
- .setVibrationEnabled(false)
- .build()
- nm.createNotificationChannel(channel)
- }
- }
-
- private suspend fun updateForegroundNotification(title: String, iconRes: Int) {
- ensureForegroundTaskNotificationChannel()
-
- val nm = NotificationManagerCompat.from(this)
- val state = foregroundTaskState.value
-
- if (state is ForegroundTaskState.InProgress) {
- val notification = NotificationCompat.Builder(this, CHANNEL_ID)
- .setContentTitle(title)
- .setProgress(100, state.progress, state.progress == 0)
- .setSmallIcon(iconRes)
- .setPriority(NotificationCompat.PRIORITY_LOW)
- .setOngoing(true)
- .setOnlyAlertOnce(true)
- .build()
-
- if (state.progress == 0) {
- startForeground(FOREGROUND_ID, notification)
- } else if (checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {
- nm.notify(FOREGROUND_ID, notification)
- }
-
- // Yield out so that the main looper can handle the notification event
- // Without this yield, the notification sent above will not be shown in time.
- yield()
- } else {
- stopForeground(STOP_FOREGROUND_REMOVE)
- }
- }
-
- private fun postForegroundTaskFailureNotification(title: String) {
- if (checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
- return
- }
-
- val notification = NotificationCompat.Builder(this, CHANNEL_ID)
- .setContentTitle(title)
- .setSmallIcon(R.drawable.ic_x_black)
- .build()
- NotificationManagerCompat.from(this).notify(TASK_FAILURE_ID, notification)
- }
-
- /**
- * Recover the subscriber to a foreground task that is recently launched.
- *
- * null if the task doesn't exist, or was launched too long ago.
- */
- fun recoverForegroundTaskSubscriber(taskId: Long): ForegroundTaskSubscriberFlow? =
- foregroundTaskSubscribers[taskId]?.let {
- ForegroundTaskSubscriberFlow(taskId, it.applyCompletionTransform())
- }
-
- /**
- * Launch a potentially blocking foreground task in this service's lifecycle context.
- * This function does not block, but returns a Flow that emits ForegroundTaskState
- * updates associated with this task. The last update the returned flow will emit is
- * always ForegroundTaskState.Done.
- *
- * The returned flow can only be subscribed to once even though the underlying implementation
- * is a SharedFlow. This is due to the need to apply transformations so that the stream
- * actually completes. In order to subscribe multiple times, use `recoverForegroundTaskSubscriber`
- * to acquire another instance.
- *
- * The task closure is expected to update foregroundTaskState whenever appropriate.
- * If a foreground task is already running, this function returns null.
- *
- * To wait for foreground tasks to be available, use waitForForegroundTask().
- *
- * The function will set the state back to Idle once it sees ForegroundTaskState.Done.
- */
- private fun launchForegroundTask(
- title: String,
- failureTitle: String,
- iconRes: Int,
- task: suspend EuiccChannelManagerService.() -> Unit
- ): ForegroundTaskSubscriberFlow {
- val taskID = System.currentTimeMillis()
-
- // Atomically set the state to InProgress. If this returns true, we are
- // the only task currently in progress.
- if (!foregroundTaskState.compareAndSet(
- ForegroundTaskState.Idle,
- ForegroundTaskState.InProgress(0)
- )
- ) {
- return ForegroundTaskSubscriberFlow(
- taskID,
- flow { emit(ForegroundTaskState.Done(IllegalStateException("There are tasks currently running"))) })
- }
-
- lifecycleScope.launch(Dispatchers.Main) {
- // Wait until our self-start command has succeeded.
- // We can only call startForeground() after that
- val res = withTimeoutOrNull(30 * 1000) {
- foregroundStarted.first()
- }
-
- if (res == null) {
- // The only case where the wait above could time out is if the subscriber
- // to the flow is stuck. Or we failed to start foreground.
- // In that case, we should just set our state back to Idle -- setting it
- // to Done wouldn't help much because nothing is going to then set it Idle.
- foregroundTaskState.value = ForegroundTaskState.Idle
- return@launch
- }
-
- updateForegroundNotification(title, iconRes)
-
- wakeLock.acquire(10 * 60 * 1000L /*10 minutes*/)
-
- try {
- withContext(Dispatchers.IO + NonCancellable) { // Any LPA-related task must always complete
- this@EuiccChannelManagerService.task()
- }
- // This update will be sent by the subscriber (as shown below)
- foregroundTaskState.value = ForegroundTaskState.Done(null)
- } catch (t: Throwable) {
- Log.e(TAG, "Foreground task encountered an error")
- Log.e(TAG, Log.getStackTraceString(t))
- foregroundTaskState.value = ForegroundTaskState.Done(t)
-
- if (isActive) {
- postForegroundTaskFailureNotification(failureTitle)
- }
- } finally {
- wakeLock.release()
- if (isActive) {
- stopSelf()
- }
- }
- }
-
- // This is the flow we are going to return. We allow multiple subscribers by
- // re-emitting state updates into this flow from another coroutine.
- // replay = 2 ensures that we at least have 1 previous state whenever subscribed to.
- // This is helpful when the task completed and is then re-subscribed to due to a
- // UI recreation event -- this way, the UI will know at least one last progress event
- // before completion / failure
- val subscriberFlow = MutableSharedFlow(
- replay = 2,
- onBufferOverflow = BufferOverflow.DROP_OLDEST
- )
-
- // We should be the only task running, so we can subscribe to foregroundTaskState
- // until we encounter ForegroundTaskState.Done.
- // Then, we complete the returned flow, but we also set the state back to Idle.
- // The state update back to Idle won't show up in the returned stream, because
- // it has been completed by that point.
- lifecycleScope.launch(Dispatchers.Main) {
- foregroundTaskState
- .applyCompletionTransform()
- .onEach {
- // Also update our notification when we see an update
- // But ignore the first progress = 0 update -- that is the current value.
- // we need that to be handled by the main coroutine after it finishes.
- if (it !is ForegroundTaskState.InProgress || it.progress != 0) {
- updateForegroundNotification(title, iconRes)
- }
-
- subscriberFlow.emit(it)
- }
- .onCompletion {
- // Reset state back to Idle when we are done.
- // We do it here because otherwise Idle and Done might become conflated
- // when emitted by the main coroutine in quick succession.
- // Doing it here ensures we've seen Done. This Idle event won't be
- // emitted to the consumer because the subscription has completed here.
- foregroundTaskState.value = ForegroundTaskState.Idle
- }
- .collect()
- }
-
- foregroundTaskSubscribers[taskID] = subscriberFlow.asSharedFlow()
-
- if (foregroundTaskSubscribers.size > 5) {
- // Remove enough elements so that the size is kept at 5
- for (key in foregroundTaskSubscribers.keys.sorted()
- .take(foregroundTaskSubscribers.size - 5)) {
- foregroundTaskSubscribers.remove(key)
- }
- }
-
- // Before we return, and after we have set everything up,
- // self-start with foreground permission.
- // This is going to unblock the main coroutine handling the task.
- startForegroundService(
- Intent(
- this@EuiccChannelManagerService,
- this@EuiccChannelManagerService::class.java
- )
- )
-
- return ForegroundTaskSubscriberFlow(
- taskID,
- subscriberFlow.asSharedFlow().applyCompletionTransform()
- )
- }
-
- suspend fun waitForForegroundTask() {
- foregroundTaskState.takeWhile { it != ForegroundTaskState.Idle }
- .collect()
- }
-
- fun launchProfileDownloadTask(
- slotId: Int,
- portId: Int,
- smdp: String,
- matchingId: String?,
- confirmationCode: String?,
- imei: String?
- ): ForegroundTaskSubscriberFlow =
- launchForegroundTask(
- getString(R.string.task_profile_download),
- getString(R.string.task_profile_download_failure),
- R.drawable.ic_task_sim_card_download
- ) {
- euiccChannelManager.beginTrackedOperation(slotId, portId) {
- euiccChannelManager.withEuiccChannel(slotId, portId) { channel ->
- channel.lpa.downloadProfile(
- smdp,
- matchingId,
- imei,
- confirmationCode,
- object : ProfileDownloadCallback {
- override fun onStateUpdate(state: ProfileDownloadCallback.DownloadState) {
- if (state.progress == 0) return
- foregroundTaskState.value =
- ForegroundTaskState.InProgress(state.progress)
- }
- })
- }
-
- preferenceRepository.notificationDownloadFlow.first()
- }
- }
-
- fun launchProfileRenameTask(
- slotId: Int,
- portId: Int,
- iccid: String,
- name: String
- ): ForegroundTaskSubscriberFlow =
- launchForegroundTask(
- getString(R.string.task_profile_rename),
- getString(R.string.task_profile_rename_failure),
- R.drawable.ic_task_rename
- ) {
- euiccChannelManager.withEuiccChannel(slotId, portId) { channel ->
- channel.lpa.setNickname(
- iccid,
- name
- )
- }
- }
-
- fun launchProfileDeleteTask(
- slotId: Int,
- portId: Int,
- iccid: String
- ): ForegroundTaskSubscriberFlow =
- launchForegroundTask(
- getString(R.string.task_profile_delete),
- getString(R.string.task_profile_delete_failure),
- R.drawable.ic_task_delete
- ) {
- euiccChannelManager.beginTrackedOperation(slotId, portId) {
- euiccChannelManager.withEuiccChannel(slotId, portId) { channel ->
- channel.lpa.deleteProfile(iccid)
- }
-
- preferenceRepository.notificationDeleteFlow.first()
- }
- }
-
- class SwitchingProfilesRefreshException : Exception()
-
- fun launchProfileSwitchTask(
- slotId: Int,
- portId: Int,
- iccid: String,
- enable: Boolean, // Enable or disable the profile indicated in iccid
- reconnectTimeoutMillis: Long = 0 // 0 = do not wait for reconnect
- ) =
- launchForegroundTask(
- getString(R.string.task_profile_switch),
- getString(R.string.task_profile_switch_failure),
- R.drawable.ic_task_switch
- ) {
- euiccChannelManager.beginTrackedOperation(slotId, portId) {
- val (response, refreshed) =
- euiccChannelManager.withEuiccChannel(slotId, portId) { channel ->
- val refresh = preferenceRepository.refreshAfterSwitchFlow.first()
- val response = channel.lpa.switchProfile(iccid, enable, refresh)
- if (response || !refresh) {
- Pair(response, refresh)
- } else {
- // refresh failed, but refresh was requested
- // Sometimes, we *can* enable or disable the profile, but we cannot
- // send the refresh command to the modem because the profile somehow
- // makes the modem "busy". In this case, we can still switch by setting
- // refresh to false, but then the switch cannot take effect until the
- // user resets the modem manually by toggling airplane mode or rebooting.
- Pair(
- channel.lpa.switchProfile(iccid, enable, refresh = false),
- false
- )
- }
- }
-
- if (!response) {
- throw RuntimeException("Could not switch profile")
- }
-
- if (!refreshed && slotId != EuiccChannelManager.USB_CHANNEL_ID) {
- // We may have switched the profile, but we could not refresh. Tell the caller about this
- // but only if we are talking to a modem and not a USB reader
- throw SwitchingProfilesRefreshException()
- }
-
- if (reconnectTimeoutMillis > 0) {
- // Add an unconditional delay first to account for any race condition between
- // the card sending the refresh command and the modem actually refreshing
- delay(reconnectTimeoutMillis / 10)
-
- // This throws TimeoutCancellationException if timed out
- euiccChannelManager.waitForReconnect(
- slotId,
- portId,
- reconnectTimeoutMillis / 10 * 9
- )
- }
-
- preferenceRepository.notificationSwitchFlow.first()
- }
- }
-
- fun launchMemoryReset(slotId: Int, portId: Int): ForegroundTaskSubscriberFlow =
- launchForegroundTask(
- getString(R.string.task_euicc_memory_reset),
- getString(R.string.task_euicc_memory_reset_failure),
- R.drawable.ic_euicc_memory_reset
- ) {
- euiccChannelManager.beginTrackedOperation(slotId, portId) {
- euiccChannelManager.withEuiccChannel(slotId, portId) { channel ->
- channel.lpa.euiccMemoryReset()
- }
-
- preferenceRepository.notificationDeleteFlow.first()
- }
- }
}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/BaseEuiccAccessActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/BaseEuiccAccessActivity.kt
index ae13962..d760c76 100644
--- a/app-common/src/main/java/im/angry/openeuicc/ui/BaseEuiccAccessActivity.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/ui/BaseEuiccAccessActivity.kt
@@ -9,18 +9,14 @@ import android.os.IBinder
import androidx.appcompat.app.AppCompatActivity
import im.angry.openeuicc.core.EuiccChannelManager
import im.angry.openeuicc.service.EuiccChannelManagerService
-import kotlinx.coroutines.CompletableDeferred
abstract class BaseEuiccAccessActivity : AppCompatActivity() {
- val euiccChannelManagerLoaded = CompletableDeferred()
lateinit var euiccChannelManager: EuiccChannelManager
- lateinit var euiccChannelManagerService: EuiccChannelManagerService
private val euiccChannelManagerServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
- euiccChannelManagerService = (service!! as EuiccChannelManagerService.LocalBinder).service
- euiccChannelManager = euiccChannelManagerService.euiccChannelManager
- euiccChannelManagerLoaded.complete(Unit)
+ euiccChannelManager =
+ (service!! as EuiccChannelManagerService.LocalBinder).service.euiccChannelManager
onInit()
}
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/DirectProfileDownloadActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/DirectProfileDownloadActivity.kt
new file mode 100644
index 0000000..9e79de6
--- /dev/null
+++ b/app-common/src/main/java/im/angry/openeuicc/ui/DirectProfileDownloadActivity.kt
@@ -0,0 +1,40 @@
+package im.angry.openeuicc.ui
+
+import androidx.lifecycle.lifecycleScope
+import im.angry.openeuicc.util.*
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+
+class DirectProfileDownloadActivity : BaseEuiccAccessActivity(), SlotSelectFragment.SlotSelectedListener, OpenEuiccContextMarker {
+ override fun onInit() {
+ lifecycleScope.launch {
+ val knownChannels = withContext(Dispatchers.IO) {
+ euiccChannelManager.enumerateEuiccChannels()
+ }
+
+ when {
+ knownChannels.isEmpty() -> {
+ finish()
+ }
+ knownChannels.hasMultipleChips -> {
+ SlotSelectFragment.newInstance(knownChannels.sortedBy { it.logicalSlotId })
+ .show(supportFragmentManager, SlotSelectFragment.TAG)
+ }
+ else -> {
+ // If the device has only one eSIM "chip" (but may be mapped to multiple slots),
+ // we can skip the slot selection dialog since there is only one chip to save to.
+ onSlotSelected(knownChannels[0].slotId,
+ knownChannels[0].portId)
+ }
+ }
+ }
+ }
+
+ override fun onSlotSelected(slotId: Int, portId: Int) {
+ ProfileDownloadFragment.newInstance(slotId, portId, finishWhenDone = true)
+ .show(supportFragmentManager, ProfileDownloadFragment.TAG)
+ }
+
+ override fun onSlotSelectCancelled() = finish()
+}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccInfoActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccInfoActivity.kt
deleted file mode 100644
index 248afaf..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccInfoActivity.kt
+++ /dev/null
@@ -1,204 +0,0 @@
-package im.angry.openeuicc.ui
-
-import android.annotation.SuppressLint
-import android.content.ClipData
-import android.content.ClipboardManager
-import android.os.Build
-import android.os.Bundle
-import android.view.LayoutInflater
-import android.view.MenuItem
-import android.view.View
-import android.view.ViewGroup
-import android.widget.TextView
-import android.widget.Toast
-import androidx.activity.enableEdgeToEdge
-import androidx.annotation.StringRes
-import androidx.lifecycle.lifecycleScope
-import androidx.recyclerview.widget.DividerItemDecoration
-import androidx.recyclerview.widget.LinearLayoutManager
-import androidx.recyclerview.widget.RecyclerView
-import androidx.recyclerview.widget.RecyclerView.ViewHolder
-import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
-import im.angry.openeuicc.common.R
-import im.angry.openeuicc.core.EuiccChannel
-import im.angry.openeuicc.core.EuiccChannelManager
-import im.angry.openeuicc.util.*
-import kotlinx.coroutines.launch
-import net.typeblog.lpac_jni.impl.PKID_GSMA_LIVE_CI
-import net.typeblog.lpac_jni.impl.PKID_GSMA_TEST_CI
-
-// https://euicc-manual.osmocom.org/docs/pki/eum/accredited.json
-// ref:
-private val RE_SAS = Regex(
- """^[A-Z]{2}-[A-Z]{2}(?:-UP)?-\d{4}T?(?:-\d+)?T?$""",
- setOf(RegexOption.IGNORE_CASE),
-)
-
-class EuiccInfoActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
- companion object {
- private val YES_NO = Pair(R.string.euicc_info_yes, R.string.euicc_info_no)
- }
-
- private lateinit var swipeRefresh: SwipeRefreshLayout
- private lateinit var infoList: RecyclerView
-
- private var logicalSlotId: Int = -1
-
- data class Item(
- @StringRes
- val titleResId: Int,
- val content: String?,
- val copiedToastResId: Int? = null,
- )
-
- override fun onCreate(savedInstanceState: Bundle?) {
- enableEdgeToEdge()
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_euicc_info)
- setSupportActionBar(requireViewById(R.id.toolbar))
- setupToolbarInsets()
- supportActionBar!!.setDisplayHomeAsUpEnabled(true)
-
- swipeRefresh = requireViewById(R.id.swipe_refresh)
- infoList = requireViewById(R.id.recycler_view).also {
- it.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
- it.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL))
- it.adapter = EuiccInfoAdapter()
- }
-
- logicalSlotId = intent.getIntExtra("logicalSlotId", 0)
-
- val channelTitle = if (logicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
- getString(R.string.channel_type_usb)
- } else {
- appContainer.customizableTextProvider.formatInternalChannelName(logicalSlotId)
- }
-
- title = getString(R.string.euicc_info_activity_title, channelTitle)
-
- swipeRefresh.setOnRefreshListener { refresh() }
-
- setupRootViewInsets(infoList)
- }
-
- override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
- android.R.id.home -> {
- finish()
- true
- }
-
- else -> super.onOptionsItemSelected(item)
- }
-
- override fun onInit() {
- refresh()
- }
-
- private fun refresh() {
- swipeRefresh.isRefreshing = true
-
- lifecycleScope.launch {
- (infoList.adapter!! as EuiccInfoAdapter).euiccInfoItems =
- euiccChannelManager.withEuiccChannel(logicalSlotId, ::buildEuiccInfoItems)
-
- swipeRefresh.isRefreshing = false
- }
- }
-
- private fun buildEuiccInfoItems(channel: EuiccChannel) = buildList {
- add(Item(R.string.euicc_info_access_mode, channel.type))
- add(Item(R.string.euicc_info_removable, formatByBoolean(channel.port.card.isRemovable, YES_NO)))
- add(Item(R.string.euicc_info_eid, channel.lpa.eID, copiedToastResId = R.string.toast_eid_copied))
- add(Item(R.string.euicc_info_isdr_aid, channel.isdrAid.encodeHex()))
- channel.tryParseEuiccVendorInfo()?.let { vendorInfo ->
- vendorInfo.skuName?.let { add(Item(R.string.euicc_info_sku, it)) }
- vendorInfo.serialNumber?.let { add(Item(R.string.euicc_info_sn, it, copiedToastResId = R.string.toast_sn_copied)) }
- vendorInfo.firmwareVersion?.let { add(Item(R.string.euicc_info_fw_ver, it)) }
- vendorInfo.bootloaderVersion?.let { add(Item(R.string.euicc_info_bl_ver, it)) }
- }
- channel.lpa.euiccInfo2?.let { info ->
- add(Item(R.string.euicc_info_sgp22_version, info.sgp22Version.toString()))
- add(Item(R.string.euicc_info_firmware_version, info.euiccFirmwareVersion.toString()))
- add(Item(R.string.euicc_info_gp_version, info.globalPlatformVersion.toString()))
- add(Item(R.string.euicc_info_pp_version, info.ppVersion.toString()))
- info.sasAccreditationNumber.trim().takeIf(RE_SAS::matches)
- ?.let { add(Item(R.string.euicc_info_sas_accreditation_number, it.uppercase())) }
-
- val nvramText = buildString {
- append(formatFreeSpace(info.freeNvram))
- append(' ')
- append(getString(R.string.euicc_info_free_nvram_hint))
- }
- add(Item(R.string.euicc_info_free_nvram, nvramText))
- }
- channel.lpa.euiccInfo2?.euiccCiPKIdListForSigning.orEmpty().let { signers ->
- // SGP.28 v1.0, eSIM CI Registration Criteria (Page 5 of 9, 2019-10-24)
- // https://www.gsma.com/newsroom/wp-content/uploads/SGP.28-v1.0.pdf#page=5
- // FS.27 v2.0, Security Guidelines for UICC Profiles (Page 25 of 27, 2024-01-30)
- // https://www.gsma.com/solutions-and-impact/technologies/security/wp-content/uploads/2024/01/FS.27-Security-Guidelines-for-UICC-Credentials-v2.0-FINAL-23-July.pdf#page=25
- val resId = when {
- signers.isEmpty() -> R.string.euicc_info_unknown // the case is not mp, but it's is not common
- PKID_GSMA_LIVE_CI.any(signers::contains) -> R.string.euicc_info_ci_gsma_live
- PKID_GSMA_TEST_CI.any(signers::contains) -> R.string.euicc_info_ci_gsma_test
- else -> R.string.euicc_info_ci_unknown
- }
- add(Item(R.string.euicc_info_ci_type, getString(resId)))
- }
- val atr = channel.atr?.encodeHex() ?: getString(R.string.euicc_info_unavailable)
- add(Item(R.string.euicc_info_atr, atr, copiedToastResId = R.string.toast_atr_copied))
- }
-
- @Suppress("SameParameterValue")
- private fun formatByBoolean(b: Boolean, res: Pair): String =
- getString(if (b) res.first else res.second)
-
- inner class EuiccInfoViewHolder(root: View) : ViewHolder(root) {
- private val title: TextView = root.requireViewById(R.id.euicc_info_title)
- private val content: TextView = root.requireViewById(R.id.euicc_info_content)
- private var copiedToastResId: Int? = null
-
- init {
- root.setOnClickListener {
- if (copiedToastResId != null) {
- val label = title.text.toString()
- getSystemService(ClipboardManager::class.java)!!
- .setPrimaryClip(ClipData.newPlainText(label, content.text))
- if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2) {
- Toast.makeText(
- this@EuiccInfoActivity,
- copiedToastResId!!,
- Toast.LENGTH_SHORT
- ).show()
- }
- }
- }
- }
-
- fun bind(item: Item) {
- copiedToastResId = item.copiedToastResId
- title.setText(item.titleResId)
- content.text = item.content ?: getString(R.string.euicc_info_unknown)
- }
- }
-
- inner class EuiccInfoAdapter : RecyclerView.Adapter() {
- var euiccInfoItems: List- = listOf()
- @SuppressLint("NotifyDataSetChanged")
- set(newVal) {
- field = newVal
- notifyDataSetChanged()
- }
-
- override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EuiccInfoViewHolder {
- val root = LayoutInflater.from(parent.context)
- .inflate(R.layout.euicc_info_item, parent, false)
- return EuiccInfoViewHolder(root)
- }
-
- override fun getItemCount(): Int = euiccInfoItems.size
-
- override fun onBindViewHolder(holder: EuiccInfoViewHolder, position: Int) {
- holder.bind(euiccInfoItems[position])
- }
- }
-}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt
index 016e96f..3374f07 100644
--- a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt
@@ -4,9 +4,9 @@ import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
-import android.os.Build
import android.os.Bundle
import android.text.method.PasswordTransformationMethod
+import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
@@ -19,10 +19,6 @@ import android.widget.PopupMenu
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
-import androidx.core.view.ViewCompat
-import androidx.core.view.WindowInsetsCompat
-import androidx.core.view.isVisible
-import androidx.core.view.updateLayoutParams
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
@@ -31,9 +27,7 @@ import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.google.android.material.floatingactionbutton.FloatingActionButton
import net.typeblog.lpac_jni.LocalProfileInfo
import im.angry.openeuicc.common.R
-import im.angry.openeuicc.service.EuiccChannelManagerService
-import im.angry.openeuicc.service.EuiccChannelManagerService.Companion.waitDone
-import im.angry.openeuicc.ui.wizard.DownloadWizardActivity
+import im.angry.openeuicc.core.EuiccChannelManager
import im.angry.openeuicc.util.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.TimeoutCancellationException
@@ -41,7 +35,6 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
-import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
@@ -56,8 +49,6 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
private lateinit var swipeRefresh: SwipeRefreshLayout
private lateinit var fab: FloatingActionButton
private lateinit var profileList: RecyclerView
- private var logicalSlotId: Int = -1
- private lateinit var eid: String
private val adapter = EuiccProfileAdapter()
@@ -69,8 +60,6 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
// This gives us access to the "latest" state without having to launch coroutines
private lateinit var disableSafeguardFlow: StateFlow
- private lateinit var unfilteredProfileListFlow: StateFlow
-
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
@@ -87,21 +76,6 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
fab = view.requireViewById(R.id.fab)
profileList = view.requireViewById(R.id.profile_list)
- val origFabMarginRight = (fab.layoutParams as ViewGroup.MarginLayoutParams).rightMargin
- val origFabMarginBottom = (fab.layoutParams as ViewGroup.MarginLayoutParams).bottomMargin
- ViewCompat.setOnApplyWindowInsetsListener(fab) { v, insets ->
- val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
-
- v.updateLayoutParams {
- rightMargin = origFabMarginRight + bars.right
- bottomMargin = origFabMarginBottom + bars.bottom
- }
-
- WindowInsetsCompat.CONSUMED
- }
-
- setupRootViewInsets(profileList)
-
return view
}
@@ -113,15 +87,10 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
LinearLayoutManager(view.context, LinearLayoutManager.VERTICAL, false)
fab.setOnClickListener {
- Intent(requireContext(), DownloadWizardActivity::class.java).apply {
- putExtra("selectedLogicalSlot", logicalSlotId)
- startActivity(this)
- }
+ ProfileDownloadFragment.newInstance(slotId, portId)
+ .show(childFragmentManager, ProfileDownloadFragment.TAG)
}
- }
- override fun onStart() {
- super.onStart()
refresh()
}
@@ -134,42 +103,19 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
inflater.inflate(R.menu.fragment_euicc, menu)
}
- override fun onPrepareOptionsMenu(menu: Menu) {
- super.onPrepareOptionsMenu(menu)
- menu.findItem(R.id.show_notifications).isVisible =
- logicalSlotId != -1
- menu.findItem(R.id.euicc_info).isVisible =
- logicalSlotId != -1
- menu.findItem(R.id.euicc_memory_reset).isVisible =
- runBlocking { preferenceRepository.euiccMemoryResetFlow.first() }
- }
-
- override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
- R.id.show_notifications -> {
- Intent(requireContext(), NotificationsActivity::class.java).apply {
- putExtra("logicalSlotId", logicalSlotId)
- startActivity(this)
+ override fun onOptionsItemSelected(item: MenuItem): Boolean =
+ when (item.itemId) {
+ R.id.show_notifications -> {
+ Intent(requireContext(), NotificationsActivity::class.java).apply {
+ putExtra("logicalSlotId", channel.logicalSlotId)
+ startActivity(this)
+ }
+ true
}
- true
- }
- R.id.euicc_info -> {
- Intent(requireContext(), EuiccInfoActivity::class.java).apply {
- putExtra("logicalSlotId", logicalSlotId)
- startActivity(this)
- }
- true
+ else -> super.onOptionsItemSelected(item)
}
- R.id.euicc_memory_reset -> {
- EuiccMemoryResetFragment.newInstance(slotId, portId, eid)
- .show(childFragmentManager, EuiccMemoryResetFragment.TAG)
- true
- }
-
- else -> super.onOptionsItemSelected(item)
- }
-
protected open suspend fun onCreateFooterViews(
parent: ViewGroup,
profiles: List
@@ -181,99 +127,65 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
listOf()
}
+ @SuppressLint("NotifyDataSetChanged")
private fun refresh() {
if (invalid) return
swipeRefresh.isRefreshing = true
lifecycleScope.launch {
- doRefresh()
- }
- }
+ if (!this@EuiccManagementFragment::disableSafeguardFlow.isInitialized) {
+ disableSafeguardFlow =
+ preferenceRepository.disableSafeguardFlow.stateIn(lifecycleScope)
+ }
- @SuppressLint("NotifyDataSetChanged")
- protected open suspend fun doRefresh() {
- ensureEuiccChannelManager()
- euiccChannelManagerService.waitForForegroundTask()
-
- if (!::disableSafeguardFlow.isInitialized) {
- disableSafeguardFlow =
- preferenceRepository.disableSafeguardFlow.stateIn(lifecycleScope)
- }
- if (!::unfilteredProfileListFlow.isInitialized) {
- unfilteredProfileListFlow =
- preferenceRepository.unfilteredProfileListFlow.stateIn(lifecycleScope)
- }
-
- val profiles = withEuiccChannel { channel ->
- logicalSlotId = channel.logicalSlotId
- eid = channel.lpa.eID
- euiccChannelManager.notifyEuiccProfilesChanged(channel.logicalSlotId)
- if (unfilteredProfileListFlow.value)
- channel.lpa.profiles
- else
+ val profiles = withContext(Dispatchers.IO) {
+ euiccChannelManager.notifyEuiccProfilesChanged(channel.logicalSlotId)
channel.lpa.profiles.operational
- }
+ }
- withContext(Dispatchers.Main) {
- adapter.profiles = profiles
- adapter.footerViews = onCreateFooterViews(profileList, profiles)
- adapter.notifyDataSetChanged()
- swipeRefresh.isRefreshing = false
+ withContext(Dispatchers.Main) {
+ adapter.profiles = profiles
+ adapter.footerViews = onCreateFooterViews(profileList, profiles)
+ adapter.notifyDataSetChanged()
+ swipeRefresh.isRefreshing = false
+ }
}
}
- private suspend fun showSwitchFailureText() = withContext(Dispatchers.Main) {
- Toast.makeText(
- context,
- R.string.toast_profile_enable_failed,
- Toast.LENGTH_LONG
- ).show()
- }
-
private fun enableOrDisableProfile(iccid: String, enable: Boolean) {
swipeRefresh.isRefreshing = true
fab.isEnabled = false
lifecycleScope.launch {
- ensureEuiccChannelManager()
- euiccChannelManagerService.waitForForegroundTask()
-
- val err = euiccChannelManagerService.launchProfileSwitchTask(
- slotId,
- portId,
- iccid,
- enable,
- reconnectTimeoutMillis = 30 * 1000
- ).waitDone()
-
- when (err) {
- null -> {}
- is EuiccChannelManagerService.SwitchingProfilesRefreshException -> {
- // This is only really fatal for internal eSIMs
- if (!isUsb) {
- withContext(Dispatchers.Main) {
- AlertDialog.Builder(requireContext()).apply {
- setMessage(R.string.profile_switch_did_not_refresh)
- setPositiveButton(android.R.string.ok) { dialog, _ ->
- dialog.dismiss()
- requireActivity().finish()
- }
- setOnDismissListener { _ ->
- requireActivity().finish()
- }
- show()
- }
- }
+ beginTrackedOperation {
+ val (res, refreshed) =
+ if (!channel.lpa.switchProfile(iccid, enable, refresh = true)) {
+ // Sometimes, we *can* enable or disable the profile, but we cannot
+ // send the refresh command to the modem because the profile somehow
+ // makes the modem "busy". In this case, we can still switch by setting
+ // refresh to false, but then the switch cannot take effect until the
+ // user resets the modem manually by toggling airplane mode or rebooting.
+ Pair(channel.lpa.switchProfile(iccid, enable, refresh = false), false)
+ } else {
+ Pair(true, true)
}
+
+ if (!res) {
+ Log.d(TAG, "Failed to enable / disable profile $iccid")
+ withContext(Dispatchers.Main) {
+ Toast.makeText(
+ context,
+ R.string.toast_profile_enable_failed,
+ Toast.LENGTH_LONG
+ ).show()
+ }
+ return@beginTrackedOperation false
}
- is TimeoutCancellationException -> {
+ if (!refreshed && !isUsb) {
withContext(Dispatchers.Main) {
- // Prevent this Fragment from being used again
- invalid = true
- // Timed out waiting for SIM to come back online, we can no longer assume that the LPA is still valid
AlertDialog.Builder(requireContext()).apply {
- setMessage(appContainer.customizableTextProvider.profileSwitchingTimeoutMessage)
+ setMessage(R.string.switch_did_not_refresh)
setPositiveButton(android.R.string.ok) { dialog, _ ->
dialog.dismiss()
requireActivity().finish()
@@ -284,11 +196,39 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
show()
}
}
+ return@beginTrackedOperation true
}
- else -> showSwitchFailureText()
- }
+ if (!isUsb) {
+ try {
+ euiccChannelManager.waitForReconnect(
+ slotId,
+ portId,
+ timeoutMillis = 30 * 1000
+ )
+ } catch (e: TimeoutCancellationException) {
+ withContext(Dispatchers.Main) {
+ // Prevent this Fragment from being used again
+ invalid = true
+ // Timed out waiting for SIM to come back online, we can no longer assume that the LPA is still valid
+ AlertDialog.Builder(requireContext()).apply {
+ setMessage(R.string.enable_disable_timeout)
+ setPositiveButton(android.R.string.ok) { dialog, _ ->
+ dialog.dismiss()
+ requireActivity().finish()
+ }
+ setOnDismissListener { _ ->
+ requireActivity().finish()
+ }
+ show()
+ }
+ }
+ return@beginTrackedOperation false
+ }
+ }
+ preferenceRepository.notificationSwitchFlow.first()
+ }
refresh()
fab.isEnabled = true
}
@@ -316,7 +256,7 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
companion object {
fun fromInt(value: Int) =
- entries.first { it.value == value }
+ Type.values().first { it.value == value }
}
}
}
@@ -344,10 +284,7 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
private val name: TextView = root.requireViewById(R.id.name)
private val state: TextView = root.requireViewById(R.id.state)
private val provider: TextView = root.requireViewById(R.id.provider)
- private val profileClassLabel: TextView = root.requireViewById(R.id.profile_class_label)
- private val profileClass: TextView = root.requireViewById(R.id.profile_class)
private val profileMenu: ImageButton = root.requireViewById(R.id.profile_menu)
- private val profileSeqNumber: TextView = root.requireViewById(R.id.profile_sequence_number)
init {
iccid.setOnClickListener {
@@ -359,17 +296,14 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
}
iccid.setOnLongClickListener {
- requireContext().getSystemService(ClipboardManager::class.java)!!
+ requireContext().getSystemService(ClipboardManager::class.java)
.setPrimaryClip(ClipData.newPlainText("iccid", iccid.text))
- if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2) Toast
- .makeText(requireContext(), R.string.toast_iccid_copied, Toast.LENGTH_SHORT)
+ Toast.makeText(requireContext(), R.string.toast_iccid_copied, Toast.LENGTH_SHORT)
.show()
true
}
- profileMenu.setOnClickListener {
- showOptionsMenu()
- }
+ profileMenu.setOnClickListener { showOptionsMenu() }
}
private lateinit var profile: LocalProfileInfo
@@ -380,32 +314,16 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
state.setText(
if (profile.isEnabled) {
- R.string.profile_state_enabled
+ R.string.enabled
} else {
- R.string.profile_state_disabled
+ R.string.disabled
}
)
provider.text = profile.providerName
- profileClassLabel.isVisible = unfilteredProfileListFlow.value
- profileClass.isVisible = unfilteredProfileListFlow.value
- profileClass.setText(
- when (profile.profileClass) {
- LocalProfileInfo.Clazz.Testing -> R.string.profile_class_testing
- LocalProfileInfo.Clazz.Provisioning -> R.string.profile_class_provisioning
- LocalProfileInfo.Clazz.Operational -> R.string.profile_class_operational
- }
- )
iccid.text = profile.iccid
iccid.transformationMethod = PasswordTransformationMethod.getInstance()
}
- fun setProfileSequenceNumber(index: Int) {
- profileSeqNumber.text = root.context.getString(
- R.string.profile_sequence_number_format,
- index,
- )
- }
-
private fun showOptionsMenu() {
// Prevent users from doing multiple things at once
if (invalid || swipeRefresh.isRefreshing) return
@@ -471,7 +389,6 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
when (holder) {
is ProfileViewHolder -> {
holder.setProfile(profiles[position])
- holder.setProfileSequenceNumber(position + 1)
}
is FooterViewHolder -> {
holder.attach(footerViews[position - profiles.size])
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccMemoryResetFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccMemoryResetFragment.kt
deleted file mode 100644
index 086a849..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccMemoryResetFragment.kt
+++ /dev/null
@@ -1,126 +0,0 @@
-package im.angry.openeuicc.ui
-
-import android.graphics.Typeface
-import android.os.Bundle
-import android.text.Editable
-import android.util.Log
-import android.widget.EditText
-import android.widget.Toast
-import androidx.appcompat.app.AlertDialog
-import androidx.fragment.app.DialogFragment
-import androidx.fragment.app.Fragment
-import androidx.lifecycle.lifecycleScope
-import im.angry.openeuicc.common.R
-import im.angry.openeuicc.service.EuiccChannelManagerService.Companion.waitDone
-import im.angry.openeuicc.util.EuiccChannelFragmentMarker
-import im.angry.openeuicc.util.EuiccProfilesChangedListener
-import im.angry.openeuicc.util.ensureEuiccChannelManager
-import im.angry.openeuicc.util.euiccChannelManagerService
-import im.angry.openeuicc.util.newInstanceEuicc
-import im.angry.openeuicc.util.notifyEuiccProfilesChanged
-import im.angry.openeuicc.util.portId
-import im.angry.openeuicc.util.slotId
-import kotlinx.coroutines.flow.onStart
-import kotlinx.coroutines.launch
-
-class EuiccMemoryResetFragment : DialogFragment(), EuiccChannelFragmentMarker {
- companion object {
- const val TAG = "EuiccMemoryResetFragment"
-
- private const val FIELD_EID = "eid"
-
- fun newInstance(slotId: Int, portId: Int, eid: String) =
- newInstanceEuicc(EuiccMemoryResetFragment::class.java, slotId, portId) {
- putString(FIELD_EID, eid)
- }
- }
-
- private val eid: String by lazy { requireArguments().getString(FIELD_EID)!! }
-
- private val confirmText: String by lazy {
- getString(R.string.euicc_memory_reset_confirm_text, eid.takeLast(8))
- }
-
- private inline val isMatched: Boolean
- get() = editText.text.toString() == confirmText
-
- private var confirmed = false
-
- private var toast: Toast? = null
- set(value) {
- toast?.cancel()
- field = value
- value?.show()
- }
-
- private val editText by lazy {
- EditText(requireContext()).apply {
- isLongClickable = false
- typeface = Typeface.MONOSPACE
- hint = Editable.Factory.getInstance()
- .newEditable(getString(R.string.euicc_memory_reset_hint_text, confirmText))
- }
- }
-
- private inline val alertDialog: AlertDialog
- get() = requireDialog() as AlertDialog
-
- override fun onCreateDialog(savedInstanceState: Bundle?) =
- AlertDialog.Builder(requireContext(), R.style.AlertDialogTheme)
- .setTitle(R.string.euicc_memory_reset_title)
- .setMessage(getString(R.string.euicc_memory_reset_message, eid, confirmText))
- .setView(editText)
- // Set listener to null to prevent auto closing
- .setNegativeButton(android.R.string.cancel, null)
- .setPositiveButton(R.string.euicc_memory_reset_invoke_button, null)
- .create()
-
- override fun onResume() {
- super.onResume()
- alertDialog.setCanceledOnTouchOutside(false)
- alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
- .setOnClickListener { if (!confirmed) confirmation() }
- alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE)
- .setOnClickListener { if (!confirmed) dismiss() }
- }
-
- private fun confirmation() {
- toast?.cancel()
- if (!isMatched) {
- Log.d(TAG, buildString {
- appendLine("User input is mismatch:")
- appendLine(editText.text)
- appendLine(confirmText)
- })
- val resId = R.string.toast_euicc_memory_reset_confirm_text_mismatched
- toast = Toast.makeText(requireContext(), resId, Toast.LENGTH_LONG)
- return
- }
- confirmed = true
- preventUserAction()
-
- requireParentFragment().lifecycleScope.launch {
- ensureEuiccChannelManager()
- euiccChannelManagerService.waitForForegroundTask()
-
- euiccChannelManagerService.launchMemoryReset(slotId, portId)
- .onStart {
- parentFragment?.notifyEuiccProfilesChanged()
-
- val resId = R.string.toast_euicc_memory_reset_finitshed
- toast = Toast.makeText(requireContext(), resId, Toast.LENGTH_LONG)
-
- runCatching(::dismiss)
- }
- .waitDone()
- }
- }
-
- private fun preventUserAction() {
- editText.isEnabled = false
- alertDialog.setCancelable(false)
- alertDialog.setCanceledOnTouchOutside(false)
- alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
- alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).isEnabled = false
- }
-}
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/IsdrAidListActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/IsdrAidListActivity.kt
deleted file mode 100644
index 022a391..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/ui/IsdrAidListActivity.kt
+++ /dev/null
@@ -1,72 +0,0 @@
-package im.angry.openeuicc.ui
-
-import android.os.Bundle
-import android.text.Editable
-import android.view.Menu
-import android.view.MenuItem
-import android.widget.EditText
-import android.widget.Toast
-import androidx.activity.enableEdgeToEdge
-import androidx.appcompat.app.AppCompatActivity
-import androidx.lifecycle.lifecycleScope
-import im.angry.openeuicc.common.R
-import im.angry.openeuicc.util.preferenceRepository
-import im.angry.openeuicc.util.setupToolbarInsets
-import kotlinx.coroutines.flow.collect
-import kotlinx.coroutines.flow.onEach
-import kotlinx.coroutines.launch
-
-class IsdrAidListActivity : AppCompatActivity() {
- private lateinit var isdrAidListEditor: EditText
-
- override fun onCreate(savedInstanceState: Bundle?) {
- enableEdgeToEdge()
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_isdr_aid_list)
- setSupportActionBar(requireViewById(R.id.toolbar))
- setupToolbarInsets()
- supportActionBar!!.setDisplayHomeAsUpEnabled(true)
-
- isdrAidListEditor = requireViewById(R.id.isdr_aid_list_editor)
-
- lifecycleScope.launch {
- preferenceRepository.isdrAidListFlow.onEach {
- isdrAidListEditor.text = Editable.Factory.getInstance().newEditable(it)
- }.collect()
- }
- }
-
- override fun onCreateOptionsMenu(menu: Menu?): Boolean {
- menuInflater.inflate(R.menu.activity_isdr_aid_list, menu)
- return true
- }
-
- override fun onOptionsItemSelected(item: MenuItem): Boolean =
- when (item.itemId) {
- R.id.save -> {
- lifecycleScope.launch {
- preferenceRepository.isdrAidListFlow.updatePreference(isdrAidListEditor.text.toString())
- Toast.makeText(
- this@IsdrAidListActivity,
- R.string.isdr_aid_list_saved,
- Toast.LENGTH_SHORT
- ).show()
- }
- true
- }
-
- R.id.reset -> {
- lifecycleScope.launch {
- preferenceRepository.isdrAidListFlow.removePreference()
- }
- true
- }
-
- android.R.id.home -> {
- finish()
- true
- }
-
- else -> super.onOptionsItemSelected(item)
- }
-}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/LogsActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/LogsActivity.kt
index 599e9d3..2b36468 100644
--- a/app-common/src/main/java/im/angry/openeuicc/ui/LogsActivity.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/ui/LogsActivity.kt
@@ -1,14 +1,13 @@
package im.angry.openeuicc.ui
import android.icu.text.SimpleDateFormat
-import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ScrollView
import android.widget.TextView
-import androidx.activity.enableEdgeToEdge
+import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
@@ -17,6 +16,7 @@ import im.angry.openeuicc.util.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
+import java.io.FileOutputStream
import java.util.Date
class LogsActivity : AppCompatActivity() {
@@ -26,40 +26,26 @@ class LogsActivity : AppCompatActivity() {
private lateinit var logStr: String
private val saveLogs =
- setupLogSaving(
- getLogFileName = {
- getString(
- R.string.logs_filename_template,
- SimpleDateFormat.getDateTimeInstance().format(Date())
- )
- },
- getLogText = ::buildLogText
- )
-
- private fun buildLogText() = buildString {
- appendLine("Manufacturer: ${Build.MANUFACTURER}")
- appendLine("Brand: ${Build.BRAND}")
- appendLine("Model: ${Build.MODEL}")
- appendLine("SDK Version: ${Build.VERSION.SDK_INT}")
- appendLine("App Version: $selfAppVersion")
- appendLine("-".repeat(10))
- appendLine(logStr)
- }
+ registerForActivityResult(ActivityResultContracts.CreateDocument("text/plain")) { uri ->
+ if (uri == null) return@registerForActivityResult
+ if (!this::logStr.isInitialized) return@registerForActivityResult
+ contentResolver.openFileDescriptor(uri, "w")?.use {
+ FileOutputStream(it.fileDescriptor).use { os ->
+ os.write(logStr.encodeToByteArray())
+ }
+ }
+ }
override fun onCreate(savedInstanceState: Bundle?) {
- enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_logs)
setSupportActionBar(requireViewById(R.id.toolbar))
- setupToolbarInsets()
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
swipeRefresh = requireViewById(R.id.swipe_refresh)
scrollView = requireViewById(R.id.scroll_view)
logText = requireViewById(R.id.log_text)
- setupRootViewInsets(scrollView)
-
swipeRefresh.setOnRefreshListener {
lifecycleScope.launch {
reload()
@@ -80,12 +66,10 @@ class LogsActivity : AppCompatActivity() {
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
- android.R.id.home -> {
- finish()
- true
- }
R.id.save -> {
- saveLogs()
+ saveLogs.launch(getString(R.string.logs_filename_template,
+ SimpleDateFormat.getDateTimeInstance().format(Date())
+ ))
true
}
else -> super.onOptionsItemSelected(item)
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt
index b42f4cf..0f504eb 100644
--- a/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt
@@ -5,9 +5,7 @@ import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
-import android.content.pm.PackageManager
import android.hardware.usb.UsbManager
-import android.os.Build
import android.os.Bundle
import android.telephony.TelephonyManager
import android.util.Log
@@ -15,7 +13,6 @@ import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ProgressBar
-import androidx.activity.enableEdgeToEdge
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
@@ -23,12 +20,8 @@ import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import im.angry.openeuicc.common.R
-import im.angry.openeuicc.core.EuiccChannelManager
import im.angry.openeuicc.util.*
import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.flow.collect
-import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -36,8 +29,6 @@ import kotlinx.coroutines.withContext
open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
companion object {
const val TAG = "MainActivity"
-
- const val PERMISSION_REQUEST_CODE = 1000
}
private lateinit var loadingProgress: ProgressBar
@@ -47,7 +38,6 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
private var refreshing = false
private data class Page(
- val logicalSlotId: Int,
val title: String,
val createFragment: () -> Fragment
)
@@ -74,11 +64,9 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
@SuppressLint("WrongConstant", "UnspecifiedRegisterReceiverFlag")
override fun onCreate(savedInstanceState: Bundle?) {
- enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(requireViewById(R.id.toolbar))
- setupToolbarInsets()
loadingProgress = requireViewById(R.id.loading)
tabs = requireViewById(R.id.main_tabs)
viewPager = requireViewById(R.id.view_pager)
@@ -109,7 +97,7 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
override fun onOptionsItemSelected(item: MenuItem): Boolean =
when (item.itemId) {
R.id.settings -> {
- startActivity(Intent(this, SettingsActivity::class.java))
+ startActivity(Intent(this, SettingsActivity::class.java));
true
}
R.id.reload -> {
@@ -125,95 +113,65 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
}
}
- private fun ensureNotificationPermissions() {
- val needsNotificationPerms = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU;
- val notificationPermsGranted =
- needsNotificationPerms && checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
- if (needsNotificationPerms && !notificationPermsGranted) {
- requestPermissions(
- arrayOf(android.Manifest.permission.POST_NOTIFICATIONS),
- PERMISSION_REQUEST_CODE
- )
- }
- }
-
private suspend fun init(fromUsbEvent: Boolean = false) {
refreshing = true // We don't check this here -- the check happens in refresh()
loadingProgress.visibility = View.VISIBLE
viewPager.visibility = View.GONE
tabs.visibility = View.GONE
- // Prevent concurrent access with any running foreground task
- euiccChannelManagerService.waitForForegroundTask()
- val (usbDevice, _) = withContext(Dispatchers.IO) {
- euiccChannelManager.tryOpenUsbEuiccChannel()
- }
-
- val newPages: MutableList = mutableListOf()
-
- euiccChannelManager.flowInternalEuiccPorts().onEach { (slotId, portId) ->
- Log.d(TAG, "slot $slotId port $portId")
-
- euiccChannelManager.withEuiccChannel(slotId, portId) { channel ->
- if (preferenceRepository.verboseLoggingFlow.first()) {
- Log.d(TAG, channel.lpa.eID)
- }
+ val knownChannels = withContext(Dispatchers.IO) {
+ euiccChannelManager.enumerateEuiccChannels().onEach {
+ Log.d(TAG, "slot ${it.slotId} port ${it.portId}")
+ Log.d(TAG, it.lpa.eID)
// Request the system to refresh the list of profiles every time we start
// Note that this is currently supposed to be no-op when unprivileged,
// but it could change in the future
- euiccChannelManager.notifyEuiccProfilesChanged(channel.logicalSlotId)
-
- val channelName =
- appContainer.customizableTextProvider.formatInternalChannelName(channel.logicalSlotId)
- newPages.add(Page(channel.logicalSlotId, channelName) {
- appContainer.uiComponentFactory.createEuiccManagementFragment(slotId, portId)
- })
+ euiccChannelManager.notifyEuiccProfilesChanged(it.logicalSlotId)
}
- }.collect()
-
- // If USB readers exist, add them at the very last
- // We use a wrapper fragment to handle logic specific to USB readers
- usbDevice?.let {
- val productName = it.productName ?: getString(R.string.channel_type_usb)
- newPages.add(Page(EuiccChannelManager.USB_CHANNEL_ID, productName) {
- UsbCcidReaderFragment()
- })
- }
- viewPager.visibility = View.VISIBLE
-
- if (newPages.size > 1) {
- tabs.visibility = View.VISIBLE
- } else if (newPages.isEmpty()) {
- newPages.add(Page(-1, "") {
- appContainer.uiComponentFactory.createNoEuiccPlaceholderFragment()
- })
}
- newPages.sortBy { it.logicalSlotId }
+ val (usbDevice, _) = withContext(Dispatchers.IO) {
+ euiccChannelManager.enumerateUsbEuiccChannel()
+ }
- pages.clear()
- pages.addAll(newPages)
+ withContext(Dispatchers.Main) {
+ loadingProgress.visibility = View.GONE
- loadingProgress.visibility = View.GONE
- pagerAdapter.notifyDataSetChanged()
- // Reset the adapter so that the current view actually gets cleared
- // notifyDataSetChanged() doesn't cause the current view to be removed.
- viewPager.adapter = pagerAdapter
-
- if (fromUsbEvent && usbDevice != null) {
- // If this refresh was triggered by a USB insertion while active, scroll to that page
- viewPager.post {
- viewPager.setCurrentItem(pages.size - 1, true)
+ knownChannels.sortedBy { it.logicalSlotId }.forEach { channel ->
+ pages.add(Page(
+ getString(R.string.channel_name_format, channel.logicalSlotId)
+ ) { appContainer.uiComponentFactory.createEuiccManagementFragment(channel) })
}
- } else {
- viewPager.currentItem = 0
- }
- if (pages.size > 0) {
- ensureNotificationPermissions()
- }
+ // If USB readers exist, add them at the very last
+ // We use a wrapper fragment to handle logic specific to USB readers
+ usbDevice?.let {
+ pages.add(Page(it.productName ?: getString(R.string.usb)) { UsbCcidReaderFragment() })
+ }
+ viewPager.visibility = View.VISIBLE
- refreshing = false
+ if (pages.size > 1) {
+ tabs.visibility = View.VISIBLE
+ } else if (pages.isEmpty()) {
+ pages.add(Page("") { appContainer.uiComponentFactory.createNoEuiccPlaceholderFragment() })
+ }
+
+ pagerAdapter.notifyDataSetChanged()
+ // Reset the adapter so that the current view actually gets cleared
+ // notifyDataSetChanged() doesn't cause the current view to be removed.
+ viewPager.adapter = pagerAdapter
+
+ if (fromUsbEvent && usbDevice != null) {
+ // If this refresh was triggered by a USB insertion while active, scroll to that page
+ viewPager.post {
+ viewPager.setCurrentItem(pages.size - 1, true)
+ }
+ } else {
+ viewPager.currentItem = 0
+ }
+
+ refreshing = false
+ }
}
private fun refresh(fromUsbEvent: Boolean = false) {
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/NoEuiccPlaceholderFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/NoEuiccPlaceholderFragment.kt
index 7e96af3..e9e44b1 100644
--- a/app-common/src/main/java/im/angry/openeuicc/ui/NoEuiccPlaceholderFragment.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/ui/NoEuiccPlaceholderFragment.kt
@@ -4,20 +4,15 @@ import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
-import android.widget.TextView
import androidx.fragment.app.Fragment
import im.angry.openeuicc.common.R
-import im.angry.openeuicc.util.*
-class NoEuiccPlaceholderFragment : Fragment(), OpenEuiccContextMarker {
+class NoEuiccPlaceholderFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
- val view = inflater.inflate(R.layout.fragment_no_euicc_placeholder, container, false)
- val textView = view.requireViewById(R.id.no_euicc_placeholder)
- textView.text = appContainer.customizableTextProvider.noEuiccExplanation
- return view
+ return inflater.inflate(R.layout.fragment_no_euicc_placeholder, container, false)
}
}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/NotificationsActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/NotificationsActivity.kt
index 07d5f13..59abbc5 100644
--- a/app-common/src/main/java/im/angry/openeuicc/ui/NotificationsActivity.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/ui/NotificationsActivity.kt
@@ -11,7 +11,6 @@ import android.view.MenuItem.OnMenuItemClickListener
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
-import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.core.view.forEach
import androidx.lifecycle.lifecycleScope
@@ -20,6 +19,7 @@ import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import im.angry.openeuicc.common.R
+import im.angry.openeuicc.core.EuiccChannel
import im.angry.openeuicc.core.EuiccChannelManager
import im.angry.openeuicc.util.*
import kotlinx.coroutines.Dispatchers
@@ -32,37 +32,34 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
private lateinit var notificationList: RecyclerView
private val notificationAdapter = NotificationAdapter()
- private var logicalSlotId = -1
+ private lateinit var euiccChannel: EuiccChannel
override fun onCreate(savedInstanceState: Bundle?) {
- enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_notifications)
setSupportActionBar(requireViewById(R.id.toolbar))
- setupToolbarInsets()
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
+ }
+
+ override fun onInit() {
+ euiccChannel = euiccChannelManager
+ .findEuiccChannelBySlotBlocking(intent.getIntExtra("logicalSlotId", 0))!!
swipeRefresh = requireViewById(R.id.swipe_refresh)
notificationList = requireViewById(R.id.recycler_view)
- setupRootViewInsets(notificationList)
- }
-
- override fun onInit() {
notificationList.layoutManager =
LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
notificationList.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL))
notificationList.adapter = notificationAdapter
registerForContextMenu(notificationList)
- logicalSlotId = intent.getIntExtra("logicalSlotId", 0)
-
// This is slightly different from the MainActivity logic
// due to the length (we don't want to display the full USB product name)
- val channelTitle = if (logicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
- getString(R.string.channel_type_usb)
+ val channelTitle = if (euiccChannel.logicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
+ getString(R.string.usb)
} else {
- appContainer.customizableTextProvider.formatInternalChannelName(logicalSlotId)
+ getString(R.string.channel_name_format, euiccChannel.logicalSlotId)
}
title = getString(R.string.profile_notifications_detailed_format, channelTitle)
@@ -103,10 +100,6 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
swipeRefresh.isRefreshing = true
lifecycleScope.launch {
- withContext(Dispatchers.IO) {
- euiccChannelManagerLoaded.await()
- }
-
task()
swipeRefresh.isRefreshing = false
@@ -115,16 +108,15 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
private fun refresh() {
launchTask {
- notificationAdapter.notifications =
- euiccChannelManager.withEuiccChannel(logicalSlotId) { channel ->
- val nameMap = buildMap {
- for (profile in channel.lpa.profiles) {
- put(profile.iccid, profile.displayName)
- }
- }
+ val profiles = withContext(Dispatchers.IO) {
+ euiccChannel.lpa.profiles
+ }
- channel.lpa.notifications.map {
- LocalProfileNotificationWrapper(it, nameMap[it.iccid] ?: "???")
+ notificationAdapter.notifications =
+ withContext(Dispatchers.IO) {
+ euiccChannel.lpa.notifications.map {
+ val profile = profiles.find { p -> p.iccid == it.iccid }
+ LocalProfileNotificationWrapper(it, profile?.displayName ?: "???")
}
}
}
@@ -139,8 +131,6 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
inner class NotificationViewHolder(private val root: View):
RecyclerView.ViewHolder(root), View.OnCreateContextMenuListener, OnMenuItemClickListener {
private val address: TextView = root.requireViewById(R.id.notification_address)
- private val sequenceNumber: TextView =
- root.requireViewById(R.id.notification_sequence_number)
private val profileName: TextView = root.requireViewById(R.id.notification_profile_name)
private lateinit var notification: LocalProfileNotificationWrapper
@@ -162,7 +152,6 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
}
}
-
private fun operationToLocalizedText(operation: LocalProfileNotification.Operation) =
root.context.getText(
when (operation) {
@@ -176,10 +165,6 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
notification = value
address.text = value.inner.notificationAddress
- sequenceNumber.text = root.context.getString(
- R.string.profile_notification_sequence_number_format,
- value.inner.seqNumber
- )
profileName.text = Html.fromHtml(
root.context.getString(R.string.profile_notification_name_format,
operationToLocalizedText(value.inner.profileManagementOperation),
@@ -204,9 +189,7 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
R.id.notification_process -> {
launchTask {
withContext(Dispatchers.IO) {
- euiccChannelManager.withEuiccChannel(logicalSlotId) { channel ->
- channel.lpa.handleNotification(notification.inner.seqNumber)
- }
+ euiccChannel.lpa.handleNotification(notification.inner.seqNumber)
}
refresh()
@@ -216,9 +199,7 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
R.id.notification_delete -> {
launchTask {
withContext(Dispatchers.IO) {
- euiccChannelManager.withEuiccChannel(logicalSlotId) { channel ->
- channel.lpa.deleteNotification(notification.inner.seqNumber)
- }
+ euiccChannel.lpa.deleteNotification(notification.inner.seqNumber)
}
refresh()
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/ProfileDeleteFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/ProfileDeleteFragment.kt
index 38d1bc6..7586354 100644
--- a/app-common/src/main/java/im/angry/openeuicc/ui/ProfileDeleteFragment.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/ui/ProfileDeleteFragment.kt
@@ -3,67 +3,56 @@ package im.angry.openeuicc.ui
import android.app.Dialog
import android.os.Bundle
import android.text.Editable
+import android.util.Log
import android.widget.EditText
-import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.lifecycleScope
import im.angry.openeuicc.common.R
-import im.angry.openeuicc.service.EuiccChannelManagerService.Companion.waitDone
import im.angry.openeuicc.util.*
-import kotlinx.coroutines.flow.onStart
+import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
+import java.lang.Exception
class ProfileDeleteFragment : DialogFragment(), EuiccChannelFragmentMarker {
companion object {
const val TAG = "ProfileDeleteFragment"
- private const val FIELD_ICCID = "iccid"
- private const val FIELD_NAME = "name"
- fun newInstance(slotId: Int, portId: Int, iccid: String, name: String) =
- newInstanceEuicc(ProfileDeleteFragment::class.java, slotId, portId) {
- putString(FIELD_ICCID, iccid)
- putString(FIELD_NAME, name)
+ fun newInstance(slotId: Int, portId: Int, iccid: String, name: String): ProfileDeleteFragment {
+ val instance = newInstanceEuicc(ProfileDeleteFragment::class.java, slotId, portId)
+ instance.requireArguments().apply {
+ putString("iccid", iccid)
+ putString("name", name)
+ }
+ return instance
}
}
- private val iccid by lazy {
- requireArguments().getString(FIELD_ICCID)!!
- }
-
- private val name by lazy {
- requireArguments().getString(FIELD_NAME)!!
- }
-
private val editText by lazy {
EditText(requireContext()).apply {
- hint = Editable.Factory.getInstance()
- .newEditable(getString(R.string.profile_delete_confirm_input, name))
+ hint = Editable.Factory.getInstance().newEditable(
+ getString(R.string.profile_delete_confirm_input, requireArguments().getString("name")!!)
+ )
}
}
-
private val inputMatchesName: Boolean
- get() = editText.text.toString() == name
-
- private var toast: Toast? = null
-
+ get() = editText.text.toString() == requireArguments().getString("name")!!
private var deleting = false
- private val alertDialog: AlertDialog
- get() = requireDialog() as AlertDialog
-
- override fun onCreateDialog(savedInstanceState: Bundle?): Dialog =
- AlertDialog.Builder(requireContext(), R.style.AlertDialogTheme).apply {
- setMessage(getString(R.string.profile_delete_confirm, name))
+ override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
+ return AlertDialog.Builder(requireContext(), R.style.AlertDialogTheme).apply {
+ setMessage(getString(R.string.profile_delete_confirm, requireArguments().getString("name")))
setView(editText)
setPositiveButton(android.R.string.ok, null) // Set listener to null to prevent auto closing
setNegativeButton(android.R.string.cancel, null)
}.create()
+ }
override fun onResume() {
super.onResume()
+ val alertDialog = dialog!! as AlertDialog
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
- if (!deleting) delete()
+ if (!deleting && inputMatchesName) delete()
}
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener {
if (!deleting) dismiss()
@@ -71,29 +60,30 @@ class ProfileDeleteFragment : DialogFragment(), EuiccChannelFragmentMarker {
}
private fun delete() {
- toast?.cancel()
- if (!inputMatchesName) {
- val resId = R.string.toast_profile_delete_confirm_text_mismatched
- toast = Toast.makeText(requireContext(), resId, Toast.LENGTH_LONG).also {
- it.show()
- }
- return
- }
deleting = true
+ val alertDialog = dialog!! as AlertDialog
alertDialog.setCanceledOnTouchOutside(false)
alertDialog.setCancelable(false)
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).isEnabled = false
- requireParentFragment().lifecycleScope.launch {
- ensureEuiccChannelManager()
- euiccChannelManagerService.waitForForegroundTask()
- euiccChannelManagerService.launchProfileDeleteTask(slotId, portId, iccid)
- .onStart {
- parentFragment?.notifyEuiccProfilesChanged()
- runCatching(::dismiss)
+ lifecycleScope.launch {
+ try {
+ doDelete()
+ } catch (e: Exception) {
+ Log.d(ProfileDownloadFragment.TAG, "Error deleting profile")
+ Log.d(ProfileDownloadFragment.TAG, Log.getStackTraceString(e))
+ } finally {
+ if (parentFragment is EuiccProfilesChangedListener) {
+ (parentFragment as EuiccProfilesChangedListener).onEuiccProfilesChanged()
}
- .waitDone()
+ dismiss()
+ }
}
}
+
+ private suspend fun doDelete() = beginTrackedOperation {
+ channel.lpa.deleteProfile(requireArguments().getString("iccid")!!)
+ preferenceRepository.notificationDeleteFlow.first()
+ }
}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/ProfileDownloadFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/ProfileDownloadFragment.kt
new file mode 100644
index 0000000..f8399a9
--- /dev/null
+++ b/app-common/src/main/java/im/angry/openeuicc/ui/ProfileDownloadFragment.kt
@@ -0,0 +1,266 @@
+package im.angry.openeuicc.ui
+
+import android.annotation.SuppressLint
+import android.app.Dialog
+import android.content.DialogInterface
+import android.graphics.BitmapFactory
+import android.os.Bundle
+import android.text.Editable
+import android.util.Log
+import android.view.*
+import android.widget.ProgressBar
+import android.widget.TextView
+import android.widget.Toast
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.appcompat.widget.Toolbar
+import androidx.lifecycle.lifecycleScope
+import com.google.android.material.textfield.TextInputLayout
+import com.journeyapps.barcodescanner.ScanContract
+import com.journeyapps.barcodescanner.ScanOptions
+import im.angry.openeuicc.common.R
+import im.angry.openeuicc.util.*
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import net.typeblog.lpac_jni.ProfileDownloadCallback
+import kotlin.Exception
+
+class ProfileDownloadFragment : BaseMaterialDialogFragment(),
+ Toolbar.OnMenuItemClickListener, EuiccChannelFragmentMarker {
+ companion object {
+ const val TAG = "ProfileDownloadFragment"
+
+ fun newInstance(slotId: Int, portId: Int, finishWhenDone: Boolean = false): ProfileDownloadFragment =
+ newInstanceEuicc(ProfileDownloadFragment::class.java, slotId, portId) {
+ putBoolean("finishWhenDone", finishWhenDone)
+ }
+ }
+
+ private lateinit var toolbar: Toolbar
+ private lateinit var profileDownloadServer: TextInputLayout
+ private lateinit var profileDownloadCode: TextInputLayout
+ private lateinit var profileDownloadConfirmationCode: TextInputLayout
+ private lateinit var profileDownloadIMEI: TextInputLayout
+ private lateinit var profileDownloadFreeSpace: TextView
+ private lateinit var progress: ProgressBar
+
+ private var freeNvram: Int = -1
+
+ private var downloading = false
+
+ private val finishWhenDone by lazy {
+ requireArguments().getBoolean("finishWhenDone", false)
+ }
+
+ private val barcodeScannerLauncher = registerForActivityResult(ScanContract()) { result ->
+ result.contents?.let { content ->
+ Log.d(TAG, content)
+ onScanResult(content)
+ }
+ }
+
+ private val gallerySelectorLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { result ->
+ if (result == null) return@registerForActivityResult
+
+ lifecycleScope.launch(Dispatchers.IO) {
+ runCatching {
+ requireContext().contentResolver.openInputStream(result)?.let { input ->
+ val bmp = BitmapFactory.decodeStream(input)
+ input.close()
+
+ decodeQrFromBitmap(bmp)?.let {
+ withContext(Dispatchers.Main) {
+ onScanResult(it)
+ }
+ }
+
+ bmp.recycle()
+ }
+ }
+ }
+ }
+
+ private fun onScanResult(result: String) {
+ val components = result.split("$")
+ if (components.size < 3 || components[0] != "LPA:1") return
+ profileDownloadServer.editText?.setText(components[1])
+ profileDownloadCode.editText?.setText(components[2])
+ }
+
+ override fun onCreateView(
+ inflater: LayoutInflater,
+ container: ViewGroup?,
+ savedInstanceState: Bundle?
+ ): View {
+ val view = inflater.inflate(R.layout.fragment_profile_download, container, false)
+
+ toolbar = view.requireViewById(R.id.toolbar)
+ profileDownloadServer = view.requireViewById(R.id.profile_download_server)
+ profileDownloadCode = view.requireViewById(R.id.profile_download_code)
+ profileDownloadConfirmationCode = view.requireViewById(R.id.profile_download_confirmation_code)
+ profileDownloadIMEI = view.requireViewById(R.id.profile_download_imei)
+ profileDownloadFreeSpace = view.requireViewById(R.id.profile_download_free_space)
+ progress = view.requireViewById(R.id.progress)
+
+ toolbar.inflateMenu(R.menu.fragment_profile_download)
+
+ return view
+ }
+
+ override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
+ super.onViewCreated(view, savedInstanceState)
+ toolbar.apply {
+ setTitle(R.string.profile_download)
+ setNavigationOnClickListener {
+ if (!downloading) {
+ dismiss()
+ }
+ }
+ setOnMenuItemClickListener(this@ProfileDownloadFragment)
+ }
+ }
+
+ override fun onMenuItemClick(item: MenuItem): Boolean = downloading ||
+ when (item.itemId) {
+ R.id.scan -> {
+ barcodeScannerLauncher.launch(ScanOptions().apply {
+ setDesiredBarcodeFormats(ScanOptions.QR_CODE)
+ setOrientationLocked(false)
+ })
+ true
+ }
+ R.id.scan_from_gallery -> {
+ gallerySelectorLauncher.launch("image/*")
+ true
+ }
+ R.id.ok -> {
+ startDownloadProfile()
+ true
+ }
+ else -> false
+ }
+
+ override fun onResume() {
+ super.onResume()
+ setWidthPercent(95)
+ }
+
+ @SuppressLint("MissingPermission")
+ override fun onStart() {
+ super.onStart()
+ profileDownloadIMEI.editText!!.text = Editable.Factory.getInstance().newEditable(
+ try {
+ telephonyManager.getImei(channel.logicalSlotId) ?: ""
+ } catch (e: Exception) {
+ ""
+ }
+ )
+
+ lifecycleScope.launch(Dispatchers.IO) {
+ // Fetch remaining NVRAM
+ val str = channel.lpa.euiccInfo2?.freeNvram?.also {
+ freeNvram = it
+ }?.let { formatFreeSpace(it) }
+
+ withContext(Dispatchers.Main) {
+ profileDownloadFreeSpace.text = getString(R.string.profile_download_free_space,
+ str ?: getText(R.string.unknown))
+ }
+ }
+ }
+
+ override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
+ return super.onCreateDialog(savedInstanceState).also {
+ it.setCanceledOnTouchOutside(false)
+ }
+ }
+
+ private fun startDownloadProfile() {
+ val server = profileDownloadServer.editText!!.let {
+ it.text.toString().trim().apply {
+ if (isEmpty()) {
+ it.requestFocus()
+ return@startDownloadProfile
+ }
+ }
+ }
+
+ val code = profileDownloadCode.editText!!.text.toString().trim()
+ .ifBlank { null }
+ val confirmationCode = profileDownloadConfirmationCode.editText!!.text.toString().trim()
+ .ifBlank { null }
+ val imei = profileDownloadIMEI.editText!!.text.toString().trim()
+ .ifBlank { null }
+
+ downloading = true
+
+ profileDownloadServer.editText!!.isEnabled = false
+ profileDownloadCode.editText!!.isEnabled = false
+ profileDownloadConfirmationCode.editText!!.isEnabled = false
+ profileDownloadIMEI.editText!!.isEnabled = false
+
+ progress.isIndeterminate = true
+ progress.visibility = View.VISIBLE
+
+ lifecycleScope.launch {
+ try {
+ doDownloadProfile(server, code, confirmationCode, imei)
+ } catch (e: Exception) {
+ Log.d(TAG, "Error downloading profile")
+ Log.d(TAG, Log.getStackTraceString(e))
+ Toast.makeText(context, R.string.profile_download_failed, Toast.LENGTH_LONG).show()
+ } finally {
+ if (parentFragment is EuiccProfilesChangedListener) {
+ (parentFragment as EuiccProfilesChangedListener).onEuiccProfilesChanged()
+ }
+ dismiss()
+ }
+ }
+ }
+
+ private suspend fun doDownloadProfile(
+ server: String,
+ code: String?,
+ confirmationCode: String?,
+ imei: String?
+ ) = beginTrackedOperation {
+ val res = channel.lpa.downloadProfile(
+ server,
+ code,
+ imei,
+ confirmationCode,
+ object : ProfileDownloadCallback {
+ override fun onStateUpdate(state: ProfileDownloadCallback.DownloadState) {
+ lifecycleScope.launch(Dispatchers.Main) {
+ progress.isIndeterminate = false
+ progress.progress = state.progress
+ }
+ }
+ })
+
+ if (!res) {
+ // TODO: Provide more details on the error
+ throw RuntimeException("Failed to download profile; this is typically caused by another error happened before.")
+ }
+
+ // If we get here, we are successful
+ // This function is wrapped in beginTrackedOperation, so by returning the settings value,
+ // We only send notifications if the user allowed us to
+ preferenceRepository.notificationDownloadFlow.first()
+ }
+
+ override fun onDismiss(dialog: DialogInterface) {
+ super.onDismiss(dialog)
+ if (finishWhenDone) {
+ activity?.finish()
+ }
+ }
+
+ override fun onCancel(dialog: DialogInterface) {
+ super.onCancel(dialog)
+ if (finishWhenDone) {
+ activity?.finish()
+ }
+ }
+}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/ProfileRenameFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/ProfileRenameFragment.kt
index 281e625..7987117 100644
--- a/app-common/src/main/java/im/angry/openeuicc/ui/ProfileRenameFragment.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/ui/ProfileRenameFragment.kt
@@ -2,33 +2,35 @@ package im.angry.openeuicc.ui
import android.app.Dialog
import android.os.Bundle
+import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.Toast
-import androidx.annotation.StringRes
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.lifecycleScope
import com.google.android.material.textfield.TextInputLayout
import im.angry.openeuicc.common.R
-import im.angry.openeuicc.service.EuiccChannelManagerService.Companion.waitDone
import im.angry.openeuicc.util.*
+import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
-import net.typeblog.lpac_jni.LocalProfileAssistant
+import kotlinx.coroutines.withContext
+import java.lang.Exception
+import java.lang.RuntimeException
class ProfileRenameFragment : BaseMaterialDialogFragment(), EuiccChannelFragmentMarker {
companion object {
- private const val FIELD_ICCID = "iccid"
- private const val FIELD_CURRENT_NAME = "currentName"
-
const val TAG = "ProfileRenameFragment"
- fun newInstance(slotId: Int, portId: Int, iccid: String, currentName: String) =
- newInstanceEuicc(ProfileRenameFragment::class.java, slotId, portId) {
- putString(FIELD_ICCID, iccid)
- putString(FIELD_CURRENT_NAME, currentName)
+ fun newInstance(slotId: Int, portId: Int, iccid: String, currentName: String): ProfileRenameFragment {
+ val instance = newInstanceEuicc(ProfileRenameFragment::class.java, slotId, portId)
+ instance.requireArguments().apply {
+ putString("iccid", iccid)
+ putString("currentName", currentName)
}
+ return instance
+ }
}
private lateinit var toolbar: Toolbar
@@ -37,14 +39,6 @@ class ProfileRenameFragment : BaseMaterialDialogFragment(), EuiccChannelFragment
private var renaming = false
- private val iccid: String by lazy {
- requireArguments().getString(FIELD_ICCID)!!
- }
-
- private val currentName: String by lazy {
- requireArguments().getString(FIELD_CURRENT_NAME)!!
- }
-
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
@@ -63,9 +57,8 @@ class ProfileRenameFragment : BaseMaterialDialogFragment(), EuiccChannelFragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
- profileRenameNewName.editText!!.setText(currentName)
toolbar.apply {
- setTitle(R.string.profile_rename)
+ setTitle(R.string.rename)
setNavigationOnClickListener {
if (!renaming) dismiss()
}
@@ -76,6 +69,11 @@ class ProfileRenameFragment : BaseMaterialDialogFragment(), EuiccChannelFragment
}
}
+ override fun onStart() {
+ super.onStart()
+ profileRenameNewName.editText!!.setText(requireArguments().getString("currentName"))
+ }
+
override fun onResume() {
super.onResume()
setWidthPercent(95)
@@ -87,45 +85,35 @@ class ProfileRenameFragment : BaseMaterialDialogFragment(), EuiccChannelFragment
}
}
- private fun showErrorAndCancel(@StringRes resId: Int) {
- Toast.makeText(requireContext(), resId, Toast.LENGTH_LONG).show()
-
- renaming = false
- progress.visibility = View.GONE
- }
-
private fun rename() {
+ val name = profileRenameNewName.editText!!.text.toString().trim()
+ if (name.length >= 64) {
+ Toast.makeText(context, R.string.toast_profile_name_too_long, Toast.LENGTH_LONG).show()
+ return
+ }
+
renaming = true
progress.isIndeterminate = true
progress.visibility = View.VISIBLE
- val newName = profileRenameNewName.editText!!.text.toString().trim()
-
lifecycleScope.launch {
- ensureEuiccChannelManager()
- euiccChannelManagerService.waitForForegroundTask()
- val response = euiccChannelManagerService
- .launchProfileRenameTask(slotId, portId, iccid, newName).waitDone()
-
- when (response) {
- is LocalProfileAssistant.ProfileNameTooLongException -> {
- showErrorAndCancel(R.string.profile_rename_too_long)
- }
-
- is LocalProfileAssistant.ProfileNameIsInvalidUTF8Exception -> {
- showErrorAndCancel(R.string.profile_rename_encoding_error)
- }
-
- is Throwable -> {
- showErrorAndCancel(R.string.profile_rename_failure)
- }
-
- else -> {
- parentFragment?.notifyEuiccProfilesChanged()
-
- runCatching(::dismiss)
+ try {
+ doRename(name)
+ } catch (e: Exception) {
+ Log.d(TAG, "Failed to rename profile")
+ Log.d(TAG, Log.getStackTraceString(e))
+ } finally {
+ if (parentFragment is EuiccProfilesChangedListener) {
+ (parentFragment as EuiccProfilesChangedListener).onEuiccProfilesChanged()
}
+ dismiss()
}
}
}
+
+ private suspend fun doRename(name: String) = withContext(Dispatchers.IO) {
+ if (!channel.lpa.setNickname(requireArguments().getString("iccid")!!, name)) {
+ throw RuntimeException("Profile nickname not changed")
+ }
+ }
}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/SettingsActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/SettingsActivity.kt
index bb299a3..426c546 100644
--- a/app-common/src/main/java/im/angry/openeuicc/ui/SettingsActivity.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/ui/SettingsActivity.kt
@@ -2,26 +2,17 @@ package im.angry.openeuicc.ui
import android.os.Bundle
import android.view.MenuItem
-import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
-import im.angry.openeuicc.OpenEuiccApplication
import im.angry.openeuicc.common.R
-import im.angry.openeuicc.util.*
class SettingsActivity: AppCompatActivity() {
- private val appContainer
- get() = (application as OpenEuiccApplication).appContainer
-
override fun onCreate(savedInstanceState: Bundle?) {
- enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
setSupportActionBar(requireViewById(R.id.toolbar))
- setupToolbarInsets()
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
- val settingsFragment = appContainer.uiComponentFactory.createSettingsFragment()
supportFragmentManager.beginTransaction()
- .replace(R.id.settings_container, settingsFragment)
+ .replace(R.id.settings_container, SettingsFragment())
.commit()
}
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/SettingsFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/SettingsFragment.kt
index 7a717ac..d471efa 100644
--- a/app-common/src/main/java/im/angry/openeuicc/ui/SettingsFragment.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/ui/SettingsFragment.kt
@@ -2,169 +2,60 @@ package im.angry.openeuicc.ui
import android.content.Intent
import android.net.Uri
-import android.os.Build
import android.os.Bundle
-import android.provider.Settings
-import android.widget.Toast
+import androidx.datastore.preferences.core.Preferences
import androidx.lifecycle.lifecycleScope
import androidx.preference.CheckBoxPreference
-import androidx.preference.ListPreference
import androidx.preference.Preference
-import androidx.preference.PreferenceCategory
import androidx.preference.PreferenceFragmentCompat
import im.angry.openeuicc.common.R
import im.angry.openeuicc.util.*
-import kotlinx.coroutines.flow.collect
-import kotlinx.coroutines.flow.onEach
+import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
-open class SettingsFragment: PreferenceFragmentCompat() {
- private lateinit var developerPref: PreferenceCategory
-
- // Hidden developer options switch
- private var numClicks = 0
- private var lastClickTimestamp = -1L
- private var lastToast: Toast? = null
-
+class SettingsFragment: PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.pref_settings, rootKey)
- developerPref = requirePreference("pref_developer")
+ findPreference("pref_info_app_version")
+ ?.summary = requireContext().selfAppVersion
- // Show / hide developer preference based on whether it is enabled
- lifecycleScope.launch {
- preferenceRepository.developerOptionsEnabledFlow
- .onEach(developerPref::setVisible)
- .collect()
- }
-
- requirePreference("pref_info_app_version").apply {
- summary = requireContext().selfAppVersion
-
- // Enable developer options when this is clicked for 7 times
- setOnPreferenceClickListener(::onAppVersionClicked)
- }
-
- requirePreference("pref_advanced_language").apply {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return@apply
- isVisible = true
- intent = Intent(Settings.ACTION_APP_LOCALE_SETTINGS).apply {
- data = Uri.fromParts("package", requireContext().packageName, null)
+ findPreference("pref_info_source_code")
+ ?.setOnPreferenceClickListener {
+ startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(it.summary.toString())))
+ true
}
- }
- requirePreference("pref_advanced_logs").apply {
- intent = Intent(requireContext(), LogsActivity::class.java)
- }
+ findPreference("pref_advanced_logs")
+ ?.setOnPreferenceClickListener {
+ startActivity(Intent(requireContext(), LogsActivity::class.java))
+ true
+ }
- requirePreference("pref_notifications_download")
- .bindBooleanFlow(preferenceRepository.notificationDownloadFlow)
+ findPreference("pref_notifications_download")
+ ?.bindBooleanFlow(preferenceRepository.notificationDownloadFlow, PreferenceKeys.NOTIFICATION_DOWNLOAD)
- requirePreference("pref_notifications_delete")
- .bindBooleanFlow(preferenceRepository.notificationDeleteFlow)
+ findPreference("pref_notifications_delete")
+ ?.bindBooleanFlow(preferenceRepository.notificationDeleteFlow, PreferenceKeys.NOTIFICATION_DELETE)
- requirePreference("pref_notifications_switch")
- .bindBooleanFlow(preferenceRepository.notificationSwitchFlow)
+ findPreference("pref_notifications_switch")
+ ?.bindBooleanFlow(preferenceRepository.notificationSwitchFlow, PreferenceKeys.NOTIFICATION_SWITCH)
- requirePreference("pref_advanced_disable_safeguard_removable_esim")
- .bindBooleanFlow(preferenceRepository.disableSafeguardFlow)
-
- requirePreference("pref_advanced_verbose_logging")
- .bindBooleanFlow(preferenceRepository.verboseLoggingFlow)
-
- requirePreference("pref_developer_unfiltered_profile_list")
- .bindBooleanFlow(preferenceRepository.unfilteredProfileListFlow)
-
- requirePreference("pref_developer_ignore_tls_certificate")
- .bindBooleanFlow(preferenceRepository.ignoreTLSCertificateFlow)
-
- requirePreference("pref_developer_refresh_after_switch")
- .bindBooleanFlow(preferenceRepository.refreshAfterSwitchFlow)
-
- requirePreference("pref_developer_euicc_memory_reset")
- .bindBooleanFlow(preferenceRepository.euiccMemoryResetFlow)
-
- requirePreference("pref_developer_es10x_mss")
- .bindIntFlow(preferenceRepository.es10xMssFlow, 63)
-
- requirePreference("pref_developer_isdr_aid_list").apply {
- intent = Intent(requireContext(), IsdrAidListActivity::class.java)
- }
+ findPreference("pref_advanced_disable_safeguard_removable_esim")
+ ?.bindBooleanFlow(preferenceRepository.disableSafeguardFlow, PreferenceKeys.DISABLE_SAFEGUARD_REMOVABLE_ESIM)
}
- protected fun requirePreference(key: CharSequence) =
- findPreference(key)!!
-
- override fun onStart() {
- super.onStart()
- setupRootViewInsets(requireView().requireViewById(R.id.recycler_view))
- }
-
- @Suppress("UNUSED_PARAMETER")
- private fun onAppVersionClicked(pref: Preference): Boolean {
- if (developerPref.isVisible) return false
-
- val now = System.currentTimeMillis()
- numClicks = if (now - lastClickTimestamp >= 1000) 1 else numClicks + 1
- lastClickTimestamp = now
-
+ private fun CheckBoxPreference.bindBooleanFlow(flow: Flow, key: Preferences.Key) {
lifecycleScope.launch {
- preferenceRepository.developerOptionsEnabledFlow.updatePreference(numClicks >= 7)
- }
-
- val toastText = when {
- numClicks == 7 -> getString(R.string.developer_options_enabled)
- numClicks > 1 -> getString(R.string.developer_options_steps, 7 - numClicks)
- else -> return true
- }
-
- lastToast?.cancel()
- lastToast = Toast.makeText(requireContext(), toastText, Toast.LENGTH_SHORT)
- lastToast!!.show()
- return true
- }
-
- protected fun CheckBoxPreference.bindBooleanFlow(flow: PreferenceFlowWrapper) {
- lifecycleScope.launch {
- flow.collect(::setChecked)
+ flow.collect { isChecked = it }
}
setOnPreferenceChangeListener { _, newValue ->
- lifecycleScope.launch {
- flow.updatePreference(newValue as Boolean)
+ runBlocking {
+ preferenceRepository.updatePreference(key, newValue as Boolean)
}
true
}
}
-
- private fun ListPreference.bindIntFlow(flow: PreferenceFlowWrapper, defaultValue: Int) {
- lifecycleScope.launch {
- flow.collect { value = it.toString() }
- }
-
- setOnPreferenceChangeListener { _, newValue ->
- lifecycleScope.launch {
- flow.updatePreference((newValue as String).toIntOrNull() ?: defaultValue)
- }
- true
- }
- }
-
- protected fun mergePreferenceOverlay(overlayKey: String, targetKey: String) {
- val overlayCat = requirePreference(overlayKey)
- val targetCat = requirePreference(targetKey)
-
- val prefs = buildList {
- for (i in 0..): SlotSelectFragment {
+ return SlotSelectFragment().apply {
+ arguments = Bundle().apply {
+ putIntArray("slotIds", knownChannels.map { it.slotId }.toIntArray())
+ putIntArray("logicalSlotIds", knownChannels.map { it.logicalSlotId }.toIntArray())
+ putIntArray("portIds", knownChannels.map { it.portId }.toIntArray())
+ }
+ }
+ }
+ }
+
+ interface SlotSelectedListener {
+ fun onSlotSelected(slotId: Int, portId: Int)
+ fun onSlotSelectCancelled()
+ }
+
+ private lateinit var toolbar: Toolbar
+ private lateinit var spinner: Spinner
+ private lateinit var adapter: ArrayAdapter
+ private lateinit var slotIds: IntArray
+ private lateinit var logicalSlotIds: IntArray
+ private lateinit var portIds: IntArray
+
+ override fun onCreateView(
+ inflater: LayoutInflater,
+ container: ViewGroup?,
+ savedInstanceState: Bundle?
+ ): View? {
+ val view = inflater.inflate(R.layout.fragment_slot_select, container, false)
+
+ toolbar = view.requireViewById(R.id.toolbar)
+ toolbar.setTitle(R.string.slot_select)
+ toolbar.inflateMenu(R.menu.fragment_slot_select)
+
+ adapter = ArrayAdapter(inflater.context, R.layout.spinner_item)
+
+ spinner = view.requireViewById(R.id.spinner)
+ spinner.adapter = adapter
+
+ return view
+ }
+
+ override fun onStart() {
+ super.onStart()
+
+ slotIds = requireArguments().getIntArray("slotIds")!!
+ logicalSlotIds = requireArguments().getIntArray("logicalSlotIds")!!
+ portIds = requireArguments().getIntArray("portIds")!!
+
+ logicalSlotIds.forEach { id ->
+ adapter.add(getString(R.string.channel_name_format, id))
+ }
+
+ toolbar.setNavigationOnClickListener {
+ (requireActivity() as SlotSelectedListener).onSlotSelectCancelled()
+ }
+ toolbar.setOnMenuItemClickListener {
+ val slotId = slotIds[spinner.selectedItemPosition]
+ val portId = portIds[spinner.selectedItemPosition]
+ (requireActivity() as SlotSelectedListener).onSlotSelected(slotId, portId)
+ dismiss()
+ true
+ }
+ }
+
+ override fun onResume() {
+ super.onResume()
+ setWidthPercent(75)
+ }
+
+ override fun onCancel(dialog: DialogInterface) {
+ super.onCancel(dialog)
+ (requireActivity() as SlotSelectedListener).onSlotSelectCancelled()
+ }
+}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/UsbCcidReaderFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/UsbCcidReaderFragment.kt
index 7a52ca0..3988b09 100644
--- a/app-common/src/main/java/im/angry/openeuicc/ui/UsbCcidReaderFragment.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/ui/UsbCcidReaderFragment.kt
@@ -20,6 +20,7 @@ import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.lifecycle.lifecycleScope
import im.angry.openeuicc.common.R
+import im.angry.openeuicc.core.EuiccChannel
import im.angry.openeuicc.core.EuiccChannelManager
import im.angry.openeuicc.util.*
import kotlinx.coroutines.Dispatchers
@@ -72,6 +73,7 @@ class UsbCcidReaderFragment : Fragment(), OpenEuiccContextMarker {
private lateinit var loadingProgress: ProgressBar
private var usbDevice: UsbDevice? = null
+ private var usbChannel: EuiccChannel? = null
override fun onCreateView(
inflater: LayoutInflater,
@@ -120,7 +122,7 @@ class UsbCcidReaderFragment : Fragment(), OpenEuiccContextMarker {
try {
requireContext().unregisterReceiver(usbPermissionReceiver)
} catch (_: Exception) {
- // ignore
+
}
}
@@ -129,7 +131,7 @@ class UsbCcidReaderFragment : Fragment(), OpenEuiccContextMarker {
try {
requireContext().unregisterReceiver(usbPermissionReceiver)
} catch (_: Exception) {
- // ignore
+
}
}
@@ -138,26 +140,24 @@ class UsbCcidReaderFragment : Fragment(), OpenEuiccContextMarker {
permissionButton.visibility = View.GONE
loadingProgress.visibility = View.VISIBLE
- val (device, canOpen) = withContext(Dispatchers.IO) {
- euiccChannelManager.tryOpenUsbEuiccChannel()
+ val (device, channel) = withContext(Dispatchers.IO) {
+ euiccChannelManager.enumerateUsbEuiccChannel()
}
loadingProgress.visibility = View.GONE
usbDevice = device
+ usbChannel = channel
- if (device != null && !canOpen && !usbManager.hasPermission(device)) {
+ if (device != null && channel == null && !usbManager.hasPermission(device)) {
text.text = getString(R.string.usb_permission_needed)
text.visibility = View.VISIBLE
permissionButton.visibility = View.VISIBLE
- } else if (device != null && canOpen) {
+ } else if (device != null && channel != null) {
childFragmentManager.commit {
replace(
R.id.child_container,
- appContainer.uiComponentFactory.createEuiccManagementFragment(
- slotId = EuiccChannelManager.USB_CHANNEL_ID,
- portId = 0
- )
+ appContainer.uiComponentFactory.createEuiccManagementFragment(channel)
)
}
} else {
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardActivity.kt
deleted file mode 100644
index 6574645..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardActivity.kt
+++ /dev/null
@@ -1,330 +0,0 @@
-package im.angry.openeuicc.ui.wizard
-
-import android.app.assist.AssistContent
-import android.os.Bundle
-import android.view.View
-import android.view.WindowManager
-import android.view.inputmethod.InputMethodManager
-import android.widget.Button
-import android.widget.ProgressBar
-import android.widget.Toast
-import androidx.activity.OnBackPressedCallback
-import androidx.activity.enableEdgeToEdge
-import androidx.core.net.toUri
-import androidx.core.view.ViewCompat
-import androidx.core.view.WindowInsetsCompat
-import androidx.core.view.updatePadding
-import androidx.fragment.app.Fragment
-import androidx.lifecycle.lifecycleScope
-import im.angry.openeuicc.common.R
-import im.angry.openeuicc.core.EuiccChannelManager
-import im.angry.openeuicc.ui.BaseEuiccAccessActivity
-import im.angry.openeuicc.util.*
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.launch
-import net.typeblog.lpac_jni.LocalProfileAssistant
-
-class DownloadWizardActivity: BaseEuiccAccessActivity() {
- data class DownloadWizardState(
- var currentStepFragmentClassName: String?,
- var selectedLogicalSlot: Int,
- var smdp: String,
- var matchingId: String?,
- var confirmationCode: String?,
- var imei: String?,
- var downloadStarted: Boolean,
- var downloadTaskID: Long,
- var downloadError: LocalProfileAssistant.ProfileDownloadException?,
- var skipMethodSelect: Boolean,
- var confirmationCodeRequired: Boolean,
- )
-
- private lateinit var state: DownloadWizardState
-
- private lateinit var progressBar: ProgressBar
- private lateinit var nextButton: Button
- private lateinit var prevButton: Button
-
- private var currentFragment: DownloadWizardStepFragment? = null
- set(value) {
- if (this::state.isInitialized) {
- state.currentStepFragmentClassName = value?.javaClass?.name
- }
- field = value
- }
-
- override fun onCreate(savedInstanceState: Bundle?) {
- enableEdgeToEdge()
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_download_wizard)
- onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
- override fun handleOnBackPressed() {
- // Make back == prev
- onPrevPressed()
- }
- })
-
- state = DownloadWizardState(
- currentStepFragmentClassName = null,
- selectedLogicalSlot = intent.getIntExtra("selectedLogicalSlot", 0),
- smdp = "",
- matchingId = null,
- confirmationCode = null,
- imei = null,
- downloadStarted = false,
- downloadTaskID = -1,
- downloadError = null,
- skipMethodSelect = false,
- confirmationCodeRequired = false,
- )
-
- handleDeepLink()
-
- progressBar = requireViewById(R.id.progress)
- nextButton = requireViewById(R.id.download_wizard_next)
- prevButton = requireViewById(R.id.download_wizard_back)
-
- nextButton.setOnClickListener {
- onNextPressed()
- }
-
- prevButton.setOnClickListener {
- onPrevPressed()
- }
-
- val navigation = requireViewById(R.id.download_wizard_navigation)
- val origHeight = navigation.layoutParams.height
-
- ViewCompat.setOnApplyWindowInsetsListener(navigation) { v, insets ->
- val bars = insets.getInsets(
- WindowInsetsCompat.Type.systemBars()
- or WindowInsetsCompat.Type.displayCutout()
- or WindowInsetsCompat.Type.ime()
- )
- v.updatePadding(bars.left, 0, bars.right, bars.bottom)
- val newParams = navigation.layoutParams
- newParams.height = origHeight + bars.bottom
- navigation.layoutParams = newParams
- WindowInsetsCompat.CONSUMED
- }
-
- val fragmentRoot = requireViewById(R.id.step_fragment_container)
- ViewCompat.setOnApplyWindowInsetsListener(fragmentRoot) { v, insets ->
- val bars = insets.getInsets(
- WindowInsetsCompat.Type.systemBars()
- or WindowInsetsCompat.Type.displayCutout()
- )
- v.updatePadding(bars.left, bars.top, bars.right, 0)
- WindowInsetsCompat.CONSUMED
- }
- }
-
- private fun handleDeepLink() {
- // If we get an LPA string from deep-link intents, extract from there.
- // Note that `onRestoreInstanceState` could override this with user input,
- // but that _is_ the desired behavior.
- val uri = intent.data ?: return
- if (uri.scheme.contentEquals("lpa", ignoreCase = true)) {
- val parsed = LPAString.parse(uri.schemeSpecificPart)
- state.smdp = parsed.address
- state.matchingId = parsed.matchingId
- state.confirmationCodeRequired = parsed.confirmationCodeRequired
- state.skipMethodSelect = true
- }
- }
-
- override fun onProvideAssistContent(outContent: AssistContent?) {
- super.onProvideAssistContent(outContent)
- outContent?.webUri = try {
- val activationCode = LPAString(
- state.smdp,
- state.matchingId,
- null,
- state.confirmationCode != null,
- )
- "LPA:$activationCode".toUri()
- } catch (_: Exception) {
- null
- }
- }
-
- override fun onSaveInstanceState(outState: Bundle) {
- super.onSaveInstanceState(outState)
- outState.putString("currentStepFragmentClassName", state.currentStepFragmentClassName)
- outState.putInt("selectedLogicalSlot", state.selectedLogicalSlot)
- outState.putString("smdp", state.smdp)
- outState.putString("matchingId", state.matchingId)
- outState.putString("confirmationCode", state.confirmationCode)
- outState.putString("imei", state.imei)
- outState.putBoolean("downloadStarted", state.downloadStarted)
- outState.putLong("downloadTaskID", state.downloadTaskID)
- outState.putBoolean("confirmationCodeRequired", state.confirmationCodeRequired)
- }
-
- override fun onRestoreInstanceState(savedInstanceState: Bundle) {
- super.onRestoreInstanceState(savedInstanceState)
- state.currentStepFragmentClassName = savedInstanceState.getString(
- "currentStepFragmentClassName",
- state.currentStepFragmentClassName
- )
- state.selectedLogicalSlot =
- savedInstanceState.getInt("selectedLogicalSlot", state.selectedLogicalSlot)
- state.smdp = savedInstanceState.getString("smdp", state.smdp)
- state.matchingId = savedInstanceState.getString("matchingId", state.matchingId)
- state.imei = savedInstanceState.getString("imei", state.imei)
- state.downloadStarted =
- savedInstanceState.getBoolean("downloadStarted", state.downloadStarted)
- state.downloadTaskID = savedInstanceState.getLong("downloadTaskID", state.downloadTaskID)
- state.confirmationCode = savedInstanceState.getString("confirmationCode", state.confirmationCode)
- state.confirmationCodeRequired = savedInstanceState.getBoolean("confirmationCodeRequired", state.confirmationCodeRequired)
- }
-
- private fun onPrevPressed() {
- hideIme()
-
- if (currentFragment?.hasPrev == true) {
- val prevFrag = currentFragment?.createPrevFragment()
- if (prevFrag == null) {
- finish()
- } else {
- showFragment(prevFrag, R.anim.slide_in_left, R.anim.slide_out_right)
- }
- }
- }
-
- private fun onNextPressed() {
- hideIme()
-
- nextButton.isEnabled = false
- progressBar.visibility = View.VISIBLE
- progressBar.isIndeterminate = true
-
- lifecycleScope.launch(Dispatchers.Main) {
- if (state.selectedLogicalSlot >= 0) {
- try {
- // This is run on IO by default
- euiccChannelManager.withEuiccChannel(state.selectedLogicalSlot) { channel ->
- // Be _very_ sure that the channel we got is valid
- if (!channel.valid) throw EuiccChannelManager.EuiccChannelNotFoundException()
- }
- } catch (e: EuiccChannelManager.EuiccChannelNotFoundException) {
- Toast.makeText(
- this@DownloadWizardActivity,
- R.string.download_wizard_slot_removed,
- Toast.LENGTH_LONG
- ).show()
- finish()
- }
- }
-
- progressBar.visibility = View.GONE
- nextButton.isEnabled = true
-
- if (currentFragment?.hasNext == true) {
- currentFragment?.beforeNext()
- val nextFrag = currentFragment?.createNextFragment()
- if (nextFrag == null) {
- finish()
- } else {
- showFragment(nextFrag, R.anim.slide_in_right, R.anim.slide_out_left)
- }
- }
- }
- }
-
- override fun onInit() {
- progressBar.visibility = View.GONE
-
- if (state.currentStepFragmentClassName != null) {
- val clazz = Class.forName(state.currentStepFragmentClassName!!)
- showFragment(clazz.getDeclaredConstructor().newInstance() as DownloadWizardStepFragment)
- } else {
- showFragment(DownloadWizardSlotSelectFragment())
- }
- }
-
- private fun showFragment(
- nextFrag: DownloadWizardStepFragment,
- enterAnim: Int = 0,
- exitAnim: Int = 0
- ) {
- currentFragment = nextFrag
- supportFragmentManager.beginTransaction().setCustomAnimations(enterAnim, exitAnim)
- .replace(R.id.step_fragment_container, nextFrag)
- .commit()
-
- // Sync screen on state
- if (nextFrag.keepScreenOn) {
- window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
- } else {
- window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
- }
-
- refreshButtons()
- }
-
- private fun refreshButtons() {
- currentFragment?.let {
- nextButton.visibility = if (it.hasNext) {
- View.VISIBLE
- } else {
- View.GONE
- }
- prevButton.visibility = if (it.hasPrev) {
- View.VISIBLE
- } else {
- View.GONE
- }
- }
- }
-
- private fun hideIme() {
- currentFocus?.let {
- val imm = getSystemService(InputMethodManager::class.java)
- imm.hideSoftInputFromWindow(it.windowToken, 0)
- }
- }
-
- abstract class DownloadWizardStepFragment : Fragment(), OpenEuiccContextMarker {
- protected val state: DownloadWizardState
- get() = (requireActivity() as DownloadWizardActivity).state
-
- open val keepScreenOn = false
-
- abstract val hasNext: Boolean
- abstract val hasPrev: Boolean
- abstract fun createNextFragment(): DownloadWizardStepFragment?
- abstract fun createPrevFragment(): DownloadWizardStepFragment?
-
- protected fun gotoNextFragment(next: DownloadWizardStepFragment? = null) {
- val realNext = next ?: createNextFragment()
- (requireActivity() as DownloadWizardActivity).showFragment(
- realNext!!,
- R.anim.slide_in_right,
- R.anim.slide_out_left
- )
- }
-
- protected fun hideProgressBar() {
- (requireActivity() as DownloadWizardActivity).progressBar.visibility = View.GONE
- }
-
- protected fun showProgressBar(progressValue: Int) {
- (requireActivity() as DownloadWizardActivity).progressBar.apply {
- visibility = View.VISIBLE
- if (progressValue >= 0) {
- isIndeterminate = false
- progress = progressValue
- } else {
- isIndeterminate = true
- }
- }
- }
-
- protected fun refreshButtons() {
- (requireActivity() as DownloadWizardActivity).refreshButtons()
- }
-
- open fun beforeNext() {}
- }
-}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardDetailsFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardDetailsFragment.kt
deleted file mode 100644
index 1c69de5..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardDetailsFragment.kt
+++ /dev/null
@@ -1,117 +0,0 @@
-package im.angry.openeuicc.ui.wizard
-
-import android.os.Bundle
-import android.view.LayoutInflater
-import android.view.View
-import android.view.ViewGroup
-import androidx.core.widget.addTextChangedListener
-import com.google.android.material.textfield.TextInputLayout
-import im.angry.openeuicc.common.R
-
-class DownloadWizardDetailsFragment : DownloadWizardActivity.DownloadWizardStepFragment() {
- private var inputComplete = false
-
- override val hasNext: Boolean
- get() = inputComplete
- override val hasPrev: Boolean
- get() = true
-
- private lateinit var smdp: TextInputLayout
- private lateinit var matchingId: TextInputLayout
- private lateinit var confirmationCode: TextInputLayout
- private lateinit var imei: TextInputLayout
-
- private fun saveState() {
- state.smdp = smdp.editText!!.text.toString().trim()
- // Treat empty inputs as null -- this is important for the download step
- state.matchingId = matchingId.editText!!.text.toString().trim().ifBlank { null }
- state.confirmationCode = confirmationCode.editText!!.text.toString().trim().ifBlank { null }
- state.imei = imei.editText!!.text.toString().ifBlank { null }
- }
-
- override fun beforeNext() = saveState()
-
- override fun createNextFragment(): DownloadWizardActivity.DownloadWizardStepFragment =
- DownloadWizardProgressFragment()
-
- override fun createPrevFragment(): DownloadWizardActivity.DownloadWizardStepFragment =
- if (state.skipMethodSelect) {
- DownloadWizardSlotSelectFragment()
- } else {
- DownloadWizardMethodSelectFragment()
- }
-
- override fun onCreateView(
- inflater: LayoutInflater,
- container: ViewGroup?,
- savedInstanceState: Bundle?
- ): View? {
- val view = inflater.inflate(R.layout.fragment_download_details, container, false)
- smdp = view.requireViewById(R.id.profile_download_server)
- matchingId = view.requireViewById(R.id.profile_download_code)
- confirmationCode = view.requireViewById(R.id.profile_download_confirmation_code)
- imei = view.requireViewById(R.id.profile_download_imei)
- smdp.editText!!.addTextChangedListener {
- updateInputCompleteness()
- }
- confirmationCode.editText!!.addTextChangedListener {
- updateInputCompleteness()
- }
- return view
- }
-
- override fun onStart() {
- super.onStart()
- smdp.editText!!.setText(state.smdp)
- matchingId.editText!!.setText(state.matchingId)
- confirmationCode.editText!!.setText(state.confirmationCode)
- imei.editText!!.setText(state.imei)
- updateInputCompleteness()
-
- if (state.confirmationCodeRequired) {
- confirmationCode.editText!!.requestFocus()
- confirmationCode.editText!!.hint =
- getString(R.string.profile_download_confirmation_code_required)
- } else {
- confirmationCode.editText!!.hint =
- getString(R.string.profile_download_confirmation_code)
- }
- }
-
- override fun onPause() {
- super.onPause()
- saveState()
- }
-
- private fun updateInputCompleteness() {
- inputComplete = isValidAddress(smdp.editText!!.text)
- if (state.confirmationCodeRequired) {
- inputComplete = inputComplete && confirmationCode.editText!!.text.isNotEmpty()
- }
- refreshButtons()
- }
-}
-
-private fun isValidAddress(input: CharSequence): Boolean {
- if (!input.contains('.')) return false
- var fqdn = input
- var port = 443
- if (input.contains(':')) {
- val portIndex = input.lastIndexOf(':')
- fqdn = input.substring(0, portIndex)
- port = input.substring(portIndex + 1, input.length).toIntOrNull(10) ?: 0
- }
- // see https://en.wikipedia.org/wiki/Port_(computer_networking)
- if (port < 1 || port > 0xffff) return false
- // see https://en.wikipedia.org/wiki/Fully_qualified_domain_name
- if (fqdn.isEmpty() || fqdn.length > 255) return false
- for (part in fqdn.split('.')) {
- if (part.isEmpty() || part.length > 64) return false
- if (part.first() == '-' || part.last() == '-') return false
- for (c in part) {
- if (c.isLetterOrDigit() || c == '-') continue
- return false
- }
- }
- return true
-}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardDiagnosticsFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardDiagnosticsFragment.kt
deleted file mode 100644
index 3841868..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardDiagnosticsFragment.kt
+++ /dev/null
@@ -1,141 +0,0 @@
-package im.angry.openeuicc.ui.wizard
-
-import android.icu.text.SimpleDateFormat
-import android.os.Bundle
-import android.view.LayoutInflater
-import android.view.View
-import android.view.ViewGroup
-import android.widget.TextView
-import im.angry.openeuicc.common.R
-import im.angry.openeuicc.util.*
-import org.json.JSONObject
-import java.util.Date
-
-class DownloadWizardDiagnosticsFragment : DownloadWizardActivity.DownloadWizardStepFragment() {
- override val hasNext: Boolean
- get() = true
- override val hasPrev: Boolean
- get() = false
-
- private lateinit var diagnosticTextView: TextView
-
- private val saveDiagnostics =
- setupLogSaving(
- getLogFileName = {
- getString(
- R.string.download_wizard_diagnostics_file_template,
- SimpleDateFormat.getDateTimeInstance().format(Date())
- )
- },
- getLogText = { diagnosticTextView.text.toString() }
- )
-
- override fun createNextFragment(): DownloadWizardActivity.DownloadWizardStepFragment? = null
-
- override fun createPrevFragment(): DownloadWizardActivity.DownloadWizardStepFragment? = null
-
- override fun onCreateView(
- inflater: LayoutInflater,
- container: ViewGroup?,
- savedInstanceState: Bundle?
- ): View? {
- val view = inflater.inflate(R.layout.fragment_download_diagnostics, container, false)
- view.requireViewById(R.id.download_wizard_diagnostics_save).setOnClickListener {
- saveDiagnostics()
- }
- diagnosticTextView = view.requireViewById(R.id.download_wizard_diagnostics_text)
- return view
- }
-
- override fun onStart() {
- super.onStart()
- val str = buildDiagnosticsText()
- if (str == null) {
- requireActivity().finish()
- return
- }
-
- diagnosticTextView.text = str
- }
-
- private fun buildDiagnosticsText(): String? = state.downloadError?.let { err ->
- val ret = StringBuilder()
-
- ret.appendLine(
- getString(
- R.string.download_wizard_diagnostics_error_code,
- err.lpaErrorReason
- )
- )
- ret.appendLine()
-
- err.lastHttpResponse?.let { resp ->
- if (resp.rcode != 200) {
- // Only show the status if it's not 200
- // Because we can have errors even if the rcode is 200 due to SM-DP+ servers being dumb
- // and showing 200 might mislead users
- ret.appendLine(
- getString(
- R.string.download_wizard_diagnostics_last_http_status,
- resp.rcode
- )
- )
- ret.appendLine()
- }
-
- ret.appendLine(getString(R.string.download_wizard_diagnostics_last_http_response))
- ret.appendLine()
-
- val str = resp.data.decodeToString(throwOnInvalidSequence = false)
-
- ret.appendLine(
- if (str.startsWith('{')) {
- JSONObject(str).toString(2)
- } else {
- str
- }
- )
-
- ret.appendLine()
- }
-
- err.lastHttpException?.let { e ->
- ret.appendLine(getString(R.string.download_wizard_diagnostics_last_http_exception))
- ret.appendLine()
- ret.appendLine("${e.javaClass.name}: ${e.message}")
- ret.appendLine(e.stackTrace.joinToString("\n"))
- ret.appendLine()
- }
-
- err.lastApduResponse?.let { resp ->
- val isSuccess =
- resp.size >= 2 && resp[resp.size - 2] == 0x90.toByte() && resp[resp.size - 1] == 0x00.toByte()
-
- if (isSuccess) {
- ret.appendLine(getString(R.string.download_wizard_diagnostics_last_apdu_response_success))
- } else {
- // Only show the full APDU response when it's a failure
- // Otherwise it's going to get very crammed
- ret.appendLine(
- getString(
- R.string.download_wizard_diagnostics_last_apdu_response,
- resp.encodeHex()
- )
- )
- ret.appendLine()
-
- ret.appendLine(getString(R.string.download_wizard_diagnostics_last_apdu_response_fail))
- }
- }
-
- err.lastApduException?.let { e ->
- ret.appendLine(getString(R.string.download_wizard_diagnostics_last_apdu_exception))
- ret.appendLine()
- ret.appendLine("${e.javaClass.name}: ${e.message}")
- ret.appendLine(e.stackTrace.joinToString("\n"))
- ret.appendLine()
- }
-
- ret.toString()
- }
-}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardMethodSelectFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardMethodSelectFragment.kt
deleted file mode 100644
index 4b02b7a..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardMethodSelectFragment.kt
+++ /dev/null
@@ -1,173 +0,0 @@
-package im.angry.openeuicc.ui.wizard
-
-import android.app.AlertDialog
-import android.content.ClipboardManager
-import android.graphics.BitmapFactory
-import android.os.Bundle
-import android.view.LayoutInflater
-import android.view.View
-import android.view.ViewGroup
-import android.widget.ImageView
-import android.widget.TextView
-import android.widget.Toast
-import androidx.activity.result.contract.ActivityResultContracts
-import androidx.lifecycle.lifecycleScope
-import androidx.recyclerview.widget.DividerItemDecoration
-import androidx.recyclerview.widget.LinearLayoutManager
-import androidx.recyclerview.widget.RecyclerView
-import androidx.recyclerview.widget.RecyclerView.ViewHolder
-import com.journeyapps.barcodescanner.ScanContract
-import com.journeyapps.barcodescanner.ScanOptions
-import im.angry.openeuicc.common.R
-import im.angry.openeuicc.util.*
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.launch
-import kotlinx.coroutines.withContext
-
-class DownloadWizardMethodSelectFragment : DownloadWizardActivity.DownloadWizardStepFragment() {
- data class DownloadMethod(
- val iconRes: Int,
- val titleRes: Int,
- val onClick: () -> Unit
- )
-
- // TODO: Maybe we should find a better barcode scanner (or an external one?)
- private val barcodeScannerLauncher = registerForActivityResult(ScanContract()) { result ->
- result.contents?.let { content ->
- processLpaString(content)
- }
- }
-
- private val gallerySelectorLauncher =
- registerForActivityResult(ActivityResultContracts.GetContent()) { result ->
- if (result == null) return@registerForActivityResult
-
- lifecycleScope.launch {
- val decoded = withContext(Dispatchers.IO) {
- runCatching {
- requireContext().contentResolver.openInputStream(result)?.use { input ->
- BitmapFactory.decodeStream(input).use(::decodeQrFromBitmap)
- }
- }
- }
-
- decoded.getOrNull()?.let { processLpaString(it) }
- }
- }
-
- val downloadMethods = arrayOf(
- DownloadMethod(R.drawable.ic_scan_black, R.string.download_wizard_method_qr_code) {
- barcodeScannerLauncher.launch(ScanOptions().apply {
- setDesiredBarcodeFormats(ScanOptions.QR_CODE)
- setOrientationLocked(false)
- })
- },
- DownloadMethod(R.drawable.ic_gallery_black, R.string.download_wizard_method_gallery) {
- gallerySelectorLauncher.launch("image/*")
- },
- DownloadMethod(R.drawable.ic_paste_go, R.string.download_wizard_method_clipboard) {
- handleLoadFromClipboard()
- },
- DownloadMethod(R.drawable.ic_edit, R.string.download_wizard_method_manual) {
- gotoNextFragment(DownloadWizardDetailsFragment())
- }
- )
-
- override val hasNext: Boolean
- get() = false
- override val hasPrev: Boolean
- get() = true
-
- override fun createNextFragment(): DownloadWizardActivity.DownloadWizardStepFragment? =
- null
-
- override fun createPrevFragment(): DownloadWizardActivity.DownloadWizardStepFragment =
- DownloadWizardSlotSelectFragment()
-
- override fun onCreateView(
- inflater: LayoutInflater,
- container: ViewGroup?,
- savedInstanceState: Bundle?
- ): View? {
- val view = inflater.inflate(R.layout.fragment_download_method_select, container, false)
- val recyclerView = view.requireViewById(R.id.download_method_list)
- recyclerView.adapter = DownloadMethodAdapter()
- recyclerView.layoutManager =
- LinearLayoutManager(view.context, LinearLayoutManager.VERTICAL, false)
- recyclerView.addItemDecoration(
- DividerItemDecoration(
- requireContext(),
- LinearLayoutManager.VERTICAL
- )
- )
- return view
- }
-
- private fun handleLoadFromClipboard() {
- val clipboard = requireContext().getSystemService(ClipboardManager::class.java)
- val text = clipboard.primaryClip?.getItemAt(0)?.text
-
- if (text == null) {
- Toast.makeText(
- requireContext(),
- R.string.profile_download_no_lpa_string,
- Toast.LENGTH_SHORT
- ).show()
- return
- }
-
- processLpaString(text.toString())
- }
-
- private fun processLpaString(input: String) {
- try {
- val parsed = LPAString.parse(input)
- state.smdp = parsed.address
- state.matchingId = parsed.matchingId
- state.confirmationCodeRequired = parsed.confirmationCodeRequired
- gotoNextFragment(DownloadWizardDetailsFragment())
- } catch (e: IllegalArgumentException) {
- AlertDialog.Builder(requireContext()).apply {
- setTitle(R.string.profile_download_incorrect_lpa_string)
- setMessage(R.string.profile_download_incorrect_lpa_string_message)
- setCancelable(true)
- setNegativeButton(android.R.string.cancel, null)
- show()
- }
- }
- }
-
- private inner class DownloadMethodViewHolder(private val root: View) : ViewHolder(root) {
- private val icon = root.requireViewById(R.id.download_method_icon)
- private val title = root.requireViewById(R.id.download_method_title)
-
- fun bind(item: DownloadMethod) {
- icon.setImageResource(item.iconRes)
- title.setText(item.titleRes)
- root.setOnClickListener {
- // If the user elected to use another download method, reset the confirmation code flag
- // too
- state.confirmationCodeRequired = false
- item.onClick()
- }
- }
- }
-
- private inner class DownloadMethodAdapter : RecyclerView.Adapter() {
- override fun onCreateViewHolder(
- parent: ViewGroup,
- viewType: Int
- ): DownloadMethodViewHolder {
- val view = LayoutInflater.from(parent.context)
- .inflate(R.layout.download_method_item, parent, false)
- return DownloadMethodViewHolder(view)
- }
-
- override fun getItemCount(): Int = downloadMethods.size
-
- override fun onBindViewHolder(holder: DownloadMethodViewHolder, position: Int) {
- holder.bind(downloadMethods[position])
- }
-
- }
-}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardProgressFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardProgressFragment.kt
deleted file mode 100644
index 0048190..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardProgressFragment.kt
+++ /dev/null
@@ -1,261 +0,0 @@
-package im.angry.openeuicc.ui.wizard
-
-import android.os.Bundle
-import android.view.LayoutInflater
-import android.view.View
-import android.view.ViewGroup
-import android.widget.ImageView
-import android.widget.ProgressBar
-import android.widget.TextView
-import androidx.annotation.StringRes
-import androidx.lifecycle.lifecycleScope
-import androidx.recyclerview.widget.DividerItemDecoration
-import androidx.recyclerview.widget.LinearLayoutManager
-import androidx.recyclerview.widget.RecyclerView
-import im.angry.openeuicc.common.R
-import im.angry.openeuicc.service.EuiccChannelManagerService
-import im.angry.openeuicc.util.*
-import kotlinx.coroutines.flow.collect
-import kotlinx.coroutines.flow.onEach
-import kotlinx.coroutines.launch
-import net.typeblog.lpac_jni.LocalProfileAssistant
-import net.typeblog.lpac_jni.ProfileDownloadCallback
-
-class DownloadWizardProgressFragment : DownloadWizardActivity.DownloadWizardStepFragment() {
- companion object {
- /**
- * An array of LPA-side state types, mapping 1:1 to progressItems
- */
- val LPA_PROGRESS_STATES = arrayOf(
- ProfileDownloadCallback.DownloadState.Preparing,
- ProfileDownloadCallback.DownloadState.Connecting,
- ProfileDownloadCallback.DownloadState.Authenticating,
- ProfileDownloadCallback.DownloadState.Downloading,
- ProfileDownloadCallback.DownloadState.Finalizing,
- )
- }
-
- private enum class ProgressState {
- NotStarted,
- InProgress,
- Done,
- Error
- }
-
- private data class ProgressItem(
- @StringRes val titleRes: Int,
- var state: ProgressState = ProgressState.NotStarted,
- var errorMessage: SimplifiedErrorMessages? = null,
- )
-
- private val progressItems = arrayOf(
- ProgressItem(R.string.download_wizard_progress_step_preparing),
- ProgressItem(R.string.download_wizard_progress_step_connecting),
- ProgressItem(R.string.download_wizard_progress_step_authenticating),
- ProgressItem(R.string.download_wizard_progress_step_downloading),
- ProgressItem(R.string.download_wizard_progress_step_finalizing)
- )
-
- private val adapter = ProgressItemAdapter()
-
- // We don't want to turn off the screen during a download
- override val keepScreenOn = true
-
- private var isDone = false
-
- override val hasNext: Boolean
- get() = isDone
- override val hasPrev: Boolean
- get() = false
-
- override fun createNextFragment(): DownloadWizardActivity.DownloadWizardStepFragment? =
- if (state.downloadError != null) {
- DownloadWizardDiagnosticsFragment()
- } else {
- null
- }
-
- override fun createPrevFragment(): DownloadWizardActivity.DownloadWizardStepFragment? = null
-
- override fun onCreateView(
- inflater: LayoutInflater,
- container: ViewGroup?,
- savedInstanceState: Bundle?
- ): View? {
- val view = inflater.inflate(R.layout.fragment_download_progress, container, false)
- val recyclerView = view.requireViewById(R.id.download_progress_list)
- recyclerView.adapter = adapter
- recyclerView.layoutManager =
- LinearLayoutManager(view.context, LinearLayoutManager.VERTICAL, false)
- recyclerView.addItemDecoration(
- DividerItemDecoration(
- requireContext(),
- LinearLayoutManager.VERTICAL
- )
- )
- return view
- }
-
- override fun onStart() {
- super.onStart()
-
- lifecycleScope.launch {
- showProgressBar(-1) // set indeterminate first
- ensureEuiccChannelManager()
-
- val subscriber = startDownloadOrSubscribe()
-
- if (subscriber == null) {
- requireActivity().finish()
- return@launch
- }
-
- subscriber.onEach {
- when (it) {
- is EuiccChannelManagerService.ForegroundTaskState.Done -> {
- hideProgressBar()
-
- state.downloadError =
- it.error as? LocalProfileAssistant.ProfileDownloadException
-
- // Change the state of the last InProgress item to success (or error)
- progressItems.forEachIndexed { index, progressItem ->
- if (progressItem.state == ProgressState.InProgress) {
- if (state.downloadError == null) {
- progressItem.state = ProgressState.Done
- } else {
- progressItem.state = ProgressState.Error
- progressItem.errorMessage =
- SimplifiedErrorMessages.fromDownloadError(state.downloadError!!)
- }
- }
-
- adapter.notifyItemChanged(index)
- }
-
- isDone = true
- refreshButtons()
- }
-
- is EuiccChannelManagerService.ForegroundTaskState.InProgress ->
- updateProgress(it.progress)
-
- else -> {}
- }
- }.collect()
- }
- }
-
- private suspend fun startDownloadOrSubscribe(): EuiccChannelManagerService.ForegroundTaskSubscriberFlow? =
- if (state.downloadStarted) {
- // This will also return null if task ID is -1 (uninitialized), too
- euiccChannelManagerService.recoverForegroundTaskSubscriber(state.downloadTaskID)
- } else {
- euiccChannelManagerService.waitForForegroundTask()
-
- val (slotId, portId) = euiccChannelManager.withEuiccChannel(state.selectedLogicalSlot) { channel ->
- Pair(channel.slotId, channel.portId)
- }
-
- // Set started to true even before we start -- in case we get killed in the middle
- state.downloadStarted = true
-
- val ret = euiccChannelManagerService.launchProfileDownloadTask(
- slotId,
- portId,
- state.smdp,
- state.matchingId,
- state.confirmationCode,
- state.imei
- )
-
- state.downloadTaskID = ret.taskId
-
- ret
- }
-
- private fun updateProgress(progress: Int) {
- showProgressBar(progress)
-
- val lpaState = ProfileDownloadCallback.lookupStateFromProgress(progress)
- val stateIndex = LPA_PROGRESS_STATES.indexOf(lpaState)
-
- if (stateIndex > 0) {
- for (i in (0..(R.id.download_progress_item_title)
- private val progressBar =
- root.requireViewById(R.id.download_progress_icon_progress)
- private val icon = root.requireViewById(R.id.download_progress_icon)
- private val errorTitle =
- root.requireViewById(R.id.download_progress_item_error_title)
- private val errorSuggestion =
- root.requireViewById(R.id.download_progress_item_error_suggestion)
-
- fun bind(item: ProgressItem) {
- title.text = getString(item.titleRes)
- errorTitle.visibility = View.GONE
- errorSuggestion.visibility = View.GONE
-
- when (item.state) {
- ProgressState.NotStarted -> {
- progressBar.visibility = View.GONE
- icon.visibility = View.GONE
- }
-
- ProgressState.InProgress -> {
- progressBar.visibility = View.VISIBLE
- icon.visibility = View.GONE
- }
-
- ProgressState.Done -> {
- progressBar.visibility = View.GONE
- icon.setImageResource(R.drawable.ic_checkmark_outline)
- icon.visibility = View.VISIBLE
- }
-
- ProgressState.Error -> {
- progressBar.visibility = View.GONE
- icon.setImageResource(R.drawable.ic_error_outline)
- icon.visibility = View.VISIBLE
-
- item.errorMessage?.titleResId?.let {
- errorTitle.visibility = View.VISIBLE
- errorTitle.text = getString(it)
- }
- item.errorMessage?.suggestResId?.let {
- errorSuggestion.visibility = View.VISIBLE
- errorSuggestion.text = getString(it)
- }
- }
- }
- }
- }
-
- private inner class ProgressItemAdapter : RecyclerView.Adapter() {
- override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProgressItemHolder {
- val root = LayoutInflater.from(parent.context)
- .inflate(R.layout.download_progress_item, parent, false)
- return ProgressItemHolder(root)
- }
-
- override fun getItemCount(): Int = progressItems.size
-
- override fun onBindViewHolder(holder: ProgressItemHolder, position: Int) {
- holder.bind(progressItems[position])
- }
- }
-}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardSlotSelectFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardSlotSelectFragment.kt
deleted file mode 100644
index 8097058..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardSlotSelectFragment.kt
+++ /dev/null
@@ -1,218 +0,0 @@
-package im.angry.openeuicc.ui.wizard
-
-import android.annotation.SuppressLint
-import android.os.Bundle
-import android.view.LayoutInflater
-import android.view.View
-import android.view.ViewGroup
-import android.widget.CheckBox
-import android.widget.TextView
-import androidx.appcompat.app.AlertDialog
-import androidx.lifecycle.lifecycleScope
-import androidx.recyclerview.widget.DividerItemDecoration
-import androidx.recyclerview.widget.LinearLayoutManager
-import androidx.recyclerview.widget.RecyclerView
-import androidx.recyclerview.widget.RecyclerView.ViewHolder
-import im.angry.openeuicc.common.R
-import im.angry.openeuicc.core.EuiccChannelManager
-import im.angry.openeuicc.util.*
-import kotlinx.coroutines.flow.map
-import kotlinx.coroutines.flow.toList
-import kotlinx.coroutines.launch
-
-class DownloadWizardSlotSelectFragment : DownloadWizardActivity.DownloadWizardStepFragment() {
- companion object {
- const val LOW_NVRAM_THRESHOLD =
- 30 * 1024 // < 30 KiB, alert about potential download failure
- }
-
- private data class SlotInfo(
- val logicalSlotId: Int,
- val isRemovable: Boolean,
- val hasMultiplePorts: Boolean,
- val portId: Int,
- val eID: String,
- val freeSpace: Int,
- val imei: String,
- val enabledProfileName: String?,
- val intrinsicChannelName: String?,
- )
-
- private var loaded = false
-
- private val adapter = SlotInfoAdapter()
-
- override val hasNext: Boolean
- get() = loaded && adapter.slots.isNotEmpty()
- override val hasPrev: Boolean
- get() = true
-
- override fun createNextFragment(): DownloadWizardActivity.DownloadWizardStepFragment =
- if (state.skipMethodSelect) {
- DownloadWizardDetailsFragment()
- } else {
- DownloadWizardMethodSelectFragment()
- }
-
- override fun createPrevFragment(): DownloadWizardActivity.DownloadWizardStepFragment? = null
-
- override fun beforeNext() {
- super.beforeNext()
-
- if (adapter.selected.freeSpace < LOW_NVRAM_THRESHOLD) {
- val activity = requireActivity()
-
- AlertDialog.Builder(requireContext()).apply {
- setTitle(R.string.profile_download_low_nvram_title)
- setMessage(R.string.profile_download_low_nvram_message)
- setCancelable(true)
- setPositiveButton(android.R.string.ok, null)
- setNegativeButton(android.R.string.cancel) { _, _ ->
- activity.finish()
- }
- show()
- }
- }
- }
-
- override fun onCreateView(
- inflater: LayoutInflater,
- container: ViewGroup?,
- savedInstanceState: Bundle?
- ): View? {
- val view = inflater.inflate(R.layout.fragment_download_slot_select, container, false)
- val recyclerView = view.requireViewById(R.id.download_slot_list)
- recyclerView.adapter = adapter
- recyclerView.layoutManager =
- LinearLayoutManager(view.context, LinearLayoutManager.VERTICAL, false)
- recyclerView.addItemDecoration(DividerItemDecoration(requireContext(), LinearLayoutManager.VERTICAL))
- return view
- }
-
- override fun onStart() {
- super.onStart()
- if (!loaded) {
- lifecycleScope.launch { init() }
- }
- }
-
- @SuppressLint("NotifyDataSetChanged", "MissingPermission")
- private suspend fun init() {
- ensureEuiccChannelManager()
- showProgressBar(-1)
- val slots = euiccChannelManager.flowAllOpenEuiccPorts().map { (slotId, portId) ->
- euiccChannelManager.withEuiccChannel(slotId, portId) { channel ->
- SlotInfo(
- channel.logicalSlotId,
- channel.port.card.isRemovable,
- channel.port.card.ports.size > 1,
- channel.portId,
- channel.lpa.eID,
- channel.lpa.euiccInfo2?.freeNvram ?: 0,
- try {
- telephonyManager.getImei(channel.logicalSlotId) ?: ""
- } catch (e: Exception) {
- ""
- },
- channel.lpa.profiles.enabled?.displayName,
- channel.intrinsicChannelName,
- )
- }
- }.toList().sortedBy { it.logicalSlotId }
- adapter.slots = slots
-
- // Ensure we always have a selected slot by default
- val selectedIdx = slots.indexOfFirst { it.logicalSlotId == state.selectedLogicalSlot }
- adapter.currentSelectedIdx = if (selectedIdx > 0) {
- selectedIdx
- } else {
- if (slots.isNotEmpty()) {
- state.selectedLogicalSlot = slots[0].logicalSlotId
- }
- 0
- }
-
- if (slots.isNotEmpty()) {
- state.imei = slots[adapter.currentSelectedIdx].imei
- }
-
- adapter.notifyDataSetChanged()
- hideProgressBar()
- loaded = true
- refreshButtons()
- }
-
- private inner class SlotItemHolder(val root: View) : ViewHolder(root) {
- private val title = root.requireViewById(R.id.slot_item_title)
- private val type = root.requireViewById(R.id.slot_item_type)
- private val eID = root.requireViewById(R.id.slot_item_eid)
- private val activeProfile = root.requireViewById(R.id.slot_item_active_profile)
- private val freeSpace = root.requireViewById(R.id.slot_item_free_space)
- private val checkBox = root.requireViewById(R.id.slot_checkbox)
-
- private var curIdx = -1
-
- init {
- root.setOnClickListener(this::onSelect)
- checkBox.setOnClickListener(this::onSelect)
- }
-
- @Suppress("UNUSED_PARAMETER")
- fun onSelect(view: View) {
- if (curIdx < 0) return
- checkBox.isChecked = true
- if (adapter.currentSelectedIdx == curIdx) return
- val lastIdx = adapter.currentSelectedIdx
- adapter.currentSelectedIdx = curIdx
- adapter.notifyItemChanged(lastIdx)
- adapter.notifyItemChanged(curIdx)
- // Selected index isn't logical slot ID directly, needs a conversion
- state.selectedLogicalSlot = adapter.slots[adapter.currentSelectedIdx].logicalSlotId
- state.imei = adapter.slots[adapter.currentSelectedIdx].imei
- }
-
- fun bind(item: SlotInfo, idx: Int) {
- curIdx = idx
-
- type.text = if (item.isRemovable) {
- root.context.getString(R.string.download_wizard_slot_type_removable)
- } else if (!item.hasMultiplePorts) {
- root.context.getString(R.string.download_wizard_slot_type_internal)
- } else {
- root.context.getString(
- R.string.download_wizard_slot_type_internal_port,
- item.portId
- )
- }
-
- title.text = if (item.logicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
- item.intrinsicChannelName ?: root.context.getString(R.string.channel_type_usb)
- } else {
- appContainer.customizableTextProvider.formatInternalChannelName(item.logicalSlotId)
- }
- eID.text = item.eID
- activeProfile.text = item.enabledProfileName ?: root.context.getString(R.string.profile_no_enabled_profile)
- freeSpace.text = formatFreeSpace(item.freeSpace)
- checkBox.isChecked = adapter.currentSelectedIdx == idx
- }
- }
-
- private inner class SlotInfoAdapter : RecyclerView.Adapter() {
- var slots: List = listOf()
- var currentSelectedIdx = -1
-
- val selected: SlotInfo
- get() = slots[currentSelectedIdx]
-
- override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SlotItemHolder {
- val root = LayoutInflater.from(parent.context).inflate(R.layout.download_slot_item, parent, false)
- return SlotItemHolder(root)
- }
-
- override fun getItemCount(): Int = slots.size
-
- override fun onBindViewHolder(holder: SlotItemHolder, position: Int) {
- holder.bind(slots[position], position)
- }
- }
-}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/wizard/SimplifiedErrorMessages.kt b/app-common/src/main/java/im/angry/openeuicc/ui/wizard/SimplifiedErrorMessages.kt
deleted file mode 100644
index 8ce5740..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/ui/wizard/SimplifiedErrorMessages.kt
+++ /dev/null
@@ -1,154 +0,0 @@
-package im.angry.openeuicc.ui.wizard
-
-import androidx.annotation.StringRes
-import im.angry.openeuicc.common.R
-import net.typeblog.lpac_jni.LocalProfileAssistant
-import org.json.JSONObject
-import java.net.NoRouteToHostException
-import java.net.PortUnreachableException
-import java.net.SocketException
-import java.net.SocketTimeoutException
-import java.net.UnknownHostException
-import javax.net.ssl.SSLException
-
-enum class SimplifiedErrorMessages(
- @StringRes val titleResId: Int,
- @StringRes val suggestResId: Int?
-) {
- ICCIDAlreadyInUse(
- R.string.download_wizard_error_iccid_already,
- R.string.download_wizard_error_suggest_profile_installed
- ),
- InsufficientMemory(
- R.string.download_wizard_error_insufficient_memory,
- R.string.download_wizard_error_suggest_insufficient_memory
- ),
- UnsupportedProfile(
- R.string.download_wizard_error_unsupported_profile,
- null
- ),
- CardInternalError(
- R.string.download_wizard_error_card_internal_error,
- null
- ),
- EIDNotSupported(
- R.string.download_wizard_error_eid_not_supported,
- R.string.download_wizard_error_suggest_contact_carrier
- ),
- EIDMismatch(
- R.string.download_wizard_error_eid_mismatch,
- R.string.download_wizard_error_suggest_contact_reissue
- ),
- UnreleasedProfile(
- R.string.download_wizard_error_profile_unreleased,
- R.string.download_wizard_error_suggest_contact_reissue
- ),
- MatchingIDRefused(
- R.string.download_wizard_error_matching_id_refused,
- R.string.download_wizard_error_suggest_contact_carrier
- ),
- ProfileRetriesExceeded(
- R.string.download_wizard_error_profile_retries_exceeded,
- R.string.download_wizard_error_suggest_contact_carrier
- ),
- ConfirmationCodeMissing(
- R.string.download_wizard_error_confirmation_code_missing,
- R.string.download_wizard_error_suggest_contact_carrier
- ),
- ConfirmationCodeRefused(
- R.string.download_wizard_error_confirmation_code_refused,
- R.string.download_wizard_error_suggest_contact_carrier
- ),
- ConfirmationCodeRetriesExceeded(
- R.string.download_wizard_error_confirmation_code_retries_exceeded,
- R.string.download_wizard_error_suggest_contact_carrier
- ),
- ProfileExpired(
- R.string.download_wizard_error_profile_expired,
- R.string.download_wizard_error_suggest_contact_carrier
- ),
- UnknownHost(
- R.string.download_wizard_error_unknown_hostname,
- null
- ),
- NetworkUnreachable(
- R.string.download_wizard_error_network_unreachable,
- R.string.download_wizard_error_suggest_network_unreachable
- ),
- TLSError(
- R.string.download_wizard_error_tls_certificate,
- null
- );
-
- companion object {
- private val httpErrors = buildMap {
- // Stage: AuthenticateClient
- put("8.1" to "4.8", InsufficientMemory)
- put("8.1.1" to "2.1", EIDNotSupported)
- put("8.1.1" to "3.8", EIDMismatch)
- put("8.2" to "1.2", UnreleasedProfile)
- put("8.2.6" to "3.8", MatchingIDRefused)
- put("8.8.5" to "6.4", ProfileRetriesExceeded)
-
- // Stage: GetBoundProfilePackage
- put("8.2.7" to "2.2", ConfirmationCodeMissing)
- put("8.2.7" to "3.8", ConfirmationCodeRefused)
- put("8.2.7" to "6.4", ConfirmationCodeRetriesExceeded)
-
- // Stage: AuthenticateClient, GetBoundProfilePackage
- put("8.8.5" to "4.10", ProfileExpired)
- }
-
- fun fromDownloadError(exc: LocalProfileAssistant.ProfileDownloadException) = when {
- exc.lpaErrorReason != "ES10B_ERROR_REASON_UNDEFINED" -> fromLPAErrorReason(exc.lpaErrorReason)
- exc.lastHttpResponse?.rcode == 200 -> fromHTTPResponse(exc.lastHttpResponse!!)
- exc.lastHttpException != null -> fromHTTPException(exc.lastHttpException!!)
- exc.lastApduResponse != null -> fromAPDUResponse(exc.lastApduResponse!!)
- else -> null
- }
-
- private fun fromLPAErrorReason(reason: String) = when (reason) {
- "ES10B_ERROR_REASON_UNSUPPORTED_CRT_VALUES" -> UnsupportedProfile
- "ES10B_ERROR_REASON_UNSUPPORTED_REMOTE_OPERATION_TYPE" -> UnsupportedProfile
- "ES10B_ERROR_REASON_UNSUPPORTED_PROFILE_CLASS" -> UnsupportedProfile
- "ES10B_ERROR_REASON_INSTALL_FAILED_DUE_TO_ICCID_ALREADY_EXISTS_ON_EUICC" -> ICCIDAlreadyInUse
- "ES10B_ERROR_REASON_INSTALL_FAILED_DUE_TO_INSUFFICIENT_MEMORY_FOR_PROFILE" -> InsufficientMemory
- "ES10B_ERROR_REASON_INSTALL_FAILED_DUE_TO_INTERRUPTION" -> CardInternalError
- "ES10B_ERROR_REASON_INSTALL_FAILED_DUE_TO_PE_PROCESSING_ERROR" -> CardInternalError
- else -> null
- }
-
- private fun fromHTTPResponse(httpResponse: net.typeblog.lpac_jni.HttpInterface.HttpResponse): SimplifiedErrorMessages? {
- if (httpResponse.data.first().toInt() != '{'.code) return null
- val response = JSONObject(httpResponse.data.decodeToString())
- val statusCodeData = response.optJSONObject("header")
- ?.optJSONObject("functionExecutionStatus")
- ?.optJSONObject("statusCodeData")
- ?: return null
- val subjectCode = statusCodeData.optString("subjectCode")
- val reasonCode = statusCodeData.optString("reasonCode")
- return httpErrors[subjectCode to reasonCode]
- }
-
- private fun fromHTTPException(exc: Exception) = when (exc) {
- is SSLException -> TLSError
- is UnknownHostException -> UnknownHost
- is NoRouteToHostException -> NetworkUnreachable
- is PortUnreachableException -> NetworkUnreachable
- is SocketTimeoutException -> NetworkUnreachable
- is SocketException -> exc.message
- ?.contains("Connection reset", ignoreCase = true)
- ?.let { if (it) NetworkUnreachable else null }
-
- else -> null
- }
-
- private fun fromAPDUResponse(resp: ByteArray): SimplifiedErrorMessages? {
- val isSuccess = resp.size >= 2 &&
- resp[resp.size - 2] == 0x90.toByte() &&
- resp[resp.size - 1] == 0x00.toByte()
- if (isSuccess) return null
- return CardInternalError
- }
- }
-}
diff --git a/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt b/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt
index b44bef8..a324ac3 100644
--- a/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt
@@ -4,69 +4,49 @@ import android.os.Bundle
import androidx.fragment.app.Fragment
import im.angry.openeuicc.core.EuiccChannel
import im.angry.openeuicc.core.EuiccChannelManager
-import im.angry.openeuicc.service.EuiccChannelManagerService
import im.angry.openeuicc.ui.BaseEuiccAccessActivity
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
-private const val FIELD_SLOT_ID = "slotId"
-private const val FIELD_PORT_ID = "portId"
-
-interface EuiccChannelFragmentMarker : OpenEuiccContextMarker
-
-private typealias BundleSetter = Bundle.() -> Unit
+interface EuiccChannelFragmentMarker: OpenEuiccContextMarker
// We must use extension functions because there is no way to add bounds to the type of "self"
// in the definition of an interface, so the only way is to limit where the extension functions
// can be applied.
-fun newInstanceEuicc(clazz: Class, slotId: Int, portId: Int, addArguments: BundleSetter = {}): T
- where T : Fragment, T : EuiccChannelFragmentMarker =
- clazz.getDeclaredConstructor().newInstance().apply {
- arguments = Bundle()
- arguments!!.putInt(FIELD_SLOT_ID, slotId)
- arguments!!.putInt(FIELD_PORT_ID, portId)
- arguments!!.addArguments()
+fun newInstanceEuicc(clazz: Class, slotId: Int, portId: Int, addArguments: Bundle.() -> Unit = {}): T where T: Fragment, T: EuiccChannelFragmentMarker {
+ val instance = clazz.newInstance()
+ instance.arguments = Bundle().apply {
+ putInt("slotId", slotId)
+ putInt("portId", portId)
+ addArguments()
}
+ return instance
+}
// Convenient methods to avoid using `channel` for these
// `channel` requires that the channel actually exists in EuiccChannelManager, which is
// not always the case during operations such as switching
-val T.slotId: Int
- where T : Fragment, T : EuiccChannelFragmentMarker
- get() = requireArguments().getInt(FIELD_SLOT_ID)
-val T.portId: Int
- where T : Fragment, T : EuiccChannelFragmentMarker
- get() = requireArguments().getInt(FIELD_PORT_ID)
-val T.isUsb: Boolean
- where T : Fragment, T : EuiccChannelFragmentMarker
- get() = slotId == EuiccChannelManager.USB_CHANNEL_ID
+val T.slotId: Int where T: Fragment, T: EuiccChannelFragmentMarker
+ get() = requireArguments().getInt("slotId")
+val T.portId: Int where T: Fragment, T: EuiccChannelFragmentMarker
+ get() = requireArguments().getInt("portId")
+val T.isUsb: Boolean where T: Fragment, T: EuiccChannelFragmentMarker
+ get() = requireArguments().getInt("slotId") == EuiccChannelManager.USB_CHANNEL_ID
-private fun T.requireEuiccActivity(): BaseEuiccAccessActivity
- where T : Fragment, T : OpenEuiccContextMarker =
- requireActivity() as BaseEuiccAccessActivity
-
-val T.euiccChannelManager: EuiccChannelManager
- where T : Fragment, T : OpenEuiccContextMarker
- get() = requireEuiccActivity().euiccChannelManager
-
-val T.euiccChannelManagerService: EuiccChannelManagerService
- where T : Fragment, T : OpenEuiccContextMarker
- get() = requireEuiccActivity().euiccChannelManagerService
-
-suspend fun T.withEuiccChannel(fn: suspend (EuiccChannel) -> R): R
- where T : Fragment, T : EuiccChannelFragmentMarker {
- ensureEuiccChannelManager()
- return euiccChannelManager.withEuiccChannel(slotId, portId, fn)
-}
-
-suspend fun T.ensureEuiccChannelManager() where T : Fragment, T : OpenEuiccContextMarker =
- requireEuiccActivity().euiccChannelManagerLoaded.await()
-
-fun T.notifyEuiccProfilesChanged() where T : Fragment {
- if (this !is EuiccProfilesChangedListener) return
- // Trigger a refresh in the parent fragment -- it should wait until
- // any foreground task is completed before actually doing a refresh
- this.onEuiccProfilesChanged()
-}
+val T.euiccChannelManager: EuiccChannelManager where T: Fragment, T: EuiccChannelFragmentMarker
+ get() = (requireActivity() as BaseEuiccAccessActivity).euiccChannelManager
+val T.channel: EuiccChannel where T: Fragment, T: EuiccChannelFragmentMarker
+ get() =
+ euiccChannelManager.findEuiccChannelByPortBlocking(slotId, portId)!!
interface EuiccProfilesChangedListener {
fun onEuiccProfilesChanged()
+}
+
+suspend fun T.beginTrackedOperation(op: suspend () -> Boolean) where T: Fragment, T: EuiccChannelFragmentMarker {
+ withContext(Dispatchers.IO) {
+ euiccChannelManager.beginTrackedOperationBlocking(slotId, portId) {
+ op()
+ }
+ }
}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/util/LPAString.kt b/app-common/src/main/java/im/angry/openeuicc/util/LPAString.kt
deleted file mode 100644
index 63a81f1..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/util/LPAString.kt
+++ /dev/null
@@ -1,34 +0,0 @@
-package im.angry.openeuicc.util
-
-data class LPAString(
- val address: String,
- val matchingId: String?,
- val oid: String?,
- val confirmationCodeRequired: Boolean,
-) {
- companion object {
- fun parse(input: String): LPAString {
- var token = input
- if (token.startsWith("LPA:", ignoreCase = true)) token = token.drop(4)
- val components = token.split('$').map { it.trim().ifBlank { null } }
- require(components.getOrNull(0) == "1") { "Invalid AC_Format" }
- return LPAString(
- requireNotNull(components.getOrNull(1)) { "SM-DP+ is required" },
- components.getOrNull(2),
- components.getOrNull(3),
- components.getOrNull(4) == "1"
- )
- }
- }
-
- override fun toString(): String {
- val parts = arrayOf(
- "1",
- address,
- matchingId ?: "",
- oid ?: "",
- if (confirmationCodeRequired) "1" else ""
- )
- return parts.joinToString("$").trimEnd('$')
- }
-}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt b/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt
index 9f95412..50b2077 100644
--- a/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt
@@ -3,6 +3,9 @@ package im.angry.openeuicc.util
import android.util.Log
import im.angry.openeuicc.core.EuiccChannel
import im.angry.openeuicc.core.EuiccChannelManager
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withContext
import net.typeblog.lpac_jni.LocalProfileAssistant
import net.typeblog.lpac_jni.LocalProfileInfo
@@ -16,10 +19,9 @@ val LocalProfileInfo.isEnabled: Boolean
get() = state == LocalProfileInfo.State.Enabled
val List.operational: List
- get() = filter { it.profileClass == LocalProfileInfo.Clazz.Operational }
-
-val List.enabled: LocalProfileInfo?
- get() = find { it.isEnabled }
+ get() = filter {
+ it.profileClass == LocalProfileInfo.Clazz.Operational
+ }
val List.hasMultipleChips: Boolean
get() = distinctBy { it.slotId }.size > 1
@@ -40,27 +42,22 @@ fun LocalProfileAssistant.switchProfile(
* See EuiccManager.waitForReconnect()
*/
fun LocalProfileAssistant.disableActiveProfile(refresh: Boolean): Boolean =
- profiles.enabled?.let {
+ profiles.find { it.isEnabled }?.let {
Log.i(TAG, "Disabling active profile ${it.iccid}")
disableProfile(it.iccid, refresh)
} ?: true
/**
- * Disable the current active profile if any. If refresh is true, also cause a refresh command.
+ * Disable the active profile, return a lambda that reverts this action when called.
+ * If refreshOnDisable is true, also cause a eUICC refresh command. Note that refreshing
+ * will disconnect the eUICC and might need some time before being operational again.
* See EuiccManager.waitForReconnect()
- *
- * Return the iccid of the profile being disabled, or null if no active profile found or failed to
- * disable.
*/
-fun LocalProfileAssistant.disableActiveProfileKeepIccId(refresh: Boolean): String? =
- profiles.enabled?.let {
- Log.i(TAG, "Disabling active profile ${it.iccid}")
- if (disableProfile(it.iccid, refresh)) {
- it.iccid
- } else {
- null
- }
- }
+fun LocalProfileAssistant.disableActiveProfileWithUndo(refreshOnDisable: Boolean): () -> Unit =
+ profiles.find { it.isEnabled }?.let {
+ disableProfile(it.iccid, refreshOnDisable)
+ return { enableProfile(it.iccid) }
+ } ?: { }
/**
* Begin a "tracked" operation where notifications may be generated by the eSIM
@@ -76,26 +73,29 @@ fun LocalProfileAssistant.disableActiveProfileKeepIccId(refresh: Boolean): Strin
* should be the concern of op() itself, and this function assumes that when
* op() returns, the slotId and portId will correspond to a valid channel again.
*/
-suspend inline fun EuiccChannelManager.beginTrackedOperation(
+inline fun EuiccChannelManager.beginTrackedOperationBlocking(
slotId: Int,
portId: Int,
op: () -> Boolean
) {
- val latestSeq = withEuiccChannel(slotId, portId) { channel ->
- channel.lpa.notifications.firstOrNull()?.seqNumber
+ val latestSeq =
+ findEuiccChannelByPortBlocking(slotId, portId)!!.lpa.notifications.firstOrNull()?.seqNumber
?: 0
- }
Log.d(TAG, "Latest notification is $latestSeq before operation")
if (op()) {
Log.d(TAG, "Operation has requested notification handling")
try {
// Note that the exact instance of "channel" might have changed here if reconnected;
- // this is why we need to use two distinct calls to withEuiccChannel()
- withEuiccChannel(slotId, portId) { channel ->
- channel.lpa.notifications.filter { it.seqNumber > latestSeq }.forEach {
- Log.d(TAG, "Handling notification $it")
- channel.lpa.handleNotification(it.seqNumber)
- }
+ // so we MUST use the automatic getter for "channel"
+ findEuiccChannelByPortBlocking(
+ slotId,
+ portId
+ )?.lpa?.notifications?.filter { it.seqNumber > latestSeq }?.forEach {
+ Log.d(TAG, "Handling notification $it")
+ findEuiccChannelByPortBlocking(
+ slotId,
+ portId
+ )?.lpa?.handleNotification(it.seqNumber)
}
} catch (e: Exception) {
// Ignore any error during notification handling
diff --git a/app-common/src/main/java/im/angry/openeuicc/util/PreferenceUtils.kt b/app-common/src/main/java/im/angry/openeuicc/util/PreferenceUtils.kt
index 2fef3db..5315340 100644
--- a/app-common/src/main/java/im/angry/openeuicc/util/PreferenceUtils.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/util/PreferenceUtils.kt
@@ -5,14 +5,11 @@ 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.intPreferencesKey
-import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import androidx.fragment.app.Fragment
import im.angry.openeuicc.OpenEuiccApplication
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
-import java.util.Base64
private val Context.dataStore: DataStore by preferencesDataStore(name = "prefs")
@@ -22,110 +19,34 @@ val Context.preferenceRepository: PreferenceRepository
val Fragment.preferenceRepository: PreferenceRepository
get() = requireContext().preferenceRepository
-internal object PreferenceKeys {
- // ---- Profile Notifications ----
+object PreferenceKeys {
val NOTIFICATION_DOWNLOAD = booleanPreferencesKey("notification_download")
val NOTIFICATION_DELETE = booleanPreferencesKey("notification_delete")
val NOTIFICATION_SWITCH = booleanPreferencesKey("notification_switch")
-
- // ---- Advanced ----
val DISABLE_SAFEGUARD_REMOVABLE_ESIM = booleanPreferencesKey("disable_safeguard_removable_esim")
- val VERBOSE_LOGGING = booleanPreferencesKey("verbose_logging")
-
- // ---- Developer Options ----
- val DEVELOPER_OPTIONS_ENABLED = booleanPreferencesKey("developer_options_enabled")
- val REFRESH_AFTER_SWITCH = booleanPreferencesKey("refresh_after_switch")
- val UNFILTERED_PROFILE_LIST = booleanPreferencesKey("unfiltered_profile_list")
- val IGNORE_TLS_CERTIFICATE = booleanPreferencesKey("ignore_tls_certificate")
- val EUICC_MEMORY_RESET = booleanPreferencesKey("euicc_memory_reset")
- val ISDR_AID_LIST = stringPreferencesKey("isdr_aid_list")
- val ES10X_MSS = intPreferencesKey("es10x_mss")
}
-const val EUICC_DEFAULT_ISDR_AID = "A0000005591010FFFFFFFF8900000100"
+class PreferenceRepository(context: Context) {
+ private val dataStore = context.dataStore
-internal object PreferenceConstants {
- val DEFAULT_AID_LIST = """
- # One AID per line. Comment lines start with #.
- # Refs:
-
- # eUICC standard
- $EUICC_DEFAULT_ISDR_AID
-
- # ESTKme AUX (deprecated, use SE0 instead)
- A06573746B6D65FFFFFFFF4953442D52
-
- # ESTKme SE0
- A06573746B6D65FFFF4953442D522030
-
- # eSIM.me
- A0000005591010000000008900000300
-
- # 5ber.eSIM
- A0000005591010FFFFFFFF8900050500
-
- # Xesim
- A0000005591010FFFFFFFF8900000177
- """.trimIndent()
-}
-
-open class PreferenceRepository(private val context: Context) {
// Expose flows so that we can also handle default values
// ---- Profile Notifications ----
- val notificationDownloadFlow = bindFlow(PreferenceKeys.NOTIFICATION_DOWNLOAD, true)
- val notificationDeleteFlow = bindFlow(PreferenceKeys.NOTIFICATION_DELETE, true)
- val notificationSwitchFlow = bindFlow(PreferenceKeys.NOTIFICATION_SWITCH, false)
+ val notificationDownloadFlow: Flow =
+ dataStore.data.map { it[PreferenceKeys.NOTIFICATION_DOWNLOAD] ?: true }
+
+ val notificationDeleteFlow: Flow =
+ dataStore.data.map { it[PreferenceKeys.NOTIFICATION_DELETE] ?: true }
+
+ val notificationSwitchFlow: Flow =
+ dataStore.data.map { it[PreferenceKeys.NOTIFICATION_SWITCH] ?: false }
// ---- Advanced ----
- val disableSafeguardFlow = bindFlow(PreferenceKeys.DISABLE_SAFEGUARD_REMOVABLE_ESIM, false)
- val verboseLoggingFlow = bindFlow(PreferenceKeys.VERBOSE_LOGGING, false)
+ val disableSafeguardFlow: Flow =
+ dataStore.data.map { it[PreferenceKeys.DISABLE_SAFEGUARD_REMOVABLE_ESIM] ?: false }
- // ---- Developer Options ----
- val refreshAfterSwitchFlow = bindFlow(PreferenceKeys.REFRESH_AFTER_SWITCH, true)
- val developerOptionsEnabledFlow = bindFlow(PreferenceKeys.DEVELOPER_OPTIONS_ENABLED, false)
- val unfilteredProfileListFlow = bindFlow(PreferenceKeys.UNFILTERED_PROFILE_LIST, false)
- val ignoreTLSCertificateFlow = bindFlow(PreferenceKeys.IGNORE_TLS_CERTIFICATE, false)
- val euiccMemoryResetFlow = bindFlow(PreferenceKeys.EUICC_MEMORY_RESET, false)
- val isdrAidListFlow = bindFlow(
- PreferenceKeys.ISDR_AID_LIST,
- PreferenceConstants.DEFAULT_AID_LIST,
- { Base64.getEncoder().encodeToString(it.encodeToByteArray()) },
- { Base64.getDecoder().decode(it).decodeToString() })
- val es10xMssFlow = bindFlow(PreferenceKeys.ES10X_MSS, 63)
-
- protected fun bindFlow(
- key: Preferences.Key,
- defaultValue: T,
- encoder: (T) -> T = { it },
- decoder: (T) -> T = { it }
- ): PreferenceFlowWrapper =
- PreferenceFlowWrapper(context, key, defaultValue, encoder, decoder)
-}
-
-class PreferenceFlowWrapper private constructor(
- private val context: Context,
- private val key: Preferences.Key,
- inner: Flow,
- private val encoder: (T) -> T,
-) : Flow by inner {
- internal constructor(
- context: Context,
- key: Preferences.Key,
- defaultValue: T,
- encoder: (T) -> T,
- decoder: (T) -> T
- ) : this(
- context,
- key,
- context.dataStore.data.map { it[key]?.let(decoder) ?: defaultValue },
- encoder
- )
-
- suspend fun updatePreference(value: T) {
- context.dataStore.edit { it[key] = encoder(value) }
+ suspend fun updatePreference(key: Preferences.Key, value: T) {
+ dataStore.edit {
+ it[key] = value
+ }
}
-
- suspend fun removePreference() {
- context.dataStore.edit { it.remove(key) }
- }
-}
+}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/util/StringUtils.kt b/app-common/src/main/java/im/angry/openeuicc/util/StringUtils.kt
index 57d150b..ebf8729 100644
--- a/app-common/src/main/java/im/angry/openeuicc/util/StringUtils.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/util/StringUtils.kt
@@ -1,7 +1,7 @@
package im.angry.openeuicc.util
fun String.decodeHex(): ByteArray {
- require(length % 2 == 0) { "Must have an even length" }
+ check(length % 2 == 0) { "Must have an even length" }
val decodedLength = length / 2
val out = ByteArray(decodedLength)
@@ -27,17 +27,4 @@ fun formatFreeSpace(size: Int): String =
"%.2f KiB".format(size.toDouble() / 1024)
} else {
"$size B"
- }
-
-/**
- * Decode a list of potential ISDR AIDs, one per line. Lines starting with '#' are ignored.
- * If none is found, at least EUICC_DEFAULT_ISDR_AID is returned
- */
-fun parseIsdrAidList(s: String): List =
- s.split('\n')
- .map(String::trim)
- .filter { !it.startsWith('#') }
- .map(String::trim)
- .filter(String::isNotEmpty)
- .mapNotNull { runCatching(it::decodeHex).getOrNull() }
- .ifEmpty { listOf(EUICC_DEFAULT_ISDR_AID.decodeHex()) }
+ }
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/util/TelephonyCompat.kt b/app-common/src/main/java/im/angry/openeuicc/util/TelephonyCompat.kt
index b831f01..5c7d217 100644
--- a/app-common/src/main/java/im/angry/openeuicc/util/TelephonyCompat.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/util/TelephonyCompat.kt
@@ -45,8 +45,6 @@ fun SEService.getUiccReaderCompat(slotNumber: Int): Reader {
interface UiccCardInfoCompat {
val physicalSlotIndex: Int
val ports: Collection
- val isRemovable: Boolean
- get() = true // This defaults to removable unless overridden
}
interface UiccPortInfoCompat {
diff --git a/app-common/src/main/java/im/angry/openeuicc/util/UiUtils.kt b/app-common/src/main/java/im/angry/openeuicc/util/UiUtils.kt
index c7c859d..24c1ad8 100644
--- a/app-common/src/main/java/im/angry/openeuicc/util/UiUtils.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/util/UiUtils.kt
@@ -1,24 +1,9 @@
package im.angry.openeuicc.util
-import android.content.ClipData
-import android.content.Context
-import android.content.Intent
import android.content.res.Resources
import android.graphics.Rect
-import android.view.View
import android.view.ViewGroup
-import androidx.activity.result.ActivityResultCaller
-import androidx.activity.result.contract.ActivityResultContracts
-import androidx.appcompat.app.AlertDialog
-import androidx.appcompat.app.AppCompatActivity
-import androidx.core.view.ViewCompat
-import androidx.core.view.WindowInsetsCompat
-import androidx.core.view.updateLayoutParams
-import androidx.core.view.updatePadding
import androidx.fragment.app.DialogFragment
-import androidx.fragment.app.Fragment
-import im.angry.openeuicc.common.R
-import java.io.FileOutputStream
// Source:
/**
@@ -41,84 +26,3 @@ fun DialogFragment.setWidthPercent(percentage: Int) {
fun DialogFragment.setFullScreen() {
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
-
-fun AppCompatActivity.setupToolbarInsets() {
- val spacer = requireViewById(R.id.toolbar_spacer)
- ViewCompat.setOnApplyWindowInsetsListener(requireViewById(R.id.toolbar)) { v, insets ->
- val bars = insets.getInsets(
- WindowInsetsCompat.Type.systemBars()
- or WindowInsetsCompat.Type.displayCutout()
- )
-
- v.updateLayoutParams {
- topMargin = bars.top
- }
- v.updatePadding(bars.left, v.paddingTop, bars.right, v.paddingBottom)
-
- spacer.updateLayoutParams {
- height = v.top
- }
-
- WindowInsetsCompat.CONSUMED
- }
-}
-
-fun setupRootViewInsets(view: ViewGroup) {
- // Disable clipToPadding to make sure content actually display
- view.clipToPadding = false
- ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
- val bars = insets.getInsets(
- WindowInsetsCompat.Type.systemBars()
- or WindowInsetsCompat.Type.displayCutout()
- )
-
- v.updatePadding(bars.left, v.paddingTop, bars.right, bars.bottom)
-
- WindowInsetsCompat.CONSUMED
- }
-}
-
-fun T.setupLogSaving(
- getLogFileName: () -> String,
- getLogText: () -> String
-): () -> Unit {
- var lastFileName = "untitled"
-
- val launchSaveIntent =
- registerForActivityResult(ActivityResultContracts.CreateDocument("text/plain")) { uri ->
- if (uri == null) return@registerForActivityResult
-
- val context = when (this@setupLogSaving) {
- is Context -> this@setupLogSaving
- is Fragment -> requireContext()
- else -> throw IllegalArgumentException("Must be either Context or Fragment!")
- }
-
- context.contentResolver.openFileDescriptor(uri, "w")?.use {
- FileOutputStream(it.fileDescriptor).use { os ->
- os.write(getLogText().encodeToByteArray())
- }
- }
-
- AlertDialog.Builder(context).apply {
- setMessage(R.string.logs_saved_message)
- setNegativeButton(android.R.string.cancel) { _, _ -> }
- setPositiveButton(android.R.string.ok) { _, _ ->
- val intent = Intent(Intent.ACTION_SEND).apply {
- type = "text/plain"
- clipData = ClipData.newUri(context.contentResolver, lastFileName, uri)
- putExtra(Intent.EXTRA_TITLE, lastFileName)
- putExtra(Intent.EXTRA_STREAM, uri)
- addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
- }
-
- context.startActivity(Intent.createChooser(intent, null))
- }
- }.show()
- }
-
- return {
- lastFileName = getLogFileName()
- launchSaveIntent.launch(lastFileName)
- }
-}
\ No newline at end of file
diff --git a/app-common/src/main/java/im/angry/openeuicc/util/Utils.kt b/app-common/src/main/java/im/angry/openeuicc/util/Utils.kt
index 046657f..444c176 100644
--- a/app-common/src/main/java/im/angry/openeuicc/util/Utils.kt
+++ b/app-common/src/main/java/im/angry/openeuicc/util/Utils.kt
@@ -54,9 +54,6 @@ interface OpenEuiccContextMarker {
val appContainer: AppContainer
get() = openEuiccApplication.appContainer
- val preferenceRepository: PreferenceRepository
- get() = appContainer.preferenceRepository
-
val telephonyManager: TelephonyManager
get() = appContainer.telephonyManager
}
@@ -89,13 +86,6 @@ suspend fun connectSEService(context: Context): SEService = suspendCoroutine { c
}
}
-inline fun Bitmap.use(f: (Bitmap) -> T): T =
- try {
- f(this)
- } finally {
- recycle()
- }
-
fun decodeQrFromBitmap(bmp: Bitmap): String? =
runCatching {
val pixels = IntArray(bmp.width * bmp.height)
diff --git a/app-common/src/main/java/im/angry/openeuicc/util/Vendors.kt b/app-common/src/main/java/im/angry/openeuicc/util/Vendors.kt
deleted file mode 100644
index 529f9ee..0000000
--- a/app-common/src/main/java/im/angry/openeuicc/util/Vendors.kt
+++ /dev/null
@@ -1,112 +0,0 @@
-package im.angry.openeuicc.util
-
-import android.util.Log
-import im.angry.openeuicc.core.ApduInterfaceAtrProvider
-import im.angry.openeuicc.core.EuiccChannel
-import net.typeblog.lpac_jni.Version
-
-data class EuiccVendorInfo(
- val skuName: String?,
- val serialNumber: String?,
- val bootloaderVersion: String?,
- val firmwareVersion: String?,
-)
-
-private val EUICC_VENDORS: Array = arrayOf(EstkMe(), SimLink())
-
-fun EuiccChannel.tryParseEuiccVendorInfo(): EuiccVendorInfo? {
- EUICC_VENDORS.forEach { vendor ->
- vendor.tryParseEuiccVendorInfo(this@tryParseEuiccVendorInfo)?.let {
- return it
- }
- }
-
- return null
-}
-
-interface EuiccVendor {
- fun tryParseEuiccVendorInfo(channel: EuiccChannel): EuiccVendorInfo?
-}
-
-private class EstkMe : EuiccVendor {
- companion object {
- private val PRODUCT_AID = "A06573746B6D65FFFFFFFFFFFF6D6774".decodeHex()
- private val PRODUCT_ATR_FPR = "estk.me".encodeToByteArray()
- }
-
- private fun checkAtr(channel: EuiccChannel): Boolean {
- val iface = channel.apduInterface
- if (iface !is ApduInterfaceAtrProvider) return false
- val atr = iface.atr ?: return false
- for (index in atr.indices) {
- if (atr.size - index < PRODUCT_ATR_FPR.size) break
- if (atr.sliceArray(index until index + PRODUCT_ATR_FPR.size)
- .contentEquals(PRODUCT_ATR_FPR)
- ) return true
- }
- return false
- }
-
- private fun decodeAsn1String(b: ByteArray): String? {
- if (b.size < 2) return null
- if (b[b.size - 2] != 0x90.toByte() || b[b.size - 1] != 0x00.toByte()) return null
- return b.sliceArray(0 until b.size - 2).decodeToString()
- }
-
- override fun tryParseEuiccVendorInfo(channel: EuiccChannel): EuiccVendorInfo? {
- if (!checkAtr(channel)) return null
-
- val iface = channel.apduInterface
- return try {
- iface.withLogicalChannel(PRODUCT_AID) { transmit ->
- fun invoke(p1: Byte) =
- decodeAsn1String(transmit(byteArrayOf(0x00, 0x00, p1, 0x00, 0x00)))
- EuiccVendorInfo(
- skuName = invoke(0x03),
- serialNumber = invoke(0x00),
- bootloaderVersion = invoke(0x01),
- firmwareVersion = invoke(0x02),
- )
- }
- } catch (e: Exception) {
- Log.d(TAG, "Failed to get ESTKmeInfo", e)
- null
- }
- }
-}
-
-private class SimLink : EuiccVendor {
- companion object {
- private val EID_PATTERN = Regex("^89044045(84|21)67274948")
- }
-
- override fun tryParseEuiccVendorInfo(channel: EuiccChannel): EuiccVendorInfo? {
- val eid = channel.lpa.eID
- val version = channel.lpa.euiccInfo2?.euiccFirmwareVersion
- if (version == null || EID_PATTERN.find(eid, 0) == null) return null
- val versionName = when {
- // @formatter:off
- version >= Version(37, 1, 41) -> "v3.1 (beta 1)"
- version >= Version(36, 18, 5) -> "v3 (final)"
- version >= Version(36, 17, 39) -> "v3 (beta)"
- version >= Version(36, 17, 4) -> "v2s"
- version >= Version(36, 9, 3) -> "v2.1"
- version >= Version(36, 7, 2) -> "v2"
- // @formatter:on
- else -> null
- }
-
- val skuName = if (versionName == null) {
- "9eSIM"
- } else {
- "9eSIM $versionName"
- }
-
- return EuiccVendorInfo(
- skuName = skuName,
- serialNumber = null,
- bootloaderVersion = null,
- firmwareVersion = null
- )
- }
-}
\ No newline at end of file
diff --git a/app-common/src/main/res/anim/slide_in_left.xml b/app-common/src/main/res/anim/slide_in_left.xml
deleted file mode 100644
index 9078d1f..0000000
--- a/app-common/src/main/res/anim/slide_in_left.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
diff --git a/app-common/src/main/res/anim/slide_in_right.xml b/app-common/src/main/res/anim/slide_in_right.xml
deleted file mode 100644
index 42aa3f5..0000000
--- a/app-common/src/main/res/anim/slide_in_right.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
diff --git a/app-common/src/main/res/anim/slide_out_left.xml b/app-common/src/main/res/anim/slide_out_left.xml
deleted file mode 100644
index 1a806a9..0000000
--- a/app-common/src/main/res/anim/slide_out_left.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
diff --git a/app-common/src/main/res/anim/slide_out_right.xml b/app-common/src/main/res/anim/slide_out_right.xml
deleted file mode 100644
index f209f38..0000000
--- a/app-common/src/main/res/anim/slide_out_right.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
diff --git a/app-common/src/main/res/drawable/ic_chevron_left.xml b/app-common/src/main/res/drawable/ic_chevron_left.xml
deleted file mode 100644
index 1152da9..0000000
--- a/app-common/src/main/res/drawable/ic_chevron_left.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/app-common/src/main/res/drawable/ic_chevron_right.xml b/app-common/src/main/res/drawable/ic_chevron_right.xml
deleted file mode 100644
index 1db5e68..0000000
--- a/app-common/src/main/res/drawable/ic_chevron_right.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/app-common/src/main/res/drawable/ic_edit.xml b/app-common/src/main/res/drawable/ic_edit.xml
deleted file mode 100644
index 3c53db7..0000000
--- a/app-common/src/main/res/drawable/ic_edit.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/app-common/src/main/res/drawable/ic_euicc_memory_reset.xml b/app-common/src/main/res/drawable/ic_euicc_memory_reset.xml
deleted file mode 100644
index f1ca8c1..0000000
--- a/app-common/src/main/res/drawable/ic_euicc_memory_reset.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-
-
diff --git a/app-common/src/main/res/drawable/ic_paste_go.xml b/app-common/src/main/res/drawable/ic_paste_go.xml
deleted file mode 100644
index 7536fff..0000000
--- a/app-common/src/main/res/drawable/ic_paste_go.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
-
-
-
diff --git a/app-common/src/main/res/drawable/ic_task_delete.xml b/app-common/src/main/res/drawable/ic_task_delete.xml
deleted file mode 100644
index 883bcaa..0000000
--- a/app-common/src/main/res/drawable/ic_task_delete.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/app-common/src/main/res/drawable/ic_task_rename.xml b/app-common/src/main/res/drawable/ic_task_rename.xml
deleted file mode 100644
index 3c53db7..0000000
--- a/app-common/src/main/res/drawable/ic_task_rename.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/app-common/src/main/res/drawable/ic_task_sim_card_download.xml b/app-common/src/main/res/drawable/ic_task_sim_card_download.xml
deleted file mode 100644
index a2eadb2..0000000
--- a/app-common/src/main/res/drawable/ic_task_sim_card_download.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/app-common/src/main/res/drawable/ic_task_switch.xml b/app-common/src/main/res/drawable/ic_task_switch.xml
deleted file mode 100644
index 86504d0..0000000
--- a/app-common/src/main/res/drawable/ic_task_switch.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/app-common/src/main/res/drawable/ic_x_black.xml b/app-common/src/main/res/drawable/ic_x_black.xml
deleted file mode 100644
index f8ca0c6..0000000
--- a/app-common/src/main/res/drawable/ic_x_black.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/app-common/src/main/res/layout/activity_download_wizard.xml b/app-common/src/main/res/layout/activity_download_wizard.xml
deleted file mode 100644
index 79513bb..0000000
--- a/app-common/src/main/res/layout/activity_download_wizard.xml
+++ /dev/null
@@ -1,74 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-common/src/main/res/layout/activity_euicc_info.xml b/app-common/src/main/res/layout/activity_euicc_info.xml
deleted file mode 100644
index 8a8b001..0000000
--- a/app-common/src/main/res/layout/activity_euicc_info.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-common/src/main/res/layout/activity_logs.xml b/app-common/src/main/res/layout/activity_logs.xml
index b37328d..c305d0a 100644
--- a/app-common/src/main/res/layout/activity_logs.xml
+++ b/app-common/src/main/res/layout/activity_logs.xml
@@ -5,7 +5,13 @@
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
-
+
-
+
-
+
-
+
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-common/src/main/res/layout/download_progress_item.xml b/app-common/src/main/res/layout/download_progress_item.xml
deleted file mode 100644
index c59673b..0000000
--- a/app-common/src/main/res/layout/download_progress_item.xml
+++ /dev/null
@@ -1,81 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-common/src/main/res/layout/download_slot_item.xml b/app-common/src/main/res/layout/download_slot_item.xml
deleted file mode 100644
index d0ca176..0000000
--- a/app-common/src/main/res/layout/download_slot_item.xml
+++ /dev/null
@@ -1,108 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-common/src/main/res/layout/euicc_info_item.xml b/app-common/src/main/res/layout/euicc_info_item.xml
deleted file mode 100644
index fa148fb..0000000
--- a/app-common/src/main/res/layout/euicc_info_item.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-common/src/main/res/layout/euicc_profile.xml b/app-common/src/main/res/layout/euicc_profile.xml
index 021c53b..06aa2b8 100644
--- a/app-common/src/main/res/layout/euicc_profile.xml
+++ b/app-common/src/main/res/layout/euicc_profile.xml
@@ -28,8 +28,7 @@
app:layout_constraintRight_toLeftOf="@+id/profile_menu"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@+id/state"
- app:layout_constraintHorizontal_bias="0"
- app:layout_constrainedWidth="true" />
+ app:layout_constraintHorizontal_bias="0" />
+ app:layout_constraintBottom_toTopOf="@+id/iccid_label"/>
-
-
-
-
-
-
diff --git a/app-common/src/main/res/layout/fragment_download_details.xml b/app-common/src/main/res/layout/fragment_download_details.xml
deleted file mode 100644
index 1a25075..0000000
--- a/app-common/src/main/res/layout/fragment_download_details.xml
+++ /dev/null
@@ -1,104 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-common/src/main/res/layout/fragment_download_diagnostics.xml b/app-common/src/main/res/layout/fragment_download_diagnostics.xml
deleted file mode 100644
index 88b1ffb..0000000
--- a/app-common/src/main/res/layout/fragment_download_diagnostics.xml
+++ /dev/null
@@ -1,59 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-common/src/main/res/layout/fragment_download_method_select.xml b/app-common/src/main/res/layout/fragment_download_method_select.xml
deleted file mode 100644
index 7fe2234..0000000
--- a/app-common/src/main/res/layout/fragment_download_method_select.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-common/src/main/res/layout/fragment_download_progress.xml b/app-common/src/main/res/layout/fragment_download_progress.xml
deleted file mode 100644
index 82ebb25..0000000
--- a/app-common/src/main/res/layout/fragment_download_progress.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-common/src/main/res/layout/fragment_download_slot_select.xml b/app-common/src/main/res/layout/fragment_download_slot_select.xml
deleted file mode 100644
index 69b1535..0000000
--- a/app-common/src/main/res/layout/fragment_download_slot_select.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-common/src/main/res/layout/fragment_euicc.xml b/app-common/src/main/res/layout/fragment_euicc.xml
index c5fde7b..4ae7523 100644
--- a/app-common/src/main/res/layout/fragment_euicc.xml
+++ b/app-common/src/main/res/layout/fragment_euicc.xml
@@ -27,7 +27,6 @@
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
- android:contentDescription="@string/profile_download"
android:src="@drawable/ic_add"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
diff --git a/app-common/src/main/res/layout/fragment_profile_download.xml b/app-common/src/main/res/layout/fragment_profile_download.xml
new file mode 100644
index 0000000..78274dc
--- /dev/null
+++ b/app-common/src/main/res/layout/fragment_profile_download.xml
@@ -0,0 +1,126 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app-common/src/main/res/layout/fragment_slot_select.xml b/app-common/src/main/res/layout/fragment_slot_select.xml
new file mode 100644
index 0000000..b818b80
--- /dev/null
+++ b/app-common/src/main/res/layout/fragment_slot_select.xml
@@ -0,0 +1,27 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app-common/src/main/res/layout/notification_item.xml b/app-common/src/main/res/layout/notification_item.xml
index 5d56b3a..6b7253c 100644
--- a/app-common/src/main/res/layout/notification_item.xml
+++ b/app-common/src/main/res/layout/notification_item.xml
@@ -15,15 +15,6 @@
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-common/src/main/res/menu/activity_isdr_aid_list.xml b/app-common/src/main/res/menu/activity_isdr_aid_list.xml
deleted file mode 100644
index 99492d6..0000000
--- a/app-common/src/main/res/menu/activity_isdr_aid_list.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-common/src/main/res/menu/activity_main.xml b/app-common/src/main/res/menu/activity_main.xml
index c15663f..0e00292 100644
--- a/app-common/src/main/res/menu/activity_main.xml
+++ b/app-common/src/main/res/menu/activity_main.xml
@@ -3,7 +3,7 @@
xmlns:app="http://schemas.android.com/apk/res-auto">
diff --git a/app-common/src/main/res/menu/activity_notifications.xml b/app-common/src/main/res/menu/activity_notifications.xml
index b80e06e..87f96a6 100644
--- a/app-common/src/main/res/menu/activity_notifications.xml
+++ b/app-common/src/main/res/menu/activity_notifications.xml
@@ -4,6 +4,6 @@
\ No newline at end of file
diff --git a/app-common/src/main/res/menu/fragment_euicc.xml b/app-common/src/main/res/menu/fragment_euicc.xml
index 6e2dfbe..9acb640 100644
--- a/app-common/src/main/res/menu/fragment_euicc.xml
+++ b/app-common/src/main/res/menu/fragment_euicc.xml
@@ -5,14 +5,4 @@
android:id="@+id/show_notifications"
android:title="@string/profile_notifications_show"
app:showAsAction="never" />
-
-
-
-
\ No newline at end of file
diff --git a/app-common/src/main/res/menu/fragment_profile_download.xml b/app-common/src/main/res/menu/fragment_profile_download.xml
new file mode 100644
index 0000000..f93ae8d
--- /dev/null
+++ b/app-common/src/main/res/menu/fragment_profile_download.xml
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app-common/src/main/res/menu/fragment_profile_rename.xml b/app-common/src/main/res/menu/fragment_profile_rename.xml
index f55c56c..bde850f 100644
--- a/app-common/src/main/res/menu/fragment_profile_rename.xml
+++ b/app-common/src/main/res/menu/fragment_profile_rename.xml
@@ -4,6 +4,6 @@
\ No newline at end of file
diff --git a/app-unpriv/src/main/res/menu/fragment_sim_toolkit.xml b/app-common/src/main/res/menu/fragment_slot_select.xml
similarity index 52%
rename from app-unpriv/src/main/res/menu/fragment_sim_toolkit.xml
rename to app-common/src/main/res/menu/fragment_slot_select.xml
index 610b3a1..e129008 100644
--- a/app-unpriv/src/main/res/menu/fragment_sim_toolkit.xml
+++ b/app-common/src/main/res/menu/fragment_slot_select.xml
@@ -2,8 +2,8 @@
+ android:id="@+id/ok"
+ android:icon="@drawable/ic_check_black"
+ android:title="@string/slot_select_select"
+ app:showAsAction="ifRoom"/>
\ No newline at end of file
diff --git a/app-common/src/main/res/menu/profile_options.xml b/app-common/src/main/res/menu/profile_options.xml
index 60722d6..6add53d 100644
--- a/app-common/src/main/res/menu/profile_options.xml
+++ b/app-common/src/main/res/menu/profile_options.xml
@@ -2,18 +2,18 @@
+ android:title="@string/enable"/>
+ android:title="@string/disable"/>
+ android:title="@string/rename"/>
+ android:title="@string/delete"/>
\ No newline at end of file
diff --git a/app-common/src/main/res/values-ja/strings.xml b/app-common/src/main/res/values-ja/strings.xml
deleted file mode 100644
index b171972..0000000
--- a/app-common/src/main/res/values-ja/strings.xml
+++ /dev/null
@@ -1,202 +0,0 @@
-
-
- このアプリでアクセスできるリムーバブル eUICC カードがデバイス上で検出されていません。互換性のあるカード挿入または USB リーダーを接続してください。
- この eSIM にはプロファイルがありません。
- ヘルプ
- スロットを再読み込み
- 不明
- 論理スロット %d
-
- 有効化済み
- 無効化済み
- プロバイダー:
- クラス:
- テスト中
- プロビジョニング
- 稼働中
- 有効化
- 無効化
- 削除
- 名前を変更
- eSIM チップがプロファイルの切り替えの待機中にタイムアウトしました。これはデバイスのモデムファームウェアのバグの可能性があります。機内モードに切り替えるかアプリを再起動、デバイスを再起動してください。
- 操作は成功しましたが、デバイスのモデムが更新を拒否しました。新しいプロファイルを使用するには機内モードに切り替えるか、再起動する必要があります。
- 新しい eSIM プロファイルに切り替えることができません。
- 確認文字列が一致しません
- 確認文字列が一致しません
- このチップは消去されました
- ICCID をクリップボードにコピーしました
- シリアル番号をクリップボードにコピーしました
- EID をクリップボードにコピーしました
- ATR をクリップボードにコピーしました
- USB の権限を許可
- USB スマートカードリーダーにアクセスするには許可が必要です。
- USB スマートカードリーダー経由で eSIM に接続できません。
- 長時間実行されるタスク
- eSIM プロファイルをダウンロード中です
- eSIM プロファイルのダウンロードに失敗しました
- eSIM プロファイルの名前を変更中です
- eSIM プロファイルの名前の変更に失敗しました
- eSIM プロファイルを削除中です
- eSIM プロファイルの削除に失敗しました
- eSIM プロファイルを切り替え中
- eSIM プロファイルの切り替えに失敗しました
- eSIM チップを消去中
- eSIM チップの消去に失敗しました
- 新しい eSIM
- サーバー (RSP / SM-DP+)
- アクティベーションコード
- 確認コード (オプション)
- 確認コード (必須)
- IMEI (オプション)
- 残りの容量が少量です
- 残り容量が少ないため、このプロファイルのダウンロードに失敗する可能性があります。
- クリップボードに LPA コードがありません
- 解析できません
- QR コードまたはクリップボードの内容を LPA コードとして解析できませんでした。
- ダウンロードウィザード
- 戻る
- 次へ
- 選択した SIM が削除されました
- ダウンロードする eSIM を選択または確認:
- タイプ:
- リムーバブル
- 内部
- 内部 - ポート: %d
- 有効なプロファイル:
- 空き容量:
- eSIM プロファイルをどの方法でダウンロードしますか?
- カメラで QR コードをスキャン
- ギャラリーから QR コードをスキャン
- クリップボードから読み込む
- 手動で入力
- eSIM をダウンロードするための詳細情報を入力または確認:
- eSIM をダウンロード中です…
- 準備中
- サーバーへの接続を確立しています
- サーバーでデバイスを認証中です
- eSIM プロファイルをダウンロード中です
- eSIM プロファイルをストレージに読み込み中です
- エラー診断
- エラーコード: %s
- 最終の HTTP ステータス (サーバー): %d
- 最終の HTTP レスポンス (サーバー):
- 最終の HTTP 例外:
- 最終の APDU レスポンス (SIM): %s
- 最終の APDU レスポンス (SIM) は成功しました
- 最終の APDU レスポンス (SIM) は失敗しました
- 最終の APDU 例外:
- 保存
- 「%s」での診断
- この eSIM プロファイルはすでに eSIM チップに存在します。
- eSIM チップにはプロファイルをダウンロードするのに必要なメモリが残っていません。
- この eSIM プロファイルは、eSIM チップではサポートされていません。
- eSIM チップでエラーが発生しました。
- 使用しているデバイスまたは eSIM チップの EID は、通信事業者によってサポートされていません。
- この eSIM プロファイルは、別のデバイスにダウンロードされています。
- この eSIM プロファイルは取り消されました。
- アクティベーションコードが無効です。
- eSIM プロファイルのダウンロード試行回数の上限を超えました。
- このプロファイルをダウンロードするには確認コードが必要です。
- 入力した確認コードは無効です。
- この eSIM プロファイルは有効期限が切れています。
- 確認コードのダウンロード試行回数の上限を超えました。
- 不明な SM-DP+ アドレス
- ネットワークにアクセスできません
- TLS 証明書エラー、この eSIM プロファイルはサポートされていません
- ダウンロード済みの eSIM プロファイルを再インストールしようとしています
- 未使用の eSIM プロファイルをいくつか削除して、再度お試しください
- サポートについては、通信事業者にお問い合わせください。
- この eSIM プロファイルを再発行するには、通信事業者にお問い合わせください。
- 別のネットワークに接続後 (例: Wi-Fi とデータを切り替え) を行った後に再度お試しください。
- ログは共有したパスに保存されました。別のアプリで共有しますか?
- 新しいニックネーム
- ニックネームを UTF-8 にエンコードできませんでした
- ニックネームが 64 文字を超えています
- プロファイルの名前変更時に不明なエラーが発生しました
- %s のプロファイルを削除してもよろしいですか?この操作は元に戻せません。
- 削除を確認するには「%s」を入力してください
- 通知
- 通知 (%s)
- 通知の管理
- eSIM プロファイルはダウンロードや削除、有効化や無効化されたときに通信事業者に通知を送信できます。送信されるこれらの通知のキューはここにリストされます。\n\n設定では、各タイプの通知を自動的に送信するかどうかを指定できます。通知が送信された場合でもキューのスペースが不足していない限り、記録から自動的に削除されることはありません。\n\nここでは保留中の各通知を手動で送信または削除できます。
- ダウンロードしました
- 削除しました
- 有効化済み
- 無効化済み
- 処理
- 削除
- eUICC 情報
- eUICC 情報 (%s)
- アクセスモード
- リムーバブル
- 製品名
- 製品シリアル番号
- 製品ブートローダーバージョン
- 製品ファームウェアバージョン
- SGP.22 バージョン
- eUICC OS バージョン
- グローバルプラットフォームのバージョン
- SAS 認定番号
- 保護されたプロファイルのバージョン
- NVRAM の空き容量 (eSIM プロファイルストレージ)
- (参照用)
- 証明書発行者 (CI)
- GSMA ライブ CI
- GSMA テスト CI
- 不明な eSIM CI
- eUICC を消去
- eUICC を消去
- このチップ上のすべてのプロファイルを削除することを確認してください。この操作は元に戻せないことを理解してください。\n\nEID: %1$s\n\n%2$s
- 確認のために「%s」を入力してください
- EID が %s で終わるチップを消去することを確認し、この操作は元に戻せないことを理解してください
- 消去
-
- はい
- いいえ
- 不明
- 情報がありません
- 保存
- %s のログ
- 開発者になるまであと %d ステップです。
- あなたは開発者になりました!
- ISD-R AID リスト
- カスタム ISD-R AID リストを保存しました。
- リセット
- 設定
- 通知
- eSIM のプロファイル操作により、通信事業者に通知が送信されます。必要に応じてこの動作を微調整できます。
- ダウンロード
- プロファイルをダウンロード中 の通知を送信します
- 削除
- プロファイルを削除中 の通知を送信します
- 切り替え中
- プロファイルを切り替え中 の通知を送信します\nこのタイプの通知は信頼できないことに注意してください。
- 高度な設定
- プロファイルの無効化と削除を許可
- デフォルトでは、このアプリでデバイスに挿入されたリムーバブル eSIM の有効なプロファイルを無効化することを防いでいます。なぜなのかというと時々 アクセスができなくなるからです。\nこのチェックボックスを ON にすることで、この保護機能を解除 します。
- 詳細ログ
- 詳細ログを有効化します。これには個人的な情報が含まれている可能性があります。この機能を ON にした後は、信頼できるユーザーとのみログを共有してください。
- 言語
- アプリの言語
- ログ
- アプリの最新デバッグログを表示します
- 開発者オプション
- モデムに更新コマンドを送信
- プロファイルを切り替えた後にモデムに更新コマンドを送信するかどうかを設定します。クラッシュが発生する場合は、この機能を無効化してください。
- フィルタリングされていないプロファイル一覧を表示
- 非運用のプロファイルも含めます
- SM-DP+ TLS 証明書を無視する
- RSP サーバーで使用される TLS 証明書を受け入れます
- eUICC の消去を許可
- これは危険な操作であり、デフォルトでは非表示になっています。代わりとしてすべてのプロファイルを手動で削除することもできます。
- グローバル ES10x MSS
-
- - 高速
- - 互換モード
-
- ISD-R AID リストをカスタマイズ
- 一部ブランドのリムーバブル eUICC は独自の非標準な ISD-R AID を使用しているため、サードパーティー製アプリからアクセスできない場合があります。このリストに追加された非標準な AID の使用を試みますが、動作の保証はできません。
- 情報
- アプリバージョン
- ソースコード
-
diff --git a/app-common/src/main/res/values-zh-rCN/strings.xml b/app-common/src/main/res/values-zh-rCN/strings.xml
deleted file mode 100644
index 7303d2d..0000000
--- a/app-common/src/main/res/values-zh-rCN/strings.xml
+++ /dev/null
@@ -1,200 +0,0 @@
-
-
- 在此设备上未检测到此应用程序可访问的可插拔 eUICC 卡。请插入兼容卡或 USB 读卡器。
- 此 eSIM 上还没有配置文件
- 未知
- 帮助
- 重新加载卡槽
- 未知
- 逻辑卡槽 %d
- 已启用
- 已禁用
- 提供商:
- 类型:
- 启用
- 禁用
- 删除
- 重命名
- 等待 eSIM 芯片切换配置文件时超时。这可能是您手机基带固件中的一个错误。请尝试切换飞行模式、重新启动应用程序或重新启动手机
- 操作成功, 但是您手机的基带拒绝刷新。您可能需要切换飞行模式或重新启动,以便使用新的配置文件。
- 无法切换到新的 eSIM 配置文件。
- 输入的确认文本不匹配
- 已复制 ICCID 到剪贴板
- 已复制 EID 到剪贴板
- 已复制 ATR 到剪贴板
- 授予 USB 权限
- 需要获得访问 USB 智能卡读卡器的权限。
- 无法通过 USB 智能卡读卡器连接到 eSIM。
- 长时间运行的后台任务
- 正在下载 eSIM 配置文件
- 无法下载 eSIM 配置文件
- 正在重命名 eSIM 配置文件
- 无法重命名 eSIM 配置文件
- 正在删除 eSIM 配置文件
- 无法删除 eSIM 配置文件
- 正在切换 eSIM 配置文件
- 无法切换 eSIM 配置文件
- 添加新 eSIM
- 服务器 (RSP / SM-DP+)
- 激活码
- 确认码 (可选)
- 已复制序列号到剪贴板
- 产品名称
- 产品序列号
- 产品 Bootloader 版本
- 产品固件版本
- 确认码 (必需)
- IMEI (可选)
- 剩余空间不足
- 当前芯片的剩余空间不足,可能导致配置下载失败。\n是否继续下载?
- 请连接到其他网络(例如在 Wi-Fi 和数据之间切换)后重试。
- 日志已保存到指定路径。需要通过其他 App 分享吗?
- 新昵称
- 无法将昵称编码为 UTF-8
- 昵称长于 64 字符
- 重命名配置文件时发生了未知错误
- 您确定要删除 %s 吗?此操作是不可逆的。
- 请输入\'%s\'以确认删除
- 通知列表
- 通知列表 (%s)
- 管理通知
- eSIM 配置文件可以在下载、删除、启用或禁用时向运营商发送通知。此处列出了要发送的这些通知的队列。\n\n在\"设置\"中,您可以指定是否自动发送每种类型的通知。请注意,即使通知已发送,也不会自动从记录中删除,除非队列空间不足。\n\n在这里,您可以手动发送或删除每个待处理的通知。
- 已下载
- 已删除
- 已启用
- 已禁用
- 处理
- 删除
- 保存日志
- %s 的日志
- 自定义 ISD-R AID 列表已保存
- 设置
- 通知
- 操作 eSIM 配置文件会向运营商发送通知。根据需要在此处微调此行为。
- 下载
- 发送 下载 配置文件的通知
- 删除
- 发送 删除 配置文件的通知
- 切换
- 发送 切换 配置文件的通知\n注意,这种类型的通知是不可靠的。
- 高级
- 允许 禁用/删除 已启用的配置文件
- 默认情况下,此应用程序会阻止您禁用可插拔 eSIM 中已启用的配置文件。\n因为这样做 有时 会使其无法访问。\n勾选此框以 移除 此保护措施。
- 记录详细日志
- 详细日志中包含敏感信息,开启此功能后请仅与你信任的人共享你的日志。
- 日志
- 查看应用程序的最新调试日志
- 某些品牌的可移除 eUICC 可能会使用自己的非标准 ISD-R AID,导致第三方应用无法访问。此 App 可以尝试使用此列表中添加的非标准 AID,但不能保证它们一定有效。
- 全局 ES10x MSS
-
- - 最佳效率
- - 最佳兼容性
-
- 信息
- App 版本
- 源码
- 测试
- 准备中
- 可用
- 未在剪贴板上发现 LPA 码
- LPA 码解析错误
- 无法将二维码或剪贴板内容解析为 LPA 码
- 下载向导
- 返回
- 下一步
- 您选择的 SIM 已被移除
- 请选择或确认下载目标 eSIM 卡槽:
- 类型:
- 可插拔
- 内置
- 内置, 端口 %d
- 当前配置文件:
- 剩余空间:
- 您想要如何下载 eSIM 配置文件?
- 用相机扫描二维码
- 从图库选择二维码
- 从剪贴板读取
- 手动输入
- 请输入或确认下载 eSIM 的详细信息:
- 正在下载您的 eSIM...
- 准备中
- 正在连接服务器
- 正在向服务器认证您的设备
- 正在下载 eSIM 配置文件
- 正在写入 eSIM 配置文件
- 错误诊断
- 错误代码: %s
- 上次 HTTP 状态码 (来自服务器): %d
- 上次 HTTP 应答 (来自服务器):
- 上次 HTTP 错误:
- 上次 APDU 应答 (来自 SIM): %s
- 上次 APDU 应答 (来自 SIM) 是成功的
- 上次 APDU 应答 (来自 SIM) 是失败的
- 上次 APDU 错误:
- 保存
- %s 的错误诊断
- eUICC 详情
- eUICC 详情 (%s)
- 访问方式
- 可插拔
- SGP.22 版本
- eUICC OS 版本
- GlobalPlatform 版本
- SAS 认证号码
- Protected Profile 版本
- NVRAM 剩余空间 (eSIM 存储容量)
- (仅供参考)
- 证书签发者 (CI)
- GSMA 生产环境 CI
- GSMA 测试 CI
- 未知 eSIM CI
- 是
- 否
- 还有 %d 步成为开发者
- 你现在是开发者了!
- 语言
- 选择 App 语言
- 开发者选项
- 切换配置文件后是否向基带发送刷新命令。如果发现崩溃,请尝试禁用此功能。
- 显示未经过滤的配置文件列表
- 在配置文件列表中包括非生产环境的配置文件
- 无视 SM-DP+ 的 TLS 证书
- 允许 RSP 服务器使用任意证书
- 无信息
- 输入的确认文本不匹配
- 此芯片已被擦除
- 正在擦除 eSIM 芯片
- eSIM 芯片擦除失败
- 擦除 eSIM 芯片
- 擦除 eSIM 芯片
- 请确认删除此芯片上的所有配置文件,并了解此操作不可逆。\n\nEID: %1$s\n\n%2$s
- 请在此处输入「%s」以确认
- 我确认擦除 EID 以 %s 结尾的芯片,并了解此操作不可逆
- 擦除
- 允许擦除 eUICC
- 此操作是默认隐藏的危险操作。作为替代方案,您可以手动删除所有配置文件。
- 向基带发送刷新命令
- 自定义 ISD-R AID 列表
- 重置
- ISD-R AID 列表
- 此 eSIM 配置文件已存在于您的 eSIM 芯片上。
- 您的 eSIM 芯片没有足够的空间来下载配置文件。
- 您的 eSIM 芯片不支持此 eSIM 配置文件。
- eSIM 芯片错误。
- 您的设备或 eSIM 芯片的 EID 不受您的运营商支持。
- 此 eSIM 配置文件已被下载到另一台设备上。
- 此 eSIM 配置文件已被撤销。
- 激活码无效。
- 已超出 eSIM 配置文件的最大下载尝试次数。
- 下载此配置文件需要确认码。
- 您输入的确认码无效。
- 此 eSIM 配置文件已过期。
- 已超出确认码的最大下载尝试次数。
- 未知的 SM-DP+ 地址
- 网络不可达
- TLS 证书错误,不支持此 eSIM 配置文件
- 您正在尝试重新安装已下载的 eSIM 配置文件
- 请删除一些未使用的 eSIM 配置文件,然后重试
- 请联系您的运营商寻求帮助。
- 请联系您的运营商重新签发此 eSIM 配置文件。
-
\ No newline at end of file
diff --git a/app-common/src/main/res/values-zh-rTW/strings.xml b/app-common/src/main/res/values-zh-rTW/strings.xml
deleted file mode 100644
index ef6c842..0000000
--- a/app-common/src/main/res/values-zh-rTW/strings.xml
+++ /dev/null
@@ -1,196 +0,0 @@
-
-
- 在此裝置上未檢測到此應用程式可訪問的可插拔 eUICC 卡。請插入相容卡或 USB 晶片讀卡機。
- 此 eSIM 上還沒有設定檔
- 未知
- 幫助
- 重新載入卡槽
- 未知
- 虛擬卡槽 %d
- 已啟用
- 已停用
- 電信業者:
- 類型:
- 啟用
- 停用
- 刪除
- 重新命名
- 等待 eSIM 切換設定檔時逾時。這可能是您手機基頻處理器韌體中的一個錯誤。請嘗試切換飛航模式、重新啟動應用程式或重新啟動手機
- 操作成功, 但是您手機的基頻處理器沒有重新整理。您可能需要切換飛航模式或重新啟動,以便使用新的設定檔。
- 無法切換到新的 eSIM 設定檔。
- 輸入的確認文字不匹配
- 已複製 ICCID 到剪貼簿
- 已複製 EID 到剪貼簿
- 已複製 ATR 到剪貼簿
- 授予 USB 權限
- 需要獲得訪問 USB 晶片讀卡機的權限。
- 無法透過 USB 晶片讀卡機連線到 eSIM。
- 長時間運行的背景作業
- 正在下載 eSIM 設定檔
- 無法下載 eSIM 設定檔
- 正在重新命名 eSIM 設定檔
- 無法重新命名 eSIM 設定檔
- 正在刪除 eSIM 設定檔
- 無法刪除 eSIM 設定檔
- 正在切換 eSIM 設定檔
- 無法切換 eSIM 設定檔
- 新增新 eSIM
- 伺服器 (RSP / SM-DP+)
- 啟用碼
- 確認碼 (可選)
- 已複製序號到剪貼簿
- 產品名稱
- 產品序號
- 產品引導程式版本
- 產品韌體版本
- 確認碼 (必需)
- IMEI (可選)
- 剩餘空間不足
- 目前晶片的剩餘空間不足,可能導致配置下載失敗。\n是否繼續下載?
- 請連接到其他網路(例如在 Wi-Fi 和資料之間切換)後重試。
- 日誌已儲存到指定路徑。需要透過其他 App 分享嗎?
- 新名稱
- 無法將名稱編碼為 UTF-8
- 名稱長於 64 字元
- 重新命名設定檔時發生了未知錯誤
- 您確定要刪除 %s 嗎?此動作無法還原。
- 請輸入\'%s\'以確認刪除
- 通知列表
- 通知列表 (%s)
- 管理通知
- eSIM 設定檔可以在下載、刪除、啟用或停用時向電信業者傳送通知。此處列出了要傳送的這些通知的佇列。\n\n在\"設定\"中,您可以指定是否自動傳送每種型別的通知。請注意,即使通知已傳送,也不會自動從記錄中刪除,除非佇列空間不足。\n\n在這裡,您可以手動傳送或刪除每個待處理的通知。
- 已下載
- 已刪除
- 已啟用
- 已停用
- 處理
- 刪除
- 儲存日誌
- %s 的日誌
- 自訂 ISD-R AID 列表已儲存
- 設定
- 通知
- 變更 eSIM 設定檔會向電信業者傳送通知。根據需要在此處微調此行為。
- 下載
- 傳送 下載 設定檔的通知
- 刪除
- 傳送 刪除 設定檔的通知
- 切換
- 記錄詳細日誌
- 詳細日誌中包含敏感資訊,開啟此功能後請僅與你信任的人共享你的日誌。
- 日誌
- 檢視應用程式的最新除錯日誌
- 傳送 切換 設定檔的通知\n注意,這種型別的通知是不可靠的。
- 進階
- 允許 停用/刪除 已啟用的設定檔
- 預設情況下,此應用程式會阻止您停用可插拔 eSIM 中已啟用的設定檔。\n因為這樣做 有時 會導致無法存取。\n勾選此框以 移除 此保護措施。
- 某些品牌的可移除 eUICC 可能會使用自己的非標準 ISD-R AID,導致第三方應用程式無法存取。此 App 可以嘗試使用此清單中新增的非標準 AID,但不能保證它們一定有效。
- 全局 ES10x MSS
- 資訊
- App 版本
- 原始碼
- 測試
- 準備中
- 可用
- 未在剪貼簿上發現 LPA 碼
- LPA 碼解析錯誤
- 無法將二維碼或剪貼簿內容解析為 LPA 碼
- 下載精靈
- 返回
- 下一步
- 您選擇的 SIM 卡已被移除
- 請選擇或確認下載目標 eSIM 卡槽:
- 型別:
- 可插拔
- 內建
- 內建, 埠 %d
- 目前設定檔:
- 剩餘空間:
- 您想要如何下載 eSIM 設定檔?
- 用相機掃描二維碼
- 從相簿選擇二維碼
- 從剪貼簿讀取
- 手動輸入
- 請輸入或確認下載 eSIM 的詳細資訊:
- 正在下載您的 eSIM...
- 準備中
- 正在連線到伺服器
- 正在向伺服器驗證您的裝置
- 正在下載 eSIM 設定檔
- 正在寫入 eSIM 設定檔
- 錯誤診斷
- 錯誤代碼: %s
- 上次 HTTP 狀態碼 (來自伺服器): %d
- 上次 HTTP 應答 (來自伺服器):
- 上次 HTTP 錯誤:
- 上次 APDU 應答 (來自 SIM): %s
- 上次 APDU 應答 (來自 SIM) 是成功的
- 上次 APDU 應答 (來自 SIM) 是失敗的
- 上次 APDU 錯誤:
- 儲存
- %s 的錯誤診斷
- eUICC 詳情
- eUICC 詳情 (%s)
- 訪問方式
- 可插拔
- SGP.22 版本
- eUICC OS 版本
- GlobalPlatform 版本
- SAS 認證號碼
- Protected Profile 版本
- NVRAM 剩餘空間 (eSIM 儲存容量)
- (僅供參考)
- 證書簽發者 (CI)
- GSMA 生產環境 CI
- GSMA 測試 CI
- 未知 eSIM CI
- 是
- 否
- 還有 %d 步成為開發者
- 您現在是開發者了!
- 語言
- 選擇 App 語言
- 開發人員選項
- 切換設定檔後是否向基帶發送刷新命令。如果發現崩潰,請嘗試停用此功能。
- 顯示未經過濾的設定檔列表
- 在設定檔列表中包括非生產環境的設定檔
- 忽略 SM-DP+ 的 TLS 證書
- 允許 RSP 伺服器使用任意證書
- 無資訊
- 輸入的確認文字不匹配
- 此晶片已被擦除
- 正在擦除 eSIM 晶片
- eSIM 晶片擦除失敗
- 擦除 eSIM 晶片
- 擦除 eSIM 晶片
- 請確認刪除此晶片上的所有配置文件,並了解此操作不可逆。\n\nEID: %1$s\n\n%2$s
- 請在此輸入「%s」以確認
- 我確認擦除 EID 以 %s 結尾的晶片,並了解此操作不可逆
- 擦除
- 允許擦除 eUICC
- 此操作是預設隱藏的危險操作。作為替代方案,您可以手動刪除所有設定檔。
- 向基帶發送刷新命令
- 自訂 ISD-R AID 列表
- 重置
- ISD-R AID 列表
- 此 eSIM 設定檔已存在於您的 eSIM 晶片上。
- 您的 eSIM 晶片沒有足夠的空間來下載設定檔。
- 您的 eSIM 晶片不支援此 eSIM 設定檔。
- eSIM 晶片錯誤。
- 您的裝置或 eSIM 晶片的 EID 不受您的電信業者支援。
- 此 eSIM 設定檔已被下載到另一台裝置上。
- 此 eSIM 設定檔已被撤銷。
- 啟用碼無效。
- 已超出 eSIM 設定檔的最大下載嘗試次數。
- 下載此設定檔需要確認碼。
- 您輸入的確認碼無效。
- 此 eSIM 設定檔已過期。
- 已超出確認碼的最大下載嘗試次數。
- 未知的 SM-DP+ 位址
- 網路不可達
- TLS 憑證錯誤,不支援此 eSIM 設定檔
- 您正在嘗試重新安裝已下載的 eSIM 設定文件
- 請刪除一些未使用的 eSIM 設定文件,然後重試
- 請聯絡您的電信業者尋求協助。
- 請聯絡您的電信業者重新簽發此 eSIM 設定檔。
-
\ No newline at end of file
diff --git a/app-common/src/main/res/values/strings.xml b/app-common/src/main/res/values/strings.xml
index 39a762f..7647815 100644
--- a/app-common/src/main/res/values/strings.xml
+++ b/app-common/src/main/res/values/strings.xml
@@ -2,136 +2,49 @@
No removable eUICC card accessible by this app is detected on this device. Insert a compatible card or a USB reader.
No profiles (yet) on this eSIM.
-
- Help
-
- Reload Slots
- Unknown
+ Unknown
+ Help
+ Reload Slots
Logical Slot %d
- USB
- OpenMobile API (OMAPI)
+ USB
-
- Enabled
- Disabled
- Provider:
- Class:
- Testing
- Provisioning
- Operational
- ICCID:
- #%d
+ Enabled
+ Disabled
+ Provider:
+ ICCID:
- Enable
- Disable
- Delete
- Rename
+ Enable
+ Disable
+ Delete
+ Rename
- Timed out waiting for the eSIM chip to switch profiles. This may be a bug in your phone\'s modem firmware. Try toggling airplane mode, restarting the application, or rebooting the phone.
- The operation was successful, but your phone\'s modem refused to refresh. You might need to toggle airplane mode or reboot in order to use the new profile.
+ Timed out waiting for the eSIM chip to switch profiles. This may be a bug in your phone\'s modem firmware. Try toggling airplane mode, restarting the application, or rebooting the phone.
+ The operation was successful, but your phone\'s modem refused to refresh. You might need to toggle airplane mode or reboot in order to use the new profile.
Cannot switch to new eSIM profile.
- Confirmation string mismatch
- Confirmation string mismatch
- This chip has been erased
+ Nickname cannot be longer than 64 characters
ICCID copied to clipboard
- Serial number copied to clipboard
- EID copied to clipboard
- ATR copied to clipboard
+
+ Select Slot
+ Select
Grant USB permission
Permission is needed to access the USB smart card reader.
Cannot connect to eSIM via a USB smart card reader.
- Long-running Tasks
- Downloading eSIM profile
- Failed to download eSIM profile
- Renaming eSIM profile
- Failed to rename eSIM profile
- Deleting eSIM profile
- Failed to delete eSIM profile
- Switching eSIM profile
- Failed to switch eSIM profile
- Erasing eSIM chip
- Failed to erase eSIM chip
-
New eSIM
Server (RSP / SM-DP+)
Activation Code
Confirmation Code (Optional)
- Confirmation Code (Required)
IMEI (Optional)
-
- Low remaining capacity
- This profile may fail to download due to low remaining capacity.
- No LPA code found in clipboard
- Unable to parse
- Could not parse QR code or clipboard content as a LPA code.
-
- Download Wizard
- Back
- Next
- Selected SIM has been removed
- Select or confirm the eSIM you would like to download to:
- Type:
- Removable
- Internal
- Internal, port %d
- eID:
- Active Profile:
- Free Space:
- How would you like to download the eSIM profile?
- Scan a QR code with camera
- Load a QR code from gallery
- Load from Clipboard
- Enter manually
- Input or confirm details for downloading your eSIM:
- Downloading your eSIM…
- Preparing
- Establishing connection to server
- Authenticating your device with server
- Downloading eSIM profile
- Loading eSIM profile into storage
- Error diagnostics
- Error code: %s
- Last HTTP status (from server): %d
- Last HTTP response (from server):
- Last HTTP exception:
- Last APDU response (from SIM): %s
- Last APDU response (from SIM) is successful
- Last APDU response (from SIM) is a failure
- Last APDU exception:
- Save
- Diagnostics at %s
- This eSIM profile is already present on your eSIM chip.
- Your eSIM chip does not have sufficient memory left to download the profile.
- This eSIM profile is unsupported by your eSIM chip.
- An error occurred in your eSIM chip.
- The EID of your device or eSIM chip is unsupported by your carrier.
- This eSIM profile has been downloaded on another device.
- This eSIM profile has been revoked.
- The activation code is invalid.
- The maximum number of download attempts for the eSIM profile has been exceeded.
- Confirmation code is required to download this profile.
- The confirmation code you entered is invalid.
- This eSIM profile has expired.
- The maximum number of download attempts for the confirmation code has been exceeded.
- Unknown SM-DP+ address
- Network is unreachable
- TLS certificate error, this eSIM profile is not supported
- You are trying to reinstall an already downloaded eSIM profile
- Please delete some unused eSIM profiles and try again
- Please contact your carrier for assistance.
- Please contact your carrier to reissue this eSIM profile.
- Please try again after connecting to a different network (e.g. switching between Wi-Fi and data).
-
- Logs have been saved to the selected path. Would you like to share the log through another app?
+ Space remaining: %s
+ Scan QR Code
+ Scan QR Code from Gallery
+ Download
+ Failed to download eSIM. Check your activation / QR code.
New nickname
- Failed to encode nickname as UTF-8
- Nickname is longer than 64 characters
- Unknown failure when renaming profile
Are you sure you want to delete the profile %s? This operation is irreversible.
Type \'%s\' here to confirm deletion
@@ -144,57 +57,13 @@
Deleted
Enabled
Disabled
- <b>%1$s</b> %2$s (%3$s)
- #%d
+ <b>%1$s</b> %2$s (%3$s)
Process
Delete
- eUICC Info
- eUICC Info (%s)
- Access Mode
- Removable
- Product Name
- Product Serial Number
- Product Bootloader Version
- Product Firmware Version
- EID
- ISD-R AID
- SGP.22 Version
- eUICC OS Version
- GlobalPlatform Version
- SAS Accreditation Number
- Protected Profile Version
- Free NVRAM (eSIM profile storage)
- (for reference only)
- Certificate Issuer (CI)
- GSMA Live CI
- GSMA Test CI
- Unknown eSIM CI
- Answer To Reset (ATR)
-
- Erase eUICC
- Erase eUICC
- Please confirm to delete all profiles on this chip and understand that this operation is irreversible.\n\nEID: %1$s\n\n%2$s
- Type \'%s\' here to confirm
- I CONFIRM TO ERASE THE CHIP WHOSE EID ENDS WITH %s AND UNDERSTAND THAT THIS IS IRREVERSIBLE
- Erase
-
-
- Yes
- No
- Unknown
- Information Unavailable
-
Save
Logs at %s
- You are %d steps away from being a developer.
- You are now a developer!
-
- ISD-R AID List
- Saved custom ISD-R AID list.
- Reset
-
Settings
Notifications
eSIM profile operations send notifications to the carrier. Fine-tune this behavior as needed here.
@@ -205,35 +74,10 @@
Switching
Send notifications for switching profiles\nNote that this type of notification is unreliable.
Advanced
- Allow Disabling / Deleting Active Profile
+ Disable Safeguards for Removable eSIMs
By default, this app prevents you from disabling the active profile on a removable eSIM inserted in the device, because doing so may sometimes render it inaccessible.\nCheck this box to remove this safeguard.
- Verbose Logging
- Enable verbose logs, which may contain sensitive information. Only share your logs with someone you trust after turning this on.
- Language
- Select app language
Logs
View recent debug logs of the application
- Developer Options
- Send refresh command to modem
- Whether to send a refresh command to the modem after switching profiles. Try disabling this if you see crashes.
- Show unfiltered profile list
- Include non-production profiles in the list
- Ignore SM-DP+ TLS certificate
- Accept any TLS certificate used by the RSP server
- Allow erasing eUICC
- This is a dangerous operation and hidden by default. As an alternative, you can delete all profiles manually.
- ES10x MSS
- Global ES10x MSS
-
- - High Efficiency
- - Most Compatible
-
-
- - 255
- - 63
-
- Customize ISD-R AID list
- Some brands of removable eUICCs may use their own non-standard ISD-R AID, rendering them inaccessible to third-party apps. We can attempt to use non-standard AIDs added in this list, but there is no guarantee that they will work.
Info
App Version
Source Code
diff --git a/app-common/src/main/res/xml/locale_config.xml b/app-common/src/main/res/xml/locale_config.xml
deleted file mode 100644
index 6d7f076..0000000
--- a/app-common/src/main/res/xml/locale_config.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-common/src/main/res/xml/pref_settings.xml b/app-common/src/main/res/xml/pref_settings.xml
index 831b04d..db348fc 100644
--- a/app-common/src/main/res/xml/pref_settings.xml
+++ b/app-common/src/main/res/xml/pref_settings.xml
@@ -1,6 +1,5 @@
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+ app:key="pref_info_source_code"/>
\ No newline at end of file
diff --git a/app-deps/.gitignore b/app-deps/.gitignore
index c23e5a2..42afabf 100644
--- a/app-deps/.gitignore
+++ b/app-deps/.gitignore
@@ -1,2 +1 @@
-/build
-/libs
\ No newline at end of file
+/build
\ No newline at end of file
diff --git a/app-deps/Android.bp b/app-deps/Android.bp
index b98d862..3143e3f 100644
--- a/app-deps/Android.bp
+++ b/app-deps/Android.bp
@@ -8,7 +8,6 @@ java_defaults {
"androidx-constraintlayout_constraintlayout",
"androidx.preference_preference",
"androidx.lifecycle_lifecycle-runtime-ktx",
- "androidx.lifecycle_lifecycle-service",
"androidx.swiperefreshlayout_swiperefreshlayout",
"androidx.cardview_cardview",
"androidx.viewpager2_viewpager2",
diff --git a/app-deps/build.gradle.kts b/app-deps/build.gradle.kts
index 2f4d70e..2111436 100644
--- a/app-deps/build.gradle.kts
+++ b/app-deps/build.gradle.kts
@@ -13,7 +13,7 @@ apply {
android {
namespace = "im.angry.openeuicc_deps"
- compileSdk = 34
+ compileSdk = 33
defaultConfig {
minSdk = 28
@@ -48,7 +48,6 @@ dependencies {
//noinspection KtxExtensionAvailable
api("androidx.preference:preference:1.2.1")
api("androidx.lifecycle:lifecycle-runtime-ktx:2.6.2")
- api("androidx.lifecycle:lifecycle-service:2.6.2")
api("androidx.swiperefreshlayout:swiperefreshlayout:1.1.0")
api("androidx.cardview:cardview:1.0.0")
api("androidx.viewpager2:viewpager2:1.1.0")
diff --git a/app-unpriv/build.gradle.kts b/app-unpriv/build.gradle.kts
index d59fe71..f1aa79d 100644
--- a/app-unpriv/build.gradle.kts
+++ b/app-unpriv/build.gradle.kts
@@ -17,19 +17,16 @@ apply {
android {
namespace = "im.angry.easyeuicc"
- compileSdk = 35
+ compileSdk = 34
ndkVersion = "26.1.10909125"
defaultConfig {
applicationId = "im.angry.easyeuicc"
minSdk = 28
- targetSdk = 35
+ targetSdk = 34
}
buildTypes {
- defaultConfig {
- versionNameSuffix = "-unpriv"
- }
release {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
diff --git a/app-unpriv/src/main/AndroidManifest.xml b/app-unpriv/src/main/AndroidManifest.xml
index 9c14163..e72b112 100644
--- a/app-unpriv/src/main/AndroidManifest.xml
+++ b/app-unpriv/src/main/AndroidManifest.xml
@@ -1,6 +1,5 @@
-
+
+ android:theme="@style/Theme.OpenEUICC">
+ android:name="im.angry.openeuicc.ui.CompatibilityCheckActivity"
+ android:label="@string/compatibility_check"
+ android:exported="false" />
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-unpriv/src/main/java/im/angry/openeuicc/di/UnprivilegedAppContainer.kt b/app-unpriv/src/main/java/im/angry/openeuicc/di/UnprivilegedAppContainer.kt
index 042c720..22d5a62 100644
--- a/app-unpriv/src/main/java/im/angry/openeuicc/di/UnprivilegedAppContainer.kt
+++ b/app-unpriv/src/main/java/im/angry/openeuicc/di/UnprivilegedAppContainer.kt
@@ -1,18 +1,9 @@
package im.angry.openeuicc.di
import android.content.Context
-import im.angry.openeuicc.util.UnprivilegedPreferenceRepository
class UnprivilegedAppContainer(context: Context) : DefaultAppContainer(context) {
override val uiComponentFactory by lazy {
UnprivilegedUiComponentFactory()
}
-
- override val customizableTextProvider by lazy {
- UnprivilegedCustomizableTextProvider(context)
- }
-
- override val preferenceRepository by lazy {
- UnprivilegedPreferenceRepository(context)
- }
}
\ No newline at end of file
diff --git a/app-unpriv/src/main/java/im/angry/openeuicc/di/UnprivilegedCustomizableTextProvider.kt b/app-unpriv/src/main/java/im/angry/openeuicc/di/UnprivilegedCustomizableTextProvider.kt
deleted file mode 100644
index 929ce84..0000000
--- a/app-unpriv/src/main/java/im/angry/openeuicc/di/UnprivilegedCustomizableTextProvider.kt
+++ /dev/null
@@ -1,10 +0,0 @@
-package im.angry.openeuicc.di
-
-import android.content.Context
-import im.angry.easyeuicc.R
-
-class UnprivilegedCustomizableTextProvider(private val context: Context) :
- DefaultCustomizableTextProvider(context) {
- override fun formatInternalChannelName(logicalSlotId: Int): String =
- context.getString(R.string.channel_name_format_unpriv, logicalSlotId)
-}
\ No newline at end of file
diff --git a/app-unpriv/src/main/java/im/angry/openeuicc/di/UnprivilegedUiComponentFactory.kt b/app-unpriv/src/main/java/im/angry/openeuicc/di/UnprivilegedUiComponentFactory.kt
index 3eb09c0..f117038 100644
--- a/app-unpriv/src/main/java/im/angry/openeuicc/di/UnprivilegedUiComponentFactory.kt
+++ b/app-unpriv/src/main/java/im/angry/openeuicc/di/UnprivilegedUiComponentFactory.kt
@@ -1,22 +1,9 @@
package im.angry.openeuicc.di
import androidx.fragment.app.Fragment
-import im.angry.openeuicc.ui.EuiccManagementFragment
-import im.angry.openeuicc.ui.QuickCompatibilityFragment
-import im.angry.openeuicc.ui.UnprivilegedEuiccManagementFragment
import im.angry.openeuicc.ui.UnprivilegedNoEuiccPlaceholderFragment
-import im.angry.openeuicc.ui.UnprivilegedSettingsFragment
-
-open class UnprivilegedUiComponentFactory : DefaultUiComponentFactory() {
- override fun createEuiccManagementFragment(slotId: Int, portId: Int): EuiccManagementFragment =
- UnprivilegedEuiccManagementFragment.newInstance(slotId, portId)
+class UnprivilegedUiComponentFactory : DefaultUiComponentFactory() {
override fun createNoEuiccPlaceholderFragment(): Fragment =
UnprivilegedNoEuiccPlaceholderFragment()
-
- override fun createSettingsFragment(): Fragment =
- UnprivilegedSettingsFragment()
-
- open fun createQuickCompatibilityFragment(): Fragment =
- QuickCompatibilityFragment()
}
\ No newline at end of file
diff --git a/app-unpriv/src/main/java/im/angry/openeuicc/ui/CompatibilityCheckActivity.kt b/app-unpriv/src/main/java/im/angry/openeuicc/ui/CompatibilityCheckActivity.kt
new file mode 100644
index 0000000..b747bef
--- /dev/null
+++ b/app-unpriv/src/main/java/im/angry/openeuicc/ui/CompatibilityCheckActivity.kt
@@ -0,0 +1,94 @@
+package im.angry.openeuicc.ui
+
+import android.os.Bundle
+import android.util.Log
+import android.view.MenuItem
+import android.view.View
+import android.view.ViewGroup
+import android.widget.TextView
+import androidx.appcompat.app.AppCompatActivity
+import androidx.core.view.children
+import androidx.lifecycle.lifecycleScope
+import androidx.recyclerview.widget.DividerItemDecoration
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import im.angry.easyeuicc.R
+import im.angry.openeuicc.util.*
+import kotlinx.coroutines.launch
+
+class CompatibilityCheckActivity: AppCompatActivity() {
+ private lateinit var compatibilityCheckList: RecyclerView
+ private val compatibilityChecks: List by lazy { getCompatibilityChecks(this) }
+ private val adapter = CompatibilityChecksAdapter()
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_compatibility_check)
+ setSupportActionBar(requireViewById(R.id.toolbar))
+ supportActionBar!!.setDisplayHomeAsUpEnabled(true)
+
+ compatibilityCheckList = requireViewById(R.id.recycler_view)
+ compatibilityCheckList.layoutManager =
+ LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
+ compatibilityCheckList.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL))
+ compatibilityCheckList.adapter = adapter
+ }
+
+ override fun onStart() {
+ super.onStart()
+ lifecycleScope.launch {
+ compatibilityChecks.executeAll { adapter.notifyDataSetChanged() }
+ }
+ }
+
+ override fun onOptionsItemSelected(item: MenuItem): Boolean =
+ when (item.itemId) {
+ android.R.id.home -> {
+ finish()
+ true
+ }
+ else -> super.onOptionsItemSelected(item)
+ }
+
+ inner class ViewHolder(private val root: View): RecyclerView.ViewHolder(root) {
+ private val titleView: TextView = root.requireViewById(R.id.compatibility_check_title)
+ private val descView: TextView = root.requireViewById(R.id.compatibility_check_desc)
+ private val statusContainer: ViewGroup = root.requireViewById(R.id.compatibility_check_status_container)
+
+ fun bindItem(item: CompatibilityCheck) {
+ titleView.text = item.title
+ descView.text = item.description
+
+ statusContainer.children.forEach {
+ it.visibility = View.GONE
+ }
+
+ when (item.state) {
+ CompatibilityCheck.State.SUCCESS -> {
+ root.requireViewById(R.id.compatibility_check_checkmark).visibility = View.VISIBLE
+ }
+ CompatibilityCheck.State.FAILURE -> {
+ root.requireViewById(R.id.compatibility_check_error).visibility = View.VISIBLE
+ }
+ CompatibilityCheck.State.FAILURE_UNKNOWN -> {
+ root.requireViewById(R.id.compatibility_check_unknown).visibility = View.VISIBLE
+ }
+ else -> {
+ root.requireViewById(R.id.compatibility_check_progress_bar).visibility = View.VISIBLE
+ }
+ }
+ }
+ }
+
+ inner class CompatibilityChecksAdapter: RecyclerView.Adapter() {
+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
+ ViewHolder(layoutInflater.inflate(R.layout.compatibility_check_item, parent, false))
+
+ override fun getItemCount(): Int =
+ compatibilityChecks.indexOfLast { it.state != CompatibilityCheck.State.NOT_STARTED } + 1
+
+ override fun onBindViewHolder(holder: ViewHolder, position: Int) {
+ holder.bindItem(compatibilityChecks[position])
+ }
+ }
+}
\ No newline at end of file
diff --git a/app-unpriv/src/main/java/im/angry/openeuicc/ui/QuickCompatibilityActivity.kt b/app-unpriv/src/main/java/im/angry/openeuicc/ui/QuickCompatibilityActivity.kt
deleted file mode 100644
index d5e599f..0000000
--- a/app-unpriv/src/main/java/im/angry/openeuicc/ui/QuickCompatibilityActivity.kt
+++ /dev/null
@@ -1,24 +0,0 @@
-package im.angry.openeuicc.ui
-
-import android.os.Bundle
-import androidx.activity.enableEdgeToEdge
-import androidx.appcompat.app.AppCompatActivity
-import im.angry.easyeuicc.R
-import im.angry.openeuicc.di.UnprivilegedUiComponentFactory
-import im.angry.openeuicc.util.OpenEuiccContextMarker
-
-class QuickCompatibilityActivity : AppCompatActivity(), OpenEuiccContextMarker {
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- enableEdgeToEdge()
- setContentView(R.layout.activity_quick_compatibility)
-
- val quickCompatibilityFragment =
- (appContainer.uiComponentFactory as UnprivilegedUiComponentFactory)
- .createQuickCompatibilityFragment()
-
- supportFragmentManager.beginTransaction()
- .replace(R.id.quick_compatibility_container, quickCompatibilityFragment)
- .commit()
- }
-}
diff --git a/app-unpriv/src/main/java/im/angry/openeuicc/ui/QuickCompatibilityFragment.kt b/app-unpriv/src/main/java/im/angry/openeuicc/ui/QuickCompatibilityFragment.kt
deleted file mode 100644
index 9b41730..0000000
--- a/app-unpriv/src/main/java/im/angry/openeuicc/ui/QuickCompatibilityFragment.kt
+++ /dev/null
@@ -1,186 +0,0 @@
-package im.angry.openeuicc.ui
-
-import android.content.pm.PackageManager
-import android.icu.text.ListFormatter
-import android.os.Build
-import android.os.Bundle
-import android.se.omapi.Reader
-import android.view.LayoutInflater
-import android.view.View
-import android.view.ViewGroup
-import android.widget.Button
-import android.widget.CheckBox
-import android.widget.TextView
-import androidx.core.view.isVisible
-import androidx.fragment.app.Fragment
-import androidx.lifecycle.lifecycleScope
-import im.angry.easyeuicc.R
-import im.angry.openeuicc.util.EUICC_DEFAULT_ISDR_AID
-import im.angry.openeuicc.util.UnprivilegedEuiccContextMarker
-import im.angry.openeuicc.util.connectSEService
-import im.angry.openeuicc.util.decodeHex
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.launch
-import kotlinx.coroutines.runBlocking
-import kotlinx.coroutines.withContext
-
-open class QuickCompatibilityFragment : Fragment(), UnprivilegedEuiccContextMarker {
- companion object {
- enum class Compatibility {
- COMPATIBLE,
- NOT_COMPATIBLE,
- }
-
- data class CompatibilityResult(
- val compatibility: Compatibility,
- val slotsOmapi: List = emptyList(),
- val slotsIsdr: List = emptyList()
- )
- }
-
- private val conclusion: TextView by lazy {
- requireView().requireViewById(R.id.quick_compatibility_conclusion)
- }
-
- private val resultSlots: TextView by lazy {
- requireView().requireViewById(R.id.quick_compatibility_result_slots)
- }
-
- private val resultSlotsIsdr: TextView by lazy {
- requireView().requireViewById(R.id.quick_compatibility_result_slots_isdr)
- }
-
- private val resultNotes: TextView by lazy {
- requireView().requireViewById(R.id.quick_compatibility_result_notes)
- }
-
- private val skipCheckBox: CheckBox by lazy {
- requireView().requireViewById(R.id.quick_compatibility_skip)
- }
-
- override fun onCreateView(
- inflater: LayoutInflater,
- container: ViewGroup?,
- savedInstanceState: Bundle?
- ): View = inflater.inflate(R.layout.fragment_quick_compatibility, container, false).apply {
- requireViewById(R.id.quick_compatibility_device_information)
- .text = formatDeviceInformation()
- requireViewById(R.id.quick_compatibility_button_continue)
- .setOnClickListener { onContinueToApp() }
- // Can't use the lazy field yet
- requireViewById(R.id.quick_compatibility_skip).setOnCheckedChangeListener { compoundButton, b ->
- if (compoundButton.isVisible) {
- runBlocking {
- preferenceRepository.skipQuickCompatibilityFlow
- .updatePreference(b)
- }
- }
- }
- }
-
- override fun onStart() {
- super.onStart()
- lifecycleScope.launch {
- onCompatibilityUpdate(withContext(Dispatchers.IO) {
- getCompatibilityCheckResult()
- })
- }
- }
-
- private fun onContinueToApp() {
- requireActivity().finish()
- }
-
- private fun onCompatibilityUpdate(result: CompatibilityResult) {
- conclusion.text = formatConclusion(result)
- if (result.compatibility == Compatibility.COMPATIBLE) {
- // Don't show the message again, ever, if the result is compatible
- runBlocking {
- preferenceRepository.skipQuickCompatibilityFlow
- .updatePreference(true)
- }
- resultSlots.isVisible = true
- resultSlots.text = getString(
- R.string.quick_compatibility_result_slots,
- ListFormatter.getInstance().format(result.slotsOmapi)
- )
- resultSlotsIsdr.isVisible = true
- resultSlotsIsdr.text =
- getString(
- R.string.quick_compatibility_result_slots_isdr,
- if (result.slotsIsdr.isEmpty()) {
- getString(R.string.quick_compatibility_unknown)
- } else {
- ListFormatter.getInstance().format(result.slotsIsdr)
- }
- )
- resultNotes.isVisible = true
- } else {
- resultNotes.isVisible = true
- resultNotes.text = getString(R.string.quick_compatibility_result_notes_incompatible)
- skipCheckBox.isVisible = true
- }
- }
-
- private suspend fun getCompatibilityCheckResult(): CompatibilityResult {
- val service = connectSEService(requireContext())
- if (!service.isConnected) {
- return CompatibilityResult(Compatibility.NOT_COMPATIBLE)
- }
- val readers = service.readers.filter(Reader::isSIM)
- val omapiSlots = readers.mapNotNull(Reader::slotIndex)
- val slots = readers.mapNotNull { reader ->
- try {
- // Note: we ONLY check the default ISD-R AID, because this test is for the _device_,
- // NOT the eUICC. We don't care what AID a potential eUICC might use, all we need to
- // check is we can open _some_ AID.
- reader.openSession().openLogicalChannel(EUICC_DEFAULT_ISDR_AID.decodeHex())?.close()
- reader.slotIndex
- } catch (_: SecurityException) {
- // Ignore; this is expected when everything works
- // ref: https://android.googlesource.com/platform/frameworks/base/+/4fe64fb4712a99d5da9c9a0eb8fd5169b252e1e1/omapi/java/android/se/omapi/Session.java#305
- // SecurityException is only thrown when Channel is constructed, which means everything else needs to succeed
- reader.slotIndex
- } catch (_: Exception) {
- null
- }
- }
- if (omapiSlots.isEmpty()) {
- return CompatibilityResult(Compatibility.NOT_COMPATIBLE)
- }
- val formatChannelName = appContainer.customizableTextProvider::formatInternalChannelName
- return CompatibilityResult(
- Compatibility.COMPATIBLE,
- slotsOmapi = omapiSlots.map(formatChannelName),
- slotsIsdr = slots.map(formatChannelName),
- )
- }
-
- open fun formatConclusion(result: CompatibilityResult): String {
- val usbHost = requireContext().packageManager
- .hasSystemFeature(PackageManager.FEATURE_USB_HOST)
- val resId = when (result.compatibility) {
- Compatibility.COMPATIBLE ->
- R.string.quick_compatibility_compatible
-
- Compatibility.NOT_COMPATIBLE -> if (usbHost)
- R.string.quick_compatibility_not_compatible_but_usb else
- R.string.quick_compatibility_not_compatible
- }
- return getString(resId, getString(R.string.app_name))
- }
-
- open fun formatDeviceInformation() = buildString {
- appendLine("BRAND: ${Build.BRAND}")
- appendLine("DEVICE: ${Build.DEVICE}")
- appendLine("MODEL: ${Build.MODEL}")
- appendLine("VERSION.RELEASE: ${Build.VERSION.RELEASE}")
- appendLine("VERSION.SDK_INT: ${Build.VERSION.SDK_INT}")
- }
-}
-
-private inline val Reader.isSIM: Boolean
- get() = name.startsWith("SIM")
-
-private inline val Reader.slotIndex: Int
- get() = (name.replace("SIM", "").toIntOrNull() ?: 1) - 1 // 0-based index
\ No newline at end of file
diff --git a/app-unpriv/src/main/java/im/angry/openeuicc/ui/UnprivilegedEuiccManagementFragment.kt b/app-unpriv/src/main/java/im/angry/openeuicc/ui/UnprivilegedEuiccManagementFragment.kt
deleted file mode 100644
index 7cf300c..0000000
--- a/app-unpriv/src/main/java/im/angry/openeuicc/ui/UnprivilegedEuiccManagementFragment.kt
+++ /dev/null
@@ -1,55 +0,0 @@
-package im.angry.openeuicc.ui
-
-import android.content.pm.PackageManager
-import android.provider.Settings
-import android.view.Menu
-import android.view.MenuInflater
-import android.view.MenuItem
-import android.widget.Toast
-import im.angry.easyeuicc.R
-import im.angry.openeuicc.util.SIMToolkit
-import im.angry.openeuicc.util.newInstanceEuicc
-import im.angry.openeuicc.util.slotId
-
-
-class UnprivilegedEuiccManagementFragment : EuiccManagementFragment() {
- companion object {
- const val TAG = "UnprivilegedEuiccManagementFragment"
-
- fun newInstance(slotId: Int, portId: Int): EuiccManagementFragment =
- newInstanceEuicc(UnprivilegedEuiccManagementFragment::class.java, slotId, portId)
- }
-
- private val stk by lazy {
- SIMToolkit(requireContext())
- }
-
- override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
- super.onCreateOptionsMenu(menu, inflater)
- inflater.inflate(R.menu.fragment_sim_toolkit, menu)
- }
-
- override fun onPrepareOptionsMenu(menu: Menu) {
- super.onPrepareOptionsMenu(menu)
- menu.findItem(R.id.open_sim_toolkit).apply {
- intent = stk[slotId]?.intent
- isVisible = intent != null
- }
- }
-
- override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
- R.id.open_sim_toolkit -> {
- SIMToolkit.getDisabledPackageName(item.intent)?.also { packageName ->
- val label = requireContext().packageManager.getApplicationLabel(packageName)
- val message = getString(R.string.toast_prompt_to_enable_sim_toolkit, label)
- Toast.makeText(requireContext(), message, Toast.LENGTH_LONG).show()
- }
- super.onOptionsItemSelected(item) // handling intent
- }
-
- else -> super.onOptionsItemSelected(item)
- }
-}
-
-private fun PackageManager.getApplicationLabel(packageName: String): CharSequence =
- getApplicationLabel(getApplicationInfo(packageName, 0))
diff --git a/app-unpriv/src/main/java/im/angry/openeuicc/ui/UnprivilegedMainActivity.kt b/app-unpriv/src/main/java/im/angry/openeuicc/ui/UnprivilegedMainActivity.kt
index 47bc904..1ed0cce 100644
--- a/app-unpriv/src/main/java/im/angry/openeuicc/ui/UnprivilegedMainActivity.kt
+++ b/app-unpriv/src/main/java/im/angry/openeuicc/ui/UnprivilegedMainActivity.kt
@@ -1,22 +1,11 @@
package im.angry.openeuicc.ui
import android.content.Intent
-import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import im.angry.easyeuicc.R
-import im.angry.openeuicc.util.UnprivilegedEuiccContextMarker
-import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.runBlocking
-
-class UnprivilegedMainActivity : MainActivity(), UnprivilegedEuiccContextMarker {
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- if (runBlocking { !preferenceRepository.skipQuickCompatibilityFlow.first() }) {
- startActivity(Intent(this, QuickCompatibilityActivity::class.java))
- }
- }
+class UnprivilegedMainActivity: MainActivity() {
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.activity_main_unprivileged, menu)
@@ -26,7 +15,7 @@ class UnprivilegedMainActivity : MainActivity(), UnprivilegedEuiccContextMarker
override fun onOptionsItemSelected(item: MenuItem): Boolean =
when (item.itemId) {
R.id.compatibility_check -> {
- startActivity(Intent(this, QuickCompatibilityActivity::class.java))
+ startActivity(Intent(this, CompatibilityCheckActivity::class.java))
true
}
else -> super.onOptionsItemSelected(item)
diff --git a/app-unpriv/src/main/java/im/angry/openeuicc/ui/UnprivilegedNoEuiccPlaceholderFragment.kt b/app-unpriv/src/main/java/im/angry/openeuicc/ui/UnprivilegedNoEuiccPlaceholderFragment.kt
index 56ad690..92cda23 100644
--- a/app-unpriv/src/main/java/im/angry/openeuicc/ui/UnprivilegedNoEuiccPlaceholderFragment.kt
+++ b/app-unpriv/src/main/java/im/angry/openeuicc/ui/UnprivilegedNoEuiccPlaceholderFragment.kt
@@ -21,7 +21,7 @@ class UnprivilegedNoEuiccPlaceholderFragment : Fragment() {
)
view.findViewById(R.id.compatibility_check).setOnClickListener {
- startActivity(Intent(requireContext(), QuickCompatibilityActivity::class.java))
+ startActivity(Intent(requireContext(), CompatibilityCheckActivity::class.java))
}
return view
diff --git a/app-unpriv/src/main/java/im/angry/openeuicc/ui/UnprivilegedSettingsFragment.kt b/app-unpriv/src/main/java/im/angry/openeuicc/ui/UnprivilegedSettingsFragment.kt
deleted file mode 100644
index 23589a6..0000000
--- a/app-unpriv/src/main/java/im/angry/openeuicc/ui/UnprivilegedSettingsFragment.kt
+++ /dev/null
@@ -1,46 +0,0 @@
-package im.angry.openeuicc.ui
-
-import android.content.ClipData
-import android.content.ClipboardManager
-import android.content.pm.PackageManager
-import android.os.Build
-import android.os.Bundle
-import android.widget.Toast
-import androidx.preference.Preference
-import im.angry.easyeuicc.R
-import im.angry.openeuicc.util.encodeHex
-import java.security.MessageDigest
-
-class UnprivilegedSettingsFragment : SettingsFragment() {
- private val firstSigner by lazy {
- val packageInfo = requireContext().let {
- it.packageManager.getPackageInfo(
- it.packageName,
- PackageManager.GET_SIGNING_CERTIFICATES,
- )
- }
- packageInfo.signingInfo!!.apkContentsSigners.first().let {
- MessageDigest.getInstance("SHA-1")
- .apply { update(it.toByteArray()) }
- .digest()
- }
- }
-
- override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
- super.onCreatePreferences(savedInstanceState, rootKey)
- addPreferencesFromResource(R.xml.pref_unprivileged_settings)
- mergePreferenceOverlay("pref_info_overlay", "pref_info")
-
- requirePreference("pref_info_ara_m").apply {
- summary = firstSigner.encodeHex()
- setOnPreferenceClickListener {
- requireContext().getSystemService(ClipboardManager::class.java)!!
- .setPrimaryClip(ClipData.newPlainText("ara-m", summary))
- if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2) Toast
- .makeText(requireContext(), R.string.toast_ara_m_copied, Toast.LENGTH_SHORT)
- .show()
- true
- }
- }
- }
-}
\ No newline at end of file
diff --git a/app-unpriv/src/main/java/im/angry/openeuicc/util/CompatibilityCheck.kt b/app-unpriv/src/main/java/im/angry/openeuicc/util/CompatibilityCheck.kt
new file mode 100644
index 0000000..49811bc
--- /dev/null
+++ b/app-unpriv/src/main/java/im/angry/openeuicc/util/CompatibilityCheck.kt
@@ -0,0 +1,281 @@
+package im.angry.openeuicc.util
+
+import android.content.Context
+import android.content.pm.PackageManager
+import android.os.Build
+import android.se.omapi.Reader
+import android.telephony.TelephonyManager
+import im.angry.easyeuicc.R
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.withContext
+import java.io.IOException
+
+fun getCompatibilityChecks(context: Context): List =
+ listOf(
+ HasSystemFeaturesCheck(context),
+ OmapiConnCheck(context),
+ IsdrChannelAccessCheck(context),
+ KnownBrokenCheck(context),
+ UsbCheck(context),
+ Verdict(context),
+ )
+
+inline fun List.findCheck(): T? =
+ find { it.javaClass == T::class.java }?.let { it as T }
+
+suspend fun List.executeAll(callback: () -> Unit) = withContext(Dispatchers.IO) {
+ forEach {
+ it.run(this@executeAll)
+ withContext(Dispatchers.Main) {
+ callback()
+ }
+ }
+}
+
+private val Reader.isSIM: Boolean
+ get() = name.startsWith("SIM")
+
+private val Reader.slotIndex: Int
+ get() = (name.replace("SIM", "").toIntOrNull() ?: 1)
+
+abstract class CompatibilityCheck(context: Context) {
+ enum class State {
+ NOT_STARTED,
+ IN_PROGRESS,
+ SUCCESS,
+ FAILURE_UNKNOWN, // The check technically failed, but no conclusion can be drawn
+ FAILURE
+ }
+
+ var state = State.NOT_STARTED
+
+ abstract val title: String
+ protected abstract val defaultDescription: String
+ protected lateinit var successDescription: String
+ protected lateinit var failureDescription: String
+
+ val description: String
+ get() = when {
+ (state == State.FAILURE || state == State.FAILURE_UNKNOWN) && this::failureDescription.isInitialized -> failureDescription
+ state == State.SUCCESS && this::successDescription.isInitialized -> successDescription
+ else -> defaultDescription
+ }
+
+ protected abstract suspend fun doCheck(allChecks: List): State
+
+ suspend fun run(allChecks: List) {
+ state = State.IN_PROGRESS
+ delay(200)
+ state = try {
+ doCheck(allChecks)
+ } catch (_: Exception) {
+ State.FAILURE
+ }
+ }
+}
+
+internal class HasSystemFeaturesCheck(private val context: Context): CompatibilityCheck(context) {
+ override val title: String
+ get() = context.getString(R.string.compatibility_check_system_features)
+ override val defaultDescription: String
+ get() = context.getString(R.string.compatibility_check_system_features_desc)
+
+ override suspend fun doCheck(allChecks: List): State {
+ if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+ failureDescription = context.getString(R.string.compatibility_check_system_features_no_telephony)
+ return State.FAILURE
+ }
+
+ // We can check OMAPI UICC availability on R or later (if before R, we check OMAPI connectivity later)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !context.packageManager.hasSystemFeature(
+ PackageManager.FEATURE_SE_OMAPI_UICC
+ )) {
+ failureDescription = context.getString(R.string.compatibility_check_system_features_no_omapi)
+ return State.FAILURE_UNKNOWN
+ }
+
+ return State.SUCCESS
+ }
+}
+
+internal class OmapiConnCheck(private val context: Context): CompatibilityCheck(context) {
+ override val title: String
+ get() = context.getString(R.string.compatibility_check_omapi_connectivity)
+ override val defaultDescription: String
+ get() = context.getString(R.string.compatibility_check_omapi_connectivity_desc)
+
+ override suspend fun doCheck(allChecks: List): State {
+ val seService = connectSEService(context)
+ if (!seService.isConnected) {
+ failureDescription = context.getString(R.string.compatibility_check_omapi_connectivity_fail)
+ return State.FAILURE
+ }
+
+ val tm = context.getSystemService(TelephonyManager::class.java)
+ val simReaders = seService.readers.filter { it.isSIM }
+ if (simReaders.isEmpty()) {
+ failureDescription = context.getString(R.string.compatibility_check_omapi_connectivity_fail)
+ return State.FAILURE_UNKNOWN
+ } else if (simReaders.size < tm.activeModemCountCompat) {
+ successDescription = context.getString(R.string.compatibility_check_omapi_connectivity_partial_success_sim_number,
+ simReaders.map { it.slotIndex }.joinToString(", "))
+ return State.SUCCESS
+ }
+
+ return State.SUCCESS
+ }
+}
+
+internal class IsdrChannelAccessCheck(private val context: Context): CompatibilityCheck(context) {
+ companion object {
+ val ISDR_AID = "A0000005591010FFFFFFFF8900000100".decodeHex()
+ }
+
+ override val title: String
+ get() = context.getString(R.string.compatibility_check_isdr_channel)
+ override val defaultDescription: String
+ get() = context.getString(R.string.compatibility_check_isdr_channel_desc)
+
+ override suspend fun doCheck(allChecks: List): State {
+ val seService = connectSEService(context)
+ val readers = seService.readers.filter { it.isSIM }
+ if (readers.isEmpty()) {
+ failureDescription = context.getString(R.string.compatibility_check_isdr_channel_desc_unknown)
+ return State.FAILURE_UNKNOWN
+ }
+
+ val (validSlotIds, result) = readers.map {
+ try {
+ it.openSession().openLogicalChannel(ISDR_AID)?.close()
+ Pair(it.slotIndex, State.SUCCESS)
+ } catch (_: SecurityException) {
+ // Ignore; this is expected when everything works
+ // ref: https://android.googlesource.com/platform/frameworks/base/+/4fe64fb4712a99d5da9c9a0eb8fd5169b252e1e1/omapi/java/android/se/omapi/Session.java#305
+ // SecurityException is only thrown when Channel is constructed, which means everything else needs to succeed
+ Pair(it.slotIndex, State.SUCCESS)
+ } catch (e: IOException) {
+ e.printStackTrace()
+ if (e.message?.contains("Secure Element is not present") == true) {
+ failureDescription = context.getString(R.string.compatibility_check_isdr_channel_desc_unknown)
+ Pair(it.slotIndex, State.FAILURE_UNKNOWN)
+ } else {
+ Pair(it.slotIndex, State.FAILURE)
+ }
+ } catch (e: Exception) {
+ e.printStackTrace()
+ Pair(it.slotIndex, State.FAILURE)
+ }
+ }.fold(Pair(mutableListOf(), State.SUCCESS)) { (ids, result), (id, ok) ->
+ if (ok != State.SUCCESS) {
+ Pair(ids, ok)
+ } else {
+ Pair(ids.apply { add(id) }, result)
+ }
+ }
+
+ if (result != State.SUCCESS && validSlotIds.size > 0) {
+ if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_EUICC)) {
+ failureDescription = context.getString(
+ R.string.compatibility_check_isdr_channel_desc_partial_fail,
+ validSlotIds.joinToString(", ")
+ )
+ } else {
+ // If the device has embedded eSIMs, we can likely ignore the failure here;
+ // the OMAPI failure likely resulted from trying to access internal eSIMs.
+ return State.SUCCESS
+ }
+ }
+
+ return result
+ }
+}
+
+internal class KnownBrokenCheck(private val context: Context): CompatibilityCheck(context) {
+ companion object {
+ val BROKEN_MANUFACTURERS = arrayOf("xiaomi")
+ }
+
+ override val title: String
+ get() = context.getString(R.string.compatibility_check_known_broken)
+ override val defaultDescription: String
+ get() = context.getString(R.string.compatibility_check_known_broken_desc)
+
+ init {
+ failureDescription = context.getString(R.string.compatibility_check_known_broken_fail)
+ }
+
+ override suspend fun doCheck(allChecks: List): State =
+ if (Build.MANUFACTURER.lowercase() in BROKEN_MANUFACTURERS) {
+ State.FAILURE
+ } else {
+ State.SUCCESS
+ }
+}
+
+internal class UsbCheck(private val context: Context) : CompatibilityCheck(context) {
+ override val title: String
+ get() = context.getString(R.string.compatibility_check_usb)
+ override val defaultDescription: String
+ get() = context.getString(R.string.compatibility_check_usb_desc)
+
+ init {
+ successDescription = context.getString(R.string.compatibility_check_usb_ok)
+ failureDescription = context.getString(R.string.compatibility_check_usb_fail)
+ }
+
+ override suspend fun doCheck(allChecks: List): State =
+ if (context.packageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) {
+ State.SUCCESS
+ } else {
+ State.FAILURE
+ }
+
+}
+
+internal class Verdict(private val context: Context) : CompatibilityCheck(context) {
+ override val title: String
+ get() = context.getString(R.string.compatibility_check_verdict)
+ override val defaultDescription: String
+ get() = context.getString(R.string.compatibility_check_verdict_desc)
+
+ override suspend fun doCheck(allChecks: List): State {
+ if (allChecks.findCheck()?.state == State.FAILURE) {
+ failureDescription = context.getString(
+ R.string.compatibility_check_verdict_known_broken,
+ context.getString(R.string.compatibility_check_verdict_fail_shared)
+ )
+ return State.FAILURE
+ }
+
+ if (allChecks.findCheck()?.state == State.SUCCESS &&
+ allChecks.findCheck()?.state == State.SUCCESS
+ ) {
+ successDescription = context.getString(R.string.compatibility_check_verdict_ok)
+ return State.SUCCESS
+ }
+
+ if (allChecks.findCheck()?.state == State.FAILURE_UNKNOWN ||
+ allChecks.findCheck()?.state == State.FAILURE_UNKNOWN
+ ) {
+ // We are not sure because we can't fully check OMAPI
+ // however we can guess based on feature flags
+ // TODO: We probably need a "known-good" list for these devices as well?
+ failureDescription = context.getString(
+ if (allChecks.findCheck()?.state == State.SUCCESS) {
+ R.string.compatibility_check_verdict_unknown_likely_ok
+ } else {
+ R.string.compatibility_check_verdict_unknown_likely_fail
+ },
+ context.getString(R.string.compatibility_check_verdict_fail_shared)
+ )
+ return State.FAILURE_UNKNOWN
+ }
+
+ failureDescription = context.getString(
+ R.string.compatibility_check_verdict_unknown,
+ context.getString(R.string.compatibility_check_verdict_fail_shared)
+ )
+ return State.FAILURE_UNKNOWN
+ }
+}
\ No newline at end of file
diff --git a/app-unpriv/src/main/java/im/angry/openeuicc/util/SIMToolkit.kt b/app-unpriv/src/main/java/im/angry/openeuicc/util/SIMToolkit.kt
deleted file mode 100644
index f58f76a..0000000
--- a/app-unpriv/src/main/java/im/angry/openeuicc/util/SIMToolkit.kt
+++ /dev/null
@@ -1,86 +0,0 @@
-package im.angry.openeuicc.util
-
-import android.content.ComponentName
-import android.content.Context
-import android.content.Intent
-import android.content.pm.ActivityInfo
-import android.content.pm.PackageManager
-import android.net.Uri
-import android.provider.Settings
-import androidx.annotation.ArrayRes
-import im.angry.easyeuicc.R
-import im.angry.openeuicc.core.EuiccChannelManager
-
-class SIMToolkit(private val context: Context) {
- private val slots = buildMap {
- fun getComponentNames(@ArrayRes id: Int) = context.resources
- .getStringArray(id).mapNotNull(ComponentName::unflattenFromString)
- put(-1, getComponentNames(R.array.sim_toolkit_slot_selection))
- put(0, getComponentNames(R.array.sim_toolkit_slot_1))
- put(1, getComponentNames(R.array.sim_toolkit_slot_2))
- }
-
- operator fun get(slotId: Int): Slot? = when (slotId) {
- -1, EuiccChannelManager.USB_CHANNEL_ID -> null
- else -> Slot(context.packageManager, buildSet {
- addAll(slots.getOrDefault(slotId, emptySet()))
- addAll(slots.getOrDefault(-1, emptySet()))
- })
- }
-
- data class Slot(private val packageManager: PackageManager, private val components: Set) {
- private val packageNames: Iterable
- get() = components.map(ComponentName::getPackageName).toSet()
- .filter(packageManager::isInstalledApp)
-
- private val launchIntent: Intent?
- get() = packageNames.firstNotNullOfOrNull(packageManager::getLaunchIntentForPackage)
-
- private val activities: Iterable
- get() = packageNames.flatMap(packageManager::getActivities)
- .filter(ActivityInfo::exported).map { ComponentName(it.packageName, it.name) }
-
- private fun getActivityIntent(): Intent? {
- for (activity in activities) {
- if (!components.contains(activity)) continue
- if (isDisabledState(packageManager.getComponentEnabledSetting(activity))) continue
- return Intent.makeMainActivity(activity)
- }
- return launchIntent
- }
-
- private fun getDisabledPackageIntent(): Intent? {
- val disabledPackageName = packageNames
- .find { isDisabledState(packageManager.getApplicationEnabledSetting(it)) }
- ?: return null
- val uri = Uri.fromParts("package", disabledPackageName, null)
- return Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, uri)
- }
-
- val intent: Intent?
- get() = getActivityIntent() ?: getDisabledPackageIntent()
- }
-
- companion object {
- fun getDisabledPackageName(intent: Intent?): String? {
- if (intent?.action != Settings.ACTION_APPLICATION_DETAILS_SETTINGS) return null
- return intent.data?.schemeSpecificPart
- }
- }
-}
-
-private fun isDisabledState(state: Int) = when (state) {
- PackageManager.COMPONENT_ENABLED_STATE_DISABLED -> true
- PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER -> true
- else -> false
-}
-
-private fun PackageManager.isInstalledApp(packageName: String) = try {
- getPackageInfo(packageName, 0)
- true
-} catch (_: PackageManager.NameNotFoundException) {
- false
-}
-
-private fun PackageManager.getActivities(packageName: String) =
- getPackageInfo(packageName, PackageManager.GET_ACTIVITIES).activities?.toList() ?: emptyList()
diff --git a/app-unpriv/src/main/java/im/angry/openeuicc/util/UnprivilegedPreferenceRepository.kt b/app-unpriv/src/main/java/im/angry/openeuicc/util/UnprivilegedPreferenceRepository.kt
deleted file mode 100644
index 6066858..0000000
--- a/app-unpriv/src/main/java/im/angry/openeuicc/util/UnprivilegedPreferenceRepository.kt
+++ /dev/null
@@ -1,14 +0,0 @@
-package im.angry.openeuicc.util
-
-import android.content.Context
-import androidx.datastore.preferences.core.booleanPreferencesKey
-
-internal object UnprivilegedPreferenceKeys {
- // ---- Miscellaneous ----
- val SKIP_QUICK_COMPATIBILITY = booleanPreferencesKey("skip_quick_compatibility")
-}
-
-class UnprivilegedPreferenceRepository(context: Context) : PreferenceRepository(context) {
- // ---- Miscellaneous ----
- val skipQuickCompatibilityFlow = bindFlow(UnprivilegedPreferenceKeys.SKIP_QUICK_COMPATIBILITY, false)
-}
\ No newline at end of file
diff --git a/app-unpriv/src/main/java/im/angry/openeuicc/util/UnprivilegedUtils.kt b/app-unpriv/src/main/java/im/angry/openeuicc/util/UnprivilegedUtils.kt
deleted file mode 100644
index a8b2246..0000000
--- a/app-unpriv/src/main/java/im/angry/openeuicc/util/UnprivilegedUtils.kt
+++ /dev/null
@@ -1,6 +0,0 @@
-package im.angry.openeuicc.util
-
-interface UnprivilegedEuiccContextMarker : OpenEuiccContextMarker {
- override val preferenceRepository: UnprivilegedPreferenceRepository
- get() = appContainer.preferenceRepository as UnprivilegedPreferenceRepository
-}
\ No newline at end of file
diff --git a/app-common/src/main/res/drawable/ic_checkmark_outline.xml b/app-unpriv/src/main/res/drawable/ic_checkmark_outline.xml
similarity index 100%
rename from app-common/src/main/res/drawable/ic_checkmark_outline.xml
rename to app-unpriv/src/main/res/drawable/ic_checkmark_outline.xml
diff --git a/app-common/src/main/res/drawable/ic_error_outline.xml b/app-unpriv/src/main/res/drawable/ic_error_outline.xml
similarity index 100%
rename from app-common/src/main/res/drawable/ic_error_outline.xml
rename to app-unpriv/src/main/res/drawable/ic_error_outline.xml
diff --git a/app-common/src/main/res/layout/activity_isdr_aid_list.xml b/app-unpriv/src/main/res/layout/activity_compatibility_check.xml
similarity index 55%
rename from app-common/src/main/res/layout/activity_isdr_aid_list.xml
rename to app-unpriv/src/main/res/layout/activity_compatibility_check.xml
index 48135fb..2304c86 100644
--- a/app-common/src/main/res/layout/activity_isdr_aid_list.xml
+++ b/app-unpriv/src/main/res/layout/activity_compatibility_check.xml
@@ -1,24 +1,24 @@
-
+
-
+ app:layout_constraintBottom_toBottomOf="parent" />
\ No newline at end of file
diff --git a/app-unpriv/src/main/res/layout/activity_quick_compatibility.xml b/app-unpriv/src/main/res/layout/activity_quick_compatibility.xml
deleted file mode 100644
index ae691d5..0000000
--- a/app-unpriv/src/main/res/layout/activity_quick_compatibility.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-unpriv/src/main/res/layout/fragment_quick_compatibility.xml b/app-unpriv/src/main/res/layout/fragment_quick_compatibility.xml
deleted file mode 100644
index a4203a3..0000000
--- a/app-unpriv/src/main/res/layout/fragment_quick_compatibility.xml
+++ /dev/null
@@ -1,62 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-unpriv/src/main/res/mipmap-anydpi-v31/ic_launcher.xml b/app-unpriv/src/main/res/mipmap-anydpi-v31/ic_launcher.xml
deleted file mode 100644
index 50ec886..0000000
--- a/app-unpriv/src/main/res/mipmap-anydpi-v31/ic_launcher.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-unpriv/src/main/res/mipmap-anydpi-v31/ic_launcher_round.xml b/app-unpriv/src/main/res/mipmap-anydpi-v31/ic_launcher_round.xml
deleted file mode 100644
index 50ec886..0000000
--- a/app-unpriv/src/main/res/mipmap-anydpi-v31/ic_launcher_round.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app-unpriv/src/main/res/values-ja/strings.xml b/app-unpriv/src/main/res/values-ja/strings.xml
deleted file mode 100644
index 0734ba3..0000000
--- a/app-unpriv/src/main/res/values-ja/strings.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-
-
- 互換性の確認
- SIM ツールキットを開く
-
-
- ARA-M SHA-1 をクリップボードにコピーしました
- 「%s」アプリを有効化してください
-
- クイックで互換性を確認
- このデバイスで「%s」の対応カードを管理できます
- 使用しているデバイスは「%s」と互換性がありません
- 使用しているデバイスは「%s」と完全に互換性がありません。ただし、USB スマートカードリーダーを使用すればほぼすべての機能を利用できます。
- アクセス可能スロット: %s
- ISD-R アクセス: %s
- 注意: これらの結果は参考値です。上記に記載されていない SIM スロットでも、SIM カードを挿入 すれば互換性がある場合があります。
- 注意: 現在 SIM カードが挿入されていない場合は、SIM カードを挿入してから再度互換性の確認をお試しください。どの SIM カードでも構いません。
- 続行
- このメッセージを再度表示しない
- 不明
-
diff --git a/app-unpriv/src/main/res/values-zh-rCN/strings.xml b/app-unpriv/src/main/res/values-zh-rCN/strings.xml
deleted file mode 100644
index cd66a43..0000000
--- a/app-unpriv/src/main/res/values-zh-rCN/strings.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-
- 兼容性检查
- 打开 SIM 卡应用程序
- ARA-M SHA-1 已拷贝到剪贴板
- 请启用您的“%s”应用程序
- 简易兼容性检测
- 您的手机可以管理兼容 %s 的卡片
- 您的手机与 %s 不兼容
- 您的手机与 %s 不完全兼容,但可以使用 USB 读卡器获得几乎全部功能
- 可读取的卡槽: %s
- ISD-R 访问: %s
- 注意:以上结果仅供参考。即使某些卡槽没有被列举出来,插卡后也可能可用。
- 注意:如果您目前没有插卡,请插任意 SIM 卡后重试兼容性检测。
- 继续
- 不再显示此消息
- 未知
-
\ No newline at end of file
diff --git a/app-unpriv/src/main/res/values-zh-rTW/strings.xml b/app-unpriv/src/main/res/values-zh-rTW/strings.xml
deleted file mode 100644
index ab64d6b..0000000
--- a/app-unpriv/src/main/res/values-zh-rTW/strings.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-
- 相容性檢查
- 啟動 SIM 卡應用程式
- ARA-M SHA-1 已複製到剪貼簿
- 請啟用您的“%s”應用程式
- 簡易相容性檢測
- 您的手機可以管理相容 %s 的卡片
- 您的手機與 %s 不相容
- 您的手機與 %s 不完全相容,但可以使用 USB 讀卡機獲得幾乎全部功能
- 可讀取的卡槽: %s
- ISD-R 訪問: %s
- 注意:以上結果僅供參考。即使某些卡槽沒有被列舉出來,插卡後也可能可用。
- 注意:如果您目前沒有插卡,請插任何 SIM 卡後重試相容性檢測。
- 繼續
- 不再顯示此訊息
- 未知
-
\ No newline at end of file
diff --git a/app-unpriv/src/main/res/values/sim_toolkit.xml b/app-unpriv/src/main/res/values/sim_toolkit.xml
deleted file mode 100644
index 8db9955..0000000
--- a/app-unpriv/src/main/res/values/sim_toolkit.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-
-
-
- - com.android.stk/.StkMain
- - com.android.stk/.StkMainHide
- - com.android.stk/.StkListActivity
- - com.android.stk/.StkLauncherListActivity
- - com.android.stk/.StkSelectionActivity
-
-
- - com.android.stk/.StkMain1
- - com.android.stk/.PrimaryStkMain
- - com.android.stk/.StkLauncherActivity
- - com.android.stk/.StkLauncherActivity_Chn
- - com.android.stk/.StkLauncherActivity1
- - com.android.stk/.StkLauncherActivityI
- - com.android.stk/.OppoStkLauncherActivity1
- - com.android.stk/.OplusStkLauncherActivity1
- - com.android.stk/.mtk.StkLauncherActivityI
-
-
- - com.android.stk/.StkMain2
- - com.android.stk/.SecondaryStkMain
- - com.android.stk/.StkLauncherActivity2
- - com.android.stk/.StkLauncherActivityII
- - com.android.stk/.OppoStkLauncherActivity2
- - com.android.stk/.OplusStkLauncherActivity2
- - com.android.stk/.mtk.StkLauncherActivityII
- - com.android.stk1/.StkLauncherActivity
- - com.android.stk2/.StkLauncherActivity
- - com.android.stk2/.StkLauncherActivity_Chn
- - com.android.stk2/.StkLauncherActivity2
-
-
\ No newline at end of file
diff --git a/app-unpriv/src/main/res/values/strings.xml b/app-unpriv/src/main/res/values/strings.xml
index 76d1c76..124bedf 100644
--- a/app-unpriv/src/main/res/values/strings.xml
+++ b/app-unpriv/src/main/res/values/strings.xml
@@ -1,26 +1,34 @@
EasyEUICC
- SIM %d
+ SIM %d
Compatibility Check
- Open SIM Toolkit
-
- ARA-M SHA-1
-
-
- ARA-M SHA-1 copied to clipboard
- Please ENABLE your \"%s\" application
-
-
- Quick Compatibility Check
- Your smartphone can manage %s-compatible cards
- Your smartphone is not compatible with %s
- Your smartphone is not fully compatible with %s. However, you can still use a USB smart card reader for near-full functionality.
- Accessible slots: %s
- ISD-R access: %s
- Note: these results are for reference only. Even if a SIM slot is not listed above, it may be compatible as well once a SIM card is inserted.
- Note: if you currently do not have any SIM card inserted, try the compatibility check again after inserting one. Any SIM card will do.
- Continue
- Don\'t show this message again
- Unknown
+
+ System Features
+ Whether your device has all the required features for managing removable eUICC cards. For example, basic telephony and OMAPI support.
+ Your device has no telephony features.
+ Your device / system does not declare support for OMAPI. This could be due to missing support from hardware, or it could be simply due to a missing flag. See the following two checks to determine whether OMAPI is actually supported or not.
+ OMAPI Connectivity
+ Does your device allow access to Secure Elements on SIM cards via OMAPI?
+ Unable to detect Secure Element readers for SIM cards via OMAPI. If you have not inserted a SIM in this device, try inserting one and retry this check.
+ Successfully detected Secure Element access, but only for the following SIM slots: %s.
+ ISD-R Channel Access
+ Does your device support opening an ISD-R (management) channel to eSIMs via OMAPI?
+ Cannot determine whether ISD-R access through OMAPI is supported. You might want to retry with SIM cards inserted (any SIM card will do) if not already.
+ OMAPI access to ISD-R is only possible on the following SIM slots: %s.
+ Not on the Known Broken List
+ Making sure your device is not known to have bugs associated with removable eSIMs.
+ Oops, your device is known to have bugs when accessing removable eSIMs. This does not necessarily mean that it will not work at all, but you will have to proceed with caution.
+ USB Card Reader Support
+ Does your device support managing eSIMs via USB card readers?
+ You can manage eSIMs through standard USB CCID readers on this device (even if you had any other check items fail here). Insert the card reader and then open this app to manage eSIMs in this way.
+ Your device does not support acting as a USB host.
+ Verdict (non-USB)
+ Based on all previous checks, how likely is your device to be compatible with managing inserted removable eSIMs?
+ You can likely use and manage removable eSIMs inserted into this device.
+ Your device is known to be buggy when accessing inserted removable eSIMs.\n%s
+ We cannot determine whether inserted removable eSIMs can be managed on your device. Your device does declare support for OMAPI, though, so it is slightly more likely that it will work.\n%s
+ We cannot determine whether inserted removable eSIMs can be managed on your device. Since your device does not declare support for OMAPI, it is more likely that managing removable eSIMs on this device is unsupported.\n%s
+ We cannot determine whether inserted removable eSIMs can be managed on your device.\n%s
+ However, a removable eSIM that has already been loaded with an eSIM profile will still work; you can also most likely use a USB card reader plugged into this device to manage profiles, even if you cannot manage one inserted into your device.
\ No newline at end of file
diff --git a/app-unpriv/src/main/res/xml/pref_unprivileged_settings.xml b/app-unpriv/src/main/res/xml/pref_unprivileged_settings.xml
deleted file mode 100644
index 3281caf..0000000
--- a/app-unpriv/src/main/res/xml/pref_unprivileged_settings.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 4012227..1d29729 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -1,4 +1,3 @@
-import com.android.build.gradle.internal.api.ApkVariantOutputImpl
import im.angry.openeuicc.build.*
plugins {
@@ -13,20 +12,17 @@ apply {
android {
namespace = "im.angry.openeuicc"
- compileSdk = 35
+ compileSdk = 34
defaultConfig {
applicationId = "im.angry.openeuicc"
minSdk = 30
- targetSdk = 35
+ targetSdk = 34
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
- defaultConfig {
- versionNameSuffix = "-priv"
- }
release {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
@@ -49,63 +45,4 @@ dependencies {
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
-}
-
-val modulePropsTemplate = mutableMapOf(
- "id" to android.defaultConfig.applicationId!!,
- "name" to "OpenEUICC",
- "version" to android.defaultConfig.versionName!!,
- "versionCode" to "${android.defaultConfig.versionCode}",
- "author" to "OpenEUICC authors",
- "description" to "OpenEUICC is an open-source app that provides system-level eSIM integration."
-)
-
-val moduleCustomizeScript = project.file("magisk/customize.sh").readText()
- .replace("{APK_NAME}", "OpenEUICC")
- .replace("{PKG_NAME}", android.defaultConfig.applicationId!!)
-
-val moduleUninstallScript = project.file("magisk/uninstall.sh").readText()
- .replace("{PKG_NAME}", android.defaultConfig.applicationId!!)
-
-tasks.register("assembleDebugMagiskModuleDir") {
- variant = "debug"
- appName = "OpenEUICC"
- permsFile = project.rootProject.file("privapp_whitelist_im.angry.openeuicc.xml")
- moduleInstaller = project.file("magisk/module_installer.sh")
- moduleCustomizeScriptText = moduleCustomizeScript
- moduleUninstallScriptText = moduleUninstallScript
- moduleProp = modulePropsTemplate.let {
- it["description"] = "(debug build) ${it["description"]}"
- it["versionCode"] = "${(android.applicationVariants.find { it.name == "debug" }!!.outputs.first() as ApkVariantOutputImpl).versionCodeOverride}"
- it["updateJson"] = "https://openeuicc.com/magisk/magisk-debug.json"
- it
- }
- dependsOn("assembleDebug")
-}
-
-tasks.register("assembleDebugMagiskModule") {
- dependsOn("assembleDebugMagiskModuleDir")
- from((tasks.getByName("assembleDebugMagiskModuleDir") as MagiskModuleDirTask).outputDir)
- archiveFileName = "magisk-debug.zip"
- destinationDirectory = project.layout.buildDirectory.dir("magisk")
- entryCompression = ZipEntryCompression.STORED
-}
-
-tasks.register("assembleReleaseMagiskModuleDir") {
- variant = "release"
- appName = "OpenEUICC"
- permsFile = project.rootProject.file("privapp_whitelist_im.angry.openeuicc.xml")
- moduleInstaller = project.file("magisk/module_installer.sh")
- moduleCustomizeScriptText = moduleCustomizeScript
- moduleUninstallScriptText = moduleUninstallScript
- moduleProp = modulePropsTemplate
- dependsOn("assembleRelease")
-}
-
-tasks.register("assembleReleaseMagiskModule") {
- dependsOn("assembleReleaseMagiskModuleDir")
- from((tasks.getByName("assembleReleaseMagiskModuleDir") as MagiskModuleDirTask).outputDir)
- archiveFileName = "magisk-release.zip"
- destinationDirectory = project.layout.buildDirectory.dir("magisk")
- entryCompression = ZipEntryCompression.STORED
}
\ No newline at end of file
diff --git a/app/magisk/customize.sh b/app/magisk/customize.sh
deleted file mode 100644
index 3b57a55..0000000
--- a/app/magisk/customize.sh
+++ /dev/null
@@ -1,9 +0,0 @@
-TMP_FILE="$TMPDIR/{APK_NAME}"
-
-chmod u+x "$MODPATH/uninstall.sh"
-cp "$MODPATH/system/system_ext/priv-app/{APK_NAME}/{APK_NAME}.apk" "$TMP_FILE"
-
-pm install -r "$TMP_FILE"
-rm -f "$TMP_FILE"
-
-pm grant "{PKG_NAME}" android.permission.READ_PHONE_STATE
\ No newline at end of file
diff --git a/app/magisk/module_installer.sh b/app/magisk/module_installer.sh
deleted file mode 100644
index 28b48e5..0000000
--- a/app/magisk/module_installer.sh
+++ /dev/null
@@ -1,33 +0,0 @@
-#!/sbin/sh
-
-#################
-# Initialization
-#################
-
-umask 022
-
-# echo before loading util_functions
-ui_print() { echo "$1"; }
-
-require_new_magisk() {
- ui_print "*******************************"
- ui_print " Please install Magisk v20.4+! "
- ui_print "*******************************"
- exit 1
-}
-
-#########################
-# Load util_functions.sh
-#########################
-
-OUTFD=$2
-ZIPFILE=$3
-
-mount /data 2>/dev/null
-
-[ -f /data/adb/magisk/util_functions.sh ] || require_new_magisk
-. /data/adb/magisk/util_functions.sh
-[ $MAGISK_VER_CODE -lt 20400 ] && require_new_magisk
-
-install_module
-exit 0
diff --git a/app/magisk/uninstall.sh b/app/magisk/uninstall.sh
deleted file mode 100644
index 1eb0200..0000000
--- a/app/magisk/uninstall.sh
+++ /dev/null
@@ -1 +0,0 @@
-pm uninstall "{PKG_NAME}"
\ No newline at end of file
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index cae19d3..cd30620 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -5,8 +5,7 @@
package="im.angry.openeuicc">
+ android:required="true" />
@@ -20,9 +19,7 @@
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
- android:localeConfig="@xml/locale_config"
- android:theme="@style/Theme.OpenEUICC"
- tools:targetApi="tiramisu">
+ android:theme="@style/Theme.OpenEUICC">
@@ -52,15 +49,6 @@
-
-
-
-
diff --git a/app/src/main/java/im/angry/openeuicc/core/PrivilegedEuiccChannelFactory.kt b/app/src/main/java/im/angry/openeuicc/core/PrivilegedEuiccChannelFactory.kt
index 876387f..317248b 100644
--- a/app/src/main/java/im/angry/openeuicc/core/PrivilegedEuiccChannelFactory.kt
+++ b/app/src/main/java/im/angry/openeuicc/core/PrivilegedEuiccChannelFactory.kt
@@ -2,57 +2,40 @@ package im.angry.openeuicc.core
import android.content.Context
import android.util.Log
-import im.angry.openeuicc.R
+import im.angry.openeuicc.OpenEuiccApplication
import im.angry.openeuicc.util.*
-import kotlinx.coroutines.flow.first
import java.lang.IllegalArgumentException
-class PrivilegedEuiccChannelFactory(context: Context) : DefaultEuiccChannelFactory(context),
- PrivilegedEuiccContextMarker {
- override val openEuiccMarkerContext: Context
- get() = context
+class PrivilegedEuiccChannelFactory(context: Context) : DefaultEuiccChannelFactory(context) {
+ private val tm by lazy {
+ (context.applicationContext as OpenEuiccApplication).appContainer.telephonyManager
+ }
@Suppress("NAME_SHADOWING")
- override suspend fun tryOpenEuiccChannel(
- port: UiccPortInfoCompat,
- isdrAid: ByteArray
- ): EuiccChannel? {
+ override suspend fun tryOpenEuiccChannel(port: UiccPortInfoCompat): EuiccChannel? {
val port = port as RealUiccPortInfoCompat
if (port.card.isRemovable) {
// Attempt unprivileged (OMAPI) before TelephonyManager
// but still try TelephonyManager in case OMAPI is broken
- super.tryOpenEuiccChannel(port, isdrAid)?.let { return it }
+ super.tryOpenEuiccChannel(port)?.let { return it }
}
- if (port.card.isEuicc || preferenceRepository.removableTelephonyManagerFlow.first()) {
+ if (port.card.isEuicc) {
Log.i(
DefaultEuiccChannelManager.TAG,
"Trying TelephonyManager for slot ${port.card.physicalSlotIndex} port ${port.portIndex}"
)
try {
- return EuiccChannelImpl(
- context.getString(R.string.channel_type_telephony_manager),
- port,
- intrinsicChannelName = null,
- TelephonyManagerApduInterface(
- port,
- telephonyManager,
- context.preferenceRepository.verboseLoggingFlow
- ),
- isdrAid,
- context.preferenceRepository.verboseLoggingFlow,
- context.preferenceRepository.ignoreTLSCertificateFlow,
- context.preferenceRepository.es10xMssFlow,
- )
- } catch (_: IllegalArgumentException) {
+ return EuiccChannel(port, TelephonyManagerApduInterface(port, tm))
+ } catch (e: IllegalArgumentException) {
// Failed
Log.w(
DefaultEuiccChannelManager.TAG,
- "TelephonyManager APDU interface unavailable for slot ${port.card.physicalSlotIndex} port ${port.portIndex} with ISD-R AID: ${isdrAid.encodeHex()}."
+ "TelephonyManager APDU interface unavailable for slot ${port.card.physicalSlotIndex} port ${port.portIndex}, falling back"
)
}
}
- return super.tryOpenEuiccChannel(port, isdrAid)
+ return super.tryOpenEuiccChannel(port)
}
}
\ No newline at end of file
diff --git a/app/src/main/java/im/angry/openeuicc/core/PrivilegedEuiccChannelManager.kt b/app/src/main/java/im/angry/openeuicc/core/PrivilegedEuiccChannelManager.kt
index aaf5490..923bbab 100644
--- a/app/src/main/java/im/angry/openeuicc/core/PrivilegedEuiccChannelManager.kt
+++ b/app/src/main/java/im/angry/openeuicc/core/PrivilegedEuiccChannelManager.kt
@@ -28,9 +28,9 @@ class PrivilegedEuiccChannelManager(
}
}
- override suspend fun notifyEuiccProfilesChanged(logicalSlotId: Int) {
+ override fun notifyEuiccProfilesChanged(logicalSlotId: Int) {
appContainer.subscriptionManager.apply {
- findEuiccChannelByLogicalSlot(logicalSlotId)?.let {
+ findEuiccChannelBySlotBlocking(logicalSlotId)?.let {
tryRefreshCachedEuiccInfo(it.cardId)
}
}
diff --git a/app/src/main/java/im/angry/openeuicc/core/TelephonyManagerApduInterface.kt b/app/src/main/java/im/angry/openeuicc/core/TelephonyManagerApduInterface.kt
index f0b1909..509d7ee 100644
--- a/app/src/main/java/im/angry/openeuicc/core/TelephonyManagerApduInterface.kt
+++ b/app/src/main/java/im/angry/openeuicc/core/TelephonyManagerApduInterface.kt
@@ -2,26 +2,19 @@ package im.angry.openeuicc.core
import android.telephony.IccOpenLogicalChannelResponse
import android.telephony.TelephonyManager
-import android.util.Log
import im.angry.openeuicc.util.*
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.runBlocking
import net.typeblog.lpac_jni.ApduInterface
class TelephonyManagerApduInterface(
private val port: UiccPortInfoCompat,
- private val tm: TelephonyManager,
- private val verboseLoggingFlow: Flow
+ private val tm: TelephonyManager
): ApduInterface {
- companion object {
- const val TAG = "TelephonyManagerApduInterface"
- }
+ private var lastChannel: Int = -1
override val valid: Boolean
- get() = channels.isNotEmpty()
-
- private var channels = mutableSetOf()
+ // TelephonyManager channels will never become truly "invalid",
+ // just that transactions might return errors or nonsense
+ get() = lastChannel != -1
override fun connect() {
// Do nothing
@@ -29,39 +22,38 @@ class TelephonyManagerApduInterface(
override fun disconnect() {
// Do nothing
+ lastChannel = -1
}
override fun logicalChannelOpen(aid: ByteArray): Int {
+ check(lastChannel == -1) { "Already initialized" }
val hex = aid.encodeHex()
val channel = tm.iccOpenLogicalChannelByPortCompat(port.card.physicalSlotIndex, port.portIndex, hex, 0)
if (channel.status != IccOpenLogicalChannelResponse.STATUS_NO_ERROR || channel.channel == IccOpenLogicalChannelResponse.INVALID_CHANNEL) {
- throw IllegalArgumentException("Cannot open logical channel $hex via TelephonyManager on slot ${port.card.physicalSlotIndex} port ${port.portIndex}")
+ throw IllegalArgumentException("Cannot open logical channel $hex via TelephonManager on slot ${port.card.physicalSlotIndex} port ${port.portIndex}");
}
- channels.add(channel.channel)
- return channel.channel
+ lastChannel = channel.channel
+ return lastChannel
}
override fun logicalChannelClose(handle: Int) {
- check(channels.contains(handle)) {
- "Invalid logical channel handle $handle"
- }
+ check(handle == lastChannel) { "Invalid channel handle " }
tm.iccCloseLogicalChannelByPortCompat(port.card.physicalSlotIndex, port.portIndex, handle)
- channels.remove(handle)
+ lastChannel = -1
}
- override fun transmit(handle: Int, tx: ByteArray): ByteArray {
- check(channels.contains(handle)) {
- "Invalid logical channel handle $handle"
- }
- if (runBlocking { verboseLoggingFlow.first() }) {
- Log.d(TAG, "TelephonyManager APDU: ${tx.encodeHex()}")
- }
- val result = tm.iccTransmitApduLogicalChannelByPortCompat(
- port.card.physicalSlotIndex, port.portIndex, handle,
- tx,
- )
- if (runBlocking { verboseLoggingFlow.first() })
- Log.d(TAG, "TelephonyManager APDU response: $result")
- return result?.decodeHex() ?: byteArrayOf()
+ override fun transmit(tx: ByteArray): ByteArray {
+ check(lastChannel != -1) { "Uninitialized" }
+
+ val cla = tx[0].toUByte().toInt()
+ val instruction = tx[1].toUByte().toInt()
+ val p1 = tx[2].toUByte().toInt()
+ val p2 = tx[3].toUByte().toInt()
+ val p3 = tx[4].toUByte().toInt()
+ val p4 = tx.drop(5).toByteArray().encodeHex()
+
+ return tm.iccTransmitApduLogicalChannelByPortCompat(port.card.physicalSlotIndex, port.portIndex, lastChannel,
+ cla, instruction, p1, p2, p3, p4)?.decodeHex() ?: byteArrayOf()
}
+
}
\ No newline at end of file
diff --git a/app/src/main/java/im/angry/openeuicc/di/PrivilegedAppContainer.kt b/app/src/main/java/im/angry/openeuicc/di/PrivilegedAppContainer.kt
index 08b3cf4..c5896f2 100644
--- a/app/src/main/java/im/angry/openeuicc/di/PrivilegedAppContainer.kt
+++ b/app/src/main/java/im/angry/openeuicc/di/PrivilegedAppContainer.kt
@@ -6,7 +6,6 @@ import im.angry.openeuicc.core.EuiccChannelManagerFactory
import im.angry.openeuicc.core.PrivilegedEuiccChannelFactory
import im.angry.openeuicc.core.PrivilegedEuiccChannelManager
import im.angry.openeuicc.core.PrivilegedEuiccChannelManagerFactory
-import im.angry.openeuicc.util.*
class PrivilegedAppContainer(context: Context) : DefaultAppContainer(context) {
override val euiccChannelManager: EuiccChannelManager by lazy {
@@ -24,12 +23,4 @@ class PrivilegedAppContainer(context: Context) : DefaultAppContainer(context) {
override val euiccChannelFactory by lazy {
PrivilegedEuiccChannelFactory(context)
}
-
- override val customizableTextProvider by lazy {
- PrivilegedCustomizableTextProvider(context)
- }
-
- override val preferenceRepository by lazy {
- PrivilegedPreferenceRepository(context)
- }
}
\ No newline at end of file
diff --git a/app/src/main/java/im/angry/openeuicc/di/PrivilegedCustomizableTextProvider.kt b/app/src/main/java/im/angry/openeuicc/di/PrivilegedCustomizableTextProvider.kt
deleted file mode 100644
index e53832f..0000000
--- a/app/src/main/java/im/angry/openeuicc/di/PrivilegedCustomizableTextProvider.kt
+++ /dev/null
@@ -1,10 +0,0 @@
-package im.angry.openeuicc.di
-
-import android.content.Context
-import im.angry.openeuicc.R
-
-class PrivilegedCustomizableTextProvider(private val context: Context) :
- DefaultCustomizableTextProvider(context) {
- override val noEuiccExplanation: String
- get() = context.getString(R.string.no_euicc_priv)
-}
\ No newline at end of file
diff --git a/app/src/main/java/im/angry/openeuicc/di/PrivilegedUiComponentFactory.kt b/app/src/main/java/im/angry/openeuicc/di/PrivilegedUiComponentFactory.kt
index e5b747a..d3c5cdb 100644
--- a/app/src/main/java/im/angry/openeuicc/di/PrivilegedUiComponentFactory.kt
+++ b/app/src/main/java/im/angry/openeuicc/di/PrivilegedUiComponentFactory.kt
@@ -1,14 +1,10 @@
package im.angry.openeuicc.di
-import androidx.fragment.app.Fragment
+import im.angry.openeuicc.core.EuiccChannel
import im.angry.openeuicc.ui.EuiccManagementFragment
import im.angry.openeuicc.ui.PrivilegedEuiccManagementFragment
-import im.angry.openeuicc.ui.PrivilegedSettingsFragment
class PrivilegedUiComponentFactory : DefaultUiComponentFactory() {
- override fun createEuiccManagementFragment(slotId: Int, portId: Int): EuiccManagementFragment =
- PrivilegedEuiccManagementFragment.newInstance(slotId, portId)
-
- override fun createSettingsFragment(): Fragment =
- PrivilegedSettingsFragment()
+ override fun createEuiccManagementFragment(channel: EuiccChannel): EuiccManagementFragment =
+ PrivilegedEuiccManagementFragment.newInstance(channel.slotId, channel.portId)
}
\ No newline at end of file
diff --git a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt
index 02b3baf..572b02b 100644
--- a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt
+++ b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt
@@ -9,13 +9,12 @@ import android.telephony.euicc.DownloadableSubscription
import android.telephony.euicc.EuiccInfo
import android.util.Log
import net.typeblog.lpac_jni.LocalProfileInfo
+import im.angry.openeuicc.core.EuiccChannel
import im.angry.openeuicc.core.EuiccChannelManager
-import im.angry.openeuicc.service.EuiccChannelManagerService.Companion.waitDone
import im.angry.openeuicc.util.*
-import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
-import kotlin.IllegalStateException
+import java.lang.IllegalStateException
class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
companion object {
@@ -38,10 +37,16 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
}
private data class EuiccChannelManagerContext(
- val euiccChannelManagerService: EuiccChannelManagerService
+ val euiccChannelManager: EuiccChannelManager
) {
- val euiccChannelManager
- get() = euiccChannelManagerService.euiccChannelManager
+ fun findChannel(physicalSlotId: Int): EuiccChannel? =
+ euiccChannelManager.findEuiccChannelByPhysicalSlotBlocking(physicalSlotId)
+
+ fun findChannel(slotId: Int, portId: Int): EuiccChannel? =
+ euiccChannelManager.findEuiccChannelByPortBlocking(slotId, portId)
+
+ fun findAllChannels(physicalSlotId: Int): List? =
+ euiccChannelManager.findAllEuiccChannelsByPhysicalSlotBlocking(physicalSlotId)
}
/**
@@ -54,7 +59,7 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
*
* This function cannot be inline because non-local returns may bypass the unbind
*/
- private fun withEuiccChannelManager(fn: suspend EuiccChannelManagerContext.() -> T): T {
+ private fun withEuiccChannelManager(fn: EuiccChannelManagerContext.() -> T): T {
val (binder, unbind) = runBlocking {
bindServiceSuspended(
Intent(
@@ -68,24 +73,23 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
throw RuntimeException("Unable to bind to EuiccChannelManagerService; aborting")
}
- val localBinder = binder as EuiccChannelManagerService.LocalBinder
-
- val ret = runBlocking {
- EuiccChannelManagerContext(localBinder.service).fn()
- }
+ val ret =
+ EuiccChannelManagerContext((binder as EuiccChannelManagerService.LocalBinder).service.euiccChannelManager).fn()
unbind()
return ret
}
override fun onGetEid(slotId: Int): String? = withEuiccChannelManager {
- val portId = euiccChannelManager.findFirstAvailablePort(slotId)
- if (portId < 0) return@withEuiccChannelManager null
- euiccChannelManager.withEuiccChannel(slotId, portId) { channel ->
- channel.lpa.eID
- }
+ findChannel(slotId)?.lpa?.eID
}
+ // When two eSIM cards are present on one device, the Android settings UI
+ // gets confused and sets the incorrect slotId for profiles from one of
+ // the cards. This function helps Detect this case and abort early.
+ private fun EuiccChannel.profileExists(iccid: String?) =
+ lpa.profiles.any { it.iccid == iccid }
+
private fun ensurePortIsMapped(slotId: Int, portId: Int) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
return
@@ -110,18 +114,14 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
telephonyManager.simSlotMapping = mappings
return
} catch (_: Exception) {
- // ignore
+
}
// Sometimes hardware supports one ordering but not the reverse
telephonyManager.simSlotMapping = mappings.reversed()
}
- private suspend fun retryWithTimeout(
- timeoutMillis: Int,
- backoff: Int = 1000,
- f: suspend () -> T?
- ): T? {
+ private fun retryWithTimeout(timeoutMillis: Int, backoff: Int = 1000, f: () -> T?): T? {
val startTimeMillis = System.currentTimeMillis()
do {
try {
@@ -129,7 +129,7 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
} catch (_: Exception) {
// Ignore
} finally {
- delay(backoff.toLong())
+ Thread.sleep(backoff.toLong())
}
} while (System.currentTimeMillis() - startTimeMillis < timeoutMillis)
return null
@@ -177,56 +177,38 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
}
// TODO: Temporarily enable the slot to access its profiles if it is currently unmapped
- val port = euiccChannelManager.findFirstAvailablePort(slotId)
- if (port == -1) {
- return@withEuiccChannelManager GetEuiccProfileInfoListResult(
+ val channel =
+ findChannel(slotId) ?: return@withEuiccChannelManager GetEuiccProfileInfoListResult(
RESULT_FIRST_USER,
arrayOf(),
true
)
- }
-
- return@withEuiccChannelManager try {
- euiccChannelManager.withEuiccChannel(slotId, port) { channel ->
- val filteredProfiles =
- if (preferenceRepository.unfilteredProfileListFlow.first())
- channel.lpa.profiles
- else
- channel.lpa.profiles.operational
- val profiles = filteredProfiles.map {
- EuiccProfileInfo.Builder(it.iccid).apply {
- setProfileName(it.name)
- setNickname(it.displayName)
- setServiceProviderName(it.providerName)
- setState(
- when (it.state) {
- LocalProfileInfo.State.Enabled -> EuiccProfileInfo.PROFILE_STATE_ENABLED
- LocalProfileInfo.State.Disabled -> EuiccProfileInfo.PROFILE_STATE_DISABLED
- }
- )
- setProfileClass(
- when (it.profileClass) {
- LocalProfileInfo.Clazz.Testing -> EuiccProfileInfo.PROFILE_CLASS_TESTING
- LocalProfileInfo.Clazz.Provisioning -> EuiccProfileInfo.PROFILE_CLASS_PROVISIONING
- LocalProfileInfo.Clazz.Operational -> EuiccProfileInfo.PROFILE_CLASS_OPERATIONAL
- }
- )
- }.build()
- }
-
- GetEuiccProfileInfoListResult(
- RESULT_OK,
- profiles.toTypedArray(),
- channel.port.card.isRemovable
+ val profiles = channel.lpa.profiles.operational.map {
+ EuiccProfileInfo.Builder(it.iccid).apply {
+ setProfileName(it.name)
+ setNickname(it.displayName)
+ setServiceProviderName(it.providerName)
+ setState(
+ when (it.state) {
+ LocalProfileInfo.State.Enabled -> EuiccProfileInfo.PROFILE_STATE_ENABLED
+ LocalProfileInfo.State.Disabled -> EuiccProfileInfo.PROFILE_STATE_DISABLED
+ }
)
- }
- } catch (e: EuiccChannelManager.EuiccChannelNotFoundException) {
- GetEuiccProfileInfoListResult(
- RESULT_FIRST_USER,
- arrayOf(),
- true
- )
+ setProfileClass(
+ when (it.profileClass) {
+ LocalProfileInfo.Clazz.Testing -> EuiccProfileInfo.PROFILE_CLASS_TESTING
+ LocalProfileInfo.Clazz.Provisioning -> EuiccProfileInfo.PROFILE_CLASS_PROVISIONING
+ LocalProfileInfo.Clazz.Operational -> EuiccProfileInfo.PROFILE_CLASS_OPERATIONAL
+ }
+ )
+ }.build()
}
+
+ return@withEuiccChannelManager GetEuiccProfileInfoListResult(
+ RESULT_OK,
+ profiles.toTypedArray(),
+ channel.removable
+ )
}
override fun onGetEuiccInfo(slotId: Int): EuiccInfo {
@@ -237,26 +219,39 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
Log.i(TAG, "onDeleteSubscription slotId=$slotId iccid=$iccid")
if (shouldIgnoreSlot(slotId)) return@withEuiccChannelManager RESULT_FIRST_USER
- val ports = euiccChannelManager.findAvailablePorts(slotId)
- if (ports.isEmpty()) return@withEuiccChannelManager RESULT_FIRST_USER
+ try {
+ val channels =
+ findAllChannels(slotId) ?: return@withEuiccChannelManager RESULT_FIRST_USER
- // Check that the profile has been disabled on all slots
- val enabledAnywhere = ports.any { port ->
- euiccChannelManager.withEuiccChannel(slotId, port) { channel ->
- channel.lpa.profiles.enabled?.iccid == iccid
+ if (!channels[0].profileExists(iccid)) {
+ return@withEuiccChannelManager RESULT_FIRST_USER
}
- }
- if (enabledAnywhere) return@withEuiccChannelManager RESULT_FIRST_USER
+ // If the profile is enabled by ANY channel (port), we cannot delete it
+ channels.forEach { channel ->
+ val profile = channel.lpa.profiles.find {
+ it.iccid == iccid
+ } ?: return@withEuiccChannelManager RESULT_FIRST_USER
- euiccChannelManagerService.waitForForegroundTask()
- val success = euiccChannelManagerService.launchProfileDeleteTask(slotId, ports[0], iccid)
- .waitDone() == null
+ if (profile.state == LocalProfileInfo.State.Enabled) {
+ // Must disable the profile first
+ return@withEuiccChannelManager RESULT_FIRST_USER
+ }
+ }
- return@withEuiccChannelManager if (success) {
- RESULT_OK
- } else {
- RESULT_FIRST_USER
+ euiccChannelManager.beginTrackedOperationBlocking(channels[0].slotId, channels[0].portId) {
+ if (channels[0].lpa.deleteProfile(iccid)) {
+ return@withEuiccChannelManager RESULT_OK
+ }
+
+ runBlocking {
+ preferenceRepository.notificationDeleteFlow.first()
+ }
+ }
+
+ return@withEuiccChannelManager RESULT_FIRST_USER
+ } catch (e: Exception) {
+ return@withEuiccChannelManager RESULT_FIRST_USER
}
}
@@ -279,90 +274,51 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
if (shouldIgnoreSlot(slotId)) return@withEuiccChannelManager RESULT_FIRST_USER
try {
- // First, try to find a pair of slotId and portId we can use for the switching operation
// retryWithTimeout is needed here because this function may be called just after
// AOSP has switched slot mappings, in which case the slots may not be ready yet.
- val (foundSlotId, foundPortId) = retryWithTimeout(5000) {
- if (portIndex == -1) {
- // If port is not indicated, we can use any port
- val port = euiccChannelManager.findFirstAvailablePort(slotId).let {
- if (it < 0) {
- throw IllegalStateException("No mapped port available; may need to try again")
- }
-
- it
- }
-
- Pair(slotId, port)
- } else {
- // Else, check until the indicated port is available
- euiccChannelManager.withEuiccChannel(slotId, portIndex) { channel ->
- if (!channel.valid) {
- throw IllegalStateException("Indicated slot / port combination is unavailable; may need to try again")
- }
- }
-
- Pair(slotId, portIndex)
- }
- } ?: run {
- // Failure case: mapped slots / ports aren't usable per constraints
- // If we can't find a usable slot / port already mapped, and we aren't allowed to
- // deactivate a SIM, we can only abort
- if (!forceDeactivateSim) {
- return@withEuiccChannelManager RESULT_MUST_DEACTIVATE_SIM
- }
-
- // If port ID is not indicated, we just try to map port 0
- // This is because in order to get here, we have to have failed findFirstAvailablePort(),
- // which means no eUICC port is mapped or connected properly whatsoever.
- val foundPortId = if (portIndex == -1) {
- 0
- } else {
- portIndex
- }
-
- // Now we can try to map an unused port
- try {
- ensurePortIsMapped(slotId, foundPortId)
- } catch (_: Exception) {
- return@withEuiccChannelManager RESULT_FIRST_USER
- }
-
- // Wait for availability again
- retryWithTimeout(5000) {
- euiccChannelManager.withEuiccChannel(slotId, foundPortId) { channel ->
- if (!channel.valid) {
- throw IllegalStateException("Indicated slot / port combination is unavailable; may need to try again")
- }
- }
- } ?: return@withEuiccChannelManager RESULT_FIRST_USER
-
- Pair(slotId, foundPortId)
- }
-
- Log.i(TAG, "Found slotId=$foundSlotId, portId=$foundPortId for switching")
-
- // Now, figure out what they want us to do: disabling a profile, or enabling a new one?
- val (foundIccid, enable) = if (iccid == null) {
- // iccid == null means disabling
- val foundIccid =
- euiccChannelManager.withEuiccChannel(foundSlotId, foundPortId) { channel ->
- channel.lpa.profiles.enabled?.iccid
- } ?: return@withEuiccChannelManager RESULT_FIRST_USER
- Pair(foundIccid, false)
+ val channel = if (portIndex == -1) {
+ retryWithTimeout(5000) { findChannel(slotId) }
} else {
- Pair(iccid, true)
+ retryWithTimeout(5000) { findChannel(slotId, portIndex) }
+ } ?: run {
+ if (!forceDeactivateSim) {
+ // The user must select which SIM to deactivate
+ return@withEuiccChannelManager RESULT_MUST_DEACTIVATE_SIM
+ } else {
+ try {
+ // If we are allowed to deactivate any SIM we like, try mapping the indicated port first
+ ensurePortIsMapped(slotId, portIndex)
+ retryWithTimeout(5000) { findChannel(slotId, portIndex) }
+ } catch (e: Exception) {
+ // We cannot map the port (or it is already mapped)
+ // but we can also use any port available on the card
+ retryWithTimeout(5000) { findChannel(slotId) }
+ } ?: return@withEuiccChannelManager RESULT_FIRST_USER
+ }
}
- val res = euiccChannelManagerService.launchProfileSwitchTask(
- foundSlotId,
- foundPortId,
- foundIccid,
- enable,
- 30 * 1000
- ).waitDone()
+ if (iccid != null && !channel.profileExists(iccid)) {
+ Log.i(TAG, "onSwitchToSubscriptionWithPort iccid=$iccid not found")
+ return@withEuiccChannelManager RESULT_FIRST_USER
+ }
- if (res != null) return@withEuiccChannelManager RESULT_FIRST_USER
+ euiccChannelManager.beginTrackedOperationBlocking(channel.slotId, channel.portId) {
+ if (iccid != null) {
+ // Disable any active profile first if present
+ channel.lpa.disableActiveProfile(false)
+ if (!channel.lpa.enableProfile(iccid)) {
+ return@withEuiccChannelManager RESULT_FIRST_USER
+ }
+ } else {
+ if (!channel.lpa.disableActiveProfile(true)) {
+ return@withEuiccChannelManager RESULT_FIRST_USER
+ }
+ }
+
+ runBlocking {
+ preferenceRepository.notificationSwitchFlow.first()
+ }
+ }
return@withEuiccChannelManager RESULT_OK
} catch (e: Exception) {
@@ -379,19 +335,13 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
"onUpdateSubscriptionNickname slotId=$slotId iccid=$iccid nickname=$nickname"
)
if (shouldIgnoreSlot(slotId)) return@withEuiccChannelManager RESULT_FIRST_USER
- val port = euiccChannelManager.findFirstAvailablePort(slotId)
- if (port < 0) {
+ val channel = findChannel(slotId) ?: return@withEuiccChannelManager RESULT_FIRST_USER
+ if (!channel.profileExists(iccid)) {
return@withEuiccChannelManager RESULT_FIRST_USER
}
-
- euiccChannelManagerService.waitForForegroundTask()
- val success =
- (euiccChannelManagerService.launchProfileRenameTask(slotId, port, iccid, nickname!!)
- .waitDone()) == null
-
- euiccChannelManager.withEuiccChannel(slotId, port) { channel ->
- appContainer.subscriptionManager.tryRefreshCachedEuiccInfo(channel.cardId)
- }
+ val success = channel.lpa
+ .setNickname(iccid, nickname!!)
+ appContainer.subscriptionManager.tryRefreshCachedEuiccInfo(channel.cardId)
return@withEuiccChannelManager if (success) {
RESULT_OK
} else {
diff --git a/app/src/main/java/im/angry/openeuicc/ui/LuiActivity.kt b/app/src/main/java/im/angry/openeuicc/ui/LuiActivity.kt
index de2ca24..f12c9b4 100644
--- a/app/src/main/java/im/angry/openeuicc/ui/LuiActivity.kt
+++ b/app/src/main/java/im/angry/openeuicc/ui/LuiActivity.kt
@@ -2,35 +2,19 @@ package im.angry.openeuicc.ui
import android.content.Intent
import android.view.View
-import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
-import androidx.core.view.ViewCompat
-import androidx.core.view.WindowInsetsCompat
-import androidx.core.view.updatePadding
import im.angry.openeuicc.R
-import im.angry.openeuicc.ui.wizard.DownloadWizardActivity
class LuiActivity : AppCompatActivity() {
override fun onStart() {
super.onStart()
- enableEdgeToEdge()
setContentView(R.layout.activity_lui)
- ViewCompat.setOnApplyWindowInsetsListener(requireViewById(R.id.lui_container)) { v, insets ->
- val bars = insets.getInsets(
- WindowInsetsCompat.Type.systemBars()
- or WindowInsetsCompat.Type.displayCutout()
- )
- v.updatePadding(bars.left, bars.top, bars.right, bars.bottom)
- WindowInsetsCompat.CONSUMED
- }
-
requireViewById(R.id.lui_skip).setOnClickListener { finish() }
- // TODO: Deactivate DownloadWizardActivity if there is no eSIM found.
+ // TODO: Deactivate LuiActivity if there is no eSIM found.
// TODO: Support pre-filled download info (from carrier apps); UX
requireViewById(R.id.lui_download).setOnClickListener {
- startActivity(Intent(this, DownloadWizardActivity::class.java))
- finish()
+ startActivity(Intent(this, DirectProfileDownloadActivity::class.java))
}
}
}
\ No newline at end of file
diff --git a/app/src/main/java/im/angry/openeuicc/ui/PrivilegedEuiccManagementFragment.kt b/app/src/main/java/im/angry/openeuicc/ui/PrivilegedEuiccManagementFragment.kt
index 12b60bd..7d055f4 100644
--- a/app/src/main/java/im/angry/openeuicc/ui/PrivilegedEuiccManagementFragment.kt
+++ b/app/src/main/java/im/angry/openeuicc/ui/PrivilegedEuiccManagementFragment.kt
@@ -6,6 +6,8 @@ import android.widget.Button
import android.widget.PopupMenu
import im.angry.openeuicc.R
import im.angry.openeuicc.util.*
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
import net.typeblog.lpac_jni.LocalProfileInfo
class PrivilegedEuiccManagementFragment: EuiccManagementFragment() {
@@ -14,20 +16,14 @@ class PrivilegedEuiccManagementFragment: EuiccManagementFragment() {
newInstanceEuicc(PrivilegedEuiccManagementFragment::class.java, slotId, portId)
}
- private var isMEP = false
- private var isRemovable = false
-
override suspend fun onCreateFooterViews(
parent: ViewGroup,
profiles: List
): List =
super.onCreateFooterViews(parent, profiles).let { footers ->
- withEuiccChannel { channel ->
- isMEP = channel.isMEP
- isRemovable = channel.port.card.isRemovable
- }
-
- if (isMEP) {
+ // isMEP can map to a slow operation (UiccCardInfo.isMultipleEnabledProfilesSupported())
+ // so let's do it in the IO context
+ if (withContext(Dispatchers.IO) { channel.isMEP }) {
val view = layoutInflater.inflate(R.layout.footer_mep, parent, false)
view.requireViewById(R.id.footer_mep_slot_mapping).setOnClickListener {
(requireActivity() as PrivilegedMainActivity).showSlotMappingFragment()
@@ -40,7 +36,7 @@ class PrivilegedEuiccManagementFragment: EuiccManagementFragment() {
override fun populatePopupWithProfileActions(popup: PopupMenu, profile: LocalProfileInfo) {
super.populatePopupWithProfileActions(popup, profile)
- if (profile.isEnabled && !isRemovable) {
+ if (profile.isEnabled && !channel.removable) {
// Only show the disable option for non-removable eUICCs
// Some devices without internal eUICCs have the "optimization" of ignoring SIM
// slots without a valid profile. This can lead to "bricking" of external eUICCs
diff --git a/app/src/main/java/im/angry/openeuicc/ui/PrivilegedMainActivity.kt b/app/src/main/java/im/angry/openeuicc/ui/PrivilegedMainActivity.kt
index d00e3c0..440e529 100644
--- a/app/src/main/java/im/angry/openeuicc/ui/PrivilegedMainActivity.kt
+++ b/app/src/main/java/im/angry/openeuicc/ui/PrivilegedMainActivity.kt
@@ -16,9 +16,10 @@ class PrivilegedMainActivity : MainActivity() {
menu.findItem(R.id.slot_mapping).isVisible = false
}
- menu.findItem(R.id.dsds).apply {
- isVisible = tm.supportsDSDS
- isChecked = tm.dsdsEnabled
+ if (tm.supportsDSDS) {
+ val dsds = menu.findItem(R.id.dsds)
+ dsds.isVisible = true
+ dsds.isChecked = tm.dsdsEnabled
}
return true
diff --git a/app/src/main/java/im/angry/openeuicc/ui/PrivilegedSettingsFragment.kt b/app/src/main/java/im/angry/openeuicc/ui/PrivilegedSettingsFragment.kt
deleted file mode 100644
index c67d880..0000000
--- a/app/src/main/java/im/angry/openeuicc/ui/PrivilegedSettingsFragment.kt
+++ /dev/null
@@ -1,27 +0,0 @@
-package im.angry.openeuicc.ui
-
-import android.os.Bundle
-import androidx.preference.CheckBoxPreference
-import androidx.preference.Preference
-import im.angry.openeuicc.R
-import im.angry.openeuicc.util.*
-
-class PrivilegedSettingsFragment : SettingsFragment(), PrivilegedEuiccContextMarker {
- override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
- super.onCreatePreferences(savedInstanceState, rootKey)
- addPreferencesFromResource(R.xml.pref_privileged_settings)
- mergePreferenceOverlay("pref_developer_overlay", "pref_developer")
-
- // It's stupid to _disable_ things for privileged, but for now, the per-app locale picker
- // is not usable for apps signed with the platform key.
- // ref:
- // This is disabled here, not moved to unprivileged, because I have hope that this will
- // eventually work for platform-signed apps. Or, at some point we might introduce our own
- // locale picker, which hopefully works whether privileged or not.
- requirePreference("pref_advanced_language").isVisible = false
-
- // Force use TelephonyManager API
- requirePreference("pref_developer_removable_telephony_manager")
- .bindBooleanFlow(preferenceRepository.removableTelephonyManagerFlow)
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/im/angry/openeuicc/util/PrivilegedPreferenceRepository.kt b/app/src/main/java/im/angry/openeuicc/util/PrivilegedPreferenceRepository.kt
deleted file mode 100644
index 9e1ffcc..0000000
--- a/app/src/main/java/im/angry/openeuicc/util/PrivilegedPreferenceRepository.kt
+++ /dev/null
@@ -1,15 +0,0 @@
-package im.angry.openeuicc.util
-
-import android.content.Context
-import androidx.datastore.preferences.core.booleanPreferencesKey
-
-internal object PrivilegedPreferenceKeys {
- // ---- Developer Options ----
- val REMOVABLE_TELEPHONY_MANAGER = booleanPreferencesKey("removable_telephony_manager")
-}
-
-class PrivilegedPreferenceRepository(context: Context) : PreferenceRepository(context) {
- // ---- Developer Options ----
- val removableTelephonyManagerFlow =
- bindFlow(PrivilegedPreferenceKeys.REMOVABLE_TELEPHONY_MANAGER, false)
-}
\ No newline at end of file
diff --git a/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyCompat.kt b/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyCompat.kt
index a9df18e..b947aff 100644
--- a/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyCompat.kt
+++ b/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyCompat.kt
@@ -33,7 +33,7 @@ class RealUiccCardInfoCompat(val inner: UiccCardInfo): UiccCardInfoCompat {
val isEuicc: Boolean
get() = inner.isEuicc
- override val isRemovable: Boolean
+ val isRemovable: Boolean
get() = inner.isRemovable
val isMultipleEnabledProfilesSupported: Boolean
@@ -94,7 +94,6 @@ val TelephonyManager.uiccCardsInfoCompat: List
fun TelephonyManager.iccOpenLogicalChannelByPortCompat(
slotIndex: Int, portIndex: Int, aid: String?, p2: Int
): IccOpenLogicalChannelResponse =
- @Suppress("UNNECESSARY_NOT_NULL_ASSERTION")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
iccOpenLogicalChannelByPort(slotIndex, portIndex, aid, p2)!!
} else {
@@ -111,26 +110,15 @@ fun TelephonyManager.iccCloseLogicalChannelByPortCompat(
}
fun TelephonyManager.iccTransmitApduLogicalChannelByPortCompat(
- slotIndex: Int,
- portIndex: Int,
- channel: Int,
- tx: ByteArray
-): String? {
- val cla = tx[0].toUByte().toInt()
- val ins = tx[1].toUByte().toInt()
- val p1 = tx[2].toUByte().toInt()
- val p2 = tx[3].toUByte().toInt()
- val p3 = tx[4].toUByte().toInt()
- val p4 = tx.drop(5).toByteArray().encodeHex()
- return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ slotIndex: Int, portIndex: Int, channel: Int,
+ cla: Int, inst: Int, p1: Int, p2: Int, p3: Int, data: String?
+): String? =
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
iccTransmitApduLogicalChannelByPort(
- slotIndex, portIndex, channel,
- cla, ins, p1, p2, p3, p4
+ slotIndex, portIndex, channel, cla, inst, p1, p2, p3, data
)
} else {
iccTransmitApduLogicalChannelBySlot(
- slotIndex, channel,
- cla, ins, p1, p2, p3, p4
+ slotIndex, channel, cla, inst, p1, p2, p3, data
)
}
-}
diff --git a/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyUtils.kt b/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyUtils.kt
index 650fe74..ae7294a 100644
--- a/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyUtils.kt
+++ b/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyUtils.kt
@@ -5,7 +5,6 @@ import android.telephony.TelephonyManager
import android.telephony.UiccSlotMapping
import im.angry.openeuicc.core.EuiccChannel
import im.angry.openeuicc.core.EuiccChannelManager
-import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.runBlocking
import java.lang.Exception
@@ -16,14 +15,14 @@ val TelephonyManager.dsdsEnabled: Boolean
get() = activeModemCount >= 2
fun TelephonyManager.setDsdsEnabled(euiccManager: EuiccChannelManager, enabled: Boolean) {
+ val knownChannels = runBlocking {
+ euiccManager.enumerateEuiccChannels()
+ }
+
// Disable all eSIM profiles before performing a DSDS switch (only for internal eSIMs)
- runBlocking {
- euiccManager.flowInternalEuiccPorts().onEach { (slotId, portId) ->
- euiccManager.withEuiccChannel(slotId, portId) {
- if (!it.port.card.isRemovable) {
- it.lpa.disableActiveProfile(false)
- }
- }
+ knownChannels.forEach {
+ if (!it.removable) {
+ it.lpa.disableActiveProfileWithUndo(false)
}
}
@@ -32,7 +31,7 @@ fun TelephonyManager.setDsdsEnabled(euiccManager: EuiccChannelManager, enabled:
// Disable eSIM profiles before switching the slot mapping
// This ensures that unmapped eSIM ports never have "ghost" profiles enabled
-suspend fun TelephonyManager.updateSimSlotMapping(
+fun TelephonyManager.updateSimSlotMapping(
euiccManager: EuiccChannelManager, newMapping: Collection,
currentMapping: Collection = simSlotMapping
) {
@@ -43,24 +42,14 @@ suspend fun TelephonyManager.updateSimSlotMapping(
}
}
- val undo: List Unit> = unmapped.mapNotNull { mapping ->
- euiccManager.withEuiccChannel(mapping.physicalSlotIndex, mapping.portIndex) { channel ->
- if (!channel.port.card.isRemovable) {
- channel.lpa.disableActiveProfileKeepIccId(false)
+ val undo = unmapped.mapNotNull { mapping ->
+ euiccManager.findEuiccChannelByPortBlocking(mapping.physicalSlotIndex, mapping.portIndex)?.let { channel ->
+ if (!channel.removable) {
+ return@mapNotNull channel.lpa.disableActiveProfileWithUndo(false)
} else {
// Do not do anything for external eUICCs -- we can't really trust them to work properly
// with no profile enabled.
- null
- }
- }?.let { iccid ->
- // Generate undo closure because we can't keep reference to `channel` in the closure above
- {
- euiccManager.withEuiccChannel(
- mapping.physicalSlotIndex,
- mapping.portIndex
- ) { channel ->
- channel.lpa.enableProfile(iccid)
- }
+ return@mapNotNull null
}
}
}
@@ -86,6 +75,9 @@ fun SubscriptionManager.tryRefreshCachedEuiccInfo(cardId: Int) {
// Every EuiccChannel we use here should be backed by a RealUiccPortInfoCompat
// except when it is from a USB card reader
+val EuiccChannel.removable
+ get() = (port as? RealUiccPortInfoCompat)?.card?.isRemovable ?: true
+
val EuiccChannel.cardId
get() = (port as? RealUiccPortInfoCompat)?.card?.cardId ?: -1
diff --git a/app/src/main/java/im/angry/openeuicc/util/PrivilegedUtils.kt b/app/src/main/java/im/angry/openeuicc/util/PrivilegedUtils.kt
index 6418581..e295f26 100644
--- a/app/src/main/java/im/angry/openeuicc/util/PrivilegedUtils.kt
+++ b/app/src/main/java/im/angry/openeuicc/util/PrivilegedUtils.kt
@@ -5,16 +5,10 @@ import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
-import androidx.fragment.app.Fragment
import java.util.concurrent.Executors
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
-interface PrivilegedEuiccContextMarker : OpenEuiccContextMarker {
- override val preferenceRepository: PrivilegedPreferenceRepository
- get() = appContainer.preferenceRepository as PrivilegedPreferenceRepository
-}
-
suspend fun Context.bindServiceSuspended(intent: Intent, flags: Int): Pair Unit> =
suspendCoroutine { cont ->
var binder: IBinder?
diff --git a/app/src/main/res/layout/activity_lui.xml b/app/src/main/res/layout/activity_lui.xml
index b331156..ff4a302 100644
--- a/app/src/main/res/layout/activity_lui.xml
+++ b/app/src/main/res/layout/activity_lui.xml
@@ -2,7 +2,6 @@
diff --git a/app/src/main/res/mipmap-anydpi-v31/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v31/ic_launcher.xml
deleted file mode 100644
index 50ec886..0000000
--- a/app/src/main/res/mipmap-anydpi-v31/ic_launcher.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/mipmap-anydpi-v31/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v31/ic_launcher_round.xml
deleted file mode 100644
index 50ec886..0000000
--- a/app/src/main/res/mipmap-anydpi-v31/ic_launcher_round.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml
deleted file mode 100644
index 920801c..0000000
--- a/app/src/main/res/values-ja/strings.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
- このデバイスで eUICC が見つかりません。\nデバイスによってはアプリのメニューからデュアル SIM を有効化する必要があります。
- TelephonyManager (特権)
- デュアル SIM
- DSDS の状態が切り替わりました。モデムが再起動するまでお待ちください。
- このスロットは MEP (Multiple Enabled Profiles) をサポートしています。この機能を有効化または無効化するには「スロットマッピングツール」を使用してください。
- スロットマッピング
- 論理スロット %d:
- スロット %1$d ポート %2$d
- 使用しているデバイスは、%1$d 個の論理 SIM スロットと %2$d 個の物理 SIM スロットがあります。%3$s\n\n各論理スロットに対応する物理スロットまたはポートを選択してください。すべてのマッピングモードがハードウェアでサポートされているわけではないことにご注意ください。
- \n\n物理スロット %1$d は、複数の有効なプロファイル (MEP) をサポートしています。この機能を使用するには、%2$d の仮想ポートを上記の異なる論理スロットに割り当てます。\n\nMEP を有効化すると、ポートは共有プロファイルの一覧を除いて OpenEUICC の個別の eSIM スロットのように動作します。
- \nデュアル SIM モードはサポートされていますが、無効化されています。デバイスに内部 eSIM チップが搭載されている場合は、デフォルトで有効化されていない可能性があります。上記のマッピングを変更するか、デュアル SIM を有効化して eSIM にアクセスしてください。
- 新しいスロットマッピングが設定されました。モデムがスロットを更新するまでお待ちください。
- 指定されたマッピングが無効化されているか、ハードウェアがサポートをしていない可能性があります。
- eSIM をダウンロードしてモバイルネットワークに接続
- 使用しているデバイスは eSIM をサポートしています。モバイルネットワークに接続するには通信事業者が発行した eSIM をダウンロードするか、物理 SIM を挿入してください。
- スキップ
- eSIM をダウンロード
-
- TelephonyManager を常に使用可能にする
- デフォルトでは、非特権モード (EasyEUICC など) での動作と一致させるためにリムーバブル eUICC に対しては OMAPI のみを試行します。ただし、一部デバイスでは正常に動作しない場合があります。このオプションを選択するとリムーバブル eUICC でも TelephonyManager の使用が強制されます。
-
diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml
deleted file mode 100644
index acd9a61..0000000
--- a/app/src/main/res/values-zh-rCN/strings.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-
-
- 在此设备上找不到 eUICC 芯片。\n在某些设备上,您可能需要先在此应用的菜单中启用双卡支持。
- 双卡
- 双卡支持状态已切换。请等待基带重新启动。
- 此卡槽支持多个启用配置文件 (MEP)。要启用或禁用此功能,请使用\"卡槽映射\"工具。
- 卡槽映射
- 逻辑卡槽 %d:
- 卡槽 %1$d 端口 %2$d
- 您的手机有 %1$d 个逻辑 SIM 卡槽和 %2$d 个物理 SIM 卡槽。%3$s\n\n选择您希望每个逻辑卡槽对应的物理卡槽 和/或 \"端口\"。请注意,并非所有映射模式都受硬件支持。
- \n\n物理卡槽 %1$d 支持多个启用的配置文件 (MEP)。要使用此功能,请将其 %2$d 个虚拟\"端口\"分配给上面显示的不同逻辑卡槽。\n\n启用 MEP 后,\"端口\"会在 OpenEUICC 中显示为共享 eSIM 配置文件的独立的 eSIM 卡槽。
- \n支持双卡模式,但已禁用。如果您的设备带有内置 eSIM 芯片,则默认情况下可能不会启用。更改上面的映射或启用双卡以访问您的 eSIM。
- 您的新卡槽映射已设置完毕。请等待基带刷新卡槽。
- 指定的映射可能无效或硬件不支持您指定的映射。
- 通过下载 eSIM 连接到移动网络
- 您的设备支持 eSIM。要连接到移动网络,请下载运营商发布的 eSIM,或插入物理 SIM 卡。
- 跳过
- 下载 eSIM
- TelephonyManager (特权)
- 全局使用 TelephonyManager
- 在默认情况下,可移除 eUICC 将仅使用 OMAPI。这与非特权模式 (EasyEUICC) 一致。在某些设备上 OMAPI 可能存在问题 -- 选择此选项以强制使用 TelephonyManager。
-
\ No newline at end of file
diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml
deleted file mode 100644
index 52b5aa8..0000000
--- a/app/src/main/res/values-zh-rTW/strings.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-
-
- 在此裝置上找不到 eUICC 晶片。\n在某些裝置上,您可能需要先在此應用的選單中啟用雙卡支援。
- 雙卡
- 雙卡支援狀態已切換。請等待基頻處理器重新啟動。
- 此卡槽支援多個啟用設定檔 (MEP)。要啟用或停用此功能,請使用\"卡槽對映\"工具。
- 卡槽對映
- 虛擬卡槽 %d:
- 卡槽 %1$d 端口 %2$d
- 您的手機有 %1$d 個虛擬 SIM 卡槽和 %2$d 個實體 SIM 卡槽。%3$s\n\n選擇您希望每個虛擬卡槽對應的實體卡槽 和/或 \"端口\"。請注意,並非所有對映模式都受硬體支援。
- \n\n實體卡槽 %1$d 支援多個啟用的設定檔 (MEP)。要使用此功能,請將其 %2$d 個虛擬\"端口\"分配給上面顯示的不同虛擬卡槽。\n\n啟用 MEP 後,\"端口\"會在 OpenEUICC 中顯示為共享 eSIM 設定檔的獨立的 eSIM 卡槽。
- \n支援雙卡模式,但已停用。如果您的裝置帶有內建 eSIM 晶片,則預設情況下可能不會啟用。更改上面的對映或啟用雙卡以訪問您的 eSIM。
- 您的新卡槽對映已設定完畢。請等待基頻處理器重新整理卡槽。
- 指定的對映可能無效或硬體不支援您指定的對映。
- 透過下載 eSIM 連線到行動網路
- 您的裝置支援 eSIM。要連線到行動網路,請下載電信業者釋出的 eSIM,或插入實體 SIM 卡。
- 跳過
- 下載 eSIM
- TelephonyManager (特權)
- 全域使用 TelephonyManager
- 在預設情況下,可移除 eUICC 將僅使用 OMAPI。這與非特權模式 (EasyEUICC) 一致。在某些裝置上 OMAPI 可能有問題 -- 選擇此選項以強制使用 TelephonyManager。
-
\ No newline at end of file
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 2c26bc3..3f02430 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -1,7 +1,6 @@
- OpenEUICC
- No eUICC found on this device.\nOn some devices, you may need to enable dual SIM first in the menu of this app.
- TelephonyManager (Privileged)
+ OpenEUICC
+ No eUICC found on this device.\nOn some devices, you may need to enable dual SIM first in the menu of this app.
Dual SIM
@@ -22,8 +21,4 @@
Your device supports eSIMs. To connect to mobile network, download your eSIM issued by a carrier, or insert a physical SIM.
Skip
Download eSIM
-
-
- Use TelephonyManager everywhere
- By default, only OMAPI is attempted for removable eUICCs to match what is done in unprivileged mode (i.e. EasyEUICC). This may not work well on some devices. Select this option to force the use of TelephonyManager even for removable eUICCs.
\ No newline at end of file
diff --git a/app/src/main/res/xml/pref_privileged_settings.xml b/app/src/main/res/xml/pref_privileged_settings.xml
deleted file mode 100644
index 5279126..0000000
--- a/app/src/main/res/xml/pref_privileged_settings.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/buildSrc/.gitignore b/buildSrc/.gitignore
deleted file mode 100644
index 6fbe8a4..0000000
--- a/buildSrc/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-/.gradle
-/build
\ No newline at end of file
diff --git a/buildSrc/src/main/kotlin/im/angry/openeuicc/build/Magisk.kt b/buildSrc/src/main/kotlin/im/angry/openeuicc/build/Magisk.kt
deleted file mode 100644
index e5ccfa3..0000000
--- a/buildSrc/src/main/kotlin/im/angry/openeuicc/build/Magisk.kt
+++ /dev/null
@@ -1,74 +0,0 @@
-package im.angry.openeuicc.build
-
-import org.gradle.api.DefaultTask
-import org.gradle.api.provider.MapProperty
-import org.gradle.api.provider.Property
-import org.gradle.api.tasks.Input
-import org.gradle.api.tasks.InputDirectory
-import org.gradle.api.tasks.InputFile
-import org.gradle.api.tasks.OutputDirectory
-import org.gradle.api.tasks.TaskAction
-import java.io.File
-
-abstract class MagiskModuleDirTask : DefaultTask() {
- @get:Input
- abstract val variant : Property
-
- @get:Input
- abstract val appName : Property
-
- @get:InputFile
- abstract val permsFile : Property
-
- @get:InputFile
- abstract val moduleInstaller : Property
-
- @get:Input
- abstract val moduleCustomizeScriptText : Property
-
- @get:Input
- abstract val moduleUninstallScriptText : Property
-
- @get:Input
- abstract val moduleProp : MapProperty
-
- @InputDirectory
- val inputDir = variant.map { project.layout.buildDirectory.dir("outputs/apk/${it}") }
-
- @OutputDirectory
- val outputDir = variant.map { project.layout.buildDirectory.dir("magisk/${it}") }
-
- @TaskAction
- fun build() {
- val dir = outputDir.get().get()
- project.mkdir(dir)
- val systemExtDir = dir.dir("system/system_ext")
- val permDir = dir.dir("system/system_ext/etc/permissions")
- val appDir = systemExtDir.dir("priv-app/${appName.get()}")
- val metaInfDir = dir.dir("META-INF/com/google/android")
- project.mkdir(systemExtDir)
- project.mkdir(metaInfDir)
- project.mkdir(appDir)
- project.mkdir(permDir)
- project.copy {
- into(appDir)
- from(inputDir) {
- include("app-${variant.get()}.apk")
- rename("app-${variant.get()}.apk", "${appName.get()}.apk")
- }
- }
- project.copy {
- from(permsFile)
- into(permDir)
- }
- project.copy {
- from(moduleInstaller)
- into(metaInfDir)
- rename(".*", "update-binary")
- }
- dir.file("customize.sh").asFile.writeText(moduleCustomizeScriptText.get())
- dir.file("uninstall.sh").asFile.writeText(moduleUninstallScriptText.get())
- metaInfDir.file("updater-script").asFile.writeText("#MAGISK\n")
- dir.file("module.prop").asFile.writeText(moduleProp.get().map { (k, v) -> "$k=$v" }.joinToString("\n"))
- }
-}
\ No newline at end of file
diff --git a/buildSrc/src/main/kotlin/im/angry/openeuicc/build/Versioning.kt b/buildSrc/src/main/kotlin/im/angry/openeuicc/build/Versioning.kt
index ef07c43..24f0235 100644
--- a/buildSrc/src/main/kotlin/im/angry/openeuicc/build/Versioning.kt
+++ b/buildSrc/src/main/kotlin/im/angry/openeuicc/build/Versioning.kt
@@ -16,7 +16,7 @@ val Project.gitVersionCode: Int
standardOutput = stdout
}
stdout.toString("utf-8").trim('\n').toInt()
- } catch (_: Exception) {
+ } catch (e: Exception) {
0
}
@@ -29,7 +29,7 @@ val Project.gitVersionName: String
standardOutput = stdout
}
stdout.toString("utf-8").trim('\n')
- } catch (_: Exception) {
+ } catch (e: Exception) {
"Unknown"
}
@@ -38,7 +38,7 @@ class MyVersioningPlugin: Plugin {
target.configure {
defaultConfig {
versionCode = target.gitVersionCode
- versionName = target.gitVersionName.removePrefix("unpriv-")
+ versionName = target.gitVersionName
}
applicationVariants.all {
diff --git a/gradle.properties b/gradle.properties
index 239cc44..022338b 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -22,5 +22,4 @@ kotlin.code.style=official
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
android.defaults.buildfeatures.buildconfig=true
-android.nonFinalResIds=false
-android.suppressUnsupportedCompileSdk=35
+android.nonFinalResIds=false
\ No newline at end of file
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
index a4b76b9..e708b1c 100644
Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 9355b41..dab3589 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,7 +1,6 @@
+#Wed Jun 08 13:28:20 EDT 2022
distributionBase=GRADLE_USER_HOME
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip
-networkTimeout=10000
-validateDistributionUrl=true
-zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
diff --git a/gradlew b/gradlew
index f5feea6..4f906e0 100755
--- a/gradlew
+++ b/gradlew
@@ -1,7 +1,7 @@
-#!/bin/sh
+#!/usr/bin/env sh
#
-# Copyright © 2015-2021 the original authors.
+# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -15,104 +15,69 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-# SPDX-License-Identifier: Apache-2.0
-#
##############################################################################
-#
-# Gradle start up script for POSIX generated by Gradle.
-#
-# Important for running:
-#
-# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
-# noncompliant, but you have some other compliant shell such as ksh or
-# bash, then to run this script, type that shell name before the whole
-# command line, like:
-#
-# ksh Gradle
-#
-# Busybox and similar reduced shells will NOT work, because this script
-# requires all of these POSIX shell features:
-# * functions;
-# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
-# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
-# * compound commands having a testable exit status, especially «case»;
-# * various built-in commands including «command», «set», and «ulimit».
-#
-# Important for patching:
-#
-# (2) This script targets any POSIX shell, so it avoids extensions provided
-# by Bash, Ksh, etc; in particular arrays are avoided.
-#
-# The "traditional" practice of packing multiple parameters into a
-# space-separated string is a well documented source of bugs and security
-# problems, so this is (mostly) avoided, by progressively accumulating
-# options in "$@", and eventually passing that to Java.
-#
-# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
-# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
-# see the in-line comments for details.
-#
-# There are tweaks for specific operating systems such as AIX, CygWin,
-# Darwin, MinGW, and NonStop.
-#
-# (3) This script is generated from the Groovy template
-# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
-# within the Gradle project.
-#
-# You can find Gradle at https://github.com/gradle/gradle/.
-#
+##
+## Gradle start up script for UN*X
+##
##############################################################################
# Attempt to set APP_HOME
-
# Resolve links: $0 may be a link
-app_path=$0
-
-# Need this for daisy-chained symlinks.
-while
- APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
- [ -h "$app_path" ]
-do
- ls=$( ls -ld "$app_path" )
- link=${ls#*' -> '}
- case $link in #(
- /*) app_path=$link ;; #(
- *) app_path=$APP_HOME$link ;;
- esac
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
-# This is normally unused
-# shellcheck disable=SC2034
-APP_BASE_NAME=${0##*/}
-# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
-APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
-' "$PWD" ) || exit
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
-MAX_FD=maximum
+MAX_FD="maximum"
warn () {
echo "$*"
-} >&2
+}
die () {
echo
echo "$*"
echo
exit 1
-} >&2
+}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
-case "$( uname )" in #(
- CYGWIN* ) cygwin=true ;; #(
- Darwin* ) darwin=true ;; #(
- MSYS* | MINGW* ) msys=true ;; #(
- NONSTOP* ) nonstop=true ;;
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+ NONSTOP* )
+ nonstop=true
+ ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@@ -122,9 +87,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
- JAVACMD=$JAVA_HOME/jre/sh/java
+ JAVACMD="$JAVA_HOME/jre/sh/java"
else
- JAVACMD=$JAVA_HOME/bin/java
+ JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -133,120 +98,88 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
- JAVACMD=java
- if ! command -v java >/dev/null 2>&1
- then
- die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
- fi
fi
# Increase the maximum file descriptors if we can.
-if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
- case $MAX_FD in #(
- max*)
- # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
- # shellcheck disable=SC2039,SC3045
- MAX_FD=$( ulimit -H -n ) ||
- warn "Could not query maximum file descriptor limit"
- esac
- case $MAX_FD in #(
- '' | soft) :;; #(
- *)
- # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
- # shellcheck disable=SC2039,SC3045
- ulimit -n "$MAX_FD" ||
- warn "Could not set maximum file descriptor limit to $MAX_FD"
- esac
+if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
fi
-# Collect all arguments for the java command, stacking in reverse order:
-# * args from the command line
-# * the main class name
-# * -classpath
-# * -D...appname settings
-# * --module-path (only if needed)
-# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
# For Cygwin or MSYS, switch paths to Windows format before running java
-if "$cygwin" || "$msys" ; then
- APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
- CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
- JAVACMD=$( cygpath --unix "$JAVACMD" )
+ JAVACMD=`cygpath --unix "$JAVACMD"`
- # Now convert the arguments - kludge to limit ourselves to /bin/sh
- for arg do
- if
- case $arg in #(
- -*) false ;; # don't mess with options #(
- /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
- [ -e "$t" ] ;; #(
- *) false ;;
- esac
- then
- arg=$( cygpath --path --ignore --mixed "$arg" )
- fi
- # Roll the args list around exactly as many times as the number of
- # args, so each arg winds up back in the position where it started, but
- # possibly modified.
- #
- # NB: a `for` loop captures its iteration list before it begins, so
- # changing the positional parameters here affects neither the number of
- # iterations, nor the values presented in `arg`.
- shift # remove old arg
- set -- "$@" "$arg" # push replacement arg
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=`expr $i + 1`
+ done
+ case $i in
+ 0) set -- ;;
+ 1) set -- "$args0" ;;
+ 2) set -- "$args0" "$args1" ;;
+ 3) set -- "$args0" "$args1" "$args2" ;;
+ 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
fi
+# Escape application args
+save () {
+ for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
+ echo " "
+}
+APP_ARGS=`save "$@"`
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
-
-# Collect all arguments for the java command:
-# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
-# and any embedded shellness will be escaped.
-# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
-# treated as '${Hostname}' itself on the command line.
-
-set -- \
- "-Dorg.gradle.appname=$APP_BASE_NAME" \
- -classpath "$CLASSPATH" \
- org.gradle.wrapper.GradleWrapperMain \
- "$@"
-
-# Stop when "xargs" is not available.
-if ! command -v xargs >/dev/null 2>&1
-then
- die "xargs is not available"
-fi
-
-# Use "xargs" to parse quoted args.
-#
-# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
-#
-# In Bash we could simply go:
-#
-# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
-# set -- "${ARGS[@]}" "$@"
-#
-# but POSIX shell has neither arrays nor command substitution, so instead we
-# post-process each arg (as a line of input to sed) to backslash-escape any
-# character that might be a shell metacharacter, then use eval to reverse
-# that process (while maintaining the separation between arguments), and wrap
-# the whole thing up as a single "set" statement.
-#
-# This will of course break if any of these variables contains a newline or
-# an unmatched quote.
-#
-
-eval "set -- $(
- printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
- xargs -n1 |
- sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
- tr '\n' ' '
- )" '"$@"'
+# Collect all arguments for the java command, following the shell quoting and substitution rules
+eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
diff --git a/gradlew.bat b/gradlew.bat
index 9b42019..ac1b06f 100644
--- a/gradlew.bat
+++ b/gradlew.bat
@@ -13,10 +13,8 @@
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
-@rem SPDX-License-Identifier: Apache-2.0
-@rem
-@if "%DEBUG%"=="" @echo off
+@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@@ -27,8 +25,7 @@
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
-if "%DIRNAME%"=="" set DIRNAME=.
-@rem This is normally unused
+if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@@ -43,13 +40,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
-if %ERRORLEVEL% equ 0 goto execute
+if "%ERRORLEVEL%" == "0" goto execute
-echo. 1>&2
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
-echo. 1>&2
-echo Please set the JAVA_HOME variable in your environment to match the 1>&2
-echo location of your Java installation. 1>&2
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
goto fail
@@ -59,11 +56,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
-echo. 1>&2
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
-echo. 1>&2
-echo Please set the JAVA_HOME variable in your environment to match the 1>&2
-echo location of your Java installation. 1>&2
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
goto fail
@@ -78,15 +75,13 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end
@rem End local scope for the variables with windows NT shell
-if %ERRORLEVEL% equ 0 goto mainEnd
+if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
-set EXIT_CODE=%ERRORLEVEL%
-if %EXIT_CODE% equ 0 set EXIT_CODE=1
-if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
-exit /b %EXIT_CODE%
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
diff --git a/libs/hidden-apis-shim/src/main/java/im/angry/openeuicc/util/TelephonyManagerHiddenApi.kt b/libs/hidden-apis-shim/src/main/java/im/angry/openeuicc/util/TelephonyManagerHiddenApi.kt
index 0d42354..4203fea 100644
--- a/libs/hidden-apis-shim/src/main/java/im/angry/openeuicc/util/TelephonyManagerHiddenApi.kt
+++ b/libs/hidden-apis-shim/src/main/java/im/angry/openeuicc/util/TelephonyManagerHiddenApi.kt
@@ -69,13 +69,11 @@ fun TelephonyManager.iccOpenLogicalChannelByPort(
): IccOpenLogicalChannelResponse =
iccOpenLogicalChannelByPort.invoke(this, slotId, portId, appletId, p2) as IccOpenLogicalChannelResponse
-fun TelephonyManager.iccCloseLogicalChannelBySlot(slotId: Int, channel: Int) {
- iccCloseLogicalChannelBySlot.invoke(this, slotId, channel)
-}
+fun TelephonyManager.iccCloseLogicalChannelBySlot(slotId: Int, channel: Int): Boolean =
+ iccCloseLogicalChannelBySlot.invoke(this, slotId, channel) as Boolean
-fun TelephonyManager.iccCloseLogicalChannelByPort(slotId: Int, portId: Int, channel: Int) {
- iccCloseLogicalChannelByPort.invoke(this, slotId, portId, channel)
-}
+fun TelephonyManager.iccCloseLogicalChannelByPort(slotId: Int, portId: Int, channel: Int): Boolean =
+ iccCloseLogicalChannelByPort.invoke(this, slotId, portId, channel) as Boolean
fun TelephonyManager.iccTransmitApduLogicalChannelBySlot(
slotId: Int, channel: Int, cla: Int, instruction: Int,
diff --git a/libs/lpac-jni/.gitignore b/libs/lpac-jni/.gitignore
deleted file mode 100644
index 42afabf..0000000
--- a/libs/lpac-jni/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/build
\ No newline at end of file
diff --git a/libs/lpac-jni/build.gradle.kts b/libs/lpac-jni/build.gradle.kts
index 636cdf3..b50a953 100644
--- a/libs/lpac-jni/build.gradle.kts
+++ b/libs/lpac-jni/build.gradle.kts
@@ -5,7 +5,7 @@ plugins {
android {
namespace = "net.typeblog.lpac_jni"
- compileSdk = 35
+ compileSdk = 33
ndkVersion = "26.1.10909125"
defaultConfig {
@@ -16,9 +16,9 @@ android {
externalNativeBuild {
ndkBuild {
cFlags(
- "-fmacro-prefix-map=${project.projectDir}=/fake/path/",
- "-fdebug-prefix-map=${project.projectDir}=/fake/path/",
- "-ffile-prefix-map=${project.projectDir}=/fake/path/"
+ "-fmacro-prefix-map=${project.projectDir.toString()}=/fake/path/",
+ "-fdebug-prefix-map=${project.projectDir.toString()}=/fake/path/",
+ "-ffile-prefix-map=${project.projectDir.toString()}=/fake/path/"
)
}
}
@@ -32,7 +32,7 @@ android {
}
externalNativeBuild {
ndkBuild {
- path("src/main/jni/lpac-jni.mk")
+ path("src/main/jni/Android.mk")
}
}
compileOptions {
diff --git a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/ApduInterface.kt b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/ApduInterface.kt
index 75a6905..dfa92df 100644
--- a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/ApduInterface.kt
+++ b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/ApduInterface.kt
@@ -8,7 +8,7 @@ interface ApduInterface {
fun disconnect()
fun logicalChannelOpen(aid: ByteArray): Int
fun logicalChannelClose(handle: Int)
- fun transmit(handle: Int, tx: ByteArray): ByteArray
+ fun transmit(tx: ByteArray): ByteArray
/**
* Is this APDU connection still valid?
@@ -16,13 +16,4 @@ interface ApduInterface {
* callers should further check with the LPA to fully determine the validity of a channel
*/
val valid: Boolean
-
- fun withLogicalChannel(aid: ByteArray, cb: ((ByteArray) -> ByteArray) -> T): T {
- val handle = logicalChannelOpen(aid)
- return try {
- cb { transmit(handle, it) }
- } finally {
- logicalChannelClose(handle)
- }
- }
-}
+}
\ No newline at end of file
diff --git a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/EuiccInfo2.kt b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/EuiccInfo2.kt
index 0720049..e69c7ff 100644
--- a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/EuiccInfo2.kt
+++ b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/EuiccInfo2.kt
@@ -2,31 +2,13 @@ package net.typeblog.lpac_jni
/* Corresponds to EuiccInfo2 in SGP.22 */
data class EuiccInfo2(
- val sgp22Version: Version,
- val profileVersion: Version,
- val euiccFirmwareVersion: Version,
- val globalPlatformVersion: Version,
+ val profileVersion: String,
+ val euiccFirmwareVersion: String,
+ val globalPlatformVersion: String,
val sasAccreditationNumber: String,
- val ppVersion: Version,
+ val ppVersion: String,
val freeNvram: Int,
val freeRam: Int,
- val euiccCiPKIdListForSigning: Set,
- val euiccCiPKIdListForVerification: Set,
-)
-
-data class Version(
- val major: Int,
- val minor: Int,
- val patch: Int,
-) {
- constructor(version: String) : this(version.split('.').map(String::toInt))
- private constructor(parts: List) : this(parts[0], parts[1], parts[2])
-
- operator fun compareTo(other: Version): Int {
- if (major != other.major) return major - other.major
- if (minor != other.minor) return minor - other.minor
- return patch - other.patch
- }
-
- override fun toString() = "$major.$minor.$patch"
-}
+ val euiccCiPKIdListForSigning: Array,
+ val euiccCiPKIdListForVerification: Array,
+)
\ No newline at end of file
diff --git a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LocalProfileAssistant.kt b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LocalProfileAssistant.kt
index 48ab1c5..7e0a31b 100644
--- a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LocalProfileAssistant.kt
+++ b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LocalProfileAssistant.kt
@@ -1,21 +1,6 @@
package net.typeblog.lpac_jni
-import net.typeblog.lpac_jni.HttpInterface.HttpResponse
-
interface LocalProfileAssistant {
- @Suppress("ArrayInDataClass")
- data class ProfileDownloadException(
- val lpaErrorReason: String,
- val lastHttpResponse: HttpResponse?,
- val lastHttpException: Exception?,
- val lastApduResponse: ByteArray?,
- val lastApduException: Exception?,
- ) : Exception("Failed to download profile")
-
- class ProfileRenameException() : Exception("Failed to rename profile")
- class ProfileNameTooLongException() : Exception("Profile name too long")
- class ProfileNameIsInvalidUTF8Exception() : Exception("Profile name is invalid UTF-8")
-
val valid: Boolean
val profiles: List
val notifications: List
@@ -23,13 +8,6 @@ interface LocalProfileAssistant {
// Extended EuiccInfo for use with LUIs, containing information such as firmware version
val euiccInfo2: EuiccInfo2?
- /**
- * Set the max segment size (mss) for all es10x commands. This can help with removable
- * eUICCs that may run at a baud rate too fast for the modem.
- * By default, this is set to 60 by libeuicc.
- */
- fun setEs10xMss(mss: Byte)
-
// All blocking functions in this class assume that they are executed on non-Main threads
// The IO context in Kotlin's coroutine library is recommended.
fun enableProfile(iccid: String, refresh: Boolean = true): Boolean
@@ -37,21 +15,14 @@ interface LocalProfileAssistant {
fun deleteProfile(iccid: String): Boolean
fun downloadProfile(smdp: String, matchingId: String?, imei: String?,
- confirmationCode: String?, callback: ProfileDownloadCallback)
+ confirmationCode: String?, callback: ProfileDownloadCallback): Boolean
fun deleteNotification(seqNumber: Long): Boolean
fun handleNotification(seqNumber: Long): Boolean
- fun euiccMemoryReset()
-
- /**
- * Nickname must be valid UTF-8 and shorter than 64 chars.
- *
- * May throw one of: ProfileRenameException, ProfileNameTooLongException, ProfileNameIsInvalidUTF8Exception
- */
fun setNickname(
iccid: String, nickname: String
- )
+ ): Boolean
fun close()
}
\ No newline at end of file
diff --git a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LpacJni.kt b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LpacJni.kt
index fa9474f..5a706b9 100644
--- a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LpacJni.kt
+++ b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LpacJni.kt
@@ -5,76 +5,31 @@ internal object LpacJni {
System.loadLibrary("lpac-jni")
}
- external fun createContext(
- isdrAid: ByteArray,
- apduInterface: ApduInterface,
- httpInterface: HttpInterface
- ): Long
+ external fun createContext(apduInterface: ApduInterface, httpInterface: HttpInterface): Long
external fun destroyContext(handle: Long)
external fun euiccInit(handle: Long): Int
- external fun euiccSetMss(handle: Long, mss: Byte)
external fun euiccFini(handle: Long)
// es10c
// null returns signify errors
external fun es10cGetEid(handle: Long): String?
- external fun es10cGetProfilesInfo(handle: Long): Long
+ external fun es10cGetProfilesInfo(handle: Long): Array?
external fun es10cEnableProfile(handle: Long, iccid: String, refresh: Boolean): Int
external fun es10cDisableProfile(handle: Long, iccid: String, refresh: Boolean): Int
external fun es10cDeleteProfile(handle: Long, iccid: String): Int
- external fun es10cSetNickname(handle: Long, iccid: String, nickNullTerminated: ByteArray): Int
+ external fun es10cSetNickname(handle: Long, iccid: String, nick: String): Int
// es10b
- external fun es10bListNotification(handle: Long): Long // A native pointer to a linked list. Handle with linked list-related methods below. May be 0 (null)
+ external fun es10bListNotification(handle: Long): Array?
external fun es10bDeleteNotification(handle: Long, seqNumber: Long): Int
// es9p + es10b
// We do not expose all of the functions because of tediousness :)
external fun downloadProfile(handle: Long, smdp: String, matchingId: String?, imei: String?,
confirmationCode: String?, callback: ProfileDownloadCallback): Int
- external fun downloadErrCodeToString(code: Int): String
external fun handleNotification(handle: Long, seqNumber: Long): Int
- // Cancel any ongoing es9p and/or es10b sessions
- external fun cancelSessions(handle: Long)
- // ES10c
- external fun es10cEuiccMemoryReset(handle: Long): Int
// es10cex (actually part of es10b)
- external fun es10cexGetEuiccInfo2(handle: Long): Long
-
- // C <-> Java struct / linked list handling
- // C String arrays
- external fun stringArrNext(curr: Long): Long
- external fun stringDeref(curr: Long): String
- // Profiles
- external fun profilesNext(curr: Long): Long
- external fun profilesFree(head: Long): Long
- external fun profileGetIccid(curr: Long): String
- external fun profileGetIsdpAid(curr: Long): String
- external fun profileGetName(curr: Long): String
- external fun profileGetNickname(curr: Long): String
- external fun profileGetServiceProvider(curr: Long): String
- external fun profileGetStateString(curr: Long): String
- external fun profileGetClassString(curr: Long): String
- // Notifications
- external fun notificationsNext(curr: Long): Long
- external fun notificationGetSeq(curr: Long): Long
- external fun notificationGetOperationString(curr: Long): String
- external fun notificationGetAddress(curr: Long): String
- external fun notificationGetIccid(curr: Long): String
- external fun notificationsFree(head: Long)
- // EuiccInfo2
- external fun euiccInfo2Free(info: Long)
- external fun euiccInfo2GetSGP22Version(info: Long): String
- external fun euiccInfo2GetProfileVersion(info: Long): String
- external fun euiccInfo2GetEuiccFirmwareVersion(info: Long): String
- external fun euiccInfo2GetGlobalPlatformVersion(info: Long): String
- external fun euiccInfo2GetSasAcreditationNumber(info: Long): String
- external fun euiccInfo2GetPpVersion(info: Long): String
- external fun euiccInfo2GetFreeNonVolatileMemory(info: Long): Long
- external fun euiccInfo2GetFreeVolatileMemory(info: Long): Long
- // C String Arrays
- external fun euiccInfo2GetEuiccCiPKIdListForSigning(info: Long): Long
- external fun euiccInfo2GetEuiccCiPKIdListForVerification(info: Long): Long
+ external fun es10cexGetEuiccInfo2(handle: Long): EuiccInfo2?
}
\ No newline at end of file
diff --git a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/ProfileDownloadCallback.kt b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/ProfileDownloadCallback.kt
index 289ddf6..579ad58 100644
--- a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/ProfileDownloadCallback.kt
+++ b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/ProfileDownloadCallback.kt
@@ -1,18 +1,6 @@
package net.typeblog.lpac_jni
interface ProfileDownloadCallback {
- companion object {
- fun lookupStateFromProgress(progress: Int): DownloadState =
- when (progress) {
- 0 -> DownloadState.Preparing
- 20 -> DownloadState.Connecting
- 40 -> DownloadState.Authenticating
- 60 -> DownloadState.Downloading
- 80 -> DownloadState.Finalizing
- else -> throw IllegalArgumentException("Unknown state")
- }
- }
-
enum class DownloadState(val progress: Int) {
Preparing(0),
Connecting(20), // Before {server,client} authentication
diff --git a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/AllowAllTrustManager.kt b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/AllowAllTrustManager.kt
deleted file mode 100644
index 55b28fe..0000000
--- a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/AllowAllTrustManager.kt
+++ /dev/null
@@ -1,22 +0,0 @@
-package net.typeblog.lpac_jni.impl
-
-import android.annotation.SuppressLint
-import java.security.cert.X509Certificate
-import javax.net.ssl.X509TrustManager
-
-@SuppressLint("CustomX509TrustManager")
-class AllowAllTrustManager : X509TrustManager {
- @SuppressLint("TrustAllX509TrustManager")
- override fun checkClientTrusted(p0: Array?, p1: String?) {
- return
- }
-
- @SuppressLint("TrustAllX509TrustManager")
- override fun checkServerTrusted(p0: Array?, p1: String?) {
- return
- }
-
- override fun getAcceptedIssuers(): Array {
- return emptyArray()
- }
-}
\ No newline at end of file
diff --git a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/HttpInterfaceImpl.kt b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/HttpInterfaceImpl.kt
index c1b15f7..356ccb2 100644
--- a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/HttpInterfaceImpl.kt
+++ b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/HttpInterfaceImpl.kt
@@ -1,22 +1,15 @@
package net.typeblog.lpac_jni.impl
import android.util.Log
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.runBlocking
import net.typeblog.lpac_jni.HttpInterface
import java.net.URL
import java.security.SecureRandom
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLContext
-import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.TrustManagerFactory
-class HttpInterfaceImpl(
- private val verboseLoggingFlow: Flow,
- private val ignoreTLSCertificateFlow: Flow
-) : HttpInterface {
+class HttpInterfaceImpl: HttpInterface {
companion object {
private const val TAG = "HttpInterfaceImpl"
}
@@ -30,25 +23,18 @@ class HttpInterfaceImpl(
): HttpInterface.HttpResponse {
Log.d(TAG, "transmit(url = $url)")
- if (runBlocking { verboseLoggingFlow.first() }) {
- Log.d(TAG, "HTTP tx = ${tx.decodeToString(throwOnInvalidSequence = false)}")
- }
-
val parsedUrl = URL(url)
if (parsedUrl.protocol != "https") {
throw IllegalArgumentException("SM-DP+ servers must use the HTTPS protocol")
}
try {
+ val sslContext = SSLContext.getInstance("TLS")
+ sslContext.init(null, trustManagers, SecureRandom())
+
val conn = parsedUrl.openConnection() as HttpsURLConnection
conn.connectTimeout = 2000
-
- if (url.contains("handleNotification")) {
- conn.connectTimeout = 1000
- conn.readTimeout = 1000
- }
-
- conn.sslSocketFactory = getSocketFactory()
+ conn.sslSocketFactory = sslContext.socketFactory
conn.requestMethod = "POST"
conn.doInput = true
conn.doOutput = true
@@ -64,34 +50,13 @@ class HttpInterfaceImpl(
Log.d(TAG, "transmit responseCode = ${conn.responseCode}")
- val bytes = conn.inputStream.readBytes().also {
- if (runBlocking { verboseLoggingFlow.first() }) {
- Log.d(
- TAG,
- "HTTP response body = ${it.decodeToString(throwOnInvalidSequence = false)}"
- )
- }
- }
-
- return HttpInterface.HttpResponse(conn.responseCode, bytes)
+ return HttpInterface.HttpResponse(conn.responseCode, conn.inputStream.readBytes())
} catch (e: Exception) {
e.printStackTrace()
throw e
}
}
- private fun getSocketFactory(): SSLSocketFactory {
- val trustManagers =
- if (runBlocking { ignoreTLSCertificateFlow.first() }) {
- arrayOf(AllowAllTrustManager())
- } else {
- this.trustManagers
- }
- val sslContext = SSLContext.getInstance("TLS")
- sslContext.init(null, trustManagers, SecureRandom())
- return sslContext.socketFactory
- }
-
override fun usePublicKeyIds(pkids: Array) {
val trustManagerFactory = TrustManagerFactory.getInstance("PKIX").apply {
init(keyIdToKeystore(pkids))
diff --git a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/LocalProfileAssistantImpl.kt b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/LocalProfileAssistantImpl.kt
index ce09717..361c594 100644
--- a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/LocalProfileAssistantImpl.kt
+++ b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/LocalProfileAssistantImpl.kt
@@ -5,98 +5,29 @@ import net.typeblog.lpac_jni.LpacJni
import net.typeblog.lpac_jni.ApduInterface
import net.typeblog.lpac_jni.EuiccInfo2
import net.typeblog.lpac_jni.HttpInterface
-import net.typeblog.lpac_jni.HttpInterface.HttpResponse
import net.typeblog.lpac_jni.LocalProfileAssistant
import net.typeblog.lpac_jni.LocalProfileInfo
import net.typeblog.lpac_jni.LocalProfileNotification
import net.typeblog.lpac_jni.ProfileDownloadCallback
-import net.typeblog.lpac_jni.Version
-import java.util.concurrent.locks.ReentrantLock
-import kotlin.concurrent.withLock
class LocalProfileAssistantImpl(
- isdrAid: ByteArray,
- rawApduInterface: ApduInterface,
- rawHttpInterface: HttpInterface
-) : LocalProfileAssistant {
+ private val apduInterface: ApduInterface,
+ httpInterface: HttpInterface
+): LocalProfileAssistant {
companion object {
private const val TAG = "LocalProfileAssistantImpl"
}
- /**
- * A thin wrapper over ApduInterface to acquire exceptions and errors transparently
- */
- private class ApduInterfaceWrapper(val apduInterface: ApduInterface) :
- ApduInterface by apduInterface {
- var lastApduResponse: ByteArray? = null
- var lastApduException: Exception? = null
-
- override fun transmit(handle: Int, tx: ByteArray): ByteArray =
- try {
- apduInterface.transmit(handle, tx).also {
- lastApduException = null
- lastApduResponse = it
- }
- } catch (e: Exception) {
- lastApduResponse = null
- lastApduException = e
- throw e
- }
- }
-
- /**
- * Same for HTTP for diagnostics
- */
- private class HttpInterfaceWrapper(val httpInterface: HttpInterface) :
- HttpInterface by httpInterface {
- /**
- * The last HTTP response we have received from the SM-DP+ server.
- *
- * This is intended for error diagnosis. However, note that most SM-DP+ servers
- * respond with 200 even when there is an error. This needs to be taken into
- * account when designing UI.
- */
- var lastHttpResponse: HttpResponse? = null
-
- /**
- * The last exception that has been thrown during a HTTP connection
- */
- var lastHttpException: Exception? = null
-
- override fun transmit(url: String, tx: ByteArray, headers: Array): HttpResponse =
- try {
- httpInterface.transmit(url, tx, headers).also {
- lastHttpException = null
- lastHttpResponse = it
- }
- } catch (e: Exception) {
- lastHttpResponse = null
- lastHttpException = e
- throw e
- }
- }
-
- // Controls concurrency of every single method in this class, since
- // the C-side is explicitly NOT thread-safe
- private val lock = ReentrantLock()
-
- private val apduInterface = ApduInterfaceWrapper(rawApduInterface)
- private val httpInterface = HttpInterfaceWrapper(rawHttpInterface)
-
private var finalized = false
- private var contextHandle: Long = LpacJni.createContext(isdrAid, apduInterface, httpInterface)
+ private var contextHandle: Long = LpacJni.createContext(apduInterface, httpInterface)
init {
if (LpacJni.euiccInit(contextHandle) < 0) {
throw IllegalArgumentException("Failed to initialize LPA")
}
- val pkids = euiccInfo2?.euiccCiPKIdListForVerification ?: setOf()
- httpInterface.usePublicKeyIds(pkids.toTypedArray())
- }
-
- override fun setEs10xMss(mss: Byte) {
- LpacJni.euiccSetMss(contextHandle, mss)
+ val pkids = euiccInfo2?.euiccCiPKIdListForVerification ?: arrayOf()
+ httpInterface.usePublicKeyIds(pkids)
}
override val valid: Boolean
@@ -111,174 +42,55 @@ class LocalProfileAssistantImpl(
}
override val profiles: List
- get() = lock.withLock {
- val head = LpacJni.es10cGetProfilesInfo(contextHandle)
- var curr = head
- val ret = mutableListOf()
- while (curr != 0L) {
- val state = LocalProfileInfo.State.fromString(LpacJni.profileGetStateString(curr))
- val clazz = LocalProfileInfo.Clazz.fromString(LpacJni.profileGetClassString(curr))
- ret.add(
- LocalProfileInfo(
- LpacJni.profileGetIccid(curr),
- state,
- LpacJni.profileGetName(curr),
- LpacJni.profileGetNickname(curr),
- LpacJni.profileGetServiceProvider(curr),
- LpacJni.profileGetIsdpAid(curr),
- clazz
- )
- )
- curr = LpacJni.profilesNext(curr)
- }
-
- LpacJni.profilesFree(curr)
- return ret
- }
+ get() = LpacJni.es10cGetProfilesInfo(contextHandle)?.asList() ?: listOf()
override val notifications: List
- get() = lock.withLock {
- val head = LpacJni.es10bListNotification(contextHandle)
- var curr = head
-
- try {
- val ret = mutableListOf()
- while (curr != 0L) {
- ret.add(
- LocalProfileNotification(
- LpacJni.notificationGetSeq(curr),
- LocalProfileNotification.Operation.fromString(
- LpacJni.notificationGetOperationString(
- curr
- )
- ),
- LpacJni.notificationGetAddress(curr),
- LpacJni.notificationGetIccid(curr),
- )
- )
- curr = LpacJni.notificationsNext(curr)
- }
- return ret.sortedBy { it.seqNumber }.reversed()
- } finally {
- LpacJni.notificationsFree(head)
- }
- }
+ get() =
+ (LpacJni.es10bListNotification(contextHandle) ?: arrayOf())
+ .sortedBy { it.seqNumber }.reversed()
override val eID: String
- get() = lock.withLock { LpacJni.es10cGetEid(contextHandle)!! }
+ get() = LpacJni.es10cGetEid(contextHandle)!!
override val euiccInfo2: EuiccInfo2?
- get() = lock.withLock {
- val cInfo = LpacJni.es10cexGetEuiccInfo2(contextHandle)
- if (cInfo == 0L) return null
+ get() = LpacJni.es10cexGetEuiccInfo2(contextHandle)
- try {
- return EuiccInfo2(
- Version(LpacJni.euiccInfo2GetSGP22Version(cInfo)),
- Version(LpacJni.euiccInfo2GetProfileVersion(cInfo)),
- Version(LpacJni.euiccInfo2GetEuiccFirmwareVersion(cInfo)),
- Version(LpacJni.euiccInfo2GetGlobalPlatformVersion(cInfo)),
- LpacJni.euiccInfo2GetSasAcreditationNumber(cInfo),
- Version(LpacJni.euiccInfo2GetPpVersion(cInfo)),
- LpacJni.euiccInfo2GetFreeNonVolatileMemory(cInfo).toInt(),
- LpacJni.euiccInfo2GetFreeVolatileMemory(cInfo).toInt(),
- buildSet {
- var cursor = LpacJni.euiccInfo2GetEuiccCiPKIdListForSigning(cInfo)
- while (cursor != 0L) {
- add(LpacJni.stringDeref(cursor))
- cursor = LpacJni.stringArrNext(cursor)
- }
- },
- buildSet {
- var cursor = LpacJni.euiccInfo2GetEuiccCiPKIdListForVerification(cInfo)
- while (cursor != 0L) {
- add(LpacJni.stringDeref(cursor))
- cursor = LpacJni.stringArrNext(cursor)
- }
- },
- )
- } finally {
- LpacJni.euiccInfo2Free(cInfo)
- }
- }
-
- override fun enableProfile(iccid: String, refresh: Boolean): Boolean = lock.withLock {
+ override fun enableProfile(iccid: String, refresh: Boolean): Boolean =
LpacJni.es10cEnableProfile(contextHandle, iccid, refresh) == 0
- }
- override fun disableProfile(iccid: String, refresh: Boolean): Boolean = lock.withLock {
+ override fun disableProfile(iccid: String, refresh: Boolean): Boolean =
LpacJni.es10cDisableProfile(contextHandle, iccid, refresh) == 0
- }
- override fun deleteProfile(iccid: String): Boolean = lock.withLock {
+ override fun deleteProfile(iccid: String): Boolean =
LpacJni.es10cDeleteProfile(contextHandle, iccid) == 0
- }
- override fun downloadProfile(
- smdp: String, matchingId: String?, imei: String?,
- confirmationCode: String?, callback: ProfileDownloadCallback
- ) = lock.withLock {
- val res = LpacJni.downloadProfile(
+ @Synchronized
+ override fun downloadProfile(smdp: String, matchingId: String?, imei: String?,
+ confirmationCode: String?, callback: ProfileDownloadCallback): Boolean {
+ return LpacJni.downloadProfile(
contextHandle,
smdp,
matchingId,
imei,
confirmationCode,
callback
- )
-
- if (res != 0) {
- // Construct the error now to store any error information we _can_ access
- val err = LocalProfileAssistant.ProfileDownloadException(
- lpaErrorReason = LpacJni.downloadErrCodeToString(-res),
- httpInterface.lastHttpResponse,
- httpInterface.lastHttpException,
- apduInterface.lastApduResponse,
- apduInterface.lastApduException,
- )
-
- // Cancel sessions if possible. This will overwrite recorded errors from HTTP and APDU interfaces.
- LpacJni.cancelSessions(contextHandle)
-
- throw err
- }
+ ) == 0
}
- override fun deleteNotification(seqNumber: Long): Boolean = lock.withLock {
+ override fun deleteNotification(seqNumber: Long): Boolean =
LpacJni.es10bDeleteNotification(contextHandle, seqNumber) == 0
- }
- override fun handleNotification(seqNumber: Long): Boolean = lock.withLock {
+ @Synchronized
+ override fun handleNotification(seqNumber: Long): Boolean =
LpacJni.handleNotification(contextHandle, seqNumber).also {
Log.d(TAG, "handleNotification $seqNumber = $it")
} == 0
- }
- override fun setNickname(iccid: String, nickname: String) = lock.withLock {
- val encoded = try {
- Charsets.UTF_8.encode(nickname).array()
- } catch (e: CharacterCodingException) {
- throw LocalProfileAssistant.ProfileNameIsInvalidUTF8Exception()
- }
+ override fun setNickname(iccid: String, nickname: String): Boolean =
+ LpacJni.es10cSetNickname(contextHandle, iccid, nickname) == 0
- if (encoded.size >= 64) {
- throw LocalProfileAssistant.ProfileNameTooLongException()
- }
-
- val encodedNullTerminated = encoded + byteArrayOf(0)
-
- if (LpacJni.es10cSetNickname(contextHandle, iccid, encodedNullTerminated) != 0) {
- throw LocalProfileAssistant.ProfileRenameException()
- }
- }
-
- override fun euiccMemoryReset() {
- lock.withLock {
- LpacJni.es10cEuiccMemoryReset(contextHandle)
- }
- }
-
- override fun close() = lock.withLock {
+ @Synchronized
+ override fun close() {
if (!finalized) {
LpacJni.euiccFini(contextHandle)
LpacJni.destroyContext(contextHandle)
diff --git a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/RootCertificates.kt b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/RootCertificates.kt
index 295a911..13848b6 100644
--- a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/RootCertificates.kt
+++ b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/RootCertificates.kt
@@ -7,33 +7,6 @@ import java.security.cert.CertificateFactory
const val DEFAULT_PKID_GSMA_RSP2_ROOT_CI1 = "81370f5125d0b1d408d4c3b232e6d25e795bebfb"
-// SGP.28 v1.0, eSIM CI Registration Criteria (Page 5 of 9, 2019-10-24)
-// https://www.gsma.com/newsroom/wp-content/uploads/SGP.28-v1.0.pdf#page=5
-// FS.27 v2.0, Security Guidelines for UICC Profiles (Page 25 of 27, 2024-01-30)
-// https://www.gsma.com/solutions-and-impact/technologies/security/wp-content/uploads/2024/01/FS.27-Security-Guidelines-for-UICC-Credentials-v2.0-FINAL-23-July.pdf#page=25
-
-// List of GSMA Live CIs
-// https://www.gsma.com/solutions-and-impact/technologies/esim/gsma-root-ci/
-val PKID_GSMA_LIVE_CI = setOf(
- // GSMA RSP2 Root CI1 (SGP.22 v2+v3, CA: DigiCert)
- // https://euicc-manual.osmocom.org/docs/pki/ci/files/81370f.txt
- DEFAULT_PKID_GSMA_RSP2_ROOT_CI1,
- // OISITE GSMA CI G1 (SGP.22 v2+v3, CA: WISeKey)
- // https://euicc-manual.osmocom.org/docs/pki/ci/files/4c2796.txt
- "4c27967ad20c14b391e9601e41e604ad57c0222f",
-)
-
-// SGP.26 v3.0, 2023-12-01
-// https://www.gsma.com/solutions-and-impact/technologies/esim/wp-content/uploads/2023/12/SGP.26-v3.0.pdf
-val PKID_GSMA_TEST_CI = setOf(
- // Test CI (SGP.26, NIST P256)
- // https://euicc-manual.osmocom.org/docs/pki/ci/files/34eecf.txt
- "34eecf13156518d48d30bdf06853404d115f955d",
- // Test CI (SGP.26, BRP P256r1)
- // https://euicc-manual.osmocom.org/docs/pki/ci/files/2209f6.txt
- "2209f61cd9ec5c9c854e787341ff83ecf9776a5b",
-)
-
private fun getCertificate(keyId: String): Certificate? =
KNOWN_CI_CERTS[keyId]?.toByteArray()?.let { cert ->
ByteArrayInputStream(cert).use { stream ->
@@ -62,7 +35,7 @@ internal fun keyIdToKeystore(keyIds: Array): KeyStore {
return ret
}
-// ref:
+// ref:
internal val KNOWN_CI_CERTS = hashMapOf(
// GSM Association - RSP2 Root CI1 (CA: DigiCert)
// Specs: SGP.21 and SGP.22 version 2 and version 3
@@ -84,7 +57,7 @@ internal val KNOWN_CI_CERTS = hashMapOf(
-----END CERTIFICATE-----
""".trimIndent(),
// OISITE GSMA CI G1 (CA: WISeKey)
- // Specs: SGP.21 and SGP.22 version 2 and version 3
+ // Specs: SGP.21 and SGP.22 version 3
"4c27967ad20c14b391e9601e41e604ad57c0222f" to """
-----BEGIN CERTIFICATE-----
MIIB9zCCAZ2gAwIBAgIUSpBSCCDYPOEG/IFHUCKpZ2pIAQMwCgYIKoZIzj0EAwIw
diff --git a/libs/lpac-jni/src/main/jni/lpac-jni.mk b/libs/lpac-jni/src/main/jni/Android.mk
similarity index 94%
rename from libs/lpac-jni/src/main/jni/lpac-jni.mk
rename to libs/lpac-jni/src/main/jni/Android.mk
index dad173c..c0bcee7 100644
--- a/libs/lpac-jni/src/main/jni/lpac-jni.mk
+++ b/libs/lpac-jni/src/main/jni/Android.mk
@@ -1,5 +1,4 @@
LOCAL_PATH := $(call my-dir)
-LOCAL_LDFLAGS += "-Wl,-z,max-page-size=16384"
# function to find all *.c files under a directory
define all-c-files-under
diff --git a/libs/lpac-jni/src/main/jni/Application.mk b/libs/lpac-jni/src/main/jni/Application.mk
index c1d3766..2112196 100644
--- a/libs/lpac-jni/src/main/jni/Application.mk
+++ b/libs/lpac-jni/src/main/jni/Application.mk
@@ -1,5 +1,4 @@
APP_ABI := all
APP_SHORT_COMMANDS := true
APP_CFLAGS := -Wno-compound-token-split-by-macro
-APP_LDFLAGS := -Wl,--build-id=none -z muldefs
-APP_SUPPORT_FLEXIBLE_PAGE_SIZES := true
+APP_LDFLAGS := -Wl,--build-id=none -z muldefs
\ No newline at end of file
diff --git a/libs/lpac-jni/src/main/jni/lpac b/libs/lpac-jni/src/main/jni/lpac
index 90f7104..0011ea6 160000
--- a/libs/lpac-jni/src/main/jni/lpac
+++ b/libs/lpac-jni/src/main/jni/lpac
@@ -1 +1 @@
-Subproject commit 90f7104847d4bb392b275746da20a55177a67573
+Subproject commit 0011ea6cc4c045c84f7aac839c1cce7804422355
diff --git a/libs/lpac-jni/src/main/jni/lpac-jni/interface-wrapper.c b/libs/lpac-jni/src/main/jni/lpac-jni/interface-wrapper.c
index 007e80d..9059171 100644
--- a/libs/lpac-jni/src/main/jni/lpac-jni/interface-wrapper.c
+++ b/libs/lpac-jni/src/main/jni/lpac-jni/interface-wrapper.c
@@ -22,7 +22,7 @@ void interface_wrapper_init() {
"([B)I");
method_apdu_logical_channel_close = (*env)->GetMethodID(env, apdu_class, "logicalChannelClose",
"(I)V");
- method_apdu_transmit = (*env)->GetMethodID(env, apdu_class, "transmit", "(I[B)[B");
+ method_apdu_transmit = (*env)->GetMethodID(env, apdu_class, "transmit", "([B)[B");
jclass http_class = (*env)->FindClass(env, "net/typeblog/lpac_jni/HttpInterface");
method_http_transmit = (*env)->GetMethodID(env, http_class, "transmit",
@@ -53,34 +53,28 @@ apdu_interface_logical_channel_open(struct euicc_ctx *ctx, const uint8_t *aid, u
jint ret = (*env)->CallIntMethod(env, LPAC_JNI_CTX(ctx)->apdu_interface,
method_apdu_logical_channel_open, jbarr);
LPAC_JNI_EXCEPTION_RETURN;
- LPAC_JNI_CTX(ctx)->logical_channel_id = ret;
return ret;
}
-static void apdu_interface_logical_channel_close(struct euicc_ctx *ctx,
- __attribute__((unused)) uint8_t channel) {
+static void apdu_interface_logical_channel_close(struct euicc_ctx *ctx, uint8_t channel) {
LPAC_JNI_SETUP_ENV;
- jint logical_channel_id = LPAC_JNI_CTX(ctx)->logical_channel_id;
(*env)->CallVoidMethod(env, LPAC_JNI_CTX(ctx)->apdu_interface,
- method_apdu_logical_channel_close, logical_channel_id);
+ method_apdu_logical_channel_close, channel);
(*env)->ExceptionClear(env);
}
static int
apdu_interface_transmit(struct euicc_ctx *ctx, uint8_t **rx, uint32_t *rx_len, const uint8_t *tx,
uint32_t tx_len) {
- const int logic_channel = LPAC_JNI_CTX(ctx)->logical_channel_id;
LPAC_JNI_SETUP_ENV;
jbyteArray txArr = (*env)->NewByteArray(env, tx_len);
(*env)->SetByteArrayRegion(env, txArr, 0, tx_len, (const jbyte *) tx);
- jbyteArray ret = (jbyteArray) (*env)->CallObjectMethod(
- env, LPAC_JNI_CTX(ctx)->apdu_interface,
- method_apdu_transmit, logic_channel, txArr
- );
+ jbyteArray ret = (jbyteArray) (*env)->CallObjectMethod(env, LPAC_JNI_CTX(ctx)->apdu_interface,
+ method_apdu_transmit, txArr);
LPAC_JNI_EXCEPTION_RETURN;
*rx_len = (*env)->GetArrayLength(env, ret);
*rx = calloc(*rx_len, sizeof(uint8_t));
- (*env)->GetByteArrayRegion(env, ret, 0, *rx_len, (jbyte *) *rx);
+ (*env)->GetByteArrayRegion(env, ret, 0, *rx_len, *rx);
(*env)->DeleteLocalRef(env, txArr);
(*env)->DeleteLocalRef(env, ret);
return 0;
@@ -113,7 +107,7 @@ http_interface_transmit(struct euicc_ctx *ctx, const char *url, uint32_t *rcode,
jbyteArray rxArr = (jbyteArray) (*env)->GetObjectField(env, ret, field_resp_data);
*rx_len = (*env)->GetArrayLength(env, rxArr);
*rx = calloc(*rx_len, sizeof(uint8_t));
- (*env)->GetByteArrayRegion(env, rxArr, 0, *rx_len, (jbyte *) *rx);
+ (*env)->GetByteArrayRegion(env, rxArr, 0, *rx_len, *rx);
(*env)->DeleteLocalRef(env, txArr);
(*env)->DeleteLocalRef(env, rxArr);
(*env)->DeleteLocalRef(env, headersArr);
diff --git a/libs/lpac-jni/src/main/jni/lpac-jni/lpac-download.c b/libs/lpac-jni/src/main/jni/lpac-jni/lpac-download.c
index bae2ee8..f8b27ff 100644
--- a/libs/lpac-jni/src/main/jni/lpac-jni/lpac-download.c
+++ b/libs/lpac-jni/src/main/jni/lpac-jni/lpac-download.c
@@ -82,58 +82,42 @@ Java_net_typeblog_lpac_1jni_LpacJni_downloadProfile(JNIEnv *env, jobject thiz, j
(*env)->CallVoidMethod(env, callback, on_state_update, download_state_preparing);
ret = es10b_get_euicc_challenge_and_info(ctx);
syslog(LOG_INFO, "es10b_get_euicc_challenge_and_info %d", ret);
- if (ret < 0) {
- ret = -ES10B_ERROR_REASON_UNDEFINED;
+ if (ret < 0)
goto out;
- }
(*env)->CallVoidMethod(env, callback, on_state_update, download_state_connecting);
ret = es9p_initiate_authentication(ctx);
syslog(LOG_INFO, "es9p_initiate_authentication %d", ret);
- if (ret < 0) {
- ret = -ES10B_ERROR_REASON_UNDEFINED;
+ if (ret < 0)
goto out;
- }
(*env)->CallVoidMethod(env, callback, on_state_update, download_state_authenticating);
ret = es10b_authenticate_server(ctx, _matching_id, _imei);
syslog(LOG_INFO, "es10b_authenticate_server %d", ret);
- if (ret < 0) {
- ret = -ES10B_ERROR_REASON_UNDEFINED;
+ if (ret < 0)
goto out;
- }
ret = es9p_authenticate_client(ctx);
- if (ret < 0) {
- ret = -ES10B_ERROR_REASON_UNDEFINED;
+ if (ret < 0)
goto out;
- }
(*env)->CallVoidMethod(env, callback, on_state_update, download_state_downloading);
ret = es10b_prepare_download(ctx, _confirmation_code);
syslog(LOG_INFO, "es10b_prepare_download %d", ret);
- if (ret < 0) {
- ret = -ES10B_ERROR_REASON_UNDEFINED;
+ if (ret < 0)
goto out;
- }
ret = es9p_get_bound_profile_package(ctx);
if (ret < 0)
goto out;
(*env)->CallVoidMethod(env, callback, on_state_update, download_state_finalizing);
+ // TODO: Expose error code as Java-side exceptions?
ret = es10b_load_bound_profile_package(ctx, &es10b_load_bound_profile_package_result);
- syslog(LOG_INFO, "es10b_load_bound_profile_package %d, reason %d", ret, es10b_load_bound_profile_package_result.errorReason);
- if (ret < 0) {
- ret = - (int) es10b_load_bound_profile_package_result.errorReason;
- goto out;
- }
-
- euicc_http_cleanup(ctx);
+ syslog(LOG_INFO, "es10b_load_bound_profile_package %d", ret);
out:
- // We expect Java side to call cancelSessions after any error -- thus, `euicc_http_cleanup` is done there
- // This is so that Java side can access the last HTTP and/or APDU errors when we return.
+ euicc_http_cleanup(ctx);
if (_confirmation_code != NULL)
(*env)->ReleaseStringUTFChars(env, confirmation_code, _confirmation_code);
if (_matching_id != NULL)
@@ -143,42 +127,3 @@ Java_net_typeblog_lpac_1jni_LpacJni_downloadProfile(JNIEnv *env, jobject thiz, j
(*env)->ReleaseStringUTFChars(env, imei, _imei);
return ret;
}
-
-
-JNIEXPORT void JNICALL
-Java_net_typeblog_lpac_1jni_LpacJni_cancelSessions(JNIEnv *env, jobject thiz, jlong handle) {
- struct euicc_ctx *ctx = (struct euicc_ctx *) handle;
- es9p_cancel_session(ctx);
- es10b_cancel_session(ctx, ES10B_CANCEL_SESSION_REASON_UNDEFINED);
- euicc_http_cleanup(ctx);
-}
-
-#define QUOTE(S) #S
-#define ERRCODE_ENUM_TO_STRING(VARIANT) case VARIANT: return toJString(env, QUOTE(VARIANT))
-
-JNIEXPORT jstring JNICALL
-Java_net_typeblog_lpac_1jni_LpacJni_downloadErrCodeToString(JNIEnv *env, jobject thiz, jint code) {
- switch (code) {
- ERRCODE_ENUM_TO_STRING(ES10B_ERROR_REASON_INCORRECT_INPUT_VALUES);
- ERRCODE_ENUM_TO_STRING(ES10B_ERROR_REASON_INVALID_SIGNATURE);
- ERRCODE_ENUM_TO_STRING(ES10B_ERROR_REASON_INVALID_TRANSACTION_ID);
- ERRCODE_ENUM_TO_STRING(ES10B_ERROR_REASON_UNSUPPORTED_CRT_VALUES);
- ERRCODE_ENUM_TO_STRING(ES10B_ERROR_REASON_UNSUPPORTED_REMOTE_OPERATION_TYPE);
- ERRCODE_ENUM_TO_STRING(ES10B_ERROR_REASON_UNSUPPORTED_PROFILE_CLASS);
- ERRCODE_ENUM_TO_STRING(ES10B_ERROR_REASON_SCP03T_STRUCTURE_ERROR);
- ERRCODE_ENUM_TO_STRING(ES10B_ERROR_REASON_SCP03T_SECURITY_ERROR);
- ERRCODE_ENUM_TO_STRING(
- ES10B_ERROR_REASON_INSTALL_FAILED_DUE_TO_ICCID_ALREADY_EXISTS_ON_EUICC);
- ERRCODE_ENUM_TO_STRING(
- ES10B_ERROR_REASON_INSTALL_FAILED_DUE_TO_INSUFFICIENT_MEMORY_FOR_PROFILE);
- ERRCODE_ENUM_TO_STRING(ES10B_ERROR_REASON_INSTALL_FAILED_DUE_TO_INTERRUPTION);
- ERRCODE_ENUM_TO_STRING(ES10B_ERROR_REASON_INSTALL_FAILED_DUE_TO_PE_PROCESSING_ERROR);
- ERRCODE_ENUM_TO_STRING(ES10B_ERROR_REASON_INSTALL_FAILED_DUE_TO_ICCID_MISMATCH);
- ERRCODE_ENUM_TO_STRING(
- ES10B_ERROR_REASON_TEST_PROFILE_INSTALL_FAILED_DUE_TO_INVALID_NAA_KEY);
- ERRCODE_ENUM_TO_STRING(ES10B_ERROR_REASON_PPR_NOT_ALLOWED);
- ERRCODE_ENUM_TO_STRING(ES10B_ERROR_REASON_INSTALL_FAILED_DUE_TO_UNKNOWN_ERROR);
- default:
- return toJString(env, "ES10B_ERROR_REASON_UNDEFINED");
- }
-}
\ No newline at end of file
diff --git a/libs/lpac-jni/src/main/jni/lpac-jni/lpac-jni.c b/libs/lpac-jni/src/main/jni/lpac-jni/lpac-jni.c
index ca319db..6ba8ebf 100644
--- a/libs/lpac-jni/src/main/jni/lpac-jni/lpac-jni.c
+++ b/libs/lpac-jni/src/main/jni/lpac-jni/lpac-jni.c
@@ -12,15 +12,28 @@
JavaVM *jvm = NULL;
+jclass local_profile_info_class;
+jmethodID local_profile_info_constructor;
+
+jclass local_profile_state_class;
+jmethodID local_profile_state_from_string;
+
+jclass local_profile_class_class;
+jmethodID local_profile_class_from_string;
+
jstring empty_string;
jclass string_class;
jmethodID string_constructor;
+jclass euicc_info2_class;
+jmethodID euicc_info2_constructor;
+
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
jvm = vm;
interface_wrapper_init();
lpac_download_init();
+ lpac_notifications_init();
LPAC_JNI_SETUP_ENV;
string_class = (*env)->FindClass(env, "java/lang/String");
@@ -28,7 +41,31 @@ jint JNI_OnLoad(JavaVM *vm, void *reserved) {
string_constructor = (*env)->GetMethodID(env, string_class, "",
"([BLjava/lang/String;)V");
- const jchar _unused[1];
+ local_profile_info_class = (*env)->FindClass(env, "net/typeblog/lpac_jni/LocalProfileInfo");
+ local_profile_info_class = (*env)->NewGlobalRef(env, local_profile_info_class);
+ local_profile_info_constructor = (*env)->GetMethodID(env, local_profile_info_class, "",
+ "(Ljava/lang/String;Lnet/typeblog/lpac_jni/LocalProfileInfo$State;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lnet/typeblog/lpac_jni/LocalProfileInfo$Clazz;)V");
+
+ local_profile_state_class = (*env)->FindClass(env,
+ "net/typeblog/lpac_jni/LocalProfileInfo$State");
+ local_profile_state_class = (*env)->NewGlobalRef(env, local_profile_state_class);
+ local_profile_state_from_string = (*env)->GetStaticMethodID(env, local_profile_state_class,
+ "fromString",
+ "(Ljava/lang/String;)Lnet/typeblog/lpac_jni/LocalProfileInfo$State;");
+
+ local_profile_class_class = (*env)->FindClass(env,
+ "net/typeblog/lpac_jni/LocalProfileInfo$Clazz");
+ local_profile_class_class = (*env)->NewGlobalRef(env, local_profile_class_class);
+ local_profile_class_from_string = (*env)->GetStaticMethodID(env, local_profile_class_class,
+ "fromString",
+ "(Ljava/lang/String;)Lnet/typeblog/lpac_jni/LocalProfileInfo$Clazz;");
+
+ euicc_info2_class = (*env)->FindClass(env, "net/typeblog/lpac_jni/EuiccInfo2");
+ euicc_info2_class = (*env)->NewGlobalRef(env, euicc_info2_class);
+ euicc_info2_constructor = (*env)->GetMethodID(env, euicc_info2_class, "",
+ "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II[Ljava/lang/String;[Ljava/lang/String;)V");
+
+ const char _unused[1];
empty_string = (*env)->NewString(env, _unused, 0);
empty_string = (*env)->NewGlobalRef(env, empty_string);
@@ -37,30 +74,17 @@ jint JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEXPORT jlong JNICALL
Java_net_typeblog_lpac_1jni_LpacJni_createContext(JNIEnv *env, jobject thiz,
- jbyteArray isdr_aid,
jobject apdu_interface,
jobject http_interface) {
struct lpac_jni_ctx *jni_ctx = NULL;
struct euicc_ctx *ctx = NULL;
- jbyte *isdr_java = NULL;
- uint32_t isdr_len = 0;
- uint8_t *isdr_c = NULL;
ctx = calloc(1, sizeof(struct euicc_ctx));
jni_ctx = calloc(1, sizeof(struct lpac_jni_ctx));
-
- isdr_java = (*env)->GetByteArrayElements(env, isdr_aid, JNI_FALSE);
- isdr_len = (*env)->GetArrayLength(env, isdr_aid);
- isdr_c = calloc(isdr_len, sizeof(uint8_t));
- memcpy(isdr_c, isdr_java, isdr_len);
- (*env)->ReleaseByteArrayElements(env, isdr_aid, isdr_java, JNI_ABORT);
-
ctx->apdu.interface = &lpac_jni_apdu_interface;
ctx->http.interface = &lpac_jni_http_interface;
jni_ctx->apdu_interface = (*env)->NewGlobalRef(env, apdu_interface);
jni_ctx->http_interface = (*env)->NewGlobalRef(env, http_interface);
- ctx->aid = (const uint8_t *) isdr_c;
- ctx->aid_len = isdr_len;
ctx->userdata = (void *) jni_ctx;
return (jlong) ctx;
}
@@ -73,7 +97,6 @@ Java_net_typeblog_lpac_1jni_LpacJni_destroyContext(JNIEnv *env, jobject thiz, jl
(*env)->DeleteGlobalRef(env, jni_ctx->apdu_interface);
(*env)->DeleteGlobalRef(env, jni_ctx->http_interface);
free(jni_ctx);
- free((void *) ctx->aid);
free(ctx);
}
@@ -89,13 +112,6 @@ Java_net_typeblog_lpac_1jni_LpacJni_euiccFini(JNIEnv *env, jobject thiz, jlong h
euicc_fini(ctx);
}
-JNIEXPORT void JNICALL
-Java_net_typeblog_lpac_1jni_LpacJni_euiccSetMss(JNIEnv *env, jobject thiz, jlong handle,
- jbyte mss) {
- struct euicc_ctx *ctx = (struct euicc_ctx *) handle;
- ctx->es10x_mss = (uint8_t) mss;
-}
-
jstring toJString(JNIEnv *env, const char *pat) {
jbyteArray bytes = NULL;
jstring encoding = NULL;
@@ -129,23 +145,25 @@ Java_net_typeblog_lpac_1jni_LpacJni_es10cGetEid(JNIEnv *env, jobject thiz, jlong
return ret;
}
-JNIEXPORT jlong JNICALL
-Java_net_typeblog_lpac_1jni_LpacJni_es10cGetProfilesInfo(JNIEnv *env, jobject thiz, jlong handle) {
- struct euicc_ctx *ctx = (struct euicc_ctx *) handle;
- struct es10c_profile_info_list *info = NULL;
-
- if (es10c_get_profiles_info(ctx, &info) < 0) {
- return 0;
- }
-
- return (jlong) info;
-}
-
-JNIEXPORT jstring JNICALL
-Java_net_typeblog_lpac_1jni_LpacJni_profileGetStateString(JNIEnv *env, jobject thiz, jlong curr) {
- struct es10c_profile_info_list *info = (struct es10c_profile_info_list *) curr;
+jobject profile_info_native_to_java(JNIEnv *env, struct es10c_profile_info_list *info) {
const char *profileStateStr = NULL;
+ const char *profileClassStr = NULL;
+ jstring serviceProvider = NULL;
+ jstring nickName = NULL;
+ jstring isdpAid = NULL;
+ jstring iccid = NULL;
+ jstring name = NULL;
+ jobject state = NULL;
+ jobject class = NULL;
+ jobject jinfo = NULL;
+ iccid = toJString(env, info->iccid);
+ isdpAid = toJString(env, info->isdpAid);
+ name = toJString(env, info->profileName);
+ nickName = toJString(env, info->profileNickname);
+ serviceProvider = toJString(env, info->serviceProviderName);
+
+ // TODO: Maybe we should pass a Java object directly here?
switch (info->profileState) {
case ES10C_PROFILE_STATE_ENABLED:
profileStateStr = "enabled";
@@ -157,13 +175,9 @@ Java_net_typeblog_lpac_1jni_LpacJni_profileGetStateString(JNIEnv *env, jobject t
profileStateStr = "unknown";
}
- return toJString(env, profileStateStr);
-}
-
-JNIEXPORT jstring JNICALL
-Java_net_typeblog_lpac_1jni_LpacJni_profileGetClassString(JNIEnv *env, jobject thiz, jlong curr) {
- struct es10c_profile_info_list *info = (struct es10c_profile_info_list *) curr;
- const char *profileClassStr = NULL;
+ state = (*env)->CallStaticObjectMethod(env, local_profile_state_class,
+ local_profile_state_from_string,
+ toJString(env, profileStateStr));
switch (info->profileClass) {
case ES10C_PROFILE_CLASS_TEST:
@@ -180,16 +194,51 @@ Java_net_typeblog_lpac_1jni_LpacJni_profileGetClassString(JNIEnv *env, jobject t
break;
}
- return toJString(env, profileClassStr);
+ class = (*env)->CallStaticObjectMethod(env, local_profile_class_class,
+ local_profile_class_from_string,
+ toJString(env, profileClassStr));
+
+ jinfo = (*env)->NewObject(env, local_profile_info_class, local_profile_info_constructor,
+ iccid, state, name, nickName, serviceProvider, isdpAid, class);
+
+ (*env)->DeleteLocalRef(env, class);
+ (*env)->DeleteLocalRef(env, state);
+ (*env)->DeleteLocalRef(env, serviceProvider);
+ (*env)->DeleteLocalRef(env, nickName);
+ (*env)->DeleteLocalRef(env, name);
+ (*env)->DeleteLocalRef(env, isdpAid);
+ (*env)->DeleteLocalRef(env, iccid);
+
+ return jinfo;
}
-LPAC_JNI_STRUCT_GETTER_LINKED_LIST_NEXT(struct es10c_profile_info_list, profiles)
-LPAC_JNI_STRUCT_FREE(struct es10c_profile_info_list, profiles, es10c_profile_info_list_free_all)
-LPAC_JNI_STRUCT_GETTER_STRING(struct es10c_profile_info_list, profile, iccid, Iccid)
-LPAC_JNI_STRUCT_GETTER_STRING(struct es10c_profile_info_list, profile, isdpAid, IsdpAid)
-LPAC_JNI_STRUCT_GETTER_STRING(struct es10c_profile_info_list, profile, profileName, Name)
-LPAC_JNI_STRUCT_GETTER_STRING(struct es10c_profile_info_list, profile, profileNickname, Nickname)
-LPAC_JNI_STRUCT_GETTER_STRING(struct es10c_profile_info_list, profile, serviceProviderName, ServiceProvider)
+JNIEXPORT jobjectArray JNICALL
+Java_net_typeblog_lpac_1jni_LpacJni_es10cGetProfilesInfo(JNIEnv *env, jobject thiz, jlong handle) {
+ struct euicc_ctx *ctx = (struct euicc_ctx *) handle;
+ struct es10c_profile_info_list *info = NULL;
+ struct es10c_profile_info_list *curr = NULL;
+ jobjectArray ret = NULL;
+ jobject jinfo = NULL;
+ int count = 0;
+
+ if (es10c_get_profiles_info(ctx, &info) < 0) {
+ return NULL;
+ }
+
+ count = LPAC_JNI_LINKED_LIST_COUNT(info, curr);
+
+ ret = (*env)->NewObjectArray(env, count, local_profile_info_class, NULL);
+
+ // Convert the native info array to Java
+ LPAC_JNI_LINKED_LIST_FOREACH(info, curr, {
+ jinfo = profile_info_native_to_java(env, curr);
+ (*env)->SetObjectArrayElement(env, ret, i, jinfo);
+ (*env)->DeleteLocalRef(env, jinfo);
+ });
+
+ es10c_profile_info_list_free_all(info);
+ return ret;
+}
JNIEXPORT jint JNICALL
Java_net_typeblog_lpac_1jni_LpacJni_es10cEnableProfile(JNIEnv *env, jobject thiz, jlong handle,
@@ -219,16 +268,16 @@ Java_net_typeblog_lpac_1jni_LpacJni_es10cDisableProfile(JNIEnv *env, jobject thi
JNIEXPORT jint JNICALL
Java_net_typeblog_lpac_1jni_LpacJni_es10cSetNickname(JNIEnv *env, jobject thiz, jlong handle,
- jstring iccid, jbyteArray nick) {
+ jstring iccid, jstring nick) {
struct euicc_ctx *ctx = (struct euicc_ctx *) handle;
const char *_iccid = NULL;
- jbyte *_nick = NULL;
+ const char *_nick = NULL;
int ret;
_iccid = (*env)->GetStringUTFChars(env, iccid, NULL);
- _nick = (*env)->GetByteArrayElements(env, nick, NULL);
- ret = es10c_set_nickname(ctx, _iccid, (const char *) _nick);
- (*env)->ReleaseByteArrayElements(env, nick, _nick, JNI_ABORT);
+ _nick = (*env)->GetStringUTFChars(env, nick, NULL);
+ ret = es10c_set_nickname(ctx, _iccid, _nick);
+ (*env)->ReleaseStringUTFChars(env, nick, _nick);
(*env)->ReleaseStringUTFChars(env, iccid, _iccid);
return ret;
}
@@ -246,48 +295,58 @@ Java_net_typeblog_lpac_1jni_LpacJni_es10cDeleteProfile(JNIEnv *env, jobject thiz
return ret;
}
-JNIEXPORT jlong JNICALL
+JNIEXPORT jobject JNICALL
Java_net_typeblog_lpac_1jni_LpacJni_es10cexGetEuiccInfo2(JNIEnv *env, jobject thiz, jlong handle) {
struct euicc_ctx *ctx = (struct euicc_ctx *) handle;
- struct es10c_ex_euiccinfo2 *info = malloc(sizeof(struct es10c_ex_euiccinfo2));
+ struct es10c_ex_euiccinfo2 info = {0};
+ jobjectArray euiccCiPKIdListForVerification = NULL;
+ jobjectArray euiccCiPKIdListForSigning = NULL;
+ jstring sas_accreditation_number = NULL;
+ jstring global_platform_version = NULL;
+ jstring euicc_firmware_version = NULL;
+ jstring profile_version = NULL;
+ jstring pp_version = NULL;
+ jobject ret = NULL;
+ char **curr = NULL;
+ int count = 0;
- if (es10c_ex_get_euiccinfo2(ctx, info) < 0) {
- free(info);
- return 0;
- }
+ if (es10c_ex_get_euiccinfo2(ctx, &info) < 0)
+ goto out;
- return (jlong) info;
-}
+ profile_version = toJString(env, info.profileVersion);
+ euicc_firmware_version = toJString(env, info.euiccFirmwareVer);
+ global_platform_version = toJString(env, info.globalplatformVersion);
+ sas_accreditation_number = toJString(env, info.sasAcreditationNumber);
+ pp_version = toJString(env, info.ppVersion);
+ count = LPAC_JNI_NULL_TERM_LIST_COUNT(info.euiccCiPKIdListForSigning, curr);
+ euiccCiPKIdListForSigning = (*env)->NewObjectArray(env, count, string_class, NULL);
+ LPAC_JNI_NULL_TERM_LIST_FOREACH(info.euiccCiPKIdListForSigning, curr, {
+ (*env)->SetObjectArrayElement(env, euiccCiPKIdListForSigning, i, toJString(env, *curr));
+ });
-JNIEXPORT jint JNICALL
-Java_net_typeblog_lpac_1jni_LpacJni_es10cEuiccMemoryReset(JNIEnv *env, jobject thiz, jlong handle) {
- struct euicc_ctx *ctx = (struct euicc_ctx *) handle;
- int ret;
- ret = es10c_euicc_memory_reset(ctx);
+ count = LPAC_JNI_NULL_TERM_LIST_COUNT(info.euiccCiPKIdListForVerification, curr);
+ euiccCiPKIdListForVerification = (*env)->NewObjectArray(env, count, string_class, NULL);
+ LPAC_JNI_NULL_TERM_LIST_FOREACH(info.euiccCiPKIdListForVerification, curr, {
+ (*env)->SetObjectArrayElement(env, euiccCiPKIdListForVerification, i,
+ toJString(env, *curr));
+ });
+
+ ret = (*env)->NewObject(env, euicc_info2_class, euicc_info2_constructor,
+ profile_version, euicc_firmware_version,
+ global_platform_version,
+ sas_accreditation_number, pp_version,
+ info.extCardResource.freeNonVolatileMemory,
+ info.extCardResource.freeVolatileMemory,
+ euiccCiPKIdListForSigning,
+ euiccCiPKIdListForVerification);
+
+ out:
+ (*env)->DeleteLocalRef(env, profile_version);
+ (*env)->DeleteLocalRef(env, euicc_firmware_version);
+ (*env)->DeleteLocalRef(env, global_platform_version);
+ (*env)->DeleteLocalRef(env, sas_accreditation_number);
+ (*env)->DeleteLocalRef(env, pp_version);
+ es10c_ex_euiccinfo2_free(&info);
return ret;
-}
-
-JNIEXPORT jstring JNICALL
-Java_net_typeblog_lpac_1jni_LpacJni_stringDeref(JNIEnv *env, jobject thiz, jlong curr) {
- return toJString(env, *((char **) curr));
-}
-
-void lpac_jni_euiccinfo2_free(struct es10c_ex_euiccinfo2 *info) {
- es10c_ex_euiccinfo2_free(info);
- free(info);
-}
-
-LPAC_JNI_STRUCT_GETTER_NULL_TERM_LIST_NEXT(char*, stringArr)
-LPAC_JNI_STRUCT_FREE(struct es10c_ex_euiccinfo2, euiccInfo2, lpac_jni_euiccinfo2_free)
-LPAC_JNI_STRUCT_GETTER_STRING(struct es10c_ex_euiccinfo2, euiccInfo2, svn, SGP22Version)
-LPAC_JNI_STRUCT_GETTER_STRING(struct es10c_ex_euiccinfo2, euiccInfo2, profileVersion, ProfileVersion)
-LPAC_JNI_STRUCT_GETTER_STRING(struct es10c_ex_euiccinfo2, euiccInfo2, euiccFirmwareVer, EuiccFirmwareVersion)
-LPAC_JNI_STRUCT_GETTER_STRING(struct es10c_ex_euiccinfo2, euiccInfo2, globalplatformVersion, GlobalPlatformVersion)
-LPAC_JNI_STRUCT_GETTER_STRING(struct es10c_ex_euiccinfo2, euiccInfo2, sasAcreditationNumber, SasAcreditationNumber)
-LPAC_JNI_STRUCT_GETTER_STRING(struct es10c_ex_euiccinfo2, euiccInfo2, ppVersion, PpVersion)
-LPAC_JNI_STRUCT_GETTER_LONG(struct es10c_ex_euiccinfo2, euiccInfo2, extCardResource.freeNonVolatileMemory, FreeNonVolatileMemory)
-LPAC_JNI_STRUCT_GETTER_LONG(struct es10c_ex_euiccinfo2, euiccInfo2, extCardResource.freeVolatileMemory, FreeVolatileMemory)
-
-LPAC_JNI_STRUCT_GETTER_LONG(struct es10c_ex_euiccinfo2, euiccInfo2, euiccCiPKIdListForSigning, EuiccCiPKIdListForSigning)
-LPAC_JNI_STRUCT_GETTER_LONG(struct es10c_ex_euiccinfo2, euiccInfo2, euiccCiPKIdListForVerification, EuiccCiPKIdListForVerification)
+}
\ No newline at end of file
diff --git a/libs/lpac-jni/src/main/jni/lpac-jni/lpac-jni.h b/libs/lpac-jni/src/main/jni/lpac-jni/lpac-jni.h
index c2300be..1915c5e 100644
--- a/libs/lpac-jni/src/main/jni/lpac-jni/lpac-jni.h
+++ b/libs/lpac-jni/src/main/jni/lpac-jni/lpac-jni.h
@@ -8,7 +8,6 @@ _Static_assert(sizeof(void *) <= sizeof(jlong),
"jlong must be big enough to hold a platform raw pointer");
struct lpac_jni_ctx {
- jint logical_channel_id;
jobject apdu_interface;
jobject http_interface;
};
@@ -18,42 +17,37 @@ struct lpac_jni_ctx {
JNIEnv *env; \
(*jvm)->AttachCurrentThread(jvm, &env, NULL)
+#define __LPAC_JNI_LINKED_LIST_FOREACH(list, curr, body, after) { \
+ int i = 0; \
+ curr = list; \
+ while (curr != NULL) { \
+ body; \
+ curr = curr->next; \
+ i++; \
+ }; \
+ after; \
+}
+#define LPAC_JNI_LINKED_LIST_FOREACH(list, curr, body) \
+ __LPAC_JNI_LINKED_LIST_FOREACH(list, curr, body, {})
+#define LPAC_JNI_LINKED_LIST_COUNT(list, curr) \
+ (__LPAC_JNI_LINKED_LIST_FOREACH(list, curr, {}, i))
+
+#define __LPAC_JNI_NULL_TERM_LIST_FOREACH(list, curr, body, after) { \
+ int i = 0; \
+ curr = list; \
+ while (*curr != NULL) { \
+ body; \
+ curr++; \
+ i++; \
+ }; \
+ after; \
+}
+#define LPAC_JNI_NULL_TERM_LIST_FOREACH(list, curr, body) \
+ __LPAC_JNI_NULL_TERM_LIST_FOREACH(list, curr, body, {})
+#define LPAC_JNI_NULL_TERM_LIST_COUNT(list, curr) \
+ (__LPAC_JNI_NULL_TERM_LIST_FOREACH(list, curr, {}, i))
+
extern JavaVM *jvm;
extern jclass string_class;
-jstring toJString(JNIEnv *env, const char *pat);
-
-#define LPAC_JNI_STRUCT_GETTER_LINKED_LIST_NEXT(st, st_jname) \
- JNIEXPORT jlong JNICALL Java_net_typeblog_lpac_1jni_LpacJni_##st_jname##Next(JNIEnv *env, jobject thiz, jlong raw) { \
- st *p = (st *) raw; \
- if (p == NULL) return 0; \
- return (jlong) p->next; \
- }
-
-#define LPAC_JNI_STRUCT_GETTER_NULL_TERM_LIST_NEXT(st, st_jname) \
- JNIEXPORT jlong JNICALL Java_net_typeblog_lpac_1jni_LpacJni_##st_jname##Next(JNIEnv *env, jobject thiz, jlong raw) { \
- st *p = (st *) raw; \
- p++; \
- if (*p == NULL) return 0; \
- return (jlong) p; \
- }
-
-#define LPAC_JNI_STRUCT_FREE(st, st_jname, free_func) \
- JNIEXPORT void JNICALL Java_net_typeblog_lpac_1jni_LpacJni_##st_jname##Free(JNIEnv *env, jobject thiz, jlong raw) { \
- st *p = (st *) raw; \
- if (p == NULL) return; \
- free_func(p); \
- }
-
-#define LPAC_JNI_STRUCT_GETTER_LONG(st, st_name, name, jname) \
- JNIEXPORT jlong JNICALL Java_net_typeblog_lpac_1jni_LpacJni_##st_name##Get##jname(JNIEnv *env, jobject thiz, jlong raw) { \
- st *p = (st *) raw; \
- if (p == NULL) return 0; \
- return (jlong) p->name; \
- }
-
-#define LPAC_JNI_STRUCT_GETTER_STRING(st, st_name, name, jname) \
- JNIEXPORT jstring JNICALL Java_net_typeblog_lpac_1jni_LpacJni_##st_name##Get##jname(JNIEnv *env, jobject thiz, jlong raw) { \
- st *p = (st *) raw; \
- return toJString(env, p->name); \
- }
\ No newline at end of file
+jstring toJString(JNIEnv *env, const char *pat);
\ No newline at end of file
diff --git a/libs/lpac-jni/src/main/jni/lpac-jni/lpac-notifications.c b/libs/lpac-jni/src/main/jni/lpac-jni/lpac-notifications.c
index cf402cf..1a5ac7c 100644
--- a/libs/lpac-jni/src/main/jni/lpac-jni/lpac-notifications.c
+++ b/libs/lpac-jni/src/main/jni/lpac-jni/lpac-notifications.c
@@ -4,15 +4,88 @@
#include
#include
-JNIEXPORT jlong JNICALL
+jclass local_profile_notification_class;
+jmethodID local_profile_notification_constructor;
+
+jclass local_profile_notification_operation_class;
+jmethodID local_profile_notification_operation_from_string;
+
+void lpac_notifications_init() {
+ LPAC_JNI_SETUP_ENV;
+
+ local_profile_notification_class =
+ (*env)->FindClass(env, "net/typeblog/lpac_jni/LocalProfileNotification");
+ local_profile_notification_class =
+ (*env)->NewGlobalRef(env, local_profile_notification_class);
+ local_profile_notification_constructor =
+ (*env)->GetMethodID(env, local_profile_notification_class, "",
+ "(JLnet/typeblog/lpac_jni/LocalProfileNotification$Operation;Ljava/lang/String;Ljava/lang/String;)V");
+
+ local_profile_notification_operation_class =
+ (*env)->FindClass(env, "net/typeblog/lpac_jni/LocalProfileNotification$Operation");
+ local_profile_notification_operation_class =
+ (*env)->NewGlobalRef(env, local_profile_notification_operation_class);
+ local_profile_notification_operation_from_string =
+ (*env)->GetStaticMethodID(env, local_profile_notification_operation_class, "fromString",
+ "(Ljava/lang/String;)Lnet/typeblog/lpac_jni/LocalProfileNotification$Operation;");
+}
+
+JNIEXPORT jobject JNICALL
Java_net_typeblog_lpac_1jni_LpacJni_es10bListNotification(JNIEnv *env, jobject thiz, jlong handle) {
struct euicc_ctx *ctx = (struct euicc_ctx *) handle;
struct es10b_notification_metadata_list *info = NULL;
+ struct es10b_notification_metadata_list *curr = NULL;
+ const char *profileManagementOperationStr = NULL;
+ jobject notification = NULL;
+ jobject operation = NULL;
+ jobjectArray ret = NULL;
+ int count = 0;
if (es10b_list_notification(ctx, &info) < 0)
- return 0;
+ return NULL;
- return (jlong) info;
+ count = LPAC_JNI_LINKED_LIST_COUNT(info, curr);
+
+ ret = (*env)->NewObjectArray(env, count, local_profile_notification_class, NULL);
+
+ LPAC_JNI_LINKED_LIST_FOREACH(info, curr, {
+ switch (curr->profileManagementOperation) {
+ case ES10B_PROFILE_MANAGEMENT_OPERATION_INSTALL:
+ profileManagementOperationStr = "install";
+ break;
+ case ES10B_PROFILE_MANAGEMENT_OPERATION_DELETE:
+ profileManagementOperationStr = "delete";
+ break;
+ case ES10B_PROFILE_MANAGEMENT_OPERATION_ENABLE:
+ profileManagementOperationStr = "enable";
+ break;
+ case ES10B_PROFILE_MANAGEMENT_OPERATION_DISABLE:
+ profileManagementOperationStr = "disable";
+ break;
+ default:
+ profileManagementOperationStr = "unknown";
+ }
+
+ operation =
+ (*env)->CallStaticObjectMethod(env, local_profile_notification_operation_class,
+ local_profile_notification_operation_from_string,
+ toJString(env, profileManagementOperationStr));
+
+ notification =
+ (*env)->NewObject(env, local_profile_notification_class,
+ local_profile_notification_constructor, curr->seqNumber,
+ operation,
+ toJString(env, curr->notificationAddress),
+ toJString(env, curr->iccid));
+
+ (*env)->SetObjectArrayElement(env, ret, i, notification);
+
+ (*env)->DeleteLocalRef(env, operation);
+ (*env)->DeleteLocalRef(env, notification);
+ });
+
+ es10b_notification_metadata_list_free_all(info);
+ return ret;
}
JNIEXPORT jint JNICALL
@@ -44,36 +117,4 @@ Java_net_typeblog_lpac_1jni_LpacJni_es10bDeleteNotification(JNIEnv *env, jobject
jlong seq_number) {
struct euicc_ctx *ctx = (struct euicc_ctx *) handle;
return es10b_remove_notification_from_list(ctx, (unsigned long) seq_number);
-}
-
-JNIEXPORT jstring JNICALL
-Java_net_typeblog_lpac_1jni_LpacJni_notificationGetOperationString(JNIEnv *env, jobject thiz,
- jlong curr) {
- struct es10b_notification_metadata_list *info = (struct es10b_notification_metadata_list *) curr;
- const char *profileManagementOperationStr = NULL;
- switch (info->profileManagementOperation) {
- case ES10B_PROFILE_MANAGEMENT_OPERATION_INSTALL:
- profileManagementOperationStr = "install";
- break;
- case ES10B_PROFILE_MANAGEMENT_OPERATION_DELETE:
- profileManagementOperationStr = "delete";
- break;
- case ES10B_PROFILE_MANAGEMENT_OPERATION_ENABLE:
- profileManagementOperationStr = "enable";
- break;
- case ES10B_PROFILE_MANAGEMENT_OPERATION_DISABLE:
- profileManagementOperationStr = "disable";
- break;
- default:
- profileManagementOperationStr = "unknown";
- break;
- }
-
- return toJString(env, profileManagementOperationStr);
-}
-
-LPAC_JNI_STRUCT_GETTER_LINKED_LIST_NEXT(struct es10b_notification_metadata_list, notifications)
-LPAC_JNI_STRUCT_FREE(struct es10b_notification_metadata_list, notifications, es10b_notification_metadata_list_free_all)
-LPAC_JNI_STRUCT_GETTER_LONG(struct es10b_notification_metadata_list, notification, seqNumber, Seq)
-LPAC_JNI_STRUCT_GETTER_STRING(struct es10b_notification_metadata_list, notification, notificationAddress, Address)
-LPAC_JNI_STRUCT_GETTER_STRING(struct es10b_notification_metadata_list, notification, iccid, Iccid)
+}
\ No newline at end of file
diff --git a/libs/lpac-jni/src/main/jni/lpac-jni/lpac-notifications.h b/libs/lpac-jni/src/main/jni/lpac-jni/lpac-notifications.h
index 511de2f..0b88555 100644
--- a/libs/lpac-jni/src/main/jni/lpac-jni/lpac-notifications.h
+++ b/libs/lpac-jni/src/main/jni/lpac-jni/lpac-notifications.h
@@ -2,3 +2,5 @@
#include
#include "lpac-jni.h"
+
+void lpac_notifications_init();
\ No newline at end of file
diff --git a/privapp_whitelist_im.angry.openeuicc.xml b/privapp_whitelist_im.angry.openeuicc.xml
index 0f117b6..88d35cc 100644
--- a/privapp_whitelist_im.angry.openeuicc.xml
+++ b/privapp_whitelist_im.angry.openeuicc.xml
@@ -5,7 +5,5 @@
-
-