Compare commits
167 commits
unpriv-v1.
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 6837aba211 | |||
| eec2a105ff | |||
| d4855f130c | |||
| 2108696646 | |||
| 6210c81201 | |||
| 0a353a3df6 | |||
| 713ffec26d | |||
| c676c27338 | |||
| 81810b22fb | |||
| fdde41329b | |||
| 2cf2d9490a | |||
| b9863e2e54 | |||
| 56fbd34616 | |||
| 419db21b12 | |||
| 9496370135 | |||
| 84f57a4ef7 | |||
| a75478dd31 | |||
| f17e171372 | |||
| e60f98fdef | |||
| 31991c909d | |||
| 392a2927cb | |||
| f3dbba0229 | |||
| 0c305ff6ff | |||
| e5568e2164 | |||
| 639c1d0ea6 | |||
| d7fb53ce5c | |||
| d40b839911 | |||
| 76ef63efdf | |||
| b7fc164a3f | |||
| 19b127df3f | |||
| aca541593c | |||
| fd79236591 | |||
| f498c22ad8 | |||
| c23ad21421 | |||
| 65a4c887f1 | |||
| 2bb10c72f6 | |||
| 7ca832f68e | |||
| 7e1c4907bb | |||
| 22a7a5145c | |||
| 6e5bbc4085 | |||
| 709a962314 | |||
| 755499e878 | |||
| 6b0e058d5c | |||
| 1938a4ff5a | |||
| f2c7e79bee | |||
| 552aba87c0 | |||
| cd34597362 | |||
| c396223a02 | |||
| 69fe2764c9 | |||
| 8ec0757e28 | |||
| 55e7731197 | |||
| 938e298ca3 | |||
| 8f51abe1af | |||
| 5e7dfd36ab | |||
| 4d43ab4824 | |||
| 4e873f4e88 | |||
| ebdffc5032 | |||
| cc9f99a2a9 | |||
| 3821cb7de0 | |||
| 1933cffd82 | |||
| 987eb4f71b | |||
| 418010ba69 | |||
| f3f97cc942 | |||
| af6270add2 | |||
| d0bd5e7dfb | |||
| 3b0e25b8ab | |||
| c74c1f309c | |||
| b245a9c893 | |||
| 351567a972 | |||
| 0096b9005f | |||
| 525212c1b8 | |||
| bf30f1478c | |||
| 2cda633fd0 | |||
| 7db1c1ea9d | |||
| d46461bd2d | |||
| 472f9d05ac | |||
| 0c98121c2a | |||
| acfeda8dc9 | |||
| 7bae82daf9 | |||
| cce247e747 | |||
| 915a05634b | |||
| 9e40232ed0 | |||
| 27b7e50b97 | |||
| 7e7f5c2b05 | |||
| 4d8b8e8fb5 | |||
| a8b7482afb | |||
| 3fed4b2bd6 | |||
| deb0a372b1 | |||
| 72ec20f824 | |||
| 7c2157daa4 | |||
| e604f39e0d | |||
| 797f3dc722 | |||
| 1be6c25cb6 | |||
| c0cd7a25cf | |||
| dfdd8948c5 | |||
| 1fd13634fc | |||
| 29b2cba673 | |||
| 8c982ae890 | |||
| eb006b8f19 | |||
| 0506475a85 | |||
| 0b4d065d4b | |||
| 52cf68d43d | |||
| 4c221f74ff | |||
| 4991f2580e | |||
| 65775c1d06 | |||
| cbe3d1fd50 | |||
| 677b69cedf | |||
| 6d43a9207c | |||
| f056e2d313 | |||
| 4ac0820bbf | |||
|
c0dc8ac19d |
|||
| 21c04ed179 | |||
| db4645b17f | |||
| 149a19ca1c | |||
| eaef00b88a | |||
| 023f6ded28 | |||
| a601ab7d72 | |||
| 756c621d5e | |||
| 68114fa863 | |||
| 1fda120459 | |||
| 994324acb6 | |||
| 6c774450ec | |||
| 00ddf09287 | |||
| 3662f93760 | |||
| 05abed117a | |||
| 92fbfc5229 | |||
| d7bfd84de9 | |||
| c6963feb17 | |||
| dc6b3a4810 | |||
| e08f8beb45 | |||
| 6b169c505d | |||
| 33d383a3ce | |||
| 291869207a | |||
| a6286ed097 | |||
| 360760b78f | |||
| b9849afe18 | |||
| 88eb1ce0e2 | |||
| 74cc08ce8e | |||
| f6c50490b8 | |||
| c2659ddb69 | |||
| 5dd9eed4fe | |||
| 17102be7cb | |||
| ece231f17b | |||
| db8063cd5f | |||
| d3df70501a | |||
| 53f9459aed | |||
| 6557ce45a7 | |||
| 2b86d719dd | |||
| 7edde1ffa4 | |||
| e5753ec2d9 | |||
| c528962f29 | |||
| 889b08767c | |||
| 8243914588 | |||
| 2eabf719d0 | |||
| d068261ff9 | |||
| 6a5d4b9288 | |||
| 1313bfd24e | |||
| 99d9200c28 | |||
| 65c7f8de83 | |||
| 6c9063a761 | |||
| d5aefcaec7 | |||
| ef295c9d12 | |||
| 1d67fa5cfa | |||
| c8ecdee095 | |||
| 03bfdf373c | |||
| 9517f53712 | |||
| f5074acae2 |
257 changed files with 6758 additions and 3380 deletions
22
.editorconfig
Normal file
22
.editorconfig
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
indent_size = 2
|
||||
indent_style = space
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
max_line_length = 120
|
||||
|
||||
[*.{kt,java}]
|
||||
indent_size = 4
|
||||
|
||||
[*.gradle.kts]
|
||||
indent_size = 4
|
||||
|
||||
[*.xml]
|
||||
indent_size = 4
|
||||
|
||||
[.idea/**/*.xml]
|
||||
indent_size = 2
|
||||
|
|
@ -1,11 +1,15 @@
|
|||
name: Build Debug APKs
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- 'master'
|
||||
- '*'
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
build-debug:
|
||||
runs-on: [docker, android-app-certs]
|
||||
runs-on: [ docker, android-app-certs ]
|
||||
container:
|
||||
volumes:
|
||||
- android-app-keystore:/keystore
|
||||
|
|
@ -33,14 +37,23 @@ jobs:
|
|||
uses: https://gitea.angry.im/actions/setup-android@v3
|
||||
|
||||
- name: Build Debug APKs
|
||||
run: ./gradlew --no-daemon assembleDebug
|
||||
run: ./gradlew --no-daemon assembleDebug :app:assembleDebugMagiskModuleDir
|
||||
|
||||
- name: Copy Artifacts
|
||||
run: find . -name 'app*-debug.apk' -exec cp {} . \;
|
||||
run: |
|
||||
find . -name 'app*-debug.apk' -exec cp {} . \;
|
||||
cp -r app/build/magisk/debug ./magisk-debug
|
||||
|
||||
- name: Upload Artifacts
|
||||
- name: Upload APK 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
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
name: Build Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: '*'
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: [docker, android-app-certs]
|
||||
runs-on: [ docker, android-app-certs ]
|
||||
container:
|
||||
volumes:
|
||||
- android-app-keystore:/keystore
|
||||
|
|
|
|||
5
.gitmodules
vendored
5
.gitmodules
vendored
|
|
@ -1,3 +1,6 @@
|
|||
[submodule "libs/lpac-jni/src/main/jni/lpac"]
|
||||
path = libs/lpac-jni/src/main/jni/lpac
|
||||
url = https://github.com/estkme/lpac
|
||||
url = https://github.com/estkme-group/lpac.git
|
||||
[submodule "libs/lpac-jni/src/main/jni/cJSON"]
|
||||
path = libs/lpac-jni/src/main/jni/cjson/cjson
|
||||
url = https://github.com/DaveGamble/cJSON
|
||||
|
|
|
|||
20
.idea/.gitignore
generated
vendored
20
.idea/.gitignore
generated
vendored
|
|
@ -1,13 +1,7 @@
|
|||
/shelf
|
||||
/caches
|
||||
/libraries
|
||||
/assetWizardSettings.xml
|
||||
/deploymentTargetDropDown.xml
|
||||
/gradle.xml
|
||||
/misc.xml
|
||||
/modules.xml
|
||||
/navEditor.xml
|
||||
/runConfigurations.xml
|
||||
/workspace.xml
|
||||
|
||||
**/*.iml
|
||||
*
|
||||
!/codeStyles/Project.xml
|
||||
!/codeStyles/codeStyleConfig.xml
|
||||
!/vcs.xml
|
||||
!/kotlinc.xml
|
||||
!/compiler.xml
|
||||
!/migrations.xml
|
||||
|
|
|
|||
45
.idea/codeStyles/Project.xml
generated
45
.idea/codeStyles/Project.xml
generated
|
|
@ -1,5 +1,47 @@
|
|||
<component name="ProjectCodeStyleConfiguration">
|
||||
<code_scheme name="Project" version="173">
|
||||
<JavaCodeStyleSettings>
|
||||
<option name="IMPORT_LAYOUT_TABLE">
|
||||
<value>
|
||||
<package name="android" withSubpackages="true" static="true" />
|
||||
<package name="androidx" withSubpackages="true" static="true" />
|
||||
<package name="com" withSubpackages="true" static="true" />
|
||||
<package name="junit" withSubpackages="true" static="true" />
|
||||
<package name="net" withSubpackages="true" static="true" />
|
||||
<package name="org" withSubpackages="true" static="true" />
|
||||
<package name="java" withSubpackages="true" static="true" />
|
||||
<package name="javax" withSubpackages="true" static="true" />
|
||||
<package name="" withSubpackages="true" static="true" />
|
||||
<emptyLine />
|
||||
<package name="android" withSubpackages="true" static="false" />
|
||||
<emptyLine />
|
||||
<package name="androidx" withSubpackages="true" static="false" />
|
||||
<emptyLine />
|
||||
<package name="com" withSubpackages="true" static="false" />
|
||||
<emptyLine />
|
||||
<package name="junit" withSubpackages="true" static="false" />
|
||||
<emptyLine />
|
||||
<package name="net" withSubpackages="true" static="false" />
|
||||
<emptyLine />
|
||||
<package name="org" withSubpackages="true" static="false" />
|
||||
<emptyLine />
|
||||
<package name="java" withSubpackages="true" static="false" />
|
||||
<emptyLine />
|
||||
<package name="javax" withSubpackages="true" static="false" />
|
||||
<emptyLine />
|
||||
<package name="" withSubpackages="true" static="false" />
|
||||
<emptyLine />
|
||||
</value>
|
||||
</option>
|
||||
</JavaCodeStyleSettings>
|
||||
<JetCodeStyleSettings>
|
||||
<option name="PACKAGES_TO_USE_STAR_IMPORTS">
|
||||
<value>
|
||||
<package name="im.angry.openeuicc.util" alias="false" withSubpackages="true" />
|
||||
</value>
|
||||
</option>
|
||||
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
|
||||
</JetCodeStyleSettings>
|
||||
<codeStyleSettings language="XML">
|
||||
<option name="FORCE_REARRANGE_MODE" value="1" />
|
||||
<indentOptions>
|
||||
|
|
@ -113,5 +155,8 @@
|
|||
</rules>
|
||||
</arrangement>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="kotlin">
|
||||
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
|
||||
</codeStyleSettings>
|
||||
</code_scheme>
|
||||
</component>
|
||||
2
.idea/codeStyles/codeStyleConfig.xml
generated
2
.idea/codeStyles/codeStyleConfig.xml
generated
|
|
@ -1,5 +1,5 @@
|
|||
<component name="ProjectCodeStyleConfiguration">
|
||||
<state>
|
||||
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
|
||||
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
|
||||
</state>
|
||||
</component>
|
||||
2
.idea/compiler.xml
generated
2
.idea/compiler.xml
generated
|
|
@ -3,4 +3,4 @@
|
|||
<component name="CompilerConfiguration">
|
||||
<bytecodeTargetLevel target="1.7" />
|
||||
</component>
|
||||
</project>
|
||||
</project>
|
||||
|
|
|
|||
13
.idea/deploymentTargetSelector.xml
generated
13
.idea/deploymentTargetSelector.xml
generated
|
|
@ -1,13 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="deploymentTargetSelector">
|
||||
<selectionStates>
|
||||
<SelectionState runConfigName="app-unpriv">
|
||||
<option name="selectionMode" value="DROPDOWN" />
|
||||
</SelectionState>
|
||||
<SelectionState runConfigName="app">
|
||||
<option name="selectionMode" value="DROPDOWN" />
|
||||
</SelectionState>
|
||||
</selectionStates>
|
||||
</component>
|
||||
</project>
|
||||
4
.idea/kotlinc.xml
generated
4
.idea/kotlinc.xml
generated
|
|
@ -1,6 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="KotlinJpsPluginSettings">
|
||||
<option name="version" value="1.9.20" />
|
||||
<option name="version" value="1.9.24" />
|
||||
</component>
|
||||
</project>
|
||||
</project>
|
||||
|
|
|
|||
2
.idea/migrations.xml
generated
2
.idea/migrations.xml
generated
|
|
@ -7,4 +7,4 @@
|
|||
</set>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
</project>
|
||||
|
|
|
|||
2
.idea/vcs.xml
generated
2
.idea/vcs.xml
generated
|
|
@ -4,4 +4,4 @@
|
|||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
<mapping directory="$PROJECT_DIR$/libs/lpac-jni/src/main/jni/lpac" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
</project>
|
||||
|
|
|
|||
115
README.md
115
README.md
|
|
@ -2,25 +2,53 @@
|
|||
|
||||
A fully free and open-source Local Profile Assistant implementation for Android devices.
|
||||
|
||||
There are two variants of this project:
|
||||
There are two variants of this project, OpenEUICC and [EasyEUICC](https://easyeuicc.org):
|
||||
|
||||
- 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).
|
||||
- __Note__: 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.
|
||||
- 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`
|
||||
| | 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 |
|
||||
|
||||
__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.
|
||||
[^1]: Also known as "Removable eSIM"
|
||||
[^2]: Carrier Partner API unimplemented yet
|
||||
|
||||
__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.__
|
||||
Some side notes:
|
||||
|
||||
Building (Gradle)
|
||||
===
|
||||
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)
|
||||
|
||||
Make sure you have all submodules cloned and updated by running
|
||||
|
||||
|
|
@ -53,41 +81,50 @@ For EasyEUICC:
|
|||
./gradlew :app-unpriv:assembleRelease
|
||||
```
|
||||
|
||||
Building (AOSP)
|
||||
===
|
||||
# Building (AOSP)
|
||||
|
||||
There are two ways to include OpenEUICC in your AOSP-based system image:
|
||||
|
||||
1. Include this project and its [dependencies](https://gitea.angry.im/PeterCxy/android_prebuilts_openeuicc-deps) inside the AOSP tree.
|
||||
- If inclusion in `manifest.xml` is required, remember to set the `sync-s` option to clone submodules.
|
||||
- The module name is `OpenEUICC`. You can include it in `PRODUCT_PACKAGES`, or simply build it standalone using `mm`.
|
||||
- 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.
|
||||
1. Include this project and its [dependencies](https://gitea.angry.im/PeterCxy/android_prebuilts_openeuicc-deps) inside
|
||||
the AOSP tree.
|
||||
|
||||
FAQs
|
||||
===
|
||||
- If inclusion in `manifest.xml` is required, remember to set the `sync-s` option to clone submodules.
|
||||
- The module name is `OpenEUICC`. You can include it in `PRODUCT_PACKAGES`, or simply build it standalone using `mm`.
|
||||
- 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.
|
||||
|
||||
- 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.
|
||||
2. If compilation against AOSP source tree is not possible, consider [building with gradle](#building-gradle) and import
|
||||
the apk as a prebuilt.
|
||||
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
- 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.
|
||||
[`privapp_whitelist_im.angry.openeuicc.xml`]: privapp_whitelist_im.angry.openeuicc.xml "OpenEUICC Privapp Whitelist"
|
||||
|
||||
- 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.
|
||||
# FAQs
|
||||
|
||||
Copyright
|
||||
===
|
||||
- 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: 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.
|
||||
|
||||
# Copyright
|
||||
|
||||
Everything except `libs/lpac-jni` and `art/`:
|
||||
|
||||
```
|
||||
Copyright 2022-2024 OpenEUICC contributors
|
||||
Copyright 2022-2026 OpenEUICC contributors
|
||||
|
||||
This program is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU General Public License
|
||||
|
|
@ -106,7 +143,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
|||
`libs/lpac-jni`:
|
||||
|
||||
```
|
||||
Copyright (C) 2022-2024 OpenEUICC contributiors
|
||||
Copyright (C) 2022-2026 OpenEUICC contributiors
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
|
|
@ -122,4 +159,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.
|
||||
|
|
|
|||
|
|
@ -1,13 +1,11 @@
|
|||
package im.angry.openeuicc.common
|
||||
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
import org.junit.Assert.*
|
||||
|
||||
/**
|
||||
* Instrumented test, which will execute on an Android device.
|
||||
*
|
||||
|
|
@ -21,4 +19,4 @@ class ExampleInstrumentedTest {
|
|||
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
assertEquals("im.angry.openeuicc.common.test", appContext.packageName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,13 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:tools="http://schemas.android.com/tools"
|
||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
package="im.angry.openeuicc.common">
|
||||
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
|
||||
<application
|
||||
android:enableOnBackInvokedCallback="true"
|
||||
|
|
@ -28,13 +29,33 @@
|
|||
android:label="@string/pref_advanced_logs" />
|
||||
|
||||
<activity
|
||||
android:exported="true"
|
||||
android:name="im.angry.openeuicc.ui.IsdrAidListActivity"
|
||||
android:label="@string/isdr_aid_list" />
|
||||
|
||||
<activity
|
||||
android:name="im.angry.openeuicc.ui.wizard.DownloadWizardActivity"
|
||||
android:label="@string/download_wizard" />
|
||||
android:exported="true"
|
||||
android:label="@string/download_wizard">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
|
||||
<!-- Accepts URIs that begin with "lpa:" -->
|
||||
<!-- for example: "LPA:1$..." -->
|
||||
<!-- refs: https://www.iana.org/assignments/uri-schemes/prov/lpa -->
|
||||
<data android:scheme="lpa" />
|
||||
<data
|
||||
android:scheme="LPA"
|
||||
tools:ignore="AppLinkUrlError" />
|
||||
<data android:sspPrefix="1$" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity-alias
|
||||
android:exported="true"
|
||||
android:name="im.angry.openeuicc.ui.DirectProfileDownloadActivity"
|
||||
android:exported="true"
|
||||
android:targetActivity="im.angry.openeuicc.ui.wizard.DownloadWizardActivity" />
|
||||
|
||||
<activity
|
||||
|
|
@ -44,7 +65,7 @@
|
|||
|
||||
<service
|
||||
android:name="im.angry.openeuicc.service.EuiccChannelManagerService"
|
||||
android:foregroundServiceType="shortService"
|
||||
android:exported="false" />
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="shortService" />
|
||||
</application>
|
||||
</manifest>
|
||||
|
|
|
|||
|
|
@ -1,87 +1,91 @@
|
|||
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.getIoEndpoints
|
||||
import im.angry.openeuicc.core.usb.UsbCcidContext
|
||||
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): EuiccChannel? {
|
||||
override suspend fun tryOpenEuiccChannel(
|
||||
port: UiccPortInfoCompat,
|
||||
isdrAid: ByteArray,
|
||||
seId: EuiccChannel.SecureElementId,
|
||||
): EuiccChannel? = try {
|
||||
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}")
|
||||
try {
|
||||
return EuiccChannelImpl(
|
||||
context.getString(R.string.omapi),
|
||||
Log.i(
|
||||
DefaultEuiccChannelManager.TAG,
|
||||
"Trying OMAPI for physical slot ${port.card.physicalSlotIndex}"
|
||||
)
|
||||
EuiccChannelImpl(
|
||||
context.getString(R.string.channel_type_omapi),
|
||||
port,
|
||||
OmapiApduInterface(
|
||||
seService!!,
|
||||
port,
|
||||
intrinsicChannelName = null,
|
||||
OmapiApduInterface(
|
||||
seService!!,
|
||||
port,
|
||||
context.preferenceRepository.verboseLoggingFlow
|
||||
),
|
||||
context.preferenceRepository.verboseLoggingFlow,
|
||||
context.preferenceRepository.ignoreTLSCertificateFlow,
|
||||
).also {
|
||||
Log.i(DefaultEuiccChannelManager.TAG, "Is OMAPI channel, setting MSS to 60")
|
||||
it.lpa.setEs10xMss(60)
|
||||
}
|
||||
} catch (e: IllegalArgumentException) {
|
||||
// Failed
|
||||
Log.w(
|
||||
DefaultEuiccChannelManager.TAG,
|
||||
"OMAPI APDU interface unavailable for physical slot ${port.card.physicalSlotIndex}."
|
||||
)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
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 EuiccChannelImpl(
|
||||
context.getString(R.string.usb),
|
||||
FakeUiccPortInfoCompat(FakeUiccCardInfoCompat(EuiccChannelManager.USB_CHANNEL_ID)),
|
||||
intrinsicChannelName = usbDevice.productName,
|
||||
UsbApduInterface(
|
||||
conn,
|
||||
bulkIn,
|
||||
bulkOut,
|
||||
context.preferenceRepository.verboseLoggingFlow
|
||||
),
|
||||
isdrAid,
|
||||
seId,
|
||||
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
|
||||
}
|
||||
|
||||
override fun tryOpenUsbEuiccChannel(
|
||||
ccidCtx: UsbCcidContext,
|
||||
isdrAid: ByteArray,
|
||||
seId: EuiccChannel.SecureElementId
|
||||
): EuiccChannel? = try {
|
||||
EuiccChannelImpl(
|
||||
context.getString(R.string.channel_type_usb),
|
||||
FakeUiccPortInfoCompat(FakeUiccCardInfoCompat(EuiccChannelManager.USB_CHANNEL_ID)),
|
||||
UsbApduInterface(
|
||||
ccidCtx
|
||||
),
|
||||
isdrAid,
|
||||
seId,
|
||||
context.preferenceRepository.verboseLoggingFlow,
|
||||
context.preferenceRepository.ignoreTLSCertificateFlow,
|
||||
context.preferenceRepository.es10xMssFlow,
|
||||
)
|
||||
} catch (_: IllegalArgumentException) {
|
||||
// Failed
|
||||
Log.w(
|
||||
DefaultEuiccChannelManager.TAG,
|
||||
"USB APDU interface unavailable for ISD-R AID: ${isdrAid.encodeHex()}."
|
||||
)
|
||||
null
|
||||
}
|
||||
|
||||
override fun cleanup() {
|
||||
seService?.shutdown()
|
||||
seService = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,12 +5,15 @@ import android.hardware.usb.UsbDevice
|
|||
import android.hardware.usb.UsbManager
|
||||
import android.telephony.SubscriptionManager
|
||||
import android.util.Log
|
||||
import im.angry.openeuicc.core.usb.getSmartCardInterface
|
||||
import im.angry.openeuicc.core.usb.UsbCcidContext
|
||||
import im.angry.openeuicc.core.usb.interfaces
|
||||
import im.angry.openeuicc.core.usb.smartCard
|
||||
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
|
||||
|
|
@ -29,7 +32,7 @@ open class DefaultEuiccChannelManager(
|
|||
|
||||
private val channelCache = mutableListOf<EuiccChannel>()
|
||||
|
||||
private var usbChannel: EuiccChannel? = null
|
||||
private var usbChannels = mutableListOf<EuiccChannel>()
|
||||
|
||||
private val lock = Mutex()
|
||||
|
||||
|
|
@ -48,25 +51,94 @@ open class DefaultEuiccChannelManager(
|
|||
protected open val uiccCards: Collection<UiccCardInfoCompat>
|
||||
get() = (0..<tm.activeModemCountCompat).map { FakeUiccCardInfoCompat(it) }
|
||||
|
||||
private suspend fun tryOpenEuiccChannel(port: UiccPortInfoCompat): EuiccChannel? {
|
||||
lock.withLock {
|
||||
if (port.card.physicalSlotIndex == EuiccChannelManager.USB_CHANNEL_ID) {
|
||||
return if (usbChannel != null && usbChannel!!.valid) {
|
||||
usbChannel
|
||||
} else {
|
||||
usbChannel = null
|
||||
null
|
||||
private suspend inline fun tryOpenChannelWithKnownAids(
|
||||
openFn: (ByteArray, EuiccChannel.SecureElementId) -> EuiccChannel?
|
||||
): List<EuiccChannel> {
|
||||
var isdrAidList =
|
||||
parseIsdrAidList(appContainer.preferenceRepository.isdrAidListFlow.first())
|
||||
val ret = mutableListOf<EuiccChannel>()
|
||||
val openedAids = mutableListOf<ByteArray>()
|
||||
var hasReset = false
|
||||
var vendorDecider: VendorAidDecider? = null
|
||||
var seId = 0
|
||||
|
||||
outer@ while (true) {
|
||||
for (aid in isdrAidList) {
|
||||
if (vendorDecider != null && !vendorDecider.shouldOpenMore(openedAids, aid)) {
|
||||
break@outer
|
||||
}
|
||||
|
||||
val channel =
|
||||
openFn(aid, EuiccChannel.SecureElementId.createFromInt(seId))?.let { channel ->
|
||||
if (channel.valid) {
|
||||
seId += 1
|
||||
channel
|
||||
} else {
|
||||
channel.close()
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasReset) {
|
||||
val res = channel?.queryVendorAidListTransformation(isdrAidList)
|
||||
if (res != null) {
|
||||
// Reset the for loop since we needed to replace the AID list due to vendor-specific code
|
||||
Log.i(TAG, "AID list replaced, resetting open attempt")
|
||||
isdrAidList = res.first
|
||||
vendorDecider = res.second
|
||||
seId = 0
|
||||
ret.clear()
|
||||
openedAids.clear()
|
||||
channel.close()
|
||||
hasReset = true // Don't let anything reset again
|
||||
continue@outer
|
||||
}
|
||||
}
|
||||
|
||||
if (channel != null) {
|
||||
ret.add(channel)
|
||||
openedAids.add(aid)
|
||||
|
||||
// Don't try opening more than 1 channel unless there is a vendor
|
||||
// implementation for deciding when we should stop opening more channels
|
||||
if (vendorDecider == null) {
|
||||
break@outer
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we get here we should exit, since the inner loop completed without resetting
|
||||
break
|
||||
}
|
||||
|
||||
// Set the hasMultipleSE field now since we only get to know that after we have iterated all AIDs
|
||||
// This also flips a flag in EuiccChannelImpl and prevents the field from being set again
|
||||
ret.forEach { it.hasMultipleSE = (seId > 1) }
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
private suspend fun tryOpenEuiccChannel(
|
||||
port: UiccPortInfoCompat,
|
||||
): List<EuiccChannel>? {
|
||||
lock.withLock {
|
||||
if (port.card.physicalSlotIndex == EuiccChannelManager.USB_CHANNEL_ID) {
|
||||
return usbChannels
|
||||
}
|
||||
|
||||
// First get all channels for the requested port
|
||||
val existing =
|
||||
channelCache.find { it.slotId == port.card.physicalSlotIndex && it.portId == port.portIndex }
|
||||
if (existing != null) {
|
||||
if (existing.valid && port.logicalSlotIndex == existing.logicalSlotId) {
|
||||
channelCache.filter { it.slotId == port.card.physicalSlotIndex && it.portId == port.portIndex }
|
||||
if (existing.isNotEmpty()) {
|
||||
if (existing.all { it.valid && it.logicalSlotId == port.logicalSlotIndex }) {
|
||||
return existing
|
||||
} else {
|
||||
existing.close()
|
||||
channelCache.remove(existing)
|
||||
// If any channel shouldn't be considered valid anymore, close all existing for the same slot / port
|
||||
// and reopen
|
||||
existing.forEach {
|
||||
it.close()
|
||||
channelCache.remove(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -75,32 +147,42 @@ open class DefaultEuiccChannelManager(
|
|||
return null
|
||||
}
|
||||
|
||||
val channel = euiccChannelFactory.tryOpenEuiccChannel(port) ?: return null
|
||||
// This function is not responsible for managing USB channels (see the initial check)
|
||||
val channels =
|
||||
tryOpenChannelWithKnownAids { isdrAid, seId ->
|
||||
euiccChannelFactory.tryOpenEuiccChannel(
|
||||
port,
|
||||
isdrAid,
|
||||
seId
|
||||
)
|
||||
}
|
||||
|
||||
if (channel.valid) {
|
||||
channelCache.add(channel)
|
||||
return channel
|
||||
if (channels.isNotEmpty()) {
|
||||
channelCache.addAll(channels)
|
||||
return channels
|
||||
} else {
|
||||
Log.i(
|
||||
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? =
|
||||
protected suspend fun findEuiccChannelByLogicalSlot(
|
||||
logicalSlotId: Int,
|
||||
seId: EuiccChannel.SecureElementId
|
||||
): EuiccChannel? =
|
||||
withContext(Dispatchers.IO) {
|
||||
if (logicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
|
||||
return@withContext usbChannel
|
||||
return@withContext usbChannels.find { it.seId == seId }
|
||||
}
|
||||
|
||||
for (card in uiccCards) {
|
||||
for (port in card.ports) {
|
||||
if (port.logicalSlotIndex == logicalSlotId) {
|
||||
return@withContext tryOpenEuiccChannel(port)
|
||||
return@withContext tryOpenEuiccChannel(port)?.find { it.seId == seId }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -108,23 +190,35 @@ open class DefaultEuiccChannelManager(
|
|||
null
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all EuiccChannels associated with a _physical_ slot, including all secure elements
|
||||
* on cards with multiple of them.
|
||||
*/
|
||||
private suspend fun findAllEuiccChannelsByPhysicalSlot(physicalSlotId: Int): List<EuiccChannel>? {
|
||||
if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
|
||||
return usbChannel?.let { listOf(it) }
|
||||
return usbChannels.ifEmpty { null }
|
||||
}
|
||||
|
||||
for (card in uiccCards) {
|
||||
if (card.physicalSlotIndex != physicalSlotId) continue
|
||||
return card.ports.mapNotNull { tryOpenEuiccChannel(it) }
|
||||
.flatten()
|
||||
.ifEmpty { null }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private suspend fun findEuiccChannelByPort(physicalSlotId: Int, portId: Int): EuiccChannel? =
|
||||
/**
|
||||
* Finds all EuiccChannels associated with a physical slot + port. Note that this
|
||||
* may return multiple in case there are multiple SEs.
|
||||
*/
|
||||
private suspend fun findEuiccChannelsByPort(
|
||||
physicalSlotId: Int,
|
||||
portId: Int,
|
||||
): List<EuiccChannel>? =
|
||||
withContext(Dispatchers.IO) {
|
||||
if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
|
||||
return@withContext usbChannel
|
||||
return@withContext usbChannels.ifEmpty { null }
|
||||
}
|
||||
|
||||
uiccCards.find { it.physicalSlotIndex == physicalSlotId }?.let { card ->
|
||||
|
|
@ -147,15 +241,17 @@ open class DefaultEuiccChannelManager(
|
|||
return@withContext listOf(0)
|
||||
}
|
||||
|
||||
findAllEuiccChannelsByPhysicalSlot(physicalSlotId)?.map { it.portId } ?: listOf()
|
||||
findAllEuiccChannelsByPhysicalSlot(physicalSlotId)?.map { it.portId }?.toSet()?.toList()
|
||||
?: listOf()
|
||||
}
|
||||
|
||||
override suspend fun <R> withEuiccChannel(
|
||||
physicalSlotId: Int,
|
||||
portId: Int,
|
||||
seId: EuiccChannel.SecureElementId,
|
||||
fn: suspend (EuiccChannel) -> R
|
||||
): R {
|
||||
val channel = findEuiccChannelByPort(physicalSlotId, portId)
|
||||
val channel = findEuiccChannelsByPort(physicalSlotId, portId)?.find { it.seId == seId }
|
||||
?: throw EuiccChannelManager.EuiccChannelNotFoundException()
|
||||
val wrapper = EuiccChannelWrapper(channel)
|
||||
try {
|
||||
|
|
@ -169,9 +265,10 @@ open class DefaultEuiccChannelManager(
|
|||
|
||||
override suspend fun <R> withEuiccChannel(
|
||||
logicalSlotId: Int,
|
||||
seId: EuiccChannel.SecureElementId,
|
||||
fn: suspend (EuiccChannel) -> R
|
||||
): R {
|
||||
val channel = findEuiccChannelByLogicalSlot(logicalSlotId)
|
||||
val channel = findEuiccChannelByLogicalSlot(logicalSlotId, seId)
|
||||
?: throw EuiccChannelManager.EuiccChannelNotFoundException()
|
||||
val wrapper = EuiccChannelWrapper(channel)
|
||||
try {
|
||||
|
|
@ -184,34 +281,48 @@ open class DefaultEuiccChannelManager(
|
|||
}
|
||||
|
||||
override suspend fun waitForReconnect(physicalSlotId: Int, portId: Int, timeoutMillis: Long) {
|
||||
if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
|
||||
usbChannel?.close()
|
||||
usbChannel = null
|
||||
val numChannelsBefore = if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
|
||||
usbChannels.size
|
||||
} 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()
|
||||
// Don't use find* methods since they reopen channels if not found
|
||||
channelCache.filter { it.slotId == physicalSlotId && it.portId == portId }.size
|
||||
}
|
||||
|
||||
val resetChannels = {
|
||||
if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
|
||||
usbChannels.forEach { it.close() }
|
||||
usbChannels.clear()
|
||||
} else {
|
||||
// If there is already a valid channel, we close it proactively
|
||||
channelCache.filter { it.slotId == physicalSlotId && it.portId == portId }.forEach { it.close() }
|
||||
}
|
||||
}
|
||||
|
||||
resetChannels()
|
||||
|
||||
withTimeout(timeoutMillis) {
|
||||
while (true) {
|
||||
try {
|
||||
val channel = if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
|
||||
val channels = if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
|
||||
// tryOpenUsbEuiccChannel() will always try to reopen the channel, even if
|
||||
// a USB channel already exists
|
||||
tryOpenUsbEuiccChannel()
|
||||
usbChannel!!
|
||||
usbChannels
|
||||
} else {
|
||||
// tryOpenEuiccChannel() will automatically dispose of invalid channels
|
||||
// and recreate when needed
|
||||
findEuiccChannelByPort(physicalSlotId, portId)!!
|
||||
findEuiccChannelsByPort(physicalSlotId, portId)!!
|
||||
}
|
||||
check(channel.valid) { "Invalid channel" }
|
||||
check(channels.isNotEmpty()) { "No channel" }
|
||||
check(channels.all { it.valid }) { "Invalid channel" }
|
||||
check(numChannelsBefore > 0 && channels.size >= numChannelsBefore) { "Less channels than before" }
|
||||
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"
|
||||
)
|
||||
resetChannels()
|
||||
}
|
||||
delay(1000)
|
||||
}
|
||||
|
|
@ -240,26 +351,53 @@ open class DefaultEuiccChannelManager(
|
|||
}
|
||||
})
|
||||
|
||||
override fun flowEuiccSecureElements(
|
||||
slotId: Int,
|
||||
portId: Int
|
||||
): Flow<EuiccChannel.SecureElementId> = flow {
|
||||
findEuiccChannelsByPort(slotId, portId)?.forEach {
|
||||
emit(it.seId)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun tryOpenUsbEuiccChannel(): Pair<UsbDevice?, Boolean> =
|
||||
withContext(Dispatchers.IO) {
|
||||
usbManager.deviceList.values.forEach { device ->
|
||||
Log.i(TAG, "Scanning USB device ${device.deviceId}:${device.vendorId}")
|
||||
val iface = device.getSmartCardInterface() ?: return@forEach
|
||||
val iface = device.interfaces.smartCard ?: 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")
|
||||
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
|
||||
|
||||
try {
|
||||
val channel = euiccChannelFactory.tryOpenUsbEuiccChannel(device, iface)
|
||||
if (channel != null && channel.lpa.valid) {
|
||||
usbChannel = channel
|
||||
val channels = tryOpenChannelWithKnownAids { isdrAid, seId ->
|
||||
euiccChannelFactory.tryOpenUsbEuiccChannel(ccidCtx, isdrAid, seId)
|
||||
}
|
||||
if (channels.isNotEmpty() && channels[0].valid) {
|
||||
ccidCtx.allowDisconnect = true
|
||||
usbChannels.clear()
|
||||
usbChannels.addAll(channels)
|
||||
return@withContext Pair(device, true)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// Ignored -- skip forward
|
||||
e.printStackTrace()
|
||||
}
|
||||
Log.i(TAG, "No valid eUICC channel found on USB device ${device.deviceId}:${device.vendorId}")
|
||||
|
||||
ccidCtx.allowDisconnect = true
|
||||
ccidCtx.disconnect()
|
||||
|
||||
Log.i(
|
||||
TAG,
|
||||
"No valid eUICC channel found on USB device ${device.deviceId}:${device.vendorId}"
|
||||
)
|
||||
}
|
||||
return@withContext Pair(null, false)
|
||||
}
|
||||
|
|
@ -269,9 +407,9 @@ open class DefaultEuiccChannelManager(
|
|||
channel.close()
|
||||
}
|
||||
|
||||
usbChannel?.close()
|
||||
usbChannel = null
|
||||
usbChannels.forEach { it.close() }
|
||||
usbChannels.clear()
|
||||
channelCache.clear()
|
||||
euiccChannelFactory.cleanup()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
package im.angry.openeuicc.core
|
||||
|
||||
import android.os.Parcel
|
||||
import android.os.Parcelable
|
||||
import im.angry.openeuicc.util.*
|
||||
import net.typeblog.lpac_jni.ApduInterface
|
||||
import net.typeblog.lpac_jni.LocalProfileAssistant
|
||||
|
||||
interface EuiccChannel {
|
||||
|
|
@ -12,6 +15,67 @@ interface EuiccChannel {
|
|||
val logicalSlotId: Int
|
||||
val portId: Int
|
||||
|
||||
/**
|
||||
* A semi-obscure wrapper over the integer ID of a secure element on a card.
|
||||
*
|
||||
* Because the ID is arbitrary, this is intended to discourage the use of the
|
||||
* integer value directly. Additionally, it prevents accidentally calling the
|
||||
* wrong function in EuiccChannelManager with a ton of integer parameters.
|
||||
*/
|
||||
class SecureElementId private constructor(val id: Int) : Parcelable {
|
||||
companion object {
|
||||
val DEFAULT = SecureElementId(0)
|
||||
|
||||
/**
|
||||
* Create a SecureElementId from an integer ID. You should not call this directly
|
||||
* unless you know what you're doing.
|
||||
*
|
||||
* This is currently only ever used in the download flow.
|
||||
*/
|
||||
fun createFromInt(id: Int): SecureElementId =
|
||||
SecureElementId(id)
|
||||
|
||||
@Suppress("unused")
|
||||
@JvmField
|
||||
val CREATOR = object : Parcelable.Creator<SecureElementId> {
|
||||
override fun createFromParcel(parcel: Parcel): SecureElementId =
|
||||
createFromInt(parcel.readInt())
|
||||
|
||||
override fun newArray(size: Int): Array<SecureElementId?> = arrayOfNulls(size)
|
||||
}
|
||||
}
|
||||
|
||||
override fun hashCode(): Int =
|
||||
id.hashCode()
|
||||
|
||||
override fun equals(other: Any?): Boolean =
|
||||
if (other is SecureElementId) {
|
||||
this.id == other.id
|
||||
} else {
|
||||
super.equals(other)
|
||||
}
|
||||
|
||||
override fun describeContents(): Int = id
|
||||
|
||||
override fun writeToParcel(parcel: Parcel, flags: Int) {
|
||||
parcel.writeInt(id)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Some chips support multiple SEs on one chip. The seId here is intended
|
||||
* to distinguish channels opened from these different SEs.
|
||||
*/
|
||||
val seId: SecureElementId
|
||||
|
||||
/**
|
||||
* Does this channel belong to a chip that supports multiple SEs?
|
||||
* Note that this is only made `var` to make initialization a bit less annoying --
|
||||
* this should never be set again after the channel is originally opened.
|
||||
* Attempting to do so will yield an exception.
|
||||
*/
|
||||
var hasMultipleSE: Boolean
|
||||
|
||||
val lpa: LocalProfileAssistant
|
||||
|
||||
val valid: Boolean
|
||||
|
|
@ -22,11 +86,14 @@ interface EuiccChannel {
|
|||
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.
|
||||
* The underlying APDU interface for this channel
|
||||
*/
|
||||
val intrinsicChannelName: String?
|
||||
val apduInterface: ApduInterface
|
||||
|
||||
/**
|
||||
* The AID of the ISD-R channel currently in use
|
||||
*/
|
||||
val isdrAid: ByteArray
|
||||
|
||||
fun close()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,22 @@
|
|||
package im.angry.openeuicc.core
|
||||
|
||||
import android.hardware.usb.UsbDevice
|
||||
import android.hardware.usb.UsbInterface
|
||||
import im.angry.openeuicc.core.usb.UsbCcidContext
|
||||
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): EuiccChannel?
|
||||
suspend fun tryOpenEuiccChannel(
|
||||
port: UiccPortInfoCompat,
|
||||
isdrAid: ByteArray,
|
||||
seId: EuiccChannel.SecureElementId
|
||||
): EuiccChannel?
|
||||
|
||||
fun tryOpenUsbEuiccChannel(usbDevice: UsbDevice, usbInterface: UsbInterface): EuiccChannel?
|
||||
fun tryOpenUsbEuiccChannel(
|
||||
ccidCtx: UsbCcidContext,
|
||||
isdrAid: ByteArray,
|
||||
seId: EuiccChannel.SecureElementId
|
||||
): EuiccChannel?
|
||||
|
||||
/**
|
||||
* Release all resources used by this EuiccChannelFactory
|
||||
|
|
@ -17,4 +24,4 @@ interface EuiccChannelFactory {
|
|||
* re-acquired when this happens
|
||||
*/
|
||||
fun cleanup()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ package im.angry.openeuicc.core
|
|||
|
||||
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 net.typeblog.lpac_jni.LocalProfileAssistant
|
||||
import net.typeblog.lpac_jni.impl.HttpInterfaceImpl
|
||||
|
|
@ -10,17 +12,25 @@ import net.typeblog.lpac_jni.impl.LocalProfileAssistantImpl
|
|||
class EuiccChannelImpl(
|
||||
override val type: String,
|
||||
override val port: UiccPortInfoCompat,
|
||||
override val intrinsicChannelName: String?,
|
||||
private val apduInterface: ApduInterface,
|
||||
override val apduInterface: ApduInterface,
|
||||
override val isdrAid: ByteArray,
|
||||
override val seId: EuiccChannel.SecureElementId,
|
||||
verboseLoggingFlow: Flow<Boolean>,
|
||||
ignoreTLSCertificateFlow: Flow<Boolean>
|
||||
ignoreTLSCertificateFlow: Flow<Boolean>,
|
||||
es10xMssFlow: Flow<Int>,
|
||||
) : EuiccChannel {
|
||||
override val slotId = port.card.physicalSlotIndex
|
||||
override val logicalSlotId = port.logicalSlotIndex
|
||||
override val portId = port.portIndex
|
||||
|
||||
override val lpa: LocalProfileAssistant =
|
||||
LocalProfileAssistantImpl(apduInterface, HttpInterfaceImpl(verboseLoggingFlow, ignoreTLSCertificateFlow))
|
||||
LocalProfileAssistantImpl(
|
||||
isdrAid,
|
||||
apduInterface,
|
||||
HttpInterfaceImpl(verboseLoggingFlow, ignoreTLSCertificateFlow),
|
||||
).also {
|
||||
it.setEs10xMss(runBlocking { es10xMssFlow.first().toByte() })
|
||||
}
|
||||
|
||||
override val atr: ByteArray?
|
||||
get() = (apduInterface as? ApduInterfaceAtrProvider)?.atr
|
||||
|
|
@ -28,5 +38,16 @@ class EuiccChannelImpl(
|
|||
override val valid: Boolean
|
||||
get() = lpa.valid
|
||||
|
||||
private var hasMultipleSEInitialized = false
|
||||
|
||||
override var hasMultipleSE: Boolean = false
|
||||
set(value) {
|
||||
if (hasMultipleSEInitialized) {
|
||||
throw IllegalStateException("already initialized")
|
||||
}
|
||||
|
||||
field = value
|
||||
}
|
||||
|
||||
override fun close() = lpa.close()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import kotlinx.coroutines.flow.Flow
|
|||
* or when this instance is destroyed.
|
||||
*
|
||||
* To precisely control the lifecycle of this object itself (and thus its cached channels),
|
||||
* all other compoents must access EuiccChannelManager objects through EuiccChannelManagerService.
|
||||
* all other components must access EuiccChannelManager objects through EuiccChannelManagerService.
|
||||
* Holding references independent of EuiccChannelManagerService is unsupported.
|
||||
*/
|
||||
interface EuiccChannelManager {
|
||||
|
|
@ -37,6 +37,14 @@ interface EuiccChannelManager {
|
|||
*/
|
||||
fun flowAllOpenEuiccPorts(): Flow<Pair<Int, Int>>
|
||||
|
||||
/**
|
||||
* Iterate over all the Secure Elements available on one eUICC.
|
||||
*
|
||||
* This is going to almost always return only 1 result, except in the case where
|
||||
* a card has multiple SEs.
|
||||
*/
|
||||
fun flowEuiccSecureElements(slotId: Int, portId: Int): Flow<EuiccChannel.SecureElementId>
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
|
@ -67,7 +75,7 @@ interface EuiccChannelManager {
|
|||
*/
|
||||
suspend fun findAvailablePorts(physicalSlotId: Int): List<Int>
|
||||
|
||||
class EuiccChannelNotFoundException: Exception("EuiccChannel not found")
|
||||
class EuiccChannelNotFoundException : Exception("EuiccChannel not found")
|
||||
|
||||
/**
|
||||
* Find a EuiccChannel by its slot and port, then run a callback with a reference to it.
|
||||
|
|
@ -78,19 +86,12 @@ interface EuiccChannelManager {
|
|||
*
|
||||
* If a channel for that slot / port is not found, EuiccChannelNotFoundException is thrown
|
||||
*/
|
||||
suspend fun <R> withEuiccChannel(
|
||||
physicalSlotId: Int,
|
||||
portId: Int,
|
||||
fn: suspend (EuiccChannel) -> R
|
||||
): R
|
||||
suspend fun <R> withEuiccChannel(physicalSlotId: Int, portId: Int, seId: EuiccChannel.SecureElementId, fn: suspend (EuiccChannel) -> R): R
|
||||
|
||||
/**
|
||||
* Same as withEuiccChannel(Int, Int, (EuiccChannel) -> R) but instead uses logical slot ID
|
||||
* Same as withEuiccChannel(Int, Int, SecureElementId, (EuiccChannel) -> R) but instead uses logical slot ID
|
||||
*/
|
||||
suspend fun <R> withEuiccChannel(
|
||||
logicalSlotId: Int,
|
||||
fn: suspend (EuiccChannel) -> R
|
||||
): R
|
||||
suspend fun <R> withEuiccChannel(logicalSlotId: Int, seId: EuiccChannel.SecureElementId, fn: suspend (EuiccChannel) -> R): R
|
||||
|
||||
/**
|
||||
* Invalidate all EuiccChannels previously cached by this Manager
|
||||
|
|
@ -105,4 +106,4 @@ interface EuiccChannelManager {
|
|||
suspend fun notifyEuiccProfilesChanged(logicalSlotId: Int) {
|
||||
// no-op by default
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
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 {
|
||||
|
|
@ -25,16 +26,25 @@ class EuiccChannelWrapper(orig: EuiccChannel) : EuiccChannel {
|
|||
get() = channel.logicalSlotId
|
||||
override val portId: Int
|
||||
get() = channel.portId
|
||||
override val seId: EuiccChannel.SecureElementId
|
||||
get() = channel.seId
|
||||
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 var hasMultipleSE: Boolean
|
||||
get() = channel.hasMultipleSE
|
||||
set(value) {
|
||||
channel.hasMultipleSE = value
|
||||
}
|
||||
|
||||
override fun close() = channel.close()
|
||||
|
||||
|
|
@ -45,4 +55,4 @@ class EuiccChannelWrapper(orig: EuiccChannel) : EuiccChannel {
|
|||
(lpa as LocalProfileAssistantWrapper).invalidateWrapper()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
package im.angry.openeuicc.core
|
||||
|
||||
import net.typeblog.lpac_jni.ProfileDownloadInput
|
||||
import net.typeblog.lpac_jni.EuiccInfo2
|
||||
import net.typeblog.lpac_jni.LocalProfileAssistant
|
||||
import net.typeblog.lpac_jni.LocalProfileInfo
|
||||
|
|
@ -40,13 +41,8 @@ class LocalProfileAssistantWrapper(orig: LocalProfileAssistant) :
|
|||
|
||||
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 downloadProfile(input: ProfileDownloadInput, callback: ProfileDownloadCallback) =
|
||||
lpa.downloadProfile(input, callback)
|
||||
|
||||
override fun deleteNotification(seqNumber: Long): Boolean = lpa.deleteNotification(seqNumber)
|
||||
|
||||
|
|
@ -63,4 +59,4 @@ class LocalProfileAssistantWrapper(orig: LocalProfileAssistant) :
|
|||
fun invalidateWrapper() {
|
||||
_inner = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,21 +7,22 @@ import android.util.Log
|
|||
import im.angry.openeuicc.util.*
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.single
|
||||
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<Boolean>
|
||||
): ApduInterface, ApduInterfaceAtrProvider {
|
||||
) : ApduInterface, ApduInterfaceAtrProvider {
|
||||
companion object {
|
||||
const val TAG = "OmapiApduInterface"
|
||||
}
|
||||
|
||||
private lateinit var session: Session
|
||||
private lateinit var lastChannel: Channel
|
||||
private val index = AtomicInteger(0)
|
||||
private val channels = mutableMapOf<Int, Channel>()
|
||||
|
||||
override val valid: Boolean
|
||||
get() = service.isConnected && (this::session.isInitialized && !session.isClosed)
|
||||
|
|
@ -38,24 +39,23 @@ class OmapiApduInterface(
|
|||
}
|
||||
|
||||
override fun logicalChannelOpen(aid: ByteArray): Int {
|
||||
check(!this::lastChannel.isInitialized) {
|
||||
"Can only open one channel"
|
||||
}
|
||||
lastChannel = session.openLogicalChannel(aid)!!
|
||||
return 1
|
||||
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
|
||||
}
|
||||
|
||||
override fun logicalChannelClose(handle: Int) {
|
||||
check(handle == 1 && !this::lastChannel.isInitialized) {
|
||||
"Unknown channel"
|
||||
}
|
||||
lastChannel.close()
|
||||
val channel = channels[handle]
|
||||
check(channel != null) { "Invalid logical channel handle $handle" }
|
||||
if (channel.isOpen) channel.close()
|
||||
synchronized(channels) { channels.remove(handle) }
|
||||
}
|
||||
|
||||
override fun transmit(tx: ByteArray): ByteArray {
|
||||
check(this::lastChannel.isInitialized) {
|
||||
"Unknown channel"
|
||||
}
|
||||
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()}")
|
||||
|
|
@ -63,7 +63,7 @@ class OmapiApduInterface(
|
|||
|
||||
try {
|
||||
for (i in 0..10) {
|
||||
val res = lastChannel.transmit(tx)
|
||||
val res = channel.transmit(tx)
|
||||
if (runBlocking { verboseLoggingFlow.first() }) {
|
||||
Log.d(TAG, "OMAPI APDU response: ${res.encodeHex()}")
|
||||
}
|
||||
|
|
@ -83,4 +83,4 @@ class OmapiApduInterface(
|
|||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,56 +1,103 @@
|
|||
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 kotlinx.coroutines.flow.Flow
|
||||
import im.angry.openeuicc.util.decodeHex
|
||||
import im.angry.openeuicc.util.encodeHex
|
||||
import net.typeblog.lpac_jni.ApduInterface
|
||||
|
||||
class UsbApduInterface(
|
||||
private val conn: UsbDeviceConnection,
|
||||
private val bulkIn: UsbEndpoint,
|
||||
private val bulkOut: UsbEndpoint,
|
||||
private val verboseLoggingFlow: Flow<Boolean>
|
||||
private val ccidCtx: UsbCcidContext
|
||||
) : ApduInterface, ApduInterfaceAtrProvider {
|
||||
companion object {
|
||||
private const val TAG = "UsbApduInterface"
|
||||
}
|
||||
|
||||
private lateinit var ccidDescription: UsbCcidDescription
|
||||
private lateinit var transceiver: UsbCcidTransceiver
|
||||
override val atr: ByteArray?
|
||||
get() = ccidCtx.atr
|
||||
|
||||
private var channelId = -1
|
||||
override val valid: Boolean
|
||||
get() = channels.isNotEmpty()
|
||||
|
||||
override var atr: ByteArray? = null
|
||||
private var channels = mutableSetOf<Int>()
|
||||
|
||||
// ATR parser
|
||||
// Specs: ISO/IEC 7816-3:2006 8.2 Answer-to-Reset
|
||||
// See also: https://en.wikipedia.org/wiki/Answer_to_reset
|
||||
class ParsedAtr private constructor(val ts: Byte?, val t0: Byte?, val ta1: Byte?, val tb1: Byte?, val tc1: Byte?, val td1: Byte?, val ta2: Byte?, val tb2: Byte?, val tc2: Byte?, val td2: Byte?) {
|
||||
companion object {
|
||||
fun parse(atr: ByteArray): ParsedAtr {
|
||||
val ts = atr[0]
|
||||
val t0 = atr[1]
|
||||
val tx1 = arrayOf<Byte?>(null, null, null, null)
|
||||
val tx2 = arrayOf<Byte?>(null, null, null, null)
|
||||
var pointer = 2
|
||||
|
||||
for (i in 0..3) {
|
||||
if (t0.toInt() and (0x10 shl i) != 0) {
|
||||
tx1[i] = atr[pointer]
|
||||
pointer++
|
||||
}
|
||||
}
|
||||
|
||||
val td1 = tx1[3] ?: 0
|
||||
|
||||
for (i in 0..3) {
|
||||
if (td1.toInt() and (0x10 shl i) != 0) {
|
||||
tx2[i] = atr[pointer]
|
||||
pointer++
|
||||
}
|
||||
}
|
||||
|
||||
return ParsedAtr(ts=ts, t0=t0, ta1=tx1[0], tb1=tx1[1], tc1=tx1[2], td1=tx1[3],
|
||||
ta2=tx2[0], tb2=tx2[1], tc2=tx2[2], td2=tx2[3],
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun connect() {
|
||||
ccidDescription = UsbCcidDescription.fromRawDescriptors(conn.rawDescriptors)!!
|
||||
ccidCtx.connect()
|
||||
|
||||
if (!ccidDescription.hasT0Protocol) {
|
||||
throw IllegalArgumentException("Unsupported card reader; T=0 support is required")
|
||||
if (ccidCtx.transceiver.isTpdu) {
|
||||
// Send parameter selection
|
||||
// Specs: USB-CCID 3.2.1 TPDU level of exchange
|
||||
val parsedAtr = ParsedAtr.parse(atr!!)
|
||||
val ta1 = parsedAtr.ta1 ?: 0x11.toByte()
|
||||
val pts1 = ta1 // TODO: Check that reader supports baud rate proposed by the card
|
||||
val pps = byteArrayOf(0xff.toByte(), 0x10.toByte(), pts1, 0x00.toByte())
|
||||
Log.d(TAG, "PTS1=${pts1} PPS: ${pps.encodeHex()}")
|
||||
ccidCtx.transceiver.sendXfrBlock(pps)
|
||||
|
||||
// Send Set Parameters
|
||||
// Specs: USB-CCID 6.1.7 PC_to_RDR_SetParameters
|
||||
|
||||
val param = byteArrayOf(
|
||||
pts1,
|
||||
(if (parsedAtr.ts == 0x3F.toByte()) 0x02 else 0x00),
|
||||
parsedAtr.tc1 ?: 0,
|
||||
parsedAtr.tc2 ?: 0x0A,
|
||||
0x00
|
||||
)
|
||||
|
||||
Log.d(TAG, "Param: ${param.encodeHex()}")
|
||||
|
||||
ccidCtx.transceiver.sendParamBlock(param)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
// 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)
|
||||
}
|
||||
|
||||
override fun disconnect() {
|
||||
conn.close()
|
||||
}
|
||||
override fun disconnect() = ccidCtx.disconnect()
|
||||
|
||||
override fun logicalChannelOpen(aid: ByteArray): Int {
|
||||
check(channelId == -1) { "Logical channel already opened" }
|
||||
|
||||
// OPEN LOGICAL CHANNEL
|
||||
val req = manageChannelCmd(true, 0)
|
||||
|
||||
|
|
@ -66,8 +113,9 @@ class UsbApduInterface(
|
|||
return -1
|
||||
}
|
||||
|
||||
channelId = resp[0].toInt()
|
||||
val channelId = resp[0].toInt()
|
||||
Log.d(TAG, "channelId = $channelId")
|
||||
channels.add(channelId)
|
||||
|
||||
// Then, select AID
|
||||
val selectAid = selectByDfCmd(aid, channelId.toByte())
|
||||
|
|
@ -75,6 +123,8 @@ class UsbApduInterface(
|
|||
|
||||
if (!isSuccessResponse(selectAidResp)) {
|
||||
Log.d(TAG, "Select DF failed : ${selectAidResp.encodeHex()}")
|
||||
logicalChannelClose(channelId)
|
||||
Log.d(TAG, "Closed logical channel $channelId due to select DF failure")
|
||||
return -1
|
||||
}
|
||||
|
||||
|
|
@ -82,28 +132,26 @@ class UsbApduInterface(
|
|||
}
|
||||
|
||||
override fun logicalChannelClose(handle: Int) {
|
||||
check(handle == channelId) { "Logical channel ID mismatch" }
|
||||
check(channelId != -1) { "Logical channel is not opened" }
|
||||
|
||||
check(channels.contains(handle)) {
|
||||
"Invalid logical channel handle $handle"
|
||||
}
|
||||
// CLOSE LOGICAL CHANNEL
|
||||
val req = manageChannelCmd(false, channelId.toByte())
|
||||
val resp = transmitApduByChannel(req, channelId.toByte())
|
||||
val req = manageChannelCmd(false, handle.toByte())
|
||||
val resp = transmitApduByChannel(req, handle.toByte())
|
||||
|
||||
if (!isSuccessResponse(resp)) {
|
||||
Log.d(TAG, "CLOSE LOGICAL CHANNEL failed: ${resp.encodeHex()}")
|
||||
}
|
||||
|
||||
channelId = -1
|
||||
channels.remove(handle)
|
||||
}
|
||||
|
||||
override fun transmit(tx: ByteArray): ByteArray {
|
||||
check(channelId != -1) { "Logical channel is not opened" }
|
||||
return transmitApduByChannel(tx, channelId.toByte())
|
||||
override fun transmit(handle: Int, tx: ByteArray): ByteArray {
|
||||
check(channels.contains(handle)) {
|
||||
"Invalid logical channel handle $handle"
|
||||
}
|
||||
return transmitApduByChannel(tx, handle.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()
|
||||
|
||||
|
|
@ -137,7 +185,7 @@ class UsbApduInterface(
|
|||
// OR the channel mask into the CLA byte
|
||||
realTx[0] = ((realTx[0].toInt() and 0xFC) or channel.toInt()).toByte()
|
||||
|
||||
var resp = transceiver.sendXfrBlock(realTx).data!!
|
||||
var resp = ccidCtx.transceiver.sendXfrBlock(realTx).data!!
|
||||
|
||||
if (resp.size < 2) throw RuntimeException("APDU response smaller than 2 (sw1 + sw2)!")
|
||||
|
||||
|
|
@ -148,7 +196,7 @@ class UsbApduInterface(
|
|||
// 0x6C = wrong le
|
||||
// so we fix the le field here
|
||||
realTx[realTx.size - 1] = resp[resp.size - 1]
|
||||
resp = transceiver.sendXfrBlock(realTx).data!!
|
||||
resp = ccidCtx.transceiver.sendXfrBlock(realTx).data!!
|
||||
} else if (sw1 == 0x61) {
|
||||
// 0x61 = X bytes available
|
||||
// continue reading by GET RESPONSE
|
||||
|
|
@ -158,7 +206,7 @@ class UsbApduInterface(
|
|||
realTx[0], 0xC0.toByte(), 0x00, 0x00, sw2.toByte()
|
||||
)
|
||||
|
||||
val tmp = transceiver.sendXfrBlock(getResponseCmd).data!!
|
||||
val tmp = ccidCtx.transceiver.sendXfrBlock(getResponseCmd).data!!
|
||||
|
||||
resp = resp.sliceArray(0 until (resp.size - 2)) + tmp
|
||||
|
||||
|
|
@ -169,4 +217,4 @@ class UsbApduInterface(
|
|||
|
||||
return resp
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,85 @@
|
|||
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 verboseLoggingFlow: Flow<Boolean>
|
||||
) {
|
||||
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,
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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_EXCHAGE_LEVEL_EXTENDED_APDU = 0x40000
|
||||
private const val FEATURE_EXCHANGE_LEVEL_EXTENDED_APDU = 0x40000
|
||||
|
||||
// bVoltageSupport Masks
|
||||
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 VOLTAGE_5V0: Byte = 1
|
||||
private const val VOLTAGE_3V0: Byte = 2
|
||||
private const val VOLTAGE_1V8: Byte = 4
|
||||
|
||||
private const val SLOT_OFFSET = 4
|
||||
private const val FEATURES_OFFSET = 40
|
||||
|
|
@ -71,35 +71,30 @@ data class UsbCcidDescription(
|
|||
}
|
||||
|
||||
enum class Voltage(powerOnValue: Int, mask: Int) {
|
||||
AUTO(0, 0), _5V(1, VOLTAGE_5V.toInt()), _3V(2, VOLTAGE_3V.toInt()), _1_8V(
|
||||
3,
|
||||
VOLTAGE_1_8V.toInt()
|
||||
);
|
||||
// @formatter:off
|
||||
AUTO(0, 0),
|
||||
V50(1, VOLTAGE_5V0.toInt()),
|
||||
V30(2, VOLTAGE_3V0.toInt()),
|
||||
V18(3, VOLTAGE_1V8.toInt());
|
||||
// @formatter:on
|
||||
|
||||
val mask = powerOnValue.toByte()
|
||||
val powerOnValue = mask.toByte()
|
||||
}
|
||||
|
||||
private fun hasFeature(feature: Int): Boolean =
|
||||
(dwFeatures and feature) != 0
|
||||
private fun hasFeature(feature: Int) = (dwFeatures and feature) != 0
|
||||
|
||||
val voltages: Array<Voltage>
|
||||
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 isTpdu = hasFeature(0x10000)
|
||||
|
||||
val voltages: List<Voltage>
|
||||
get() {
|
||||
if (hasFeature(FEATURE_AUTOMATIC_VOLTAGE)) return listOf(Voltage.AUTO)
|
||||
return Voltage.entries.filter { (it.mask.toInt() and bVoltageSupport.toInt()) != 0 }
|
||||
}
|
||||
|
||||
val hasAutomaticPps: Boolean
|
||||
get() = hasFeature(FEATURE_AUTOMATIC_PPS)
|
||||
|
||||
val hasT0Protocol: Boolean
|
||||
get() = (dwProtocols and MASK_T0_PROTO) != 0
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import android.hardware.usb.UsbDeviceConnection
|
|||
import android.hardware.usb.UsbEndpoint
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import im.angry.openeuicc.util.*
|
||||
import im.angry.openeuicc.util.encodeHex
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
|
@ -95,6 +95,7 @@ class UsbCcidTransceiver(
|
|||
data class UsbCcidErrorException(val msg: String, val errorResponse: CcidDataBlock) :
|
||||
Exception(msg)
|
||||
|
||||
@Suppress("ArrayInDataClass")
|
||||
data class CcidDataBlock(
|
||||
val dwLength: Int,
|
||||
val bSlot: Byte,
|
||||
|
|
@ -142,6 +143,8 @@ class UsbCcidTransceiver(
|
|||
|
||||
val hasAutomaticPps = usbCcidDescription.hasAutomaticPps
|
||||
|
||||
val isTpdu = usbCcidDescription.isTpdu
|
||||
|
||||
private val inputBuffer = ByteArray(usbBulkIn.maxPacketSize)
|
||||
|
||||
private var currentSequenceNumber: Byte = 0
|
||||
|
|
@ -157,6 +160,46 @@ class UsbCcidTransceiver(
|
|||
}
|
||||
}
|
||||
|
||||
private fun receiveParamBlock(expectedSequenceNumber: Byte): ByteArray {
|
||||
var response: ByteArray?
|
||||
do {
|
||||
response = receiveParamBlockImmediate(expectedSequenceNumber)
|
||||
} while (response!![7] == 0x80.toByte())
|
||||
return response
|
||||
}
|
||||
|
||||
private fun receiveParamBlockImmediate(expectedSequenceNumber: Byte): ByteArray {
|
||||
/*
|
||||
* Some USB CCID devices (notably NitroKey 3) may time-out and need a subsequent poke to
|
||||
* carry on communications. No particular reason why the number 3 was chosen. If we get a
|
||||
* zero-sized reply (or a time-out), we try again. Clamped retries prevent an infinite loop
|
||||
* if things really turn sour.
|
||||
*/
|
||||
var attempts = 3
|
||||
Log.d(TAG, "Receive data block immediate seq=$expectedSequenceNumber")
|
||||
var readBytes: Int
|
||||
do {
|
||||
readBytes = usbConnection.bulkTransfer(
|
||||
usbBulkIn, inputBuffer, inputBuffer.size, DEVICE_COMMUNICATE_TIMEOUT_MILLIS
|
||||
)
|
||||
if (runBlocking { verboseLoggingFlow.first() }) {
|
||||
Log.d(TAG, "Received $readBytes bytes: ${inputBuffer.encodeHex()}")
|
||||
}
|
||||
} while (readBytes <= 0 && attempts-- > 0)
|
||||
if (inputBuffer[0] != 0x82.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))
|
||||
}
|
||||
})
|
||||
}
|
||||
return inputBuffer
|
||||
}
|
||||
|
||||
private fun receiveDataBlock(expectedSequenceNumber: Byte): CcidDataBlock {
|
||||
var response: CcidDataBlock?
|
||||
do {
|
||||
|
|
@ -183,31 +226,26 @@ class UsbCcidTransceiver(
|
|||
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()) {
|
||||
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]
|
||||
)
|
||||
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))
|
||||
}
|
||||
})
|
||||
}
|
||||
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)
|
||||
|
|
@ -218,9 +256,7 @@ 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
|
||||
|
|
@ -285,7 +321,39 @@ 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
|
||||
}
|
||||
|
||||
fun sendParamBlock(
|
||||
payload: ByteArray
|
||||
): ByteArray {
|
||||
val startTime = SystemClock.elapsedRealtime()
|
||||
val l = payload.size
|
||||
val sequenceNumber: Byte = currentSequenceNumber++
|
||||
val headerData = byteArrayOf(
|
||||
0x61.toByte(),
|
||||
l.toByte(),
|
||||
(l shr 8).toByte(),
|
||||
(l shr 16).toByte(),
|
||||
(l shr 24).toByte(),
|
||||
SLOT_NUMBER.toByte(),
|
||||
sequenceNumber,
|
||||
0x00.toByte(),
|
||||
0x00.toByte(),
|
||||
0x00.toByte()
|
||||
)
|
||||
val data: ByteArray = headerData + payload
|
||||
Log.d(TAG, "USB ParamBlock: ${data.encodeHex()}")
|
||||
var sentBytes = 0
|
||||
while (sentBytes < data.size) {
|
||||
val bytesToSend = usbBulkOut.maxPacketSize.coerceAtMost(data.size - sentBytes)
|
||||
sendRaw(data, sentBytes, bytesToSend)
|
||||
sentBytes += bytesToSend
|
||||
}
|
||||
val ccidDataBlock = receiveParamBlock(sequenceNumber)
|
||||
val elapsedTime = SystemClock.elapsedRealtime() - startTime
|
||||
Log.d(TAG, "USB ParamBlock call took ${elapsedTime}ms")
|
||||
return ccidDataBlock
|
||||
}
|
||||
|
||||
|
|
@ -293,13 +361,13 @@ class UsbCcidTransceiver(
|
|||
val startTime = SystemClock.elapsedRealtime()
|
||||
skipAvailableInput()
|
||||
var response: CcidDataBlock? = null
|
||||
for (v in usbCcidDescription.voltages) {
|
||||
Log.v(TAG, "CCID: attempting to power on with voltage $v")
|
||||
for (voltage in usbCcidDescription.voltages) {
|
||||
Log.v(TAG, "CCID: attempting to power on with voltage $voltage")
|
||||
response = try {
|
||||
iccPowerOnVoltage(v.powerOnValue)
|
||||
iccPowerOnVoltage(voltage.powerOnValue)
|
||||
} catch (e: UsbCcidErrorException) {
|
||||
if (e.errorResponse.bError.toInt() == 7) { // Power select error
|
||||
Log.v(TAG, "CCID: failed to power on with voltage $v")
|
||||
Log.v(TAG, "CCID: failed to power on with voltage $voltage")
|
||||
iccPowerOff()
|
||||
Log.v(TAG, "CCID: powered off")
|
||||
continue
|
||||
|
|
@ -314,8 +382,11 @@ class UsbCcidTransceiver(
|
|||
val elapsedTime = SystemClock.elapsedRealtime() - startTime
|
||||
Log.d(
|
||||
TAG,
|
||||
"Usb transport connected, took " + elapsedTime + "ms, ATR=" +
|
||||
response.data?.encodeHex()
|
||||
buildString {
|
||||
append("Usb transport connected")
|
||||
append(", took ", elapsedTime, "ms")
|
||||
append(", ATR=", response.data?.encodeHex())
|
||||
}
|
||||
)
|
||||
return response
|
||||
}
|
||||
|
|
@ -345,4 +416,4 @@ class UsbCcidTransceiver(
|
|||
)
|
||||
sendRaw(iccPowerCommand, 0, iccPowerCommand.size)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,31 +6,22 @@ import android.hardware.usb.UsbDevice
|
|||
import android.hardware.usb.UsbEndpoint
|
||||
import android.hardware.usb.UsbInterface
|
||||
|
||||
class UsbTransportException(msg: String) : Exception(msg)
|
||||
class UsbTransportException(message: String) : Exception(message)
|
||||
|
||||
fun UsbInterface.getIoEndpoints(): Pair<UsbEndpoint?, UsbEndpoint?> {
|
||||
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)
|
||||
}
|
||||
val UsbDevice.interfaces: Iterable<UsbInterface>
|
||||
get() = (0 until interfaceCount).map(::getInterface)
|
||||
|
||||
fun UsbDevice.getSmartCardInterface(): UsbInterface? {
|
||||
for (i in 0 until interfaceCount) {
|
||||
val anInterface = getInterface(i)
|
||||
if (anInterface.interfaceClass == UsbConstants.USB_CLASS_CSCID) {
|
||||
return anInterface
|
||||
}
|
||||
val Iterable<UsbInterface>.smartCard: UsbInterface?
|
||||
get() = find { it.interfaceClass == UsbConstants.USB_CLASS_CSCID }
|
||||
|
||||
val UsbInterface.endpoints: Iterable<UsbEndpoint>
|
||||
get() = (0 until endpointCount).map(::getEndpoint)
|
||||
|
||||
val Iterable<UsbEndpoint>.bulkPair: Pair<UsbEndpoint?, UsbEndpoint?>
|
||||
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 },
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
|
@ -16,4 +16,4 @@ interface AppContainer {
|
|||
val uiComponentFactory: UiComponentFactory
|
||||
val euiccChannelFactory: EuiccChannelFactory
|
||||
val customizableTextProvider: CustomizableTextProvider
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
package im.angry.openeuicc.di
|
||||
|
||||
import android.net.Uri
|
||||
import im.angry.openeuicc.core.EuiccChannel
|
||||
|
||||
interface CustomizableTextProvider {
|
||||
/**
|
||||
* Explanation string for when no eUICC is found on the device.
|
||||
|
|
@ -13,8 +16,18 @@ interface CustomizableTextProvider {
|
|||
val profileSwitchingTimeoutMessage: String
|
||||
|
||||
/**
|
||||
* Format the name of a logical slot; internal only -- not intended for
|
||||
* other channels such as USB.
|
||||
* Display the website link in settings; null if not available.
|
||||
*/
|
||||
fun formatInternalChannelName(logicalSlotId: Int): String
|
||||
}
|
||||
val websiteUri: Uri?
|
||||
|
||||
/**
|
||||
* Format the name of a logical slot -- not for USB channels
|
||||
*/
|
||||
fun formatNonUsbChannelName(logicalSlotId: Int): String
|
||||
|
||||
/**
|
||||
* Format the name of a logical slot with a SE ID, in case of multi-SE chips; currently
|
||||
* this is used in the download flow to distinguish between them on the same chip.
|
||||
*/
|
||||
fun formatNonUsbChannelNameWithSeId(logicalSlotId: Int, seId: EuiccChannel.SecureElementId): String
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,4 +42,4 @@ open class DefaultAppContainer(context: Context) : AppContainer {
|
|||
override val customizableTextProvider by lazy {
|
||||
DefaultCustomizableTextProvider(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,23 @@
|
|||
package im.angry.openeuicc.di
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import im.angry.openeuicc.common.R
|
||||
import im.angry.openeuicc.core.EuiccChannel
|
||||
|
||||
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.enable_disable_timeout)
|
||||
get() = context.getString(R.string.profile_switch_timeout)
|
||||
|
||||
override fun formatInternalChannelName(logicalSlotId: Int): String =
|
||||
override val websiteUri: Uri?
|
||||
get() = null
|
||||
|
||||
override fun formatNonUsbChannelName(logicalSlotId: Int): String =
|
||||
context.getString(R.string.channel_name_format, logicalSlotId)
|
||||
}
|
||||
|
||||
override fun formatNonUsbChannelNameWithSeId(logicalSlotId: Int, seId: EuiccChannel.SecureElementId): String =
|
||||
context.getString(R.string.channel_name_format_se, logicalSlotId, seId.id)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,16 +1,20 @@
|
|||
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(
|
||||
slotId: Int,
|
||||
portId: Int,
|
||||
seId: EuiccChannel.SecureElementId
|
||||
): EuiccManagementFragment =
|
||||
EuiccManagementFragment.newInstance(slotId, portId, seId)
|
||||
|
||||
override fun createNoEuiccPlaceholderFragment(): Fragment = NoEuiccPlaceholderFragment()
|
||||
|
||||
override fun createSettingsFragment(): Fragment = SettingsFragment()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,16 @@
|
|||
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(
|
||||
slotId: Int,
|
||||
portId: Int,
|
||||
seId: EuiccChannel.SecureElementId
|
||||
): EuiccManagementFragment
|
||||
|
||||
fun createNoEuiccPlaceholderFragment(): Fragment
|
||||
fun createSettingsFragment(): Fragment
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ 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
|
||||
|
|
@ -11,6 +12,7 @@ import androidx.core.app.NotificationManagerCompat
|
|||
import androidx.lifecycle.LifecycleService
|
||||
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
|
||||
|
|
@ -36,6 +38,9 @@ import kotlinx.coroutines.withContext
|
|||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlinx.coroutines.yield
|
||||
import net.typeblog.lpac_jni.ProfileDownloadCallback
|
||||
import net.typeblog.lpac_jni.ProfileDownloadInput
|
||||
import net.typeblog.lpac_jni.ProfileDownloadState
|
||||
import net.typeblog.lpac_jni.RemoteProfileInfo
|
||||
|
||||
/**
|
||||
* An Android Service wrapper for EuiccChannelManager.
|
||||
|
|
@ -91,6 +96,12 @@ 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())
|
||||
*/
|
||||
|
|
@ -275,6 +286,8 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
|
|||
|
||||
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()
|
||||
|
|
@ -290,6 +303,7 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
|
|||
postForegroundTaskFailureNotification(failureTitle)
|
||||
}
|
||||
} finally {
|
||||
wakeLock.release()
|
||||
if (isActive) {
|
||||
stopSelf()
|
||||
}
|
||||
|
|
@ -368,32 +382,33 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
|
|||
}
|
||||
|
||||
fun launchProfileDownloadTask(
|
||||
slotId: Int,
|
||||
portId: Int,
|
||||
smdp: String,
|
||||
matchingId: String?,
|
||||
confirmationCode: String?,
|
||||
imei: String?
|
||||
slotId: Int, portId: Int, seId: EuiccChannel.SecureElementId,
|
||||
input: ProfileDownloadInput
|
||||
): 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)
|
||||
euiccChannelManager.beginTrackedOperation(slotId, portId, seId) {
|
||||
euiccChannelManager.withEuiccChannel(slotId, portId, seId) { channel ->
|
||||
channel.lpa.downloadProfile(input, object : ProfileDownloadCallback {
|
||||
override fun onStateUpdate(state: ProfileDownloadState) {
|
||||
if (state.progress == 0) return
|
||||
foregroundTaskState.value = ForegroundTaskState.InProgress(state.progress)
|
||||
}
|
||||
|
||||
override fun onConfirmMetadata(metadata: RemoteProfileInfo?): Boolean {
|
||||
// TODO: Actually do something here and not just logging?
|
||||
if (metadata != null) {
|
||||
Log.i(
|
||||
TAG,
|
||||
"Downloading profile provider=${metadata.providerName} name=${metadata.name}"
|
||||
)
|
||||
}
|
||||
})
|
||||
return true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
preferenceRepository.notificationDownloadFlow.first()
|
||||
|
|
@ -403,6 +418,7 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
|
|||
fun launchProfileRenameTask(
|
||||
slotId: Int,
|
||||
portId: Int,
|
||||
seId: EuiccChannel.SecureElementId,
|
||||
iccid: String,
|
||||
name: String
|
||||
): ForegroundTaskSubscriberFlow =
|
||||
|
|
@ -411,7 +427,7 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
|
|||
getString(R.string.task_profile_rename_failure),
|
||||
R.drawable.ic_task_rename
|
||||
) {
|
||||
euiccChannelManager.withEuiccChannel(slotId, portId) { channel ->
|
||||
euiccChannelManager.withEuiccChannel(slotId, portId, seId) { channel ->
|
||||
channel.lpa.setNickname(
|
||||
iccid,
|
||||
name
|
||||
|
|
@ -422,6 +438,7 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
|
|||
fun launchProfileDeleteTask(
|
||||
slotId: Int,
|
||||
portId: Int,
|
||||
seId: EuiccChannel.SecureElementId,
|
||||
iccid: String
|
||||
): ForegroundTaskSubscriberFlow =
|
||||
launchForegroundTask(
|
||||
|
|
@ -429,8 +446,8 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
|
|||
getString(R.string.task_profile_delete_failure),
|
||||
R.drawable.ic_task_delete
|
||||
) {
|
||||
euiccChannelManager.beginTrackedOperation(slotId, portId) {
|
||||
euiccChannelManager.withEuiccChannel(slotId, portId) { channel ->
|
||||
euiccChannelManager.beginTrackedOperation(slotId, portId, seId) {
|
||||
euiccChannelManager.withEuiccChannel(slotId, portId, seId) { channel ->
|
||||
channel.lpa.deleteProfile(iccid)
|
||||
}
|
||||
|
||||
|
|
@ -443,33 +460,38 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
|
|||
fun launchProfileSwitchTask(
|
||||
slotId: Int,
|
||||
portId: Int,
|
||||
seId: EuiccChannel.SecureElementId,
|
||||
iccid: String,
|
||||
enable: Boolean, // Enable or disable the profile indicated in iccid
|
||||
reconnectTimeoutMillis: Long = 0 // 0 = do not wait for reconnect
|
||||
): ForegroundTaskSubscriberFlow =
|
||||
) =
|
||||
launchForegroundTask(
|
||||
getString(R.string.task_profile_switch),
|
||||
getString(R.string.task_profile_switch_failure),
|
||||
R.drawable.ic_task_switch
|
||||
) {
|
||||
euiccChannelManager.beginTrackedOperation(slotId, portId) {
|
||||
val (res, refreshed) = euiccChannelManager.withEuiccChannel(
|
||||
slotId,
|
||||
portId
|
||||
) { channel ->
|
||||
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)
|
||||
euiccChannelManager.beginTrackedOperation(slotId, portId, seId) {
|
||||
val (response, refreshed) =
|
||||
euiccChannelManager.withEuiccChannel(slotId, portId, seId) { 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 (!res) {
|
||||
if (!response) {
|
||||
throw RuntimeException("Could not switch profile")
|
||||
}
|
||||
|
||||
|
|
@ -495,4 +517,23 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
|
|||
preferenceRepository.notificationSwitchFlow.first()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun launchMemoryReset(
|
||||
slotId: Int,
|
||||
portId: Int,
|
||||
seId: EuiccChannel.SecureElementId
|
||||
): 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, seId) {
|
||||
euiccChannelManager.withEuiccChannel(slotId, portId, seId) { channel ->
|
||||
channel.lpa.euiccMemoryReset()
|
||||
}
|
||||
|
||||
preferenceRepository.notificationDeleteFlow.first()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
package im.angry.openeuicc.ui
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.ServiceConnection
|
||||
import android.os.Bundle
|
||||
|
|
@ -36,7 +35,7 @@ abstract class BaseEuiccAccessActivity : AppCompatActivity() {
|
|||
bindService(
|
||||
Intent(this, EuiccChannelManagerService::class.java),
|
||||
euiccChannelManagerServiceConnection,
|
||||
Context.BIND_AUTO_CREATE
|
||||
BIND_AUTO_CREATE
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -49,4 +48,4 @@ abstract class BaseEuiccAccessActivity : AppCompatActivity() {
|
|||
* When called, euiccChannelManager is guaranteed to have been initialized
|
||||
*/
|
||||
abstract fun onInit()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import androidx.fragment.app.DialogFragment
|
|||
import com.google.android.material.color.DynamicColors
|
||||
import im.angry.openeuicc.common.R
|
||||
|
||||
abstract class BaseMaterialDialogFragment: DialogFragment() {
|
||||
abstract class BaseMaterialDialogFragment : DialogFragment() {
|
||||
override fun onGetLayoutInflater(savedInstanceState: Bundle?): LayoutInflater {
|
||||
val inflater = super.onGetLayoutInflater(savedInstanceState)
|
||||
val wrappedContext = ContextThemeWrapper(requireContext(), R.style.Theme_OpenEUICC)
|
||||
|
|
@ -23,4 +23,4 @@ abstract class BaseMaterialDialogFragment: DialogFragment() {
|
|||
it.window?.setBackgroundDrawableResource(R.drawable.dialog_background)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,22 +23,32 @@ 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
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
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: <https://regex101.com/r/5FFz8u>
|
||||
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.yes, R.string.no)
|
||||
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
|
||||
private var seId: EuiccChannel.SecureElementId = EuiccChannel.SecureElementId.DEFAULT
|
||||
|
||||
data class Item(
|
||||
@StringRes
|
||||
@get:StringRes
|
||||
val titleResId: Int,
|
||||
val content: String?,
|
||||
val copiedToastResId: Int? = null,
|
||||
|
|
@ -49,7 +59,6 @@ class EuiccInfoActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
super.onCreate(savedInstanceState)
|
||||
setContentView(R.layout.activity_euicc_info)
|
||||
setSupportActionBar(requireViewById(R.id.toolbar))
|
||||
setupToolbarInsets()
|
||||
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
|
||||
|
||||
swipeRefresh = requireViewById(R.id.swipe_refresh)
|
||||
|
|
@ -60,18 +69,27 @@ class EuiccInfoActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
}
|
||||
|
||||
logicalSlotId = intent.getIntExtra("logicalSlotId", 0)
|
||||
|
||||
val channelTitle = if (logicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
|
||||
getString(R.string.usb)
|
||||
seId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
intent.getParcelableExtra("seId", EuiccChannel.SecureElementId::class.java)
|
||||
} else {
|
||||
appContainer.customizableTextProvider.formatInternalChannelName(logicalSlotId)
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
intent.getParcelableExtra("seId")
|
||||
} ?: EuiccChannel.SecureElementId.DEFAULT
|
||||
|
||||
title = getString(R.string.euicc_info_activity_title, channelTitle)
|
||||
setChannelTitle(
|
||||
if (logicalSlotId == EuiccChannelManager.USB_CHANNEL_ID)
|
||||
getString(R.string.channel_name_format_usb) else
|
||||
appContainer.customizableTextProvider.formatNonUsbChannelName(logicalSlotId)
|
||||
)
|
||||
|
||||
swipeRefresh.setOnRefreshListener { refresh() }
|
||||
|
||||
setupRootViewInsets(infoList)
|
||||
setupRootViewSystemBarInsets(
|
||||
window.decorView.rootView, arrayOf(
|
||||
this::activityToolbarInsetHandler,
|
||||
mainViewPaddingInsetHandler(infoList)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
|
||||
|
|
@ -83,6 +101,10 @@ class EuiccInfoActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
else -> super.onOptionsItemSelected(item)
|
||||
}
|
||||
|
||||
private fun setChannelTitle(title: CharSequence) {
|
||||
super.setTitle(getString(R.string.euicc_info_activity_title, title))
|
||||
}
|
||||
|
||||
override fun onInit() {
|
||||
refresh()
|
||||
}
|
||||
|
|
@ -91,8 +113,24 @@ class EuiccInfoActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
swipeRefresh.isRefreshing = true
|
||||
|
||||
lifecycleScope.launch {
|
||||
(infoList.adapter!! as EuiccInfoAdapter).euiccInfoItems =
|
||||
euiccChannelManager.withEuiccChannel(logicalSlotId, ::buildEuiccInfoItems)
|
||||
euiccChannelManager.withEuiccChannel(logicalSlotId, seId) { channel ->
|
||||
if (channel.hasMultipleSE) {
|
||||
withContext(Dispatchers.Main) {
|
||||
val title = if (logicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
|
||||
getString(R.string.channel_name_format_usb_se, seId.id)
|
||||
} else {
|
||||
appContainer.customizableTextProvider.formatNonUsbChannelNameWithSeId(logicalSlotId, seId)
|
||||
}
|
||||
setChannelTitle(title)
|
||||
}
|
||||
}
|
||||
|
||||
val items = buildEuiccInfoItems(channel)
|
||||
|
||||
withContext(Dispatchers.Main) {
|
||||
(infoList.adapter!! as EuiccInfoAdapter).euiccInfoItems = items
|
||||
}
|
||||
}
|
||||
|
||||
swipeRefresh.isRefreshing = false
|
||||
}
|
||||
|
|
@ -100,26 +138,30 @@ class EuiccInfoActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
|
||||
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
|
||||
)
|
||||
)
|
||||
channel.lpa.euiccInfo2.let { info ->
|
||||
add(Item(R.string.euicc_info_sgp22_version, info?.sgp22Version))
|
||||
add(Item(R.string.euicc_info_firmware_version, info?.euiccFirmwareVersion))
|
||||
add(Item(R.string.euicc_info_globalplatform_version, info?.globalPlatformVersion))
|
||||
add(Item(R.string.euicc_info_pp_version, info?.ppVersion))
|
||||
add(Item(R.string.euicc_info_sas_accreditation_number, info?.sasAccreditationNumber))
|
||||
add(Item(R.string.euicc_info_free_nvram, info?.freeNvram?.let(::formatFreeSpace)))
|
||||
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))
|
||||
if (!channel.isdrAid.contentEquals(EUICC_DEFAULT_ISDR_AID.decodeHex())) {
|
||||
// Only show if it's not the default ISD-R AID
|
||||
add(Item(R.string.euicc_info_isdr_aid, channel.isdrAid.encodeHex()))
|
||||
}
|
||||
channel.tryParseEuiccVendorInfo()?.let { vendorInfo ->
|
||||
// @formatter:off
|
||||
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)) }
|
||||
// @formatter:on
|
||||
}
|
||||
channel.lpa.euiccInfo2?.let { info ->
|
||||
add(Item(R.string.euicc_info_sgp22_version, info.sgp22Version.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)
|
||||
|
|
@ -127,30 +169,20 @@ class EuiccInfoActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
// 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.unknown // the case is not mp, but it's is not common
|
||||
signers.isEmpty() -> R.string.euicc_info_unknown // the case is not mp, but it 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)))
|
||||
}
|
||||
add(
|
||||
Item(
|
||||
R.string.euicc_info_atr,
|
||||
channel.atr?.encodeHex() ?: getString(R.string.information_unavailable),
|
||||
copiedToastResId = R.string.toast_atr_copied,
|
||||
)
|
||||
)
|
||||
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<Int, Int>): String =
|
||||
getString(
|
||||
if (b) {
|
||||
res.first
|
||||
} else {
|
||||
res.second
|
||||
}
|
||||
)
|
||||
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)
|
||||
|
|
@ -177,7 +209,7 @@ class EuiccInfoActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
fun bind(item: Item) {
|
||||
copiedToastResId = item.copiedToastResId
|
||||
title.setText(item.titleResId)
|
||||
content.text = item.content ?: getString(R.string.unknown)
|
||||
content.text = item.content ?: getString(R.string.euicc_info_unknown)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -201,4 +233,4 @@ class EuiccInfoActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
holder.bind(euiccInfoItems[position])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,8 +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
|
||||
|
|
@ -29,8 +27,8 @@ import androidx.recyclerview.widget.LinearLayoutManager
|
|||
import androidx.recyclerview.widget.RecyclerView
|
||||
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.core.EuiccChannel
|
||||
import im.angry.openeuicc.service.EuiccChannelManagerService
|
||||
import im.angry.openeuicc.service.EuiccChannelManagerService.Companion.waitDone
|
||||
import im.angry.openeuicc.ui.wizard.DownloadWizardActivity
|
||||
|
|
@ -41,20 +39,28 @@ import kotlinx.coroutines.flow.StateFlow
|
|||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import net.typeblog.lpac_jni.LocalProfileInfo
|
||||
import net.typeblog.lpac_jni.ProfileClass
|
||||
|
||||
open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
||||
EuiccChannelFragmentMarker {
|
||||
companion object {
|
||||
const val TAG = "EuiccManagementFragment"
|
||||
|
||||
fun newInstance(slotId: Int, portId: Int): EuiccManagementFragment =
|
||||
newInstanceEuicc(EuiccManagementFragment::class.java, slotId, portId)
|
||||
fun newInstance(
|
||||
slotId: Int,
|
||||
portId: Int,
|
||||
seId: EuiccChannel.SecureElementId
|
||||
): EuiccManagementFragment =
|
||||
newInstanceEuicc(EuiccManagementFragment::class.java, slotId, portId, seId)
|
||||
}
|
||||
|
||||
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 var enabledProfile: LocalProfileInfo? = null
|
||||
|
||||
private val adapter = EuiccProfileAdapter()
|
||||
|
||||
|
|
@ -86,18 +92,22 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
|
||||
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<ViewGroup.MarginLayoutParams> {
|
||||
rightMargin = origFabMarginRight + bars.right
|
||||
bottomMargin = origFabMarginBottom + bars.bottom
|
||||
setupRootViewSystemBarInsets(
|
||||
view, arrayOf(
|
||||
mainViewPaddingInsetHandler(profileList),
|
||||
{ insets ->
|
||||
fab.updateLayoutParams<ViewGroup.MarginLayoutParams> {
|
||||
rightMargin = origFabMarginRight + insets.right
|
||||
bottomMargin = origFabMarginBottom + insets.bottom
|
||||
}
|
||||
}
|
||||
))
|
||||
|
||||
WindowInsetsCompat.CONSUMED
|
||||
}
|
||||
|
||||
setupRootViewInsets(profileList)
|
||||
profileList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||
override fun onScrollStateChanged(view: RecyclerView, newState: Int) =
|
||||
if (newState == RecyclerView.SCROLL_STATE_IDLE) fab.show() else fab.hide()
|
||||
})
|
||||
|
||||
return view
|
||||
}
|
||||
|
|
@ -110,10 +120,8 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
LinearLayoutManager(view.context, LinearLayoutManager.VERTICAL, false)
|
||||
|
||||
fab.setOnClickListener {
|
||||
Intent(requireContext(), DownloadWizardActivity::class.java).apply {
|
||||
putExtra("selectedLogicalSlot", logicalSlotId)
|
||||
startActivity(this)
|
||||
}
|
||||
val intent = DownloadWizardActivity.newIntent(requireContext(), slotId, seId)
|
||||
startActivity(intent)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -131,31 +139,44 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
inflater.inflate(R.menu.fragment_euicc, menu)
|
||||
}
|
||||
|
||||
override fun onOptionsItemSelected(item: MenuItem): Boolean =
|
||||
when (item.itemId) {
|
||||
R.id.show_notifications -> {
|
||||
if (logicalSlotId != -1) {
|
||||
Intent(requireContext(), NotificationsActivity::class.java).apply {
|
||||
putExtra("logicalSlotId", logicalSlotId)
|
||||
startActivity(this)
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
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 =
|
||||
enabledProfile == null
|
||||
}
|
||||
|
||||
R.id.euicc_info -> {
|
||||
if (logicalSlotId != -1) {
|
||||
Intent(requireContext(), EuiccInfoActivity::class.java).apply {
|
||||
putExtra("logicalSlotId", logicalSlotId)
|
||||
startActivity(this)
|
||||
}
|
||||
}
|
||||
true
|
||||
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
|
||||
R.id.show_notifications -> {
|
||||
Intent(requireContext(), NotificationsActivity::class.java).apply {
|
||||
putExtra("logicalSlotId", logicalSlotId)
|
||||
putExtra("seId", seId)
|
||||
startActivity(this)
|
||||
}
|
||||
|
||||
else -> super.onOptionsItemSelected(item)
|
||||
true
|
||||
}
|
||||
|
||||
R.id.euicc_info -> {
|
||||
Intent(requireContext(), EuiccInfoActivity::class.java).apply {
|
||||
putExtra("logicalSlotId", logicalSlotId)
|
||||
putExtra("seId", seId)
|
||||
startActivity(this)
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
R.id.euicc_memory_reset -> {
|
||||
EuiccMemoryResetFragment.newInstance(slotId, portId, seId, eid)
|
||||
.show(childFragmentManager, EuiccMemoryResetFragment.TAG)
|
||||
true
|
||||
}
|
||||
|
||||
else -> super.onOptionsItemSelected(item)
|
||||
}
|
||||
|
||||
protected open suspend fun onCreateFooterViews(
|
||||
parent: ViewGroup,
|
||||
profiles: List<LocalProfileInfo>
|
||||
|
|
@ -192,6 +213,8 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
|
||||
val profiles = withEuiccChannel { channel ->
|
||||
logicalSlotId = channel.logicalSlotId
|
||||
eid = channel.lpa.eID
|
||||
enabledProfile = channel.lpa.profiles.enabled
|
||||
euiccChannelManager.notifyEuiccProfilesChanged(channel.logicalSlotId)
|
||||
if (unfilteredProfileListFlow.value)
|
||||
channel.lpa.profiles
|
||||
|
|
@ -208,11 +231,8 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
}
|
||||
|
||||
private suspend fun showSwitchFailureText() = withContext(Dispatchers.Main) {
|
||||
Toast.makeText(
|
||||
context,
|
||||
R.string.toast_profile_enable_failed,
|
||||
Toast.LENGTH_LONG
|
||||
).show()
|
||||
val resId = R.string.toast_profile_enable_failed
|
||||
Toast.makeText(context, resId, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
|
||||
private fun enableOrDisableProfile(iccid: String, enable: Boolean) {
|
||||
|
|
@ -223,13 +243,12 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
ensureEuiccChannelManager()
|
||||
euiccChannelManagerService.waitForForegroundTask()
|
||||
|
||||
val err = euiccChannelManagerService.launchProfileSwitchTask(
|
||||
slotId,
|
||||
portId,
|
||||
iccid,
|
||||
enable,
|
||||
reconnectTimeoutMillis = 30 * 1000
|
||||
).waitDone()
|
||||
val err = euiccChannelManagerService
|
||||
.launchProfileSwitchTask(
|
||||
slotId, portId, seId, iccid, enable,
|
||||
reconnectTimeoutMillis = 30 * 1000
|
||||
)
|
||||
.waitDone()
|
||||
|
||||
when (err) {
|
||||
null -> {}
|
||||
|
|
@ -238,7 +257,7 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
if (!isUsb) {
|
||||
withContext(Dispatchers.Main) {
|
||||
AlertDialog.Builder(requireContext()).apply {
|
||||
setMessage(R.string.switch_did_not_refresh)
|
||||
setMessage(R.string.profile_switch_did_not_refresh)
|
||||
setPositiveButton(android.R.string.ok) { dialog, _ ->
|
||||
dialog.dismiss()
|
||||
requireActivity().finish()
|
||||
|
|
@ -279,19 +298,20 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
}
|
||||
}
|
||||
|
||||
protected open fun populatePopupWithProfileActions(popup: PopupMenu, profile: LocalProfileInfo) {
|
||||
protected open fun populatePopupWithProfileActions(
|
||||
popup: PopupMenu,
|
||||
profile: LocalProfileInfo
|
||||
) {
|
||||
popup.inflate(R.menu.profile_options)
|
||||
if (profile.isEnabled) {
|
||||
popup.menu.findItem(R.id.enable).isVisible = false
|
||||
popup.menu.findItem(R.id.delete).isVisible = false
|
||||
if (!profile.isEnabled) return
|
||||
popup.menu.findItem(R.id.enable).isVisible = false
|
||||
popup.menu.findItem(R.id.delete).isVisible = false
|
||||
|
||||
// We hide the disable option by default to avoid "bricking" some cards that won't get
|
||||
// recognized again by the phone's modem. However we don't have that worry if we are
|
||||
// accessing it through a USB card reader, or when the user explicitly opted in
|
||||
if (isUsb || disableSafeguardFlow.value) {
|
||||
popup.menu.findItem(R.id.disable).isVisible = true
|
||||
}
|
||||
}
|
||||
// We hide the disable option by default to avoid "bricking" some cards that won't get
|
||||
// recognized again by the phone's modem. However, we don't have that worry if we are
|
||||
// accessing it through a USB card reader, or when the user explicitly opted in
|
||||
if (!isUsb && !disableSafeguardFlow.value) return
|
||||
popup.menu.findItem(R.id.disable).isVisible = true
|
||||
}
|
||||
|
||||
sealed class ViewHolder(root: View) : RecyclerView.ViewHolder(root) {
|
||||
|
|
@ -306,7 +326,7 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
}
|
||||
}
|
||||
|
||||
inner class FooterViewHolder: ViewHolder(FrameLayout(requireContext())) {
|
||||
inner class FooterViewHolder : ViewHolder(FrameLayout(requireContext())) {
|
||||
init {
|
||||
itemView.layoutParams = ViewGroup.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
|
|
@ -332,6 +352,7 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
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 {
|
||||
|
|
@ -351,10 +372,13 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
true
|
||||
}
|
||||
|
||||
profileMenu.setOnClickListener { showOptionsMenu() }
|
||||
profileMenu.setOnClickListener {
|
||||
showOptionsMenu()
|
||||
}
|
||||
}
|
||||
|
||||
private lateinit var profile: LocalProfileInfo
|
||||
private var canEnable: Boolean = false
|
||||
|
||||
fun setProfile(profile: LocalProfileInfo) {
|
||||
this.profile = profile
|
||||
|
|
@ -362,9 +386,9 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
|
||||
state.setText(
|
||||
if (profile.isEnabled) {
|
||||
R.string.enabled
|
||||
R.string.profile_state_enabled
|
||||
} else {
|
||||
R.string.disabled
|
||||
R.string.profile_state_disabled
|
||||
}
|
||||
)
|
||||
provider.text = profile.providerName
|
||||
|
|
@ -372,15 +396,29 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
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
|
||||
ProfileClass.Testing -> R.string.profile_class_testing
|
||||
ProfileClass.Provisioning -> R.string.profile_class_provisioning
|
||||
ProfileClass.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,
|
||||
)
|
||||
}
|
||||
|
||||
fun setEnabledProfile(enabledProfile: LocalProfileInfo?) {
|
||||
// cannot cross profile class enable profile
|
||||
// e.g: testing -> operational or operational -> testing
|
||||
canEnable = enabledProfile == null ||
|
||||
enabledProfile.profileClass == profile.profileClass
|
||||
}
|
||||
|
||||
private fun showOptionsMenu() {
|
||||
// Prevent users from doing multiple things at once
|
||||
if (invalid || swipeRefresh.isRefreshing) return
|
||||
|
|
@ -395,23 +433,45 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
private fun onMenuItemClicked(item: MenuItem): Boolean =
|
||||
when (item.itemId) {
|
||||
R.id.enable -> {
|
||||
enableOrDisableProfile(profile.iccid, true)
|
||||
if (canEnable) {
|
||||
enableOrDisableProfile(profile.iccid, true)
|
||||
} else {
|
||||
val resId = R.string.toast_profile_enable_cross_class
|
||||
Toast.makeText(requireContext(), resId, Toast.LENGTH_LONG)
|
||||
.show()
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
R.id.disable -> {
|
||||
enableOrDisableProfile(profile.iccid, false)
|
||||
true
|
||||
}
|
||||
|
||||
R.id.rename -> {
|
||||
ProfileRenameFragment.newInstance(slotId, portId, profile.iccid, profile.displayName)
|
||||
ProfileRenameFragment.newInstance(
|
||||
slotId,
|
||||
portId,
|
||||
seId,
|
||||
profile.iccid,
|
||||
profile.displayName
|
||||
)
|
||||
.show(childFragmentManager, ProfileRenameFragment.TAG)
|
||||
true
|
||||
}
|
||||
|
||||
R.id.delete -> {
|
||||
ProfileDeleteFragment.newInstance(slotId, portId, profile.iccid, profile.displayName)
|
||||
ProfileDeleteFragment.newInstance(
|
||||
slotId,
|
||||
portId,
|
||||
seId,
|
||||
profile.iccid,
|
||||
profile.displayName
|
||||
)
|
||||
.show(childFragmentManager, ProfileDeleteFragment.TAG)
|
||||
true
|
||||
}
|
||||
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
|
@ -423,9 +483,11 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
|
||||
when (ViewHolder.Type.fromInt(viewType)) {
|
||||
ViewHolder.Type.PROFILE -> {
|
||||
val view = LayoutInflater.from(parent.context).inflate(R.layout.euicc_profile, parent, false)
|
||||
val view = LayoutInflater.from(parent.context)
|
||||
.inflate(R.layout.euicc_profile, parent, false)
|
||||
ProfileViewHolder(view)
|
||||
}
|
||||
|
||||
ViewHolder.Type.FOOTER -> {
|
||||
FooterViewHolder()
|
||||
}
|
||||
|
|
@ -436,9 +498,11 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
position < profiles.size -> {
|
||||
ViewHolder.Type.PROFILE.value
|
||||
}
|
||||
|
||||
position >= profiles.size && position < profiles.size + footerViews.size -> {
|
||||
ViewHolder.Type.FOOTER.value
|
||||
}
|
||||
|
||||
else -> -1
|
||||
}
|
||||
|
||||
|
|
@ -446,7 +510,10 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
when (holder) {
|
||||
is ProfileViewHolder -> {
|
||||
holder.setProfile(profiles[position])
|
||||
holder.setEnabledProfile(profiles.enabled)
|
||||
holder.setProfileSequenceNumber(position + 1)
|
||||
}
|
||||
|
||||
is FooterViewHolder -> {
|
||||
holder.attach(footerViews[position - profiles.size])
|
||||
}
|
||||
|
|
@ -461,4 +528,4 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener,
|
|||
|
||||
override fun getItemCount(): Int = profiles.size + footerViews.size
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,119 @@
|
|||
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.lifecycle.lifecycleScope
|
||||
import im.angry.openeuicc.common.R
|
||||
import im.angry.openeuicc.core.EuiccChannel
|
||||
import im.angry.openeuicc.service.EuiccChannelManagerService.Companion.waitDone
|
||||
import im.angry.openeuicc.util.*
|
||||
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, seId: EuiccChannel.SecureElementId, eid: String) =
|
||||
newInstanceEuicc(EuiccMemoryResetFragment::class.java, slotId, portId, seId) {
|
||||
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, seId)
|
||||
.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
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
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.*
|
||||
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))
|
||||
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
|
||||
|
||||
isdrAidListEditor = requireViewById(R.id.isdr_aid_list_editor)
|
||||
|
||||
setupRootViewSystemBarInsets(
|
||||
window.decorView.rootView, arrayOf(
|
||||
this::activityToolbarInsetHandler,
|
||||
mainViewPaddingInsetHandler(isdrAidListEditor)
|
||||
)
|
||||
)
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
|
@ -51,14 +51,18 @@ class LogsActivity : AppCompatActivity() {
|
|||
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)
|
||||
setupRootViewSystemBarInsets(
|
||||
window.decorView.rootView, arrayOf(
|
||||
this::activityToolbarInsetHandler,
|
||||
mainViewPaddingInsetHandler(scrollView)
|
||||
)
|
||||
)
|
||||
|
||||
swipeRefresh.setOnRefreshListener {
|
||||
lifecycleScope.launch {
|
||||
|
|
@ -84,10 +88,12 @@ class LogsActivity : AppCompatActivity() {
|
|||
finish()
|
||||
true
|
||||
}
|
||||
|
||||
R.id.save -> {
|
||||
saveLogs()
|
||||
true
|
||||
}
|
||||
|
||||
else -> super.onOptionsItemSelected(item)
|
||||
}
|
||||
|
||||
|
|
@ -107,4 +113,4 @@ class LogsActivity : AppCompatActivity() {
|
|||
scrollView.fullScroll(View.FOCUS_DOWN)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,6 +16,9 @@ import android.view.MenuItem
|
|||
import android.view.View
|
||||
import android.widget.ProgressBar
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.core.content.pm.ShortcutInfoCompat
|
||||
import androidx.core.content.pm.ShortcutManagerCompat
|
||||
import androidx.core.graphics.drawable.IconCompat
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.viewpager2.adapter.FragmentStateAdapter
|
||||
|
|
@ -23,7 +26,9 @@ 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.EuiccChannel
|
||||
import im.angry.openeuicc.core.EuiccChannelManager
|
||||
import im.angry.openeuicc.ui.wizard.DownloadWizardActivity
|
||||
import im.angry.openeuicc.util.*
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.collect
|
||||
|
|
@ -47,18 +52,30 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
private var refreshing = false
|
||||
|
||||
private data class Page(
|
||||
val id: Long,
|
||||
val logicalSlotId: Int,
|
||||
val title: String,
|
||||
val createFragment: () -> Fragment
|
||||
)
|
||||
|
||||
private val pages: MutableList<Page> = mutableListOf()
|
||||
private var nextPageId = 0L
|
||||
|
||||
private fun newPage(
|
||||
logicalSlotId: Int,
|
||||
title: String,
|
||||
createFragment: () -> Fragment
|
||||
): Page = Page(nextPageId++, logicalSlotId, title, createFragment)
|
||||
|
||||
private val pagerAdapter by lazy {
|
||||
object : FragmentStateAdapter(this) {
|
||||
override fun getItemCount() = pages.size
|
||||
|
||||
override fun createFragment(position: Int): Fragment = pages[position].createFragment()
|
||||
|
||||
override fun getItemId(position: Int): Long = pages[position].id
|
||||
|
||||
override fun containsItem(itemId: Long): Boolean = pages.any { it.id == itemId }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -78,7 +95,6 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
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)
|
||||
|
|
@ -94,6 +110,12 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
|
||||
addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
|
||||
})
|
||||
|
||||
setupRootViewSystemBarInsets(
|
||||
window.decorView.rootView, arrayOf(
|
||||
this::activityToolbarInsetHandler
|
||||
), consume = false
|
||||
)
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
|
|
@ -112,10 +134,12 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
startActivity(Intent(this, SettingsActivity::class.java))
|
||||
true
|
||||
}
|
||||
|
||||
R.id.reload -> {
|
||||
refresh()
|
||||
true
|
||||
}
|
||||
|
||||
else -> super.onOptionsItemSelected(item)
|
||||
}
|
||||
|
||||
|
|
@ -126,15 +150,10 @@ 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
|
||||
)
|
||||
}
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
|
||||
val permissions = arrayOf(android.Manifest.permission.POST_NOTIFICATIONS)
|
||||
if (permissions.all { checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED }) return
|
||||
requestPermissions(permissions, PERMISSION_REQUEST_CODE)
|
||||
}
|
||||
|
||||
private suspend fun init(fromUsbEvent: Boolean = false) {
|
||||
|
|
@ -154,29 +173,40 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
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)
|
||||
}
|
||||
// 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)
|
||||
euiccChannelManager.flowEuiccSecureElements(slotId, portId).onEach { seId ->
|
||||
euiccChannelManager.withEuiccChannel(slotId, portId, seId) { channel ->
|
||||
if (preferenceRepository.verboseLoggingFlow.first()) {
|
||||
Log.d(TAG, channel.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)
|
||||
})
|
||||
}
|
||||
val channelName = if (channel.hasMultipleSE) {
|
||||
appContainer.customizableTextProvider.formatNonUsbChannelNameWithSeId(
|
||||
channel.logicalSlotId,
|
||||
channel.seId
|
||||
)
|
||||
} else {
|
||||
appContainer.customizableTextProvider.formatNonUsbChannelName(channel.logicalSlotId)
|
||||
}
|
||||
newPages.add(newPage(channel.logicalSlotId, channelName) {
|
||||
appContainer.uiComponentFactory.createEuiccManagementFragment(
|
||||
slotId,
|
||||
portId,
|
||||
seId
|
||||
)
|
||||
})
|
||||
}
|
||||
}.collect()
|
||||
}.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.usb)
|
||||
newPages.add(Page(EuiccChannelManager.USB_CHANNEL_ID, productName) {
|
||||
UsbCcidReaderFragment()
|
||||
newPages.add(newPage(EuiccChannelManager.USB_CHANNEL_ID, getString(R.string.channel_name_format_usb)) {
|
||||
UsbCcidReaderPermissionFragment()
|
||||
})
|
||||
}
|
||||
viewPager.visibility = View.VISIBLE
|
||||
|
|
@ -184,7 +214,7 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
if (newPages.size > 1) {
|
||||
tabs.visibility = View.VISIBLE
|
||||
} else if (newPages.isEmpty()) {
|
||||
newPages.add(Page(-1, "") {
|
||||
newPages.add(newPage(-1, "") {
|
||||
appContainer.uiComponentFactory.createNoEuiccPlaceholderFragment()
|
||||
})
|
||||
}
|
||||
|
|
@ -209,10 +239,12 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
viewPager.currentItem = 0
|
||||
}
|
||||
|
||||
if (pages.size > 0) {
|
||||
if (pages.isNotEmpty()) {
|
||||
ensureNotificationPermissions()
|
||||
}
|
||||
|
||||
ShortcutManagerCompat.setDynamicShortcuts(this, buildShortcuts().take(4))
|
||||
|
||||
refreshing = false
|
||||
}
|
||||
|
||||
|
|
@ -231,4 +263,44 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
init(fromUsbEvent) // will set refreshing = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected open fun buildShortcuts(): List<ShortcutInfoCompat> {
|
||||
val downloadShortcut = ShortcutInfoCompat.Builder(this, "download")
|
||||
.setShortLabel(getString(R.string.profile_download))
|
||||
.setIcon(IconCompat.createWithResource(this, R.drawable.ic_task_sim_card_download))
|
||||
.setIntent(DownloadWizardActivity.newIntent(this).apply { action = Intent.ACTION_VIEW })
|
||||
.build()
|
||||
return listOf(downloadShortcut)
|
||||
}
|
||||
|
||||
fun instantiateUsbTabs(seIds: List<EuiccChannel.SecureElementId>) {
|
||||
val existingUsbPageIndex = pages.indexOfFirst { it.logicalSlotId == EuiccChannelManager.USB_CHANNEL_ID }
|
||||
if (existingUsbPageIndex == -1) return
|
||||
|
||||
val usbPages =
|
||||
seIds.map { seId ->
|
||||
val name = if (seIds.size == 1) {
|
||||
getString(R.string.channel_name_format_usb)
|
||||
} else {
|
||||
getString(R.string.channel_name_format_usb_se, seId.id)
|
||||
}
|
||||
newPage(EuiccChannelManager.USB_CHANNEL_ID, name) {
|
||||
appContainer.uiComponentFactory.createEuiccManagementFragment(
|
||||
EuiccChannelManager.USB_CHANNEL_ID,
|
||||
0,
|
||||
seId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Add before removing to avoid out-of-bounds problems
|
||||
pages.addAll(existingUsbPageIndex, usbPages)
|
||||
// Remove the old USB reader page
|
||||
pages.removeAt(existingUsbPageIndex + usbPages.size)
|
||||
|
||||
if (pages.size > 1) {
|
||||
tabs.visibility = View.VISIBLE
|
||||
}
|
||||
pagerAdapter.notifyDataSetChanged()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import android.view.ViewGroup
|
|||
import android.widget.TextView
|
||||
import androidx.fragment.app.Fragment
|
||||
import im.angry.openeuicc.common.R
|
||||
import im.angry.openeuicc.util.*
|
||||
import im.angry.openeuicc.util.OpenEuiccContextMarker
|
||||
|
||||
class NoEuiccPlaceholderFragment : Fragment(), OpenEuiccContextMarker {
|
||||
override fun onCreateView(
|
||||
|
|
@ -20,4 +20,4 @@ class NoEuiccPlaceholderFragment : Fragment(), OpenEuiccContextMarker {
|
|||
textView.text = appContainer.customizableTextProvider.noEuiccExplanation
|
||||
return view
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package im.angry.openeuicc.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.text.Html
|
||||
import android.view.ContextMenu
|
||||
|
|
@ -20,6 +21,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
|
||||
|
|
@ -27,45 +29,54 @@ import kotlinx.coroutines.launch
|
|||
import kotlinx.coroutines.withContext
|
||||
import net.typeblog.lpac_jni.LocalProfileNotification
|
||||
|
||||
class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
||||
class NotificationsActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
||||
private lateinit var swipeRefresh: SwipeRefreshLayout
|
||||
private lateinit var notificationList: RecyclerView
|
||||
private val notificationAdapter = NotificationAdapter()
|
||||
|
||||
private var logicalSlotId = -1
|
||||
private var seId = EuiccChannel.SecureElementId.DEFAULT
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
setContentView(R.layout.activity_notifications)
|
||||
setSupportActionBar(requireViewById(R.id.toolbar))
|
||||
setupToolbarInsets()
|
||||
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
|
||||
|
||||
swipeRefresh = requireViewById(R.id.swipe_refresh)
|
||||
notificationList = requireViewById(R.id.recycler_view)
|
||||
|
||||
setupRootViewInsets(notificationList)
|
||||
setupRootViewSystemBarInsets(
|
||||
window.decorView.rootView, arrayOf(
|
||||
this::activityToolbarInsetHandler,
|
||||
mainViewPaddingInsetHandler(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.usb)
|
||||
} else {
|
||||
appContainer.customizableTextProvider.formatInternalChannelName(logicalSlotId)
|
||||
notificationList.apply {
|
||||
val context = this@NotificationsActivity
|
||||
adapter = notificationAdapter
|
||||
layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
|
||||
addItemDecoration(DividerItemDecoration(context, LinearLayoutManager.VERTICAL))
|
||||
registerForContextMenu(this)
|
||||
}
|
||||
|
||||
title = getString(R.string.profile_notifications_detailed_format, channelTitle)
|
||||
logicalSlotId = intent.getIntExtra("logicalSlotId", 0)
|
||||
seId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
intent.getParcelableExtra("seId", EuiccChannel.SecureElementId::class.java)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
intent.getParcelableExtra("seId")
|
||||
} ?: EuiccChannel.SecureElementId.DEFAULT
|
||||
|
||||
setChannelTitle(
|
||||
if (logicalSlotId == EuiccChannelManager.USB_CHANNEL_ID)
|
||||
getString(R.string.channel_name_format_usb) else
|
||||
appContainer.customizableTextProvider.formatNonUsbChannelName(logicalSlotId)
|
||||
)
|
||||
|
||||
swipeRefresh.setOnRefreshListener {
|
||||
refresh()
|
||||
|
|
@ -86,6 +97,7 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
finish()
|
||||
true
|
||||
}
|
||||
|
||||
R.id.help -> {
|
||||
AlertDialog.Builder(this, R.style.AlertDialogTheme).apply {
|
||||
setMessage(R.string.profile_notifications_help)
|
||||
|
|
@ -96,9 +108,14 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
}
|
||||
true
|
||||
}
|
||||
|
||||
else -> super.onOptionsItemSelected(item)
|
||||
}
|
||||
|
||||
private fun setChannelTitle(title: CharSequence) {
|
||||
super.setTitle(getString(R.string.profile_notifications_detailed_format, title))
|
||||
}
|
||||
|
||||
private fun launchTask(task: suspend () -> Unit) {
|
||||
swipeRefresh.isRefreshing = true
|
||||
|
||||
|
|
@ -114,29 +131,39 @@ 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)
|
||||
}
|
||||
}
|
||||
launchTask {
|
||||
notificationAdapter.notifications = withEuiccChannel { channel ->
|
||||
if (channel.hasMultipleSE) {
|
||||
withContext(Dispatchers.Main) {
|
||||
val channelTitle = if (logicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
|
||||
getString(R.string.channel_name_format_usb_se, seId.id)
|
||||
} else {
|
||||
appContainer.customizableTextProvider.formatNonUsbChannelNameWithSeId(logicalSlotId, seId)
|
||||
}
|
||||
setChannelTitle(channelTitle)
|
||||
}
|
||||
}
|
||||
|
||||
channel.lpa.notifications.map {
|
||||
LocalProfileNotificationWrapper(it, nameMap[it.iccid] ?: "???")
|
||||
}
|
||||
}
|
||||
}
|
||||
val nameMap = channel.lpa.profiles
|
||||
.associate { Pair(it.iccid, it.displayName) }
|
||||
|
||||
channel.lpa.notifications.map {
|
||||
LocalProfileNotificationWrapper(it, nameMap[it.iccid] ?: "???")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun <R> withEuiccChannel(fn: suspend (EuiccChannel) -> R) =
|
||||
euiccChannelManager.withEuiccChannel(logicalSlotId, seId, fn)
|
||||
|
||||
data class LocalProfileNotificationWrapper(
|
||||
val inner: LocalProfileNotification,
|
||||
val profileName: String
|
||||
)
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
inner class NotificationViewHolder(private val root: View):
|
||||
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 =
|
||||
|
|
@ -170,7 +197,8 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
LocalProfileNotification.Operation.Delete -> R.string.profile_notification_operation_delete
|
||||
LocalProfileNotification.Operation.Enable -> R.string.profile_notification_operation_enable
|
||||
LocalProfileNotification.Operation.Disable -> R.string.profile_notification_operation_disable
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
fun updateNotification(value: LocalProfileNotificationWrapper) {
|
||||
notification = value
|
||||
|
|
@ -181,10 +209,13 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
value.inner.seqNumber
|
||||
)
|
||||
profileName.text = Html.fromHtml(
|
||||
root.context.getString(R.string.profile_notification_name_format,
|
||||
root.context.getString(
|
||||
R.string.profile_notification_name_format,
|
||||
operationToLocalizedText(value.inner.profileManagementOperation),
|
||||
value.profileName, value.inner.iccid),
|
||||
Html.FROM_HTML_MODE_COMPACT)
|
||||
value.profileName, value.inner.iccid
|
||||
),
|
||||
Html.FROM_HTML_MODE_COMPACT
|
||||
)
|
||||
}
|
||||
|
||||
override fun onCreateContextMenu(
|
||||
|
|
@ -204,7 +235,7 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
R.id.notification_process -> {
|
||||
launchTask {
|
||||
withContext(Dispatchers.IO) {
|
||||
euiccChannelManager.withEuiccChannel(logicalSlotId) { channel ->
|
||||
withEuiccChannel { channel ->
|
||||
channel.lpa.handleNotification(notification.inner.seqNumber)
|
||||
}
|
||||
}
|
||||
|
|
@ -213,10 +244,11 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
}
|
||||
true
|
||||
}
|
||||
|
||||
R.id.notification_delete -> {
|
||||
launchTask {
|
||||
withContext(Dispatchers.IO) {
|
||||
euiccChannelManager.withEuiccChannel(logicalSlotId) { channel ->
|
||||
withEuiccChannel { channel ->
|
||||
channel.lpa.deleteNotification(notification.inner.seqNumber)
|
||||
}
|
||||
}
|
||||
|
|
@ -225,11 +257,12 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
}
|
||||
true
|
||||
}
|
||||
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
inner class NotificationAdapter: RecyclerView.Adapter<NotificationViewHolder>() {
|
||||
inner class NotificationAdapter : RecyclerView.Adapter<NotificationViewHolder>() {
|
||||
var notifications: List<LocalProfileNotificationWrapper> = listOf()
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
set(value) {
|
||||
|
|
@ -249,4 +282,4 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker {
|
|||
holder.updateNotification(notifications[position])
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import androidx.appcompat.app.AlertDialog
|
|||
import androidx.fragment.app.DialogFragment
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import im.angry.openeuicc.common.R
|
||||
import im.angry.openeuicc.core.EuiccChannel
|
||||
import im.angry.openeuicc.service.EuiccChannelManagerService.Companion.waitDone
|
||||
import im.angry.openeuicc.util.*
|
||||
import kotlinx.coroutines.flow.onStart
|
||||
|
|
@ -20,14 +21,11 @@ class ProfileDeleteFragment : DialogFragment(), EuiccChannelFragmentMarker {
|
|||
private const val FIELD_ICCID = "iccid"
|
||||
private const val 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 {
|
||||
fun newInstance(slotId: Int, portId: Int, seId: EuiccChannel.SecureElementId, iccid: String, name: String) =
|
||||
newInstanceEuicc(ProfileDeleteFragment::class.java, slotId, portId, seId) {
|
||||
putString(FIELD_ICCID, iccid)
|
||||
putString(FIELD_NAME, name)
|
||||
}
|
||||
return instance
|
||||
}
|
||||
}
|
||||
|
||||
private val iccid by lazy {
|
||||
|
|
@ -91,19 +89,12 @@ class ProfileDeleteFragment : DialogFragment(), EuiccChannelFragmentMarker {
|
|||
requireParentFragment().lifecycleScope.launch {
|
||||
ensureEuiccChannelManager()
|
||||
euiccChannelManagerService.waitForForegroundTask()
|
||||
euiccChannelManagerService.launchProfileDeleteTask(slotId, portId, iccid).onStart {
|
||||
if (parentFragment is EuiccProfilesChangedListener) {
|
||||
// Trigger a refresh in the parent fragment -- it should wait until
|
||||
// any foreground task is completed before actually doing a refresh
|
||||
(parentFragment as EuiccProfilesChangedListener).onEuiccProfilesChanged()
|
||||
euiccChannelManagerService.launchProfileDeleteTask(slotId, portId, seId, iccid)
|
||||
.onStart {
|
||||
parentFragment?.notifyEuiccProfilesChanged()
|
||||
runCatching(::dismiss)
|
||||
}
|
||||
|
||||
try {
|
||||
dismiss()
|
||||
} catch (e: IllegalStateException) {
|
||||
// Ignored
|
||||
}
|
||||
}.waitDone()
|
||||
.waitDone()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,10 +7,12 @@ 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.core.EuiccChannel
|
||||
import im.angry.openeuicc.service.EuiccChannelManagerService.Companion.waitDone
|
||||
import im.angry.openeuicc.util.*
|
||||
import kotlinx.coroutines.launch
|
||||
|
|
@ -18,15 +20,17 @@ import net.typeblog.lpac_jni.LocalProfileAssistant
|
|||
|
||||
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): ProfileRenameFragment {
|
||||
val instance = newInstanceEuicc(ProfileRenameFragment::class.java, slotId, portId)
|
||||
instance.requireArguments().apply {
|
||||
putString("iccid", iccid)
|
||||
putString("currentName", currentName)
|
||||
}
|
||||
return instance
|
||||
fun newInstance(
|
||||
slotId: Int, portId: Int, seId: EuiccChannel.SecureElementId,
|
||||
iccid: String, currentName: String
|
||||
) = newInstanceEuicc(ProfileRenameFragment::class.java, slotId, portId, seId) {
|
||||
putString(FIELD_ICCID, iccid)
|
||||
putString(FIELD_CURRENT_NAME, currentName)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -36,6 +40,14 @@ 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?,
|
||||
|
|
@ -54,9 +66,9 @@ class ProfileRenameFragment : BaseMaterialDialogFragment(), EuiccChannelFragment
|
|||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
profileRenameNewName.editText!!.setText(requireArguments().getString("currentName"))
|
||||
profileRenameNewName.editText!!.setText(currentName)
|
||||
toolbar.apply {
|
||||
setTitle(R.string.rename)
|
||||
setTitle(R.string.profile_rename)
|
||||
setNavigationOnClickListener {
|
||||
if (!renaming) dismiss()
|
||||
}
|
||||
|
|
@ -78,12 +90,8 @@ class ProfileRenameFragment : BaseMaterialDialogFragment(), EuiccChannelFragment
|
|||
}
|
||||
}
|
||||
|
||||
private fun showErrorAndCancel(errorStrRes: Int) {
|
||||
Toast.makeText(
|
||||
requireContext(),
|
||||
errorStrRes,
|
||||
Toast.LENGTH_LONG
|
||||
).show()
|
||||
private fun showErrorAndCancel(@StringRes resId: Int) {
|
||||
Toast.makeText(requireContext(), resId, Toast.LENGTH_LONG).show()
|
||||
|
||||
renaming = false
|
||||
progress.visibility = View.GONE
|
||||
|
|
@ -94,17 +102,15 @@ class ProfileRenameFragment : BaseMaterialDialogFragment(), EuiccChannelFragment
|
|||
progress.isIndeterminate = true
|
||||
progress.visibility = View.VISIBLE
|
||||
|
||||
val newName = profileRenameNewName.editText!!.text.toString().trim()
|
||||
|
||||
lifecycleScope.launch {
|
||||
ensureEuiccChannelManager()
|
||||
euiccChannelManagerService.waitForForegroundTask()
|
||||
val res = euiccChannelManagerService.launchProfileRenameTask(
|
||||
slotId,
|
||||
portId,
|
||||
requireArguments().getString("iccid")!!,
|
||||
profileRenameNewName.editText!!.text.toString().trim()
|
||||
).waitDone()
|
||||
val response = euiccChannelManagerService
|
||||
.launchProfileRenameTask(slotId, portId, seId, iccid, newName).waitDone()
|
||||
|
||||
when (res) {
|
||||
when (response) {
|
||||
is LocalProfileAssistant.ProfileNameTooLongException -> {
|
||||
showErrorAndCancel(R.string.profile_rename_too_long)
|
||||
}
|
||||
|
|
@ -118,17 +124,11 @@ class ProfileRenameFragment : BaseMaterialDialogFragment(), EuiccChannelFragment
|
|||
}
|
||||
|
||||
else -> {
|
||||
if (parentFragment is EuiccProfilesChangedListener) {
|
||||
(parentFragment as EuiccProfilesChangedListener).onEuiccProfilesChanged()
|
||||
}
|
||||
parentFragment?.notifyEuiccProfilesChanged()
|
||||
|
||||
try {
|
||||
dismiss()
|
||||
} catch (e: IllegalStateException) {
|
||||
// Ignored
|
||||
}
|
||||
runCatching(::dismiss)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import im.angry.openeuicc.OpenEuiccApplication
|
|||
import im.angry.openeuicc.common.R
|
||||
import im.angry.openeuicc.util.*
|
||||
|
||||
class SettingsActivity: AppCompatActivity() {
|
||||
class SettingsActivity : AppCompatActivity() {
|
||||
private val appContainer
|
||||
get() = (application as OpenEuiccApplication).appContainer
|
||||
|
||||
|
|
@ -17,8 +17,14 @@ class SettingsActivity: AppCompatActivity() {
|
|||
super.onCreate(savedInstanceState)
|
||||
setContentView(R.layout.activity_settings)
|
||||
setSupportActionBar(requireViewById(R.id.toolbar))
|
||||
setupToolbarInsets()
|
||||
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
|
||||
|
||||
setupRootViewSystemBarInsets(
|
||||
window.decorView.rootView, arrayOf(
|
||||
this::activityToolbarInsetHandler
|
||||
), consume = false
|
||||
)
|
||||
|
||||
val settingsFragment = appContainer.uiComponentFactory.createSettingsFragment()
|
||||
supportFragmentManager.beginTransaction()
|
||||
.replace(R.id.settings_container, settingsFragment)
|
||||
|
|
@ -31,6 +37,7 @@ class SettingsActivity: AppCompatActivity() {
|
|||
finish()
|
||||
true
|
||||
}
|
||||
|
||||
else -> super.onOptionsItemSelected(item)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import android.provider.Settings
|
|||
import android.widget.Toast
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.preference.CheckBoxPreference
|
||||
import androidx.preference.ListPreference
|
||||
import androidx.preference.Preference
|
||||
import androidx.preference.PreferenceCategory
|
||||
import androidx.preference.PreferenceFragmentCompat
|
||||
|
|
@ -16,9 +17,8 @@ import im.angry.openeuicc.util.*
|
|||
import kotlinx.coroutines.flow.collect
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
open class SettingsFragment: PreferenceFragmentCompat() {
|
||||
open class SettingsFragment : PreferenceFragmentCompat(), OpenEuiccContextMarker {
|
||||
private lateinit var developerPref: PreferenceCategory
|
||||
|
||||
// Hidden developer options switch
|
||||
|
|
@ -34,7 +34,7 @@ open class SettingsFragment: PreferenceFragmentCompat() {
|
|||
// Show / hide developer preference based on whether it is enabled
|
||||
lifecycleScope.launch {
|
||||
preferenceRepository.developerOptionsEnabledFlow
|
||||
.onEach { developerPref.isVisible = it }
|
||||
.onEach(developerPref::setVisible)
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
|
@ -47,10 +47,9 @@ open class SettingsFragment: PreferenceFragmentCompat() {
|
|||
|
||||
requirePreference<Preference>("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)
|
||||
}
|
||||
val uri = Uri.fromParts("package", requireContext().packageName, null)
|
||||
intent = Intent(Settings.ACTION_APP_LOCALE_SETTINGS, uri)
|
||||
isVisible = intent!!.resolveActivity(requireContext().packageManager) != null
|
||||
}
|
||||
|
||||
requirePreference<Preference>("pref_advanced_logs").apply {
|
||||
|
|
@ -77,6 +76,23 @@ open class SettingsFragment: PreferenceFragmentCompat() {
|
|||
|
||||
requirePreference<CheckBoxPreference>("pref_developer_ignore_tls_certificate")
|
||||
.bindBooleanFlow(preferenceRepository.ignoreTLSCertificateFlow)
|
||||
|
||||
requirePreference<CheckBoxPreference>("pref_developer_refresh_after_switch")
|
||||
.bindBooleanFlow(preferenceRepository.refreshAfterSwitchFlow)
|
||||
|
||||
requirePreference<ListPreference>("pref_developer_es10x_mss")
|
||||
.bindIntFlow(preferenceRepository.es10xMssFlow, 63)
|
||||
|
||||
requirePreference<Preference>("pref_developer_isdr_aid_list").apply {
|
||||
intent = Intent(requireContext(), IsdrAidListActivity::class.java)
|
||||
}
|
||||
|
||||
requirePreference<Preference>("pref_info_website").apply {
|
||||
val uri = appContainer.customizableTextProvider.websiteUri ?: return@apply
|
||||
isVisible = true
|
||||
summary = uri.buildUpon().clearQuery().build().toString()
|
||||
intent = Intent(/* action = */ Intent.ACTION_VIEW, uri)
|
||||
}
|
||||
}
|
||||
|
||||
protected fun <T : Preference> requirePreference(key: CharSequence) =
|
||||
|
|
@ -84,57 +100,61 @@ open class SettingsFragment: PreferenceFragmentCompat() {
|
|||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
setupRootViewInsets(requireView().requireViewById(R.id.recycler_view))
|
||||
setupRootViewSystemBarInsets(requireView(), arrayOf(
|
||||
mainViewPaddingInsetHandler(requireView().requireViewById(R.id.recycler_view))
|
||||
))
|
||||
}
|
||||
|
||||
@Suppress("UNUSED_PARAMETER")
|
||||
private fun onAppVersionClicked(pref: Preference): Boolean {
|
||||
if (developerPref.isVisible) return false
|
||||
|
||||
val now = System.currentTimeMillis()
|
||||
if (now - lastClickTimestamp >= 1000) {
|
||||
numClicks = 1
|
||||
} else {
|
||||
numClicks++
|
||||
}
|
||||
numClicks = if (now - lastClickTimestamp >= 1000) 1 else numClicks + 1
|
||||
lastClickTimestamp = now
|
||||
|
||||
if (numClicks == 7) {
|
||||
lifecycleScope.launch {
|
||||
preferenceRepository.developerOptionsEnabledFlow.updatePreference(true)
|
||||
|
||||
lastToast?.cancel()
|
||||
Toast.makeText(
|
||||
requireContext(),
|
||||
R.string.developer_options_enabled,
|
||||
Toast.LENGTH_SHORT
|
||||
).show()
|
||||
}
|
||||
} else if (numClicks > 1) {
|
||||
lastToast?.cancel()
|
||||
lastToast = Toast.makeText(
|
||||
requireContext(),
|
||||
getString(R.string.developer_options_steps, 7 - numClicks),
|
||||
Toast.LENGTH_SHORT
|
||||
)
|
||||
lastToast!!.show()
|
||||
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
|
||||
}
|
||||
|
||||
private fun CheckBoxPreference.bindBooleanFlow(flow: PreferenceFlowWrapper<Boolean>) {
|
||||
protected fun CheckBoxPreference.bindBooleanFlow(flow: PreferenceFlowWrapper<Boolean>) {
|
||||
lifecycleScope.launch {
|
||||
flow.collect { isChecked = it }
|
||||
flow.collect(::setChecked)
|
||||
}
|
||||
|
||||
setOnPreferenceChangeListener { _, newValue ->
|
||||
runBlocking {
|
||||
lifecycleScope.launch {
|
||||
flow.updatePreference(newValue as Boolean)
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
private fun ListPreference.bindIntFlow(flow: PreferenceFlowWrapper<Int>, 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<PreferenceCategory>(overlayKey)
|
||||
val targetCat = requirePreference<PreferenceCategory>(targetKey)
|
||||
|
|
@ -152,4 +172,4 @@ open class SettingsFragment: PreferenceFragmentCompat() {
|
|||
|
||||
overlayCat.parent?.removePreference(overlayCat)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,23 +14,22 @@ import android.view.LayoutInflater
|
|||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.Button
|
||||
import android.widget.ProgressBar
|
||||
import android.widget.TextView
|
||||
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.EuiccChannelManager
|
||||
import im.angry.openeuicc.util.*
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.toList
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* A wrapper fragment over EuiccManagementFragment where we handle
|
||||
* logic specific to USB devices. This is mainly USB permission
|
||||
* requests, and the fact that USB devices may or may not be
|
||||
* available by the time the user selects it from MainActivity.
|
||||
* A fragment to handle USB reader-specific permission flow. If/after
|
||||
* permission is granted, this fragment simply calls back to MainActivity
|
||||
* to instantiate the corresponding EuiccManagementFragment(s) for the USB
|
||||
* reader.
|
||||
*
|
||||
* Having this fragment allows MainActivity to be (mostly) agnostic
|
||||
* of the underlying implementation of different types of channels.
|
||||
|
|
@ -40,7 +39,7 @@ import kotlinx.coroutines.withContext
|
|||
* Note that for now we assume there will only be one USB card reader
|
||||
* device. This is also an implicit assumption in EuiccChannelManager.
|
||||
*/
|
||||
class UsbCcidReaderFragment : Fragment(), OpenEuiccContextMarker {
|
||||
class UsbCcidReaderPermissionFragment : Fragment(), OpenEuiccContextMarker {
|
||||
companion object {
|
||||
const val ACTION_USB_PERMISSION = "im.angry.openeuicc.USB_PERMISSION"
|
||||
}
|
||||
|
|
@ -69,7 +68,7 @@ class UsbCcidReaderFragment : Fragment(), OpenEuiccContextMarker {
|
|||
|
||||
private lateinit var text: TextView
|
||||
private lateinit var permissionButton: Button
|
||||
private lateinit var loadingProgress: ProgressBar
|
||||
private lateinit var loadingProgress: View
|
||||
|
||||
private var usbDevice: UsbDevice? = null
|
||||
|
||||
|
|
@ -142,28 +141,23 @@ class UsbCcidReaderFragment : Fragment(), OpenEuiccContextMarker {
|
|||
euiccChannelManager.tryOpenUsbEuiccChannel()
|
||||
}
|
||||
|
||||
loadingProgress.visibility = View.GONE
|
||||
|
||||
usbDevice = device
|
||||
|
||||
if (device != null && !canOpen && !usbManager.hasPermission(device)) {
|
||||
loadingProgress.visibility = View.GONE
|
||||
text.text = getString(R.string.usb_permission_needed)
|
||||
text.visibility = View.VISIBLE
|
||||
permissionButton.visibility = View.VISIBLE
|
||||
} else if (device != null && canOpen) {
|
||||
childFragmentManager.commit {
|
||||
replace(
|
||||
R.id.child_container,
|
||||
appContainer.uiComponentFactory.createEuiccManagementFragment(
|
||||
slotId = EuiccChannelManager.USB_CHANNEL_ID,
|
||||
portId = 0
|
||||
)
|
||||
)
|
||||
val seIds = withContext(Dispatchers.IO) {
|
||||
euiccChannelManager.flowEuiccSecureElements(EuiccChannelManager.USB_CHANNEL_ID, 0).toList()
|
||||
}
|
||||
(requireActivity() as MainActivity).instantiateUsbTabs(seIds)
|
||||
} else {
|
||||
loadingProgress.visibility = View.GONE
|
||||
text.text = getString(R.string.usb_failed)
|
||||
text.visibility = View.VISIBLE
|
||||
permissionButton.visibility = View.GONE
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -7,10 +7,10 @@ import androidx.preference.PreferenceCategory
|
|||
import androidx.preference.PreferenceViewHolder
|
||||
|
||||
@Suppress("unused")
|
||||
class LongSummaryPreferenceCategory: PreferenceCategory {
|
||||
constructor(ctx: Context): super(ctx)
|
||||
constructor(ctx: Context, attrs: AttributeSet): super(ctx, attrs)
|
||||
constructor(ctx: Context, attrs: AttributeSet, defStyle: Int): super(ctx, attrs, defStyle)
|
||||
class LongSummaryPreferenceCategory : PreferenceCategory {
|
||||
constructor(ctx: Context) : super(ctx)
|
||||
constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs)
|
||||
constructor(ctx: Context, attrs: AttributeSet, defStyle: Int) : super(ctx, attrs, defStyle)
|
||||
|
||||
override fun onBindViewHolder(holder: PreferenceViewHolder) {
|
||||
super.onBindViewHolder(holder)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,51 @@
|
|||
package im.angry.openeuicc.ui.widget
|
||||
|
||||
import android.content.Context
|
||||
import android.util.AttributeSet
|
||||
import android.view.ViewGroup
|
||||
import com.google.android.material.R
|
||||
import com.google.android.material.tabs.TabLayout
|
||||
|
||||
/**
|
||||
* A TabLayout that automatically switches to MODE_SCROLLABLE when
|
||||
* child tabs overflow the full width of the layout.
|
||||
*/
|
||||
class DynamicModeTabLayout @JvmOverloads constructor(
|
||||
context: Context,
|
||||
attrs: AttributeSet? = null,
|
||||
defStyleAttr: Int = R.attr.tabStyle
|
||||
) : TabLayout(context, attrs, defStyleAttr) {
|
||||
init {
|
||||
addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->
|
||||
updateModeIfNecessary()
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateModeIfNecessary() {
|
||||
if (width <= 0 || tabCount == 0) return
|
||||
|
||||
val tabStrip = getChildAt(0) as? ViewGroup ?: return
|
||||
val totalTabWidth = (0 until tabStrip.childCount).sumOf { index ->
|
||||
val tabView = tabStrip.getChildAt(index)
|
||||
val layoutParams = tabView.layoutParams as? MarginLayoutParams
|
||||
tabView.measure(
|
||||
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
|
||||
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
|
||||
)
|
||||
tabView.measuredWidth + (layoutParams?.leftMargin ?: 0) + (layoutParams?.rightMargin ?: 0)
|
||||
}
|
||||
|
||||
val availableWidth = width - paddingLeft - paddingRight
|
||||
val shouldScroll = totalTabWidth > availableWidth
|
||||
val targetMode = if (shouldScroll) MODE_SCROLLABLE else MODE_FIXED
|
||||
val targetGravity = if (shouldScroll) GRAVITY_START else GRAVITY_FILL
|
||||
|
||||
if (tabMode != targetMode) {
|
||||
tabMode = targetMode
|
||||
}
|
||||
|
||||
if (tabGravity != targetGravity) {
|
||||
tabGravity = targetGravity
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,31 +1,52 @@
|
|||
package im.angry.openeuicc.ui.wizard
|
||||
|
||||
import android.app.assist.AssistContent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
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.EuiccChannel
|
||||
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 kotlinx.coroutines.withContext
|
||||
import net.typeblog.lpac_jni.LocalProfileAssistant
|
||||
|
||||
class DownloadWizardActivity: BaseEuiccAccessActivity() {
|
||||
class DownloadWizardActivity : BaseEuiccAccessActivity() {
|
||||
companion object {
|
||||
const val TAG = "DownloadWizardActivity"
|
||||
|
||||
private const val FIELD_LOGICAL_SLOT_ID = "selectedLogicalSlot"
|
||||
|
||||
fun newIntent(
|
||||
context: Context,
|
||||
logicalSlotId: Int = 0,
|
||||
seId: EuiccChannel.SecureElementId = EuiccChannel.SecureElementId.DEFAULT
|
||||
) = Intent(context, DownloadWizardActivity::class.java).apply {
|
||||
val selectedSyntheticSlotId = DownloadWizardSlotSelectFragment
|
||||
.encodeSyntheticSlotId(logicalSlotId, seId)
|
||||
putExtra(FIELD_LOGICAL_SLOT_ID, selectedSyntheticSlotId)
|
||||
}
|
||||
}
|
||||
|
||||
data class DownloadWizardState(
|
||||
var currentStepFragmentClassName: String?,
|
||||
var selectedLogicalSlot: Int,
|
||||
var selectedSyntheticSlotId: Int,
|
||||
var smdp: String,
|
||||
var matchingId: String?,
|
||||
var confirmationCode: String?,
|
||||
|
|
@ -33,6 +54,8 @@ class DownloadWizardActivity: BaseEuiccAccessActivity() {
|
|||
var downloadStarted: Boolean,
|
||||
var downloadTaskID: Long,
|
||||
var downloadError: LocalProfileAssistant.ProfileDownloadException?,
|
||||
var skipMethodSelect: Boolean,
|
||||
var confirmationCodeRequired: Boolean,
|
||||
)
|
||||
|
||||
private lateinit var state: DownloadWizardState
|
||||
|
|
@ -61,17 +84,21 @@ class DownloadWizardActivity: BaseEuiccAccessActivity() {
|
|||
})
|
||||
|
||||
state = DownloadWizardState(
|
||||
null,
|
||||
intent.getIntExtra("selectedLogicalSlot", 0),
|
||||
"",
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
false,
|
||||
-1,
|
||||
null
|
||||
currentStepFragmentClassName = null,
|
||||
selectedSyntheticSlotId = intent.getIntExtra(FIELD_LOGICAL_SLOT_ID, 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)
|
||||
|
|
@ -86,41 +113,64 @@ class DownloadWizardActivity: BaseEuiccAccessActivity() {
|
|||
|
||||
val navigation = requireViewById<View>(R.id.download_wizard_navigation)
|
||||
val origHeight = navigation.layoutParams.height
|
||||
val fragmentRoot = requireViewById<View>(R.id.step_fragment_container)
|
||||
|
||||
ViewCompat.setOnApplyWindowInsetsListener(navigation) { v, insets ->
|
||||
ViewCompat.setOnApplyWindowInsetsListener(window.decorView.rootView) { _, insets ->
|
||||
val bars = insets.getInsets(
|
||||
WindowInsetsCompat.Type.systemBars()
|
||||
or WindowInsetsCompat.Type.displayCutout()
|
||||
or WindowInsetsCompat.Type.ime()
|
||||
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
|
||||
|
||||
fragmentRoot.updatePadding(bars.left, bars.top, bars.right, 0)
|
||||
navigation.updatePadding(bars.left, 0, bars.right, bars.bottom)
|
||||
val newNavParams = navigation.layoutParams
|
||||
newNavParams.height = origHeight + bars.bottom
|
||||
navigation.layoutParams = newNavParams
|
||||
WindowInsetsCompat.CONSUMED
|
||||
}
|
||||
}
|
||||
|
||||
val fragmentRoot = requireViewById<View>(R.id.step_fragment_container)
|
||||
ViewCompat.setOnApplyWindowInsetsListener(fragmentRoot) { v, insets ->
|
||||
val bars = insets.getInsets(
|
||||
WindowInsetsCompat.Type.systemBars()
|
||||
or WindowInsetsCompat.Type.displayCutout()
|
||||
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,
|
||||
)
|
||||
v.updatePadding(bars.left, bars.top, bars.right, 0)
|
||||
WindowInsetsCompat.CONSUMED
|
||||
"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.putInt("selectedLogicalSlot", state.selectedSyntheticSlotId)
|
||||
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) {
|
||||
|
|
@ -129,14 +179,20 @@ class DownloadWizardActivity: BaseEuiccAccessActivity() {
|
|||
"currentStepFragmentClassName",
|
||||
state.currentStepFragmentClassName
|
||||
)
|
||||
state.selectedLogicalSlot =
|
||||
savedInstanceState.getInt("selectedLogicalSlot", state.selectedLogicalSlot)
|
||||
state.selectedSyntheticSlotId =
|
||||
savedInstanceState.getInt("selectedSyntheticSlotId", state.selectedSyntheticSlotId)
|
||||
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() {
|
||||
|
|
@ -160,10 +216,13 @@ class DownloadWizardActivity: BaseEuiccAccessActivity() {
|
|||
progressBar.isIndeterminate = true
|
||||
|
||||
lifecycleScope.launch(Dispatchers.Main) {
|
||||
if (state.selectedLogicalSlot >= 0) {
|
||||
if (state.selectedSyntheticSlotId >= 0) {
|
||||
try {
|
||||
val (slotId, seId) = DownloadWizardSlotSelectFragment.decodeSyntheticSlotId(
|
||||
state.selectedSyntheticSlotId
|
||||
)
|
||||
// This is run on IO by default
|
||||
euiccChannelManager.withEuiccChannel(state.selectedLogicalSlot) { channel ->
|
||||
euiccChannelManager.withEuiccChannel(slotId, seId) { channel ->
|
||||
// Be _very_ sure that the channel we got is valid
|
||||
if (!channel.valid) throw EuiccChannelManager.EuiccChannelNotFoundException()
|
||||
}
|
||||
|
|
@ -212,6 +271,14 @@ class DownloadWizardActivity: BaseEuiccAccessActivity() {
|
|||
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()
|
||||
}
|
||||
|
||||
|
|
@ -241,6 +308,8 @@ class DownloadWizardActivity: BaseEuiccAccessActivity() {
|
|||
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?
|
||||
|
|
@ -277,4 +346,4 @@ class DownloadWizardActivity: BaseEuiccAccessActivity() {
|
|||
|
||||
open fun beforeNext() {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,14 @@
|
|||
package im.angry.openeuicc.ui.wizard
|
||||
|
||||
import android.os.Bundle
|
||||
import android.util.Patterns
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.EditText
|
||||
import androidx.core.widget.addTextChangedListener
|
||||
import com.google.android.material.textfield.TextInputLayout
|
||||
import im.angry.openeuicc.common.R
|
||||
import im.angry.openeuicc.util.*
|
||||
|
||||
class DownloadWizardDetailsFragment : DownloadWizardActivity.DownloadWizardStepFragment() {
|
||||
private var inputComplete = false
|
||||
|
|
@ -17,17 +18,25 @@ class DownloadWizardDetailsFragment : DownloadWizardActivity.DownloadWizardStepF
|
|||
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 val address: EditText by lazy {
|
||||
requireView().requireViewById<TextInputLayout>(R.id.profile_download_server).editText!!
|
||||
}
|
||||
private val matchingId: EditText by lazy {
|
||||
requireView().requireViewById<TextInputLayout>(R.id.profile_download_code).editText!!
|
||||
}
|
||||
private val confirmationCode: EditText by lazy {
|
||||
requireView().requireViewById<TextInputLayout>(R.id.profile_download_confirmation_code).editText!!
|
||||
}
|
||||
private val imei: EditText by lazy {
|
||||
requireView().requireViewById<TextInputLayout>(R.id.profile_download_imei).editText!!
|
||||
}
|
||||
|
||||
private fun saveState() {
|
||||
state.smdp = smdp.editText!!.text.toString().trim()
|
||||
state.smdp = address.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 }
|
||||
state.matchingId = matchingId.text.toString().trim().ifBlank { null }
|
||||
state.confirmationCode = confirmationCode.text.toString().trim().ifBlank { null }
|
||||
state.imei = imei.text.toString().ifBlank { null }
|
||||
}
|
||||
|
||||
override fun beforeNext() = saveState()
|
||||
|
|
@ -36,31 +45,37 @@ class DownloadWizardDetailsFragment : DownloadWizardActivity.DownloadWizardStepF
|
|||
DownloadWizardProgressFragment()
|
||||
|
||||
override fun createPrevFragment(): DownloadWizardActivity.DownloadWizardStepFragment =
|
||||
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()
|
||||
if (state.skipMethodSelect) {
|
||||
DownloadWizardSlotSelectFragment()
|
||||
} else {
|
||||
DownloadWizardMethodSelectFragment()
|
||||
}
|
||||
return view
|
||||
|
||||
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
|
||||
inflater.inflate(R.layout.fragment_download_details, container, /* attachToRoot = */ false)
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
address.addTextChangedListener(onTextChanged = ::handlePasteLPAString)
|
||||
address.addTextChangedListener { updateInputCompleteness() }
|
||||
matchingId.addTextChangedListener(onTextChanged = ::handlePasteLPAString)
|
||||
confirmationCode.addTextChangedListener { updateInputCompleteness() }
|
||||
}
|
||||
|
||||
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)
|
||||
address.setText(state.smdp)
|
||||
matchingId.setText(state.matchingId)
|
||||
confirmationCode.setText(state.confirmationCode)
|
||||
imei.setText(state.imei)
|
||||
updateInputCompleteness()
|
||||
|
||||
if (state.confirmationCodeRequired) {
|
||||
confirmationCode.requestFocus()
|
||||
confirmationCode.setHint(R.string.profile_download_confirmation_code_required)
|
||||
} else {
|
||||
confirmationCode.setHint(R.string.profile_download_confirmation_code)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
|
|
@ -68,8 +83,44 @@ class DownloadWizardDetailsFragment : DownloadWizardActivity.DownloadWizardStepF
|
|||
saveState()
|
||||
}
|
||||
|
||||
private fun handlePasteLPAString(text: CharSequence?, start: Int, before: Int, count: Int) {
|
||||
if (start > 0 || before > 0) return // only handle insertions at the beginning
|
||||
if (text == null || !text.startsWith("LPA:", ignoreCase = true)) return
|
||||
val parsed = LPAString.parse(text)
|
||||
address.setText(parsed.address)
|
||||
matchingId.setText(parsed.matchingId)
|
||||
if (parsed.confirmationCodeRequired) confirmationCode.requestFocus()
|
||||
}
|
||||
|
||||
private fun updateInputCompleteness() {
|
||||
inputComplete = Patterns.DOMAIN_NAME.matcher(smdp.editText!!.text).matches()
|
||||
inputComplete = isValidAddress(address.text)
|
||||
if (state.confirmationCodeRequired) {
|
||||
inputComplete = inputComplete && confirmationCode.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.take(portIndex)
|
||||
port = input.substring(portIndex + 1, input.length).toIntOrNull(10) ?: 0
|
||||
}
|
||||
// see https://en.wikipedia.org/wiki/Port_(computer_networking)
|
||||
if (port !in 1..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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ 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() {
|
||||
|
|
@ -86,9 +87,10 @@ class DownloadWizardDiagnosticsFragment : DownloadWizardActivity.DownloadWizardS
|
|||
ret.appendLine()
|
||||
|
||||
val str = resp.data.decodeToString(throwOnInvalidSequence = false)
|
||||
|
||||
ret.appendLine(
|
||||
if (str.startsWith('{')) {
|
||||
str.prettyPrintJson()
|
||||
JSONObject(str).toString(2)
|
||||
} else {
|
||||
str
|
||||
}
|
||||
|
|
@ -136,4 +138,4 @@ class DownloadWizardDiagnosticsFragment : DownloadWizardActivity.DownloadWizardS
|
|||
|
||||
ret.toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,21 +42,16 @@ class DownloadWizardMethodSelectFragment : DownloadWizardActivity.DownloadWizard
|
|||
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) {
|
||||
processLpaString(it)
|
||||
}
|
||||
lifecycleScope.launch {
|
||||
val decoded = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
requireContext().contentResolver.openInputStream(result)?.use { input ->
|
||||
BitmapFactory.decodeStream(input).use(::decodeQrFromBitmap)
|
||||
}
|
||||
|
||||
bmp.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
decoded.getOrNull()?.let { processLpaString(it) }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -124,9 +119,14 @@ class DownloadWizardMethodSelectFragment : DownloadWizardActivity.DownloadWizard
|
|||
processLpaString(text.toString())
|
||||
}
|
||||
|
||||
private fun processLpaString(s: String) {
|
||||
val components = s.split("$")
|
||||
if (components.size < 3 || components[0] != "LPA:1") {
|
||||
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)
|
||||
|
|
@ -134,21 +134,22 @@ class DownloadWizardMethodSelectFragment : DownloadWizardActivity.DownloadWizard
|
|||
setNegativeButton(android.R.string.cancel, null)
|
||||
show()
|
||||
}
|
||||
return
|
||||
}
|
||||
state.smdp = components[1]
|
||||
state.matchingId = components[2]
|
||||
gotoNextFragment(DownloadWizardDetailsFragment())
|
||||
}
|
||||
|
||||
private class DownloadMethodViewHolder(private val root: View) : ViewHolder(root) {
|
||||
private inner class DownloadMethodViewHolder(private val root: View) : ViewHolder(root) {
|
||||
private val icon = root.requireViewById<ImageView>(R.id.download_method_icon)
|
||||
private val title = root.requireViewById<TextView>(R.id.download_method_title)
|
||||
|
||||
fun bind(item: DownloadMethod) {
|
||||
icon.setImageResource(item.iconRes)
|
||||
title.setText(item.titleRes)
|
||||
root.setOnClickListener { item.onClick() }
|
||||
root.setOnClickListener {
|
||||
// If the user elected to use another download method, reset the confirmation code flag
|
||||
// too
|
||||
state.confirmationCodeRequired = false
|
||||
item.onClick()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -169,4 +170,4 @@ class DownloadWizardMethodSelectFragment : DownloadWizardActivity.DownloadWizard
|
|||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ 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
|
||||
|
|
@ -17,8 +18,9 @@ import im.angry.openeuicc.util.*
|
|||
import kotlinx.coroutines.flow.collect
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.launch
|
||||
import net.typeblog.lpac_jni.ProfileDownloadInput
|
||||
import net.typeblog.lpac_jni.ProfileDownloadState
|
||||
import net.typeblog.lpac_jni.LocalProfileAssistant
|
||||
import net.typeblog.lpac_jni.ProfileDownloadCallback
|
||||
|
||||
class DownloadWizardProgressFragment : DownloadWizardActivity.DownloadWizardStepFragment() {
|
||||
companion object {
|
||||
|
|
@ -26,11 +28,11 @@ class DownloadWizardProgressFragment : DownloadWizardActivity.DownloadWizardStep
|
|||
* 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,
|
||||
ProfileDownloadState.Preparing,
|
||||
ProfileDownloadState.Connecting,
|
||||
ProfileDownloadState.Authenticating,
|
||||
ProfileDownloadState.Downloading,
|
||||
ProfileDownloadState.Finalizing,
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -42,23 +44,24 @@ class DownloadWizardProgressFragment : DownloadWizardActivity.DownloadWizardStep
|
|||
}
|
||||
|
||||
private data class ProgressItem(
|
||||
val titleRes: Int,
|
||||
var state: ProgressState
|
||||
@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, ProgressState.NotStarted),
|
||||
ProgressItem(R.string.download_wizard_progress_step_connecting, ProgressState.NotStarted),
|
||||
ProgressItem(
|
||||
R.string.download_wizard_progress_step_authenticating,
|
||||
ProgressState.NotStarted
|
||||
),
|
||||
ProgressItem(R.string.download_wizard_progress_step_downloading, ProgressState.NotStarted),
|
||||
ProgressItem(R.string.download_wizard_progress_step_finalizing, ProgressState.NotStarted)
|
||||
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
|
||||
|
|
@ -119,8 +122,13 @@ class DownloadWizardProgressFragment : DownloadWizardActivity.DownloadWizardStep
|
|||
// Change the state of the last InProgress item to success (or error)
|
||||
progressItems.forEachIndexed { index, progressItem ->
|
||||
if (progressItem.state == ProgressState.InProgress) {
|
||||
progressItem.state =
|
||||
if (state.downloadError == null) ProgressState.Done else ProgressState.Error
|
||||
if (state.downloadError == null) {
|
||||
progressItem.state = ProgressState.Done
|
||||
} else {
|
||||
progressItem.state = ProgressState.Error
|
||||
progressItem.errorMessage =
|
||||
SimplifiedErrorMessages.fromDownloadError(state.downloadError!!)
|
||||
}
|
||||
}
|
||||
|
||||
adapter.notifyItemChanged(index)
|
||||
|
|
@ -130,9 +138,8 @@ class DownloadWizardProgressFragment : DownloadWizardActivity.DownloadWizardStep
|
|||
refreshButtons()
|
||||
}
|
||||
|
||||
is EuiccChannelManagerService.ForegroundTaskState.InProgress -> {
|
||||
is EuiccChannelManagerService.ForegroundTaskState.InProgress ->
|
||||
updateProgress(it.progress)
|
||||
}
|
||||
|
||||
else -> {}
|
||||
}
|
||||
|
|
@ -147,7 +154,12 @@ class DownloadWizardProgressFragment : DownloadWizardActivity.DownloadWizardStep
|
|||
} else {
|
||||
euiccChannelManagerService.waitForForegroundTask()
|
||||
|
||||
val (slotId, portId) = euiccChannelManager.withEuiccChannel(state.selectedLogicalSlot) { channel ->
|
||||
val (logicalSlotId, seId) = DownloadWizardSlotSelectFragment.decodeSyntheticSlotId(state.selectedSyntheticSlotId)
|
||||
|
||||
val (slotId, portId) = euiccChannelManager.withEuiccChannel(
|
||||
logicalSlotId,
|
||||
seId
|
||||
) { channel ->
|
||||
Pair(channel.slotId, channel.portId)
|
||||
}
|
||||
|
||||
|
|
@ -155,12 +167,8 @@ class DownloadWizardProgressFragment : DownloadWizardActivity.DownloadWizardStep
|
|||
state.downloadStarted = true
|
||||
|
||||
val ret = euiccChannelManagerService.launchProfileDownloadTask(
|
||||
slotId,
|
||||
portId,
|
||||
state.smdp,
|
||||
state.matchingId,
|
||||
state.confirmationCode,
|
||||
state.imei
|
||||
slotId, portId, seId,
|
||||
ProfileDownloadInput(state.smdp, state.matchingId, state.imei, state.confirmationCode)
|
||||
)
|
||||
|
||||
state.downloadTaskID = ret.taskId
|
||||
|
|
@ -171,7 +179,7 @@ class DownloadWizardProgressFragment : DownloadWizardActivity.DownloadWizardStep
|
|||
private fun updateProgress(progress: Int) {
|
||||
showProgressBar(progress)
|
||||
|
||||
val lpaState = ProfileDownloadCallback.lookupStateFromProgress(progress)
|
||||
val lpaState = ProfileDownloadState.lookupStateFromProgress(progress)
|
||||
val stateIndex = LPA_PROGRESS_STATES.indexOf(lpaState)
|
||||
|
||||
if (stateIndex > 0) {
|
||||
|
|
@ -194,9 +202,15 @@ class DownloadWizardProgressFragment : DownloadWizardActivity.DownloadWizardStep
|
|||
private val progressBar =
|
||||
root.requireViewById<ProgressBar>(R.id.download_progress_icon_progress)
|
||||
private val icon = root.requireViewById<ImageView>(R.id.download_progress_icon)
|
||||
private val errorTitle =
|
||||
root.requireViewById<TextView>(R.id.download_progress_item_error_title)
|
||||
private val errorSuggestion =
|
||||
root.requireViewById<TextView>(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 -> {
|
||||
|
|
@ -219,6 +233,15 @@ class DownloadWizardProgressFragment : DownloadWizardActivity.DownloadWizardStep
|
|||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -237,4 +260,4 @@ class DownloadWizardProgressFragment : DownloadWizardActivity.DownloadWizardStep
|
|||
holder.bind(progressItems[position])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,37 +7,45 @@ 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.EuiccChannel
|
||||
import im.angry.openeuicc.core.EuiccChannelManager
|
||||
import im.angry.openeuicc.util.*
|
||||
import kotlinx.coroutines.flow.flatMapConcat
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.toList
|
||||
import kotlinx.coroutines.launch
|
||||
import net.typeblog.lpac_jni.LocalProfileInfo
|
||||
|
||||
class DownloadWizardSlotSelectFragment : DownloadWizardActivity.DownloadWizardStepFragment() {
|
||||
companion object {
|
||||
const val LOW_NVRAM_THRESHOLD =
|
||||
30 * 1024 // < 30 KiB, alert about potential download failure
|
||||
internal fun encodeSyntheticSlotId(logicalSlotId: Int, seId: EuiccChannel.SecureElementId): Int =
|
||||
(logicalSlotId shl 16) + seId.id
|
||||
|
||||
internal fun decodeSyntheticSlotId(id: Int): Pair<Int, EuiccChannel.SecureElementId> =
|
||||
Pair(id shr 16, EuiccChannel.SecureElementId.createFromInt(id and 0xFF))
|
||||
}
|
||||
|
||||
private data class SlotInfo(
|
||||
val logicalSlotId: Int,
|
||||
val isRemovable: Boolean,
|
||||
val hasMultiplePorts: Boolean,
|
||||
val hasMultipleSEs: Boolean,
|
||||
val portId: Int,
|
||||
val seId: EuiccChannel.SecureElementId,
|
||||
val eID: String,
|
||||
val freeSpace: Int,
|
||||
val imei: String,
|
||||
val enabledProfileName: String?,
|
||||
val intrinsicChannelName: String?,
|
||||
)
|
||||
) {
|
||||
// A synthetic slot ID used to uniquely identify this slot + SE chip in the download process
|
||||
// We assume we don't have anywhere near 2^16 ports...
|
||||
val syntheticSlotId: Int = (logicalSlotId shl 16) + seId.id
|
||||
}
|
||||
|
||||
private var loaded = false
|
||||
|
||||
|
|
@ -49,29 +57,14 @@ class DownloadWizardSlotSelectFragment : DownloadWizardActivity.DownloadWizardSt
|
|||
get() = true
|
||||
|
||||
override fun createNextFragment(): DownloadWizardActivity.DownloadWizardStepFragment =
|
||||
DownloadWizardMethodSelectFragment()
|
||||
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?,
|
||||
|
|
@ -82,7 +75,12 @@ class DownloadWizardSlotSelectFragment : DownloadWizardActivity.DownloadWizardSt
|
|||
recyclerView.adapter = adapter
|
||||
recyclerView.layoutManager =
|
||||
LinearLayoutManager(view.context, LinearLayoutManager.VERTICAL, false)
|
||||
recyclerView.addItemDecoration(DividerItemDecoration(requireContext(), LinearLayoutManager.VERTICAL))
|
||||
recyclerView.addItemDecoration(
|
||||
DividerItemDecoration(
|
||||
requireContext(),
|
||||
LinearLayoutManager.VERTICAL
|
||||
)
|
||||
)
|
||||
return view
|
||||
}
|
||||
|
||||
|
|
@ -94,37 +92,41 @@ class DownloadWizardSlotSelectFragment : DownloadWizardActivity.DownloadWizardSt
|
|||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged", "MissingPermission")
|
||||
@OptIn(kotlinx.coroutines.FlowPreview::class)
|
||||
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,
|
||||
)
|
||||
val slots = euiccChannelManager.flowAllOpenEuiccPorts().flatMapConcat { (slotId, portId) ->
|
||||
euiccChannelManager.flowEuiccSecureElements(slotId, portId).map { seId ->
|
||||
euiccChannelManager.withEuiccChannel(slotId, portId, seId) { channel ->
|
||||
SlotInfo(
|
||||
channel.logicalSlotId,
|
||||
channel.port.card.isRemovable,
|
||||
channel.port.card.ports.size > 1,
|
||||
channel.hasMultipleSE,
|
||||
channel.portId,
|
||||
channel.seId,
|
||||
channel.lpa.eID,
|
||||
channel.lpa.euiccInfo2?.freeNvram ?: 0,
|
||||
try {
|
||||
telephonyManager.getImei(channel.logicalSlotId) ?: ""
|
||||
} catch (e: Exception) {
|
||||
""
|
||||
},
|
||||
channel.lpa.profiles.enabled?.displayName,
|
||||
)
|
||||
}
|
||||
}
|
||||
}.toList().sortedBy { it.logicalSlotId }
|
||||
}.toList().sortedBy { it.syntheticSlotId }
|
||||
adapter.slots = slots
|
||||
|
||||
// Ensure we always have a selected slot by default
|
||||
val selectedIdx = slots.indexOfFirst { it.logicalSlotId == state.selectedLogicalSlot }
|
||||
val selectedIdx = slots.indexOfFirst { it.syntheticSlotId == state.selectedSyntheticSlotId }
|
||||
adapter.currentSelectedIdx = if (selectedIdx > 0) {
|
||||
selectedIdx
|
||||
} else {
|
||||
if (slots.isNotEmpty()) {
|
||||
state.selectedLogicalSlot = slots[0].logicalSlotId
|
||||
state.selectedSyntheticSlotId = slots[0].syntheticSlotId
|
||||
}
|
||||
0
|
||||
}
|
||||
|
|
@ -164,7 +166,8 @@ class DownloadWizardSlotSelectFragment : DownloadWizardActivity.DownloadWizardSt
|
|||
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.selectedSyntheticSlotId =
|
||||
adapter.slots[adapter.currentSelectedIdx].syntheticSlotId
|
||||
state.imei = adapter.slots[adapter.currentSelectedIdx].imei
|
||||
}
|
||||
|
||||
|
|
@ -183,12 +186,22 @@ class DownloadWizardSlotSelectFragment : DownloadWizardActivity.DownloadWizardSt
|
|||
}
|
||||
|
||||
title.text = if (item.logicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) {
|
||||
item.intrinsicChannelName ?: root.context.getString(R.string.usb)
|
||||
if (item.hasMultipleSEs) {
|
||||
root.context.getString(R.string.channel_name_format_usb_se, item.seId.id)
|
||||
} else {
|
||||
root.context.getString(R.string.channel_name_format_usb)
|
||||
}
|
||||
} else if (item.hasMultipleSEs) {
|
||||
appContainer.customizableTextProvider.formatNonUsbChannelNameWithSeId(
|
||||
item.logicalSlotId,
|
||||
item.seId
|
||||
)
|
||||
} else {
|
||||
appContainer.customizableTextProvider.formatInternalChannelName(item.logicalSlotId)
|
||||
appContainer.customizableTextProvider.formatNonUsbChannelName(item.logicalSlotId)
|
||||
}
|
||||
eID.text = item.eID
|
||||
activeProfile.text = item.enabledProfileName ?: root.context.getString(R.string.unknown)
|
||||
activeProfile.text = item.enabledProfileName
|
||||
?: root.context.getString(R.string.profile_no_enabled_profile)
|
||||
freeSpace.text = formatFreeSpace(item.freeSpace)
|
||||
checkBox.isChecked = adapter.currentSelectedIdx == idx
|
||||
}
|
||||
|
|
@ -202,7 +215,8 @@ class DownloadWizardSlotSelectFragment : DownloadWizardActivity.DownloadWizardSt
|
|||
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)
|
||||
val root = LayoutInflater.from(parent.context)
|
||||
.inflate(R.layout.download_slot_item, parent, false)
|
||||
return SlotItemHolder(root)
|
||||
}
|
||||
|
||||
|
|
@ -212,4 +226,4 @@ class DownloadWizardSlotSelectFragment : DownloadWizardActivity.DownloadWizardSt
|
|||
holder.bind(slots[position], position)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,176 @@
|
|||
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
|
||||
),
|
||||
UnavailableProfile(
|
||||
R.string.download_wizard_error_profile_unavailable,
|
||||
R.string.download_wizard_error_suggest_contact_carrier
|
||||
),
|
||||
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 {
|
||||
// @formatter:off
|
||||
// Stage: InitiateAuthentication
|
||||
put("8.8.1" to "3.8", UnknownHost) // Invalid SM-DP+ Address.
|
||||
put("8.8.2" to "3.1", UnsupportedProfile) // None of the proposed Public Key Identifiers is supported by the SM-DP+.
|
||||
put("8.8.3" to "3.1", UnsupportedProfile) // The SVN indicated by the eUICC is not supported by the SM-DP+.
|
||||
put("8.8.4" to "3.7", UnsupportedProfile) // The SM-DP+ has no CERT.DPAuth.ECDSA signed by one of the GSMA CI Public Key supported by the eUICC.
|
||||
|
||||
// Stage: AuthenticateClient
|
||||
put("8.1" to "4.8", InsufficientMemory) // eUICC does not have sufficient space for this Profile.
|
||||
put("8.1.1" to "2.1", EIDNotSupported) // eUICC does not support the EID.
|
||||
put("8.1.1" to "3.8", EIDMismatch) // EID doesn't match the expected value.
|
||||
put("8.1.2" to "6.1", UnsupportedProfile) // EUM Certificate is invalid.
|
||||
put("8.1.2" to "6.3", UnsupportedProfile) // EUM Certificate has expired.
|
||||
put("8.1.3" to "6.1", UnsupportedProfile) // eUICC Certificate is invalid.
|
||||
put("8.1.3" to "6.3", UnsupportedProfile) // eUICC Certificate has expired.
|
||||
put("8.2" to "1.2", UnreleasedProfile) // Profile has not yet been released.
|
||||
put("8.2.5" to "4.3", UnavailableProfile) // No eligible Profile for this eUICC/Device.
|
||||
put("8.2.6" to "3.8", MatchingIDRefused) // MatchingID (AC_Token or EventID) is refused.
|
||||
put("8.8" to "4.2", EIDNotSupported) // eUICC is not supported by the SM-DP+.
|
||||
put("8.8.5" to "6.4", ProfileRetriesExceeded) // The maximum number of retries for the Profile download order has been exceeded.
|
||||
put("8.10.1" to "3.9", UnsupportedProfile) // The RSP session identified by the TransactionID is unknown.
|
||||
put("8.11.1" to "3.9", UnsupportedProfile) // Unknown CI Public Key.
|
||||
|
||||
// Stage: GetBoundProfilePackage
|
||||
put("8.2" to "3.7", UnavailableProfile) // BPP is not available for a new binding.
|
||||
put("8.2.7" to "2.2", ConfirmationCodeMissing) // Confirmation Code is missing.
|
||||
put("8.2.7" to "3.8", ConfirmationCodeRefused) // Confirmation Code is refused.
|
||||
put("8.2.7" to "6.4", ConfirmationCodeRetriesExceeded) // The maximum number of retries for the Confirmation Code has been exceeded.
|
||||
|
||||
// Stage: AuthenticateClient, GetBoundProfilePackage
|
||||
put("8.1" to "6.1", UnsupportedProfile) // eUICC Signature is invalid.
|
||||
put("8.8.5" to "4.10", ProfileExpired) // The Download order has expired.
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
package im.angry.openeuicc.util
|
||||
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import androidx.fragment.app.Fragment
|
||||
import im.angry.openeuicc.core.EuiccChannel
|
||||
|
|
@ -7,44 +8,86 @@ import im.angry.openeuicc.core.EuiccChannelManager
|
|||
import im.angry.openeuicc.service.EuiccChannelManagerService
|
||||
import im.angry.openeuicc.ui.BaseEuiccAccessActivity
|
||||
|
||||
interface EuiccChannelFragmentMarker: OpenEuiccContextMarker
|
||||
private const val FIELD_SLOT_ID = "slotId"
|
||||
private const val FIELD_PORT_ID = "portId"
|
||||
private const val FIELD_SE_ID = "seId"
|
||||
|
||||
interface EuiccChannelFragmentMarker : OpenEuiccContextMarker
|
||||
|
||||
private typealias BundleSetter = Bundle.() -> Unit
|
||||
|
||||
// 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 <T> newInstanceEuicc(clazz: Class<T>, 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()
|
||||
fun <T> newInstanceEuicc(
|
||||
clazz: Class<T>,
|
||||
slotId: Int,
|
||||
portId: Int,
|
||||
seId: EuiccChannel.SecureElementId,
|
||||
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!!.putParcelable(FIELD_SE_ID, seId)
|
||||
arguments!!.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> T.slotId: Int where T: Fragment, T: EuiccChannelFragmentMarker
|
||||
get() = requireArguments().getInt("slotId")
|
||||
val <T> T.portId: Int where T: Fragment, T: EuiccChannelFragmentMarker
|
||||
get() = requireArguments().getInt("portId")
|
||||
val <T> T.isUsb: Boolean where T: Fragment, T: EuiccChannelFragmentMarker
|
||||
get() = requireArguments().getInt("slotId") == EuiccChannelManager.USB_CHANNEL_ID
|
||||
val <T> T.slotId: Int
|
||||
where T : Fragment, T : EuiccChannelFragmentMarker
|
||||
get() = requireArguments().getInt(FIELD_SLOT_ID)
|
||||
val <T> T.portId: Int
|
||||
where T : Fragment, T : EuiccChannelFragmentMarker
|
||||
get() = requireArguments().getInt(FIELD_PORT_ID)
|
||||
val <T> T.seId: EuiccChannel.SecureElementId
|
||||
where T : Fragment, T : EuiccChannelFragmentMarker
|
||||
get() =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
requireArguments().getParcelable(
|
||||
FIELD_SE_ID,
|
||||
EuiccChannel.SecureElementId::class.java
|
||||
)!!
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
requireArguments().getParcelable(FIELD_SE_ID)!!
|
||||
}
|
||||
val <T> T.isUsb: Boolean
|
||||
where T : Fragment, T : EuiccChannelFragmentMarker
|
||||
get() = slotId == EuiccChannelManager.USB_CHANNEL_ID
|
||||
|
||||
val <T> T.euiccChannelManager: EuiccChannelManager where T: Fragment, T: OpenEuiccContextMarker
|
||||
get() = (requireActivity() as BaseEuiccAccessActivity).euiccChannelManager
|
||||
val <T> T.euiccChannelManagerService: EuiccChannelManagerService where T: Fragment, T: OpenEuiccContextMarker
|
||||
get() = (requireActivity() as BaseEuiccAccessActivity).euiccChannelManagerService
|
||||
private fun <T> T.requireEuiccActivity(): BaseEuiccAccessActivity
|
||||
where T : Fragment, T : OpenEuiccContextMarker =
|
||||
requireActivity() as BaseEuiccAccessActivity
|
||||
|
||||
suspend fun <T, R> T.withEuiccChannel(fn: suspend (EuiccChannel) -> R): R where T : Fragment, T : EuiccChannelFragmentMarker {
|
||||
val <T> T.euiccChannelManager: EuiccChannelManager
|
||||
where T : Fragment, T : OpenEuiccContextMarker
|
||||
get() = requireEuiccActivity().euiccChannelManager
|
||||
|
||||
val <T> T.euiccChannelManagerService: EuiccChannelManagerService
|
||||
where T : Fragment, T : OpenEuiccContextMarker
|
||||
get() = requireEuiccActivity().euiccChannelManagerService
|
||||
|
||||
suspend fun <T, R> T.withEuiccChannel(fn: suspend (EuiccChannel) -> R): R
|
||||
where T : Fragment, T : EuiccChannelFragmentMarker {
|
||||
ensureEuiccChannelManager()
|
||||
return euiccChannelManager.withEuiccChannel(slotId, portId, fn)
|
||||
return euiccChannelManager.withEuiccChannel(slotId, portId, seId, fn)
|
||||
}
|
||||
|
||||
suspend fun <T> T.ensureEuiccChannelManager() where T: Fragment, T: OpenEuiccContextMarker =
|
||||
(requireActivity() as BaseEuiccAccessActivity).euiccChannelManagerLoaded.await()
|
||||
suspend fun <T> T.ensureEuiccChannelManager() where T : Fragment, T : OpenEuiccContextMarker =
|
||||
requireEuiccActivity().euiccChannelManagerLoaded.await()
|
||||
|
||||
fun <T> 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()
|
||||
}
|
||||
|
||||
interface EuiccProfilesChangedListener {
|
||||
fun onEuiccProfilesChanged()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,34 @@
|
|||
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: CharSequence): 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('$')
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ import im.angry.openeuicc.core.EuiccChannel
|
|||
import im.angry.openeuicc.core.EuiccChannelManager
|
||||
import net.typeblog.lpac_jni.LocalProfileAssistant
|
||||
import net.typeblog.lpac_jni.LocalProfileInfo
|
||||
import net.typeblog.lpac_jni.ProfileClass
|
||||
|
||||
const val TAG = "LPAUtils"
|
||||
|
||||
|
|
@ -16,7 +17,7 @@ val LocalProfileInfo.isEnabled: Boolean
|
|||
get() = state == LocalProfileInfo.State.Enabled
|
||||
|
||||
val List<LocalProfileInfo>.operational: List<LocalProfileInfo>
|
||||
get() = filter { it.profileClass == LocalProfileInfo.Clazz.Operational }
|
||||
get() = filter { it.profileClass == ProfileClass.Operational || it.isEnabled }
|
||||
|
||||
val List<LocalProfileInfo>.enabled: LocalProfileInfo?
|
||||
get() = find { it.isEnabled }
|
||||
|
|
@ -79,9 +80,10 @@ fun LocalProfileAssistant.disableActiveProfileKeepIccId(refresh: Boolean): Strin
|
|||
suspend inline fun EuiccChannelManager.beginTrackedOperation(
|
||||
slotId: Int,
|
||||
portId: Int,
|
||||
seId: EuiccChannel.SecureElementId,
|
||||
op: () -> Boolean
|
||||
) {
|
||||
val latestSeq = withEuiccChannel(slotId, portId) { channel ->
|
||||
val latestSeq = withEuiccChannel(slotId, portId, seId) { channel ->
|
||||
channel.lpa.notifications.firstOrNull()?.seqNumber
|
||||
?: 0
|
||||
}
|
||||
|
|
@ -91,7 +93,7 @@ suspend inline fun EuiccChannelManager.beginTrackedOperation(
|
|||
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 ->
|
||||
withEuiccChannel(slotId, portId, seId) { channel ->
|
||||
channel.lpa.notifications.filter { it.seqNumber > latestSeq }.forEach {
|
||||
Log.d(TAG, "Handling notification $it")
|
||||
channel.lpa.handleNotification(it.seqNumber)
|
||||
|
|
@ -103,4 +105,4 @@ suspend inline fun EuiccChannelManager.beginTrackedOperation(
|
|||
}
|
||||
}
|
||||
Log.d(TAG, "Operation complete")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,11 +5,14 @@ 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<Preferences> by preferencesDataStore(name = "prefs")
|
||||
|
||||
|
|
@ -31,11 +34,50 @@ internal object PreferenceKeys {
|
|||
|
||||
// ---- 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 ISDR_AID_LIST = stringPreferencesKey("isdr_aid_list")
|
||||
val ES10X_MSS = intPreferencesKey("es10x_mss")
|
||||
}
|
||||
|
||||
class PreferenceRepository(private val context: Context) {
|
||||
const val EUICC_DEFAULT_ISDR_AID = "A0000005591010FFFFFFFF8900000100"
|
||||
|
||||
internal object PreferenceConstants {
|
||||
val DEFAULT_AID_LIST = """
|
||||
# One AID per line. Comment lines start with #.
|
||||
# Refs: <https://euicc-manual.osmocom.org/docs/lpa/applet-id-oem/>
|
||||
|
||||
# eUICC standard
|
||||
# Even if this AID is deleted here, it will still be attempted as the last resort.
|
||||
$EUICC_DEFAULT_ISDR_AID
|
||||
|
||||
# eSIM.me
|
||||
A0000005591010000000008900000300
|
||||
|
||||
# 5ber.eSIM
|
||||
A0000005591010FFFFFFFF8900050500
|
||||
|
||||
# Xesim
|
||||
A0000005591010FFFFFFFF8900000177
|
||||
|
||||
# LinksField
|
||||
A000000559104C696E6B736669656C64
|
||||
|
||||
# ESTKme SE0
|
||||
# For multi-SE eSTK.me products, this will always be attempted even if removed from the list
|
||||
${ESTKme.ESTK_SE0_AID.encodeHex()}
|
||||
|
||||
# ESTKme SE1
|
||||
# For multi-SE eSTK.me products, this will always be attempted even if removed from the list
|
||||
${ESTKme.ESTK_SE1_AID.encodeHex()}
|
||||
|
||||
# ESTKme AUX (deprecated, use SE0 instead)
|
||||
A06573746B6D65FFFFFFFF4953442D52
|
||||
""".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)
|
||||
|
|
@ -47,26 +89,50 @@ class PreferenceRepository(private val context: Context) {
|
|||
val verboseLoggingFlow = bindFlow(PreferenceKeys.VERBOSE_LOGGING, 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 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)
|
||||
|
||||
private fun <T> bindFlow(key: Preferences.Key<T>, defaultValue: T): PreferenceFlowWrapper<T> =
|
||||
PreferenceFlowWrapper(context, key, defaultValue)
|
||||
protected fun <T> bindFlow(
|
||||
key: Preferences.Key<T>,
|
||||
defaultValue: T,
|
||||
encoder: (T) -> T = { it },
|
||||
decoder: (T) -> T = { it }
|
||||
): PreferenceFlowWrapper<T> =
|
||||
PreferenceFlowWrapper(context, key, defaultValue, encoder, decoder)
|
||||
}
|
||||
|
||||
class PreferenceFlowWrapper<T> private constructor(
|
||||
private val context: Context,
|
||||
private val key: Preferences.Key<T>,
|
||||
inner: Flow<T>
|
||||
inner: Flow<T>,
|
||||
private val encoder: (T) -> T,
|
||||
) : Flow<T> by inner {
|
||||
internal constructor(context: Context, key: Preferences.Key<T>, defaultValue: T) : this(
|
||||
internal constructor(
|
||||
context: Context,
|
||||
key: Preferences.Key<T>,
|
||||
defaultValue: T,
|
||||
encoder: (T) -> T,
|
||||
decoder: (T) -> T
|
||||
) : this(
|
||||
context,
|
||||
key,
|
||||
context.dataStore.data.map { it[key] ?: defaultValue }
|
||||
context.dataStore.data.map { it[key]?.let(decoder) ?: defaultValue },
|
||||
encoder
|
||||
)
|
||||
|
||||
suspend fun updatePreference(value: T) {
|
||||
context.dataStore.edit { it[key] = value }
|
||||
context.dataStore.edit { it[key] = encoder(value) }
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun removePreference() {
|
||||
context.dataStore.edit { it.remove(key) }
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package im.angry.openeuicc.util
|
||||
|
||||
fun String.decodeHex(): ByteArray {
|
||||
check(length % 2 == 0) { "Must have an even length" }
|
||||
require(length % 2 == 0) { "Must have an even length" }
|
||||
|
||||
val decodedLength = length / 2
|
||||
val out = ByteArray(decodedLength)
|
||||
|
| ||||