feat: socle initial Gastinel Connect et greffon WireGuard Android
- Greffon Tauri Kotlin base sur le composant officiel com.wireguard.android:tunnel (Apache-2.0) - Support du VpnService Android avec GoBackend - Interface web conformement a la charte Gastinel (theme clair, Inter local, 0 coin arrondi) - Fichier LICENCES-TIERCES.md avec mentions legales de marque WireGuard - Sous-reseau de test dedie 10.250.0.0/24
Aucun fichier ne correspond à votre recherche
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "gastinel-connect"
|
||||
version = "0.1.0"
|
||||
description = "Gastinel Connect — Client VPN multiplateforme pour l'écosystème Gastinel"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
name = "gastinel_connect_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[[bin]]
|
||||
name = "gastinel-connect"
|
||||
path = "src/main.rs"
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2", features = [] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
thiserror = "2"
|
||||
tauri-plugin-wireguard = { path = "plugins/tauri-plugin-wireguard" }
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
tauri_build::build()
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Permissions de base pour Gastinel Connect",
|
||||
"windows": ["main"],
|
||||
"permissions": ["core:default"]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
# EditorConfig is awesome: https://EditorConfig.org
|
||||
|
||||
# top-most EditorConfig file
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = false
|
||||
insert_final_newline = false
|
||||
@@ -0,0 +1,20 @@
|
||||
*.iml
|
||||
.gradle
|
||||
/local.properties
|
||||
/.idea/caches
|
||||
/.idea/libraries
|
||||
/.idea/modules.xml
|
||||
/.idea/workspace.xml
|
||||
/.idea/navEditor.xml
|
||||
/.idea/assetWizardSettings.xml
|
||||
.DS_Store
|
||||
build
|
||||
/captures
|
||||
.externalNativeBuild
|
||||
.cxx
|
||||
local.properties
|
||||
key.properties
|
||||
keystore.properties
|
||||
|
||||
/.tauri
|
||||
/tauri.settings.gradle
|
||||
@@ -0,0 +1,6 @@
|
||||
/src/main/**/generated
|
||||
/src/main/jniLibs/**/*.so
|
||||
/src/main/assets/tauri.conf.json
|
||||
/tauri.build.gradle.kts
|
||||
/proguard-tauri.pro
|
||||
/tauri.properties
|
||||
@@ -0,0 +1,77 @@
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
id("rust")
|
||||
}
|
||||
|
||||
val tauriProperties = Properties().apply {
|
||||
val propFile = file("tauri.properties")
|
||||
if (propFile.exists()) {
|
||||
propFile.inputStream().use { load(it) }
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
compileSdk = 36
|
||||
namespace = "fr.gastinel.connect"
|
||||
defaultConfig {
|
||||
manifestPlaceholders["usesCleartextTraffic"] = "false"
|
||||
applicationId = "fr.gastinel.connect"
|
||||
minSdk = 24
|
||||
targetSdk = 36
|
||||
versionCode = tauriProperties.getProperty("tauri.android.versionCode", "1").toInt()
|
||||
versionName = tauriProperties.getProperty("tauri.android.versionName", "1.0")
|
||||
}
|
||||
buildTypes {
|
||||
getByName("debug") {
|
||||
manifestPlaceholders["usesCleartextTraffic"] = "true"
|
||||
isDebuggable = true
|
||||
isJniDebuggable = true
|
||||
isMinifyEnabled = false
|
||||
packaging { jniLibs.keepDebugSymbols.add("*/arm64-v8a/*.so")
|
||||
jniLibs.keepDebugSymbols.add("*/armeabi-v7a/*.so")
|
||||
jniLibs.keepDebugSymbols.add("*/x86/*.so")
|
||||
jniLibs.keepDebugSymbols.add("*/x86_64/*.so")
|
||||
}
|
||||
}
|
||||
getByName("release") {
|
||||
isMinifyEnabled = true
|
||||
proguardFiles(
|
||||
*fileTree(".") { include("**/*.pro") }
|
||||
.plus(getDefaultProguardFile("proguard-android-optimize.txt"))
|
||||
.toList().toTypedArray()
|
||||
)
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
isCoreLibraryDesugaringEnabled = true
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = "17"
|
||||
}
|
||||
buildFeatures {
|
||||
buildConfig = true
|
||||
}
|
||||
}
|
||||
|
||||
rust {
|
||||
rootDirRel = "../../../"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.0.4")
|
||||
implementation("androidx.webkit:webkit:1.14.0")
|
||||
implementation("androidx.appcompat:appcompat:1.7.1")
|
||||
implementation("androidx.activity:activity-ktx:1.10.1")
|
||||
implementation("com.google.android.material:material:1.12.0")
|
||||
implementation("androidx.lifecycle:lifecycle-process:2.10.0")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.1.4")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.0")
|
||||
}
|
||||
|
||||
apply(from = "tauri.build.gradle.kts")
|
||||
@@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
@@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<!-- AndroidTV support -->
|
||||
<uses-feature android:name="android.software.leanback" android:required="false" />
|
||||
|
||||
<application
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/Theme.gastinel_connect"
|
||||
android:usesCleartextTraffic="${usesCleartextTraffic}">
|
||||
<activity
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
|
||||
android:launchMode="singleTask"
|
||||
android:label="@string/main_activity_title"
|
||||
android:name=".MainActivity"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
<!-- AndroidTV support -->
|
||||
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.fileprovider"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths" />
|
||||
</provider>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,11 @@
|
||||
package fr.gastinel.connect
|
||||
|
||||
import android.os.Bundle
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
|
||||
class MainActivity : TauriActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:aapt="http://schemas.android.com/aapt"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
|
||||
<aapt:attr name="android:fillColor">
|
||||
<gradient
|
||||
android:endX="85.84757"
|
||||
android:endY="92.4963"
|
||||
android:startX="42.9492"
|
||||
android:startY="49.59793"
|
||||
android:type="linear">
|
||||
<item
|
||||
android:color="#44000000"
|
||||
android:offset="0.0" />
|
||||
<item
|
||||
android:color="#00000000"
|
||||
android:offset="1.0" />
|
||||
</gradient>
|
||||
</aapt:attr>
|
||||
</path>
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:fillType="nonZero"
|
||||
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
|
||||
android:strokeWidth="1"
|
||||
android:strokeColor="#00000000" />
|
||||
</vector>
|
||||
@@ -0,0 +1,170 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path
|
||||
android:fillColor="#3DDC84"
|
||||
android:pathData="M0,0h108v108h-108z" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M9,0L9,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,0L19,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M29,0L29,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M39,0L39,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M49,0L49,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M59,0L59,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M69,0L69,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M79,0L79,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M89,0L89,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M99,0L99,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,9L108,9"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,19L108,19"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,29L108,29"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,39L108,39"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,49L108,49"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,59L108,59"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,69L108,69"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,79L108,79"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,89L108,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,99L108,99"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,29L89,29"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,39L89,39"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,49L89,49"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,59L89,59"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,69L89,69"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,79L89,79"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M29,19L29,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M39,19L39,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M49,19L49,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M59,19L59,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M69,19L69,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M79,19L79,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
</vector>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
tools:context=".MainActivity">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Hello World!"
|
||||
app:layout_constraintBottom_toBottomOf="parent"
|
||||
app:layout_constraintLeft_toLeftOf="parent"
|
||||
app:layout_constraintRight_toRightOf="parent"
|
||||
app:layout_constraintTop_toTopOf="parent" />
|
||||
|
||||
</androidx.constraintlayout.widget.ConstraintLayout>
|
||||
|
Après Largeur: | Hauteur: | Taille: 3.4 KiB |
|
Après Largeur: | Hauteur: | Taille: 14 KiB |
|
Après Largeur: | Hauteur: | Taille: 3.4 KiB |
|
Après Largeur: | Hauteur: | Taille: 3.3 KiB |
|
Après Largeur: | Hauteur: | Taille: 8.9 KiB |
|
Après Largeur: | Hauteur: | Taille: 3.3 KiB |
|
Après Largeur: | Hauteur: | Taille: 7.8 KiB |
|
Après Largeur: | Hauteur: | Taille: 18 KiB |
|
Après Largeur: | Hauteur: | Taille: 7.8 KiB |
|
Après Largeur: | Hauteur: | Taille: 12 KiB |
|
Après Largeur: | Hauteur: | Taille: 29 KiB |
|
Après Largeur: | Hauteur: | Taille: 12 KiB |
|
Après Largeur: | Hauteur: | Taille: 16 KiB |
|
Après Largeur: | Hauteur: | Taille: 40 KiB |
|
Après Largeur: | Hauteur: | Taille: 16 KiB |
@@ -0,0 +1,6 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Base application theme. -->
|
||||
<style name="Theme.gastinel_connect" parent="Theme.MaterialComponents.DayNight.NoActionBar">
|
||||
<!-- Customize your theme here. -->
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="purple_200">#FFBB86FC</color>
|
||||
<color name="purple_500">#FF6200EE</color>
|
||||
<color name="purple_700">#FF3700B3</color>
|
||||
<color name="teal_200">#FF03DAC5</color>
|
||||
<color name="teal_700">#FF018786</color>
|
||||
<color name="black">#FF000000</color>
|
||||
<color name="white">#FFFFFFFF</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,4 @@
|
||||
<resources>
|
||||
<string name="app_name">"Gastinel Connect"</string>
|
||||
<string name="main_activity_title">"Gastinel Connect"</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,6 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Base application theme. -->
|
||||
<style name="Theme.gastinel_connect" parent="Theme.MaterialComponents.DayNight.NoActionBar">
|
||||
<!-- Customize your theme here. -->
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<paths xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<external-path name="my_images" path="." />
|
||||
<cache-path name="my_cache_images" path="." />
|
||||
</paths>
|
||||
@@ -0,0 +1,22 @@
|
||||
buildscript {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath("com.android.tools.build:gradle:8.11.0")
|
||||
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.25")
|
||||
}
|
||||
}
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
tasks.register("clean").configure {
|
||||
delete("build")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
plugins {
|
||||
`kotlin-dsl`
|
||||
}
|
||||
|
||||
gradlePlugin {
|
||||
plugins {
|
||||
create("pluginsForCoolKids") {
|
||||
id = "rust"
|
||||
implementationClass = "RustPlugin"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly(gradleApi())
|
||||
implementation("com.android.tools.build:gradle:8.11.0")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import java.io.File
|
||||
import org.apache.tools.ant.taskdefs.condition.Os
|
||||
import org.gradle.api.DefaultTask
|
||||
import org.gradle.api.GradleException
|
||||
import org.gradle.api.logging.LogLevel
|
||||
import org.gradle.api.tasks.Input
|
||||
import org.gradle.api.tasks.TaskAction
|
||||
|
||||
open class BuildTask : DefaultTask() {
|
||||
@Input
|
||||
var rootDirRel: String? = null
|
||||
@Input
|
||||
var target: String? = null
|
||||
@Input
|
||||
var release: Boolean? = null
|
||||
|
||||
@TaskAction
|
||||
fun assemble() {
|
||||
val userCargo = File(System.getProperty("user.home"), ".cargo/bin/cargo.exe")
|
||||
val executable = if (userCargo.exists()) userCargo.absolutePath else "cargo"
|
||||
var tauriCliException: Exception? = null
|
||||
|
||||
try {
|
||||
runTauriCli(executable)
|
||||
} catch (e: Exception) {
|
||||
tauriCliException = e
|
||||
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
|
||||
val fallbacks = listOf(
|
||||
if (userCargo.exists()) userCargo.absolutePath else "cargo.exe",
|
||||
"cargo.exe",
|
||||
"cargo.cmd",
|
||||
"cargo.bat",
|
||||
)
|
||||
|
||||
for (fallback in fallbacks) {
|
||||
try {
|
||||
runTauriCli(fallback)
|
||||
tauriCliException = null
|
||||
break
|
||||
} catch (fallbackException: Exception) {
|
||||
tauriCliException = fallbackException
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val copied = ensureSoCopied()
|
||||
if (!copied && tauriCliException != null) {
|
||||
throw tauriCliException
|
||||
}
|
||||
}
|
||||
|
||||
private fun ensureSoCopied(): Boolean {
|
||||
val rootDirRel = rootDirRel ?: return false
|
||||
val target = target ?: return false
|
||||
val isRelease = release ?: false
|
||||
val profile = if (isRelease) "release" else "debug"
|
||||
|
||||
val targetTriple = when (target) {
|
||||
"aarch64" -> "aarch64-linux-android"
|
||||
"armv7" -> "armv7-linux-androideabi"
|
||||
"i686" -> "i686-linux-android"
|
||||
"x86_64" -> "x86_64-linux-android"
|
||||
else -> target
|
||||
}
|
||||
|
||||
val abi = when (target) {
|
||||
"aarch64" -> "arm64-v8a"
|
||||
"armv7" -> "armeabi-v7a"
|
||||
"i686" -> "x86"
|
||||
"x86_64" -> "x86_64"
|
||||
else -> target
|
||||
}
|
||||
|
||||
val srcDir = File(project.projectDir, "$rootDirRel/target/$targetTriple/$profile")
|
||||
val soFile = File(srcDir, "libgastinel_connect_lib.so")
|
||||
if (soFile.exists()) {
|
||||
val destDir = File(project.projectDir, "src/main/jniLibs/$abi")
|
||||
destDir.mkdirs()
|
||||
val destFile = File(destDir, "libgastinel_connect_lib.so")
|
||||
try {
|
||||
soFile.copyTo(destFile, overwrite = true)
|
||||
project.logger.lifecycle("Copie de libgastinel_connect_lib.so vers jniLibs/$abi/libgastinel_connect_lib.so réussie")
|
||||
return true
|
||||
} catch (e: Exception) {
|
||||
project.logger.warn("Échec de copie de libgastinel_connect_lib.so: ${e.message}")
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
fun runTauriCli(executable: String) {
|
||||
val rootDirRel = rootDirRel ?: throw GradleException("rootDirRel cannot be null")
|
||||
val target = target ?: throw GradleException("target cannot be null")
|
||||
val release = release ?: throw GradleException("release cannot be null")
|
||||
val args = listOf("tauri", "android", "android-studio-script")
|
||||
|
||||
project.exec {
|
||||
workingDir(File(project.projectDir, rootDirRel))
|
||||
executable(executable)
|
||||
args(args)
|
||||
if (project.logger.isEnabled(LogLevel.DEBUG)) {
|
||||
args("-vv")
|
||||
} else if (project.logger.isEnabled(LogLevel.INFO)) {
|
||||
args("-v")
|
||||
}
|
||||
if (release) {
|
||||
args("--release")
|
||||
}
|
||||
args(listOf("--target", target))
|
||||
}.assertNormalExitValue()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import com.android.build.api.dsl.ApplicationExtension
|
||||
import org.gradle.api.DefaultTask
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.kotlin.dsl.configure
|
||||
import org.gradle.kotlin.dsl.get
|
||||
|
||||
const val TASK_GROUP = "rust"
|
||||
|
||||
open class Config {
|
||||
lateinit var rootDirRel: String
|
||||
}
|
||||
|
||||
open class RustPlugin : Plugin<Project> {
|
||||
private lateinit var config: Config
|
||||
|
||||
override fun apply(project: Project) = with(project) {
|
||||
config = extensions.create("rust", Config::class.java)
|
||||
|
||||
val defaultAbiList = listOf("arm64-v8a", "armeabi-v7a", "x86", "x86_64");
|
||||
val abiList = (findProperty("abiList") as? String)?.split(',') ?: defaultAbiList
|
||||
|
||||
val defaultArchList = listOf("arm64", "arm", "x86", "x86_64");
|
||||
val archList = (findProperty("archList") as? String)?.split(',') ?: defaultArchList
|
||||
|
||||
val targetsList = (findProperty("targetList") as? String)?.split(',') ?: listOf("aarch64", "armv7", "i686", "x86_64")
|
||||
|
||||
extensions.configure<ApplicationExtension> {
|
||||
@Suppress("UnstableApiUsage")
|
||||
flavorDimensions.add("abi")
|
||||
productFlavors {
|
||||
create("universal") {
|
||||
dimension = "abi"
|
||||
ndk {
|
||||
abiFilters += abiList
|
||||
}
|
||||
}
|
||||
defaultArchList.forEachIndexed { index, arch ->
|
||||
create(arch) {
|
||||
dimension = "abi"
|
||||
ndk {
|
||||
abiFilters.add(defaultAbiList[index])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
afterEvaluate {
|
||||
for (profile in listOf("debug", "release")) {
|
||||
val profileCapitalized = profile.replaceFirstChar { it.uppercase() }
|
||||
val buildTask = tasks.maybeCreate(
|
||||
"rustBuildUniversal$profileCapitalized",
|
||||
DefaultTask::class.java
|
||||
).apply {
|
||||
group = TASK_GROUP
|
||||
description = "Build dynamic library in $profile mode for all targets"
|
||||
}
|
||||
|
||||
tasks["mergeUniversal${profileCapitalized}JniLibFolders"].dependsOn(buildTask)
|
||||
|
||||
for (targetPair in targetsList.withIndex()) {
|
||||
val targetName = targetPair.value
|
||||
val targetArch = archList[targetPair.index]
|
||||
val targetArchCapitalized = targetArch.replaceFirstChar { it.uppercase() }
|
||||
val targetBuildTask = project.tasks.maybeCreate(
|
||||
"rustBuild$targetArchCapitalized$profileCapitalized",
|
||||
BuildTask::class.java
|
||||
).apply {
|
||||
group = TASK_GROUP
|
||||
description = "Build dynamic library in $profile mode for $targetArch"
|
||||
rootDirRel = config.rootDirRel
|
||||
target = targetName
|
||||
release = profile == "release"
|
||||
}
|
||||
|
||||
buildTask.dependsOn(targetBuildTask)
|
||||
tasks["merge$targetArchCapitalized${profileCapitalized}JniLibFolders"].dependsOn(
|
||||
targetBuildTask
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
# Project-wide Gradle settings.
|
||||
# IDE (e.g. Android Studio) users:
|
||||
# Gradle settings configured through the IDE *will override*
|
||||
# any settings specified in this file.
|
||||
# For more details on how to configure your build environment visit
|
||||
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
||||
# Specifies the JVM arguments used for the daemon process.
|
||||
# The setting is particularly useful for tweaking memory settings.
|
||||
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||
# When configured, Gradle will run in incubating parallel mode.
|
||||
# This option should only be used with decoupled projects. More details, visit
|
||||
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
|
||||
# org.gradle.parallel=true
|
||||
# AndroidX package structure to make it clearer which packages are bundled with the
|
||||
# Android operating system, and which are packaged with your app"s APK
|
||||
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
||||
android.useAndroidX=true
|
||||
# Kotlin code style for this project: "official" or "obsolete":
|
||||
kotlin.code.style=official
|
||||
# Enables namespacing of each library's R class so that its R class includes only the
|
||||
# resources declared in the library itself and none from the library's dependencies,
|
||||
# thereby reducing the size of the R class for that library
|
||||
android.nonTransitiveRClass=true
|
||||
android.nonFinalResIds=false
|
||||
|
||||
android.enableGlobalSyntheticsGeneration=true
|
||||
@@ -0,0 +1,6 @@
|
||||
#Tue May 10 19:22:52 CST 2022
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
|
||||
distributionPath=wrapper/dists
|
||||
zipStorePath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
@@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
}
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=`expr $i + 1`
|
||||
done
|
||||
case $i in
|
||||
0) set -- ;;
|
||||
1) set -- "$args0" ;;
|
||||
2) set -- "$args0" "$args1" ;;
|
||||
3) set -- "$args0" "$args1" "$args2" ;;
|
||||
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=`save "$@"`
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
@@ -0,0 +1,89 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -0,0 +1,3 @@
|
||||
include ':app'
|
||||
|
||||
apply from: 'tauri.settings.gradle'
|
||||
@@ -0,0 +1 @@
|
||||
{"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"DenLigne tronquée
|
||||
@@ -0,0 +1 @@
|
||||
{"default":{"identifier":"default","description":"Permissions de base pour Gastinel Connect","local":true,"windows":["main"],"permissions":["core:default"]}}
|
||||
|
Après Largeur: | Hauteur: | Taille: 4.1 KiB |
|
Après Largeur: | Hauteur: | Taille: 7.6 KiB |
|
Après Largeur: | Hauteur: | Taille: 1.0 KiB |
|
Après Largeur: | Hauteur: | Taille: 18 KiB |
|
Après Largeur: | Hauteur: | Taille: 15 KiB |
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "tauri-plugin-wireguard"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "Greffon Tauri WireGuard Android pour Gastinel Connect (basé sur com.wireguard.android:tunnel)"
|
||||
links = "tauri-plugin-wireguard"
|
||||
|
||||
[build-dependencies]
|
||||
tauri-plugin = { version = "2", features = ["build"] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2", features = [] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
thiserror = "2"
|
||||
@@ -0,0 +1 @@
|
||||
/build
|
||||
@@ -0,0 +1,48 @@
|
||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "app.tauri"
|
||||
compileSdk = 36
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 21
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
consumerProguardFiles("consumer-rules.pro")
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
buildFeatures {
|
||||
buildConfig = true
|
||||
}
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget = JvmTarget.JVM_1_8
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
|
||||
implementation("androidx.core:core-ktx:1.7.0")
|
||||
implementation("androidx.appcompat:appcompat:1.6.0")
|
||||
implementation("com.google.android.material:material:1.7.0")
|
||||
implementation("com.fasterxml.jackson.core:jackson-databind:2.15.3")
|
||||
// (de)serializes org.json values (JSObject, JSArray) as JSON objects and arrays
|
||||
// instead of as beans; org.json itself is part of the Android platform
|
||||
implementation("com.fasterxml.jackson.datatype:jackson-datatype-json-org:2.15.3") {
|
||||
exclude(group = "org.json", module = "json")
|
||||
}
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.1.5")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
-keep class app.tauri.** {
|
||||
@app.tauri.JniMethod public <methods>;
|
||||
native <methods>;
|
||||
}
|
||||
|
||||
-keep class app.tauri.plugin.JSArray {
|
||||
public <init>(...);
|
||||
}
|
||||
|
||||
-keepclassmembers class org.json.JSONArray {
|
||||
public put(...);
|
||||
}
|
||||
|
||||
-keep class app.tauri.plugin.JSObject {
|
||||
public <init>(...);
|
||||
public put(...);
|
||||
}
|
||||
|
||||
-keep @app.tauri.annotation.TauriPlugin public class * {
|
||||
@app.tauri.annotation.Command public <methods>;
|
||||
@app.tauri.annotation.PermissionCallback <methods>;
|
||||
@app.tauri.annotation.ActivityCallback <methods>;
|
||||
@app.tauri.annotation.Permission <methods>;
|
||||
public <init>(...);
|
||||
}
|
||||
|
||||
-keep @app.tauri.annotation.InvokeArg public class * {
|
||||
*;
|
||||
}
|
||||
|
||||
-keep @com.fasterxml.jackson.databind.annotation.JsonDeserialize public class * {
|
||||
*;
|
||||
}
|
||||
|
||||
-keep @com.fasterxml.jackson.databind.annotation.JsonSerialize public class * {
|
||||
*;
|
||||
}
|
||||
|
||||
-keep class * extends com.fasterxml.jackson.databind.JsonDeserializer { *; }
|
||||
|
||||
-keep class * extends com.fasterxml.jackson.databind.JsonSerializer { *; }
|
||||
@@ -0,0 +1,28 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri
|
||||
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
import org.junit.Assert.*
|
||||
|
||||
/**
|
||||
* Instrumented test, which will execute on an Android device.
|
||||
*
|
||||
* See [testing documentation](http://d.android.com/tools/testing).
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class ExampleInstrumentedTest {
|
||||
@Test
|
||||
fun useAppContext() {
|
||||
// Context of the app under test.
|
||||
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
assertEquals("app.tauri.test", appContext.packageName)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
</manifest>
|
||||
@@ -0,0 +1,56 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri
|
||||
|
||||
import android.app.Activity
|
||||
import android.webkit.WebView
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import app.tauri.annotation.Command
|
||||
import app.tauri.annotation.TauriPlugin
|
||||
import app.tauri.plugin.Plugin
|
||||
import app.tauri.plugin.Invoke
|
||||
import app.tauri.plugin.JSObject
|
||||
|
||||
@TauriPlugin
|
||||
class AppPlugin(private val activity: Activity): Plugin(activity) {
|
||||
private val BACK_BUTTON_EVENT = "back-button"
|
||||
|
||||
private var webView: WebView? = null
|
||||
|
||||
override fun load(webView: WebView) {
|
||||
this.webView = webView
|
||||
}
|
||||
|
||||
init {
|
||||
val callback = object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() {
|
||||
if (!hasListener(BACK_BUTTON_EVENT)) {
|
||||
if (this@AppPlugin.webView?.canGoBack() == true) {
|
||||
this@AppPlugin.webView!!.goBack()
|
||||
} else {
|
||||
this.isEnabled = false
|
||||
this@AppPlugin.activity.onBackPressed()
|
||||
this.isEnabled = true
|
||||
}
|
||||
} else {
|
||||
val data = JSObject().apply {
|
||||
put("canGoBack", this@AppPlugin.webView?.canGoBack() ?: false)
|
||||
}
|
||||
trigger(BACK_BUTTON_EVENT, data)
|
||||
}
|
||||
}
|
||||
}
|
||||
(activity as AppCompatActivity).onBackPressedDispatcher.addCallback(activity, callback)
|
||||
}
|
||||
|
||||
// Called by the Rust side when the app exits so the activity (and any other activity
|
||||
// of the task, i.e. other windows) is closed gracefully instead of the process being killed
|
||||
@Command
|
||||
fun exit(invoke: Invoke) {
|
||||
invoke.resolve()
|
||||
activity.finishAffinity()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri
|
||||
|
||||
import android.content.ContentUris
|
||||
import android.content.Context
|
||||
import android.content.res.AssetManager
|
||||
import android.database.Cursor
|
||||
import android.net.Uri
|
||||
import android.os.Environment
|
||||
import android.provider.DocumentsContract
|
||||
import android.provider.MediaStore
|
||||
import android.provider.OpenableColumns
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import kotlin.math.min
|
||||
|
||||
internal class FsUtils {
|
||||
companion object {
|
||||
fun readAsset(assetManager: AssetManager, fileName: String): String {
|
||||
assetManager.open(fileName).bufferedReader().use {
|
||||
return it.readText()
|
||||
}
|
||||
}
|
||||
|
||||
fun getFileUrlForUri(context: Context, uri: Uri): String? {
|
||||
// DocumentProvider
|
||||
if (DocumentsContract.isDocumentUri(context, uri)) {
|
||||
// ExternalStorageProvider
|
||||
if (isExternalStorageDocument(uri)) {
|
||||
val docId: String = DocumentsContract.getDocumentId(uri)
|
||||
val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }
|
||||
.toTypedArray()
|
||||
val type = split[0]
|
||||
if ("primary".equals(type, ignoreCase = true)) {
|
||||
return legacyPrimaryPath(split[1])
|
||||
} else {
|
||||
val splitIndex = docId.indexOf(':', 1)
|
||||
val tag = docId.substring(0, splitIndex)
|
||||
val path = docId.substring(splitIndex + 1)
|
||||
val nonPrimaryVolume = getPathToNonPrimaryVolume(context, tag)
|
||||
if (nonPrimaryVolume != null) {
|
||||
val result = "$nonPrimaryVolume/$path"
|
||||
val file = File(result)
|
||||
return if (file.exists() && file.canRead()) {
|
||||
result
|
||||
} else null
|
||||
}
|
||||
}
|
||||
} else if (isDownloadsDocument(uri)) {
|
||||
val id: String = DocumentsContract.getDocumentId(uri)
|
||||
val contentUri: Uri = ContentUris.withAppendedId(
|
||||
Uri.parse("content://downloads/public_downloads"),
|
||||
java.lang.Long.valueOf(id)
|
||||
)
|
||||
return getDataColumn(context, contentUri, null, null)
|
||||
} else if (isMediaDocument(uri)) {
|
||||
val docId: String = DocumentsContract.getDocumentId(uri)
|
||||
val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }
|
||||
.toTypedArray()
|
||||
val type = split[0]
|
||||
var contentUri: Uri? = null
|
||||
when (type) {
|
||||
"image" -> {
|
||||
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
|
||||
}
|
||||
"video" -> {
|
||||
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
|
||||
}
|
||||
"audio" -> {
|
||||
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
|
||||
}
|
||||
}
|
||||
val selection = "_id=?"
|
||||
val selectionArgs = arrayOf(split[1])
|
||||
if (contentUri != null) {
|
||||
return getDataColumn(context, contentUri, selection, selectionArgs)
|
||||
}
|
||||
}
|
||||
} else if ("content".equals(uri.scheme, ignoreCase = true)) {
|
||||
// Return the remote address
|
||||
return if (isGooglePhotosUri(uri)) uri.lastPathSegment else getDataColumn(
|
||||
context,
|
||||
uri,
|
||||
null,
|
||||
null
|
||||
)
|
||||
} else if ("file".equals(uri.scheme, ignoreCase = true)) {
|
||||
return uri.path
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value of the data column for this Uri. This is useful for
|
||||
* MediaStore Uris, and other file-based ContentProviders.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param uri The Uri to query.
|
||||
* @param selection (Optional) Filter used in the query.
|
||||
* @param selectionArgs (Optional) Selection arguments used in the query.
|
||||
* @return The value of the _data column, which is typically a file path.
|
||||
*/
|
||||
private fun getDataColumn(
|
||||
context: Context,
|
||||
uri: Uri,
|
||||
selection: String?,
|
||||
selectionArgs: Array<String>?
|
||||
): String? {
|
||||
var path: String? = null
|
||||
var cursor: Cursor? = null
|
||||
val column = "_data"
|
||||
val projection = arrayOf(column)
|
||||
try {
|
||||
cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null)
|
||||
if (cursor != null && cursor.moveToFirst()) {
|
||||
val index = cursor.getColumnIndexOrThrow(column)
|
||||
path = cursor.getString(index)
|
||||
}
|
||||
} catch (ex: IllegalArgumentException) {
|
||||
return getCopyFilePath(uri, context)
|
||||
} finally {
|
||||
cursor?.close()
|
||||
}
|
||||
return path ?: getCopyFilePath(uri, context)
|
||||
}
|
||||
|
||||
private fun getCopyFilePath(uri: Uri, context: Context): String? {
|
||||
val cursor = context.contentResolver.query(uri, null, null, null, null)!!
|
||||
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
|
||||
cursor.moveToFirst()
|
||||
val name = cursor.getString(nameIndex)
|
||||
val file = File(context.filesDir, name)
|
||||
try {
|
||||
val inputStream = context.contentResolver.openInputStream(uri)
|
||||
val outputStream = FileOutputStream(file)
|
||||
var read: Int
|
||||
val maxBufferSize = 1024 * 1024
|
||||
val bufferSize = min(inputStream!!.available(), maxBufferSize)
|
||||
val buffers = ByteArray(bufferSize)
|
||||
while (inputStream.read(buffers).also { read = it } != -1) {
|
||||
outputStream.write(buffers, 0, read)
|
||||
}
|
||||
inputStream.close()
|
||||
outputStream.close()
|
||||
} catch (e: Exception) {
|
||||
return null
|
||||
} finally {
|
||||
cursor.close()
|
||||
}
|
||||
return file.path
|
||||
}
|
||||
|
||||
private fun legacyPrimaryPath(pathPart: String): String {
|
||||
return Environment.getExternalStorageDirectory().toString() + "/" + pathPart
|
||||
}
|
||||
|
||||
/**
|
||||
* @param uri The Uri to check.
|
||||
* @return Whether the Uri authority is ExternalStorageProvider.
|
||||
*/
|
||||
private fun isExternalStorageDocument(uri: Uri): Boolean {
|
||||
return "com.android.externalstorage.documents" == uri.authority
|
||||
}
|
||||
|
||||
/**
|
||||
* @param uri The Uri to check.
|
||||
* @return Whether the Uri authority is DownloadsProvider.
|
||||
*/
|
||||
private fun isDownloadsDocument(uri: Uri): Boolean {
|
||||
return "com.android.providers.downloads.documents" == uri.authority
|
||||
}
|
||||
|
||||
/**
|
||||
* @param uri The Uri to check.
|
||||
* @return Whether the Uri authority is MediaProvider.
|
||||
*/
|
||||
private fun isMediaDocument(uri: Uri): Boolean {
|
||||
return "com.android.providers.media.documents" == uri.authority
|
||||
}
|
||||
|
||||
/**
|
||||
* @param uri The Uri to check.
|
||||
* @return Whether the Uri authority is Google Photos.
|
||||
*/
|
||||
private fun isGooglePhotosUri(uri: Uri): Boolean {
|
||||
return "com.google.android.apps.photos.content" == uri.authority
|
||||
}
|
||||
|
||||
private fun getPathToNonPrimaryVolume(context: Context, tag: String): String? {
|
||||
val volumes = context.externalCacheDirs
|
||||
if (volumes != null) {
|
||||
for (volume in volumes) {
|
||||
if (volume != null) {
|
||||
val path = volume.absolutePath
|
||||
val index = path.indexOf(tag)
|
||||
if (index != -1) {
|
||||
return path.substring(0, index) + tag
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri
|
||||
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
internal annotation class JniMethod
|
||||
@@ -0,0 +1,85 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri
|
||||
|
||||
// taken from https://github.com/ionic-team/capacitor/blob/6658bca41e78239347e458175b14ca8bd5c1d6e8/android/capacitor/src/main/java/com/getcapacitor/Logger.java
|
||||
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
|
||||
class Logger {
|
||||
companion object {
|
||||
private const val LOG_TAG_CORE = "Tauri"
|
||||
|
||||
fun tags(vararg subtags: String): String {
|
||||
return if (subtags.isNotEmpty()) {
|
||||
LOG_TAG_CORE + "/" + TextUtils.join("/", subtags)
|
||||
} else LOG_TAG_CORE
|
||||
}
|
||||
|
||||
fun verbose(message: String) {
|
||||
verbose(LOG_TAG_CORE, message)
|
||||
}
|
||||
|
||||
fun verbose(tag: String, message: String) {
|
||||
if (!shouldLog()) {
|
||||
return
|
||||
}
|
||||
Log.v(tag, message)
|
||||
}
|
||||
|
||||
fun debug(message: String) {
|
||||
debug(LOG_TAG_CORE, message)
|
||||
}
|
||||
|
||||
fun debug(tag: String, message: String) {
|
||||
if (!shouldLog()) {
|
||||
return
|
||||
}
|
||||
Log.d(tag, message)
|
||||
}
|
||||
|
||||
fun info(message: String) {
|
||||
info(LOG_TAG_CORE, message)
|
||||
}
|
||||
|
||||
fun info(tag: String, message: String) {
|
||||
if (!shouldLog()) {
|
||||
return
|
||||
}
|
||||
Log.i(tag, message)
|
||||
}
|
||||
|
||||
fun warn(message: String) {
|
||||
warn(LOG_TAG_CORE, message)
|
||||
}
|
||||
|
||||
fun warn(tag: String, message: String) {
|
||||
if (!shouldLog()) {
|
||||
return
|
||||
}
|
||||
Log.w(tag, message)
|
||||
}
|
||||
|
||||
fun error(message: String) {
|
||||
error(LOG_TAG_CORE, message, null)
|
||||
}
|
||||
|
||||
fun error(message: String, e: Throwable?) {
|
||||
error(LOG_TAG_CORE, message, e)
|
||||
}
|
||||
|
||||
fun error(tag: String, message: String, e: Throwable?) {
|
||||
if (!shouldLog()) {
|
||||
return
|
||||
}
|
||||
Log.e(tag, message, e)
|
||||
}
|
||||
|
||||
private fun shouldLog(): Boolean {
|
||||
return BuildConfig.DEBUG
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri
|
||||
|
||||
import android.app.Activity
|
||||
import android.database.Cursor
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.OpenableColumns
|
||||
import app.tauri.annotation.Command
|
||||
import app.tauri.annotation.InvokeArg
|
||||
import app.tauri.annotation.TauriPlugin
|
||||
import app.tauri.plugin.Plugin
|
||||
import app.tauri.plugin.Invoke
|
||||
import app.tauri.plugin.JSObject
|
||||
|
||||
const val TAURI_ASSETS_DIRECTORY_URI = "asset://localhost/"
|
||||
|
||||
@InvokeArg
|
||||
class GetFileNameFromUriArgs {
|
||||
lateinit var uri: String
|
||||
}
|
||||
|
||||
@TauriPlugin
|
||||
class PathPlugin(private val activity: Activity): Plugin(activity) {
|
||||
private fun resolvePath(invoke: Invoke, path: String?) {
|
||||
val obj = JSObject()
|
||||
obj.put("path", path)
|
||||
invoke.resolve(obj)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun getFileNameFromUri(invoke: Invoke) {
|
||||
val args = invoke.parseArgs(GetFileNameFromUriArgs::class.java)
|
||||
val name = getRealNameFromURI(activity, Uri.parse(args.uri))
|
||||
val res = JSObject()
|
||||
res.put("name", name)
|
||||
invoke.resolve(res)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun getAudioDir(invoke: Invoke) {
|
||||
resolvePath(invoke, activity.getExternalFilesDir(Environment.DIRECTORY_MUSIC)?.absolutePath)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun getExternalCacheDir(invoke: Invoke) {
|
||||
resolvePath(invoke, activity.externalCacheDir?.absolutePath)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun getConfigDir(invoke: Invoke) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||
resolvePath(invoke, activity.dataDir.absolutePath)
|
||||
} else {
|
||||
resolvePath(invoke, activity.applicationInfo.dataDir)
|
||||
}
|
||||
}
|
||||
|
||||
@Command
|
||||
fun getDataDir(invoke: Invoke) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||
resolvePath(invoke, activity.dataDir.absolutePath)
|
||||
} else {
|
||||
resolvePath(invoke, activity.applicationInfo.dataDir)
|
||||
}
|
||||
}
|
||||
|
||||
@Command
|
||||
fun getDocumentDir(invoke: Invoke) {
|
||||
resolvePath(invoke, activity.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)?.absolutePath)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun getDownloadDir(invoke: Invoke) {
|
||||
resolvePath(invoke, activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun getPictureDir(invoke: Invoke) {
|
||||
resolvePath(invoke, activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.absolutePath)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun getPublicDir(invoke: Invoke) {
|
||||
resolvePath(invoke, activity.getExternalFilesDir(Environment.DIRECTORY_DCIM)?.absolutePath)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun getVideoDir(invoke: Invoke) {
|
||||
resolvePath(invoke, activity.getExternalFilesDir(Environment.DIRECTORY_MOVIES)?.absolutePath)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun getResourcesDir(invoke: Invoke) {
|
||||
resolvePath(invoke, TAURI_ASSETS_DIRECTORY_URI)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun getCacheDir(invoke: Invoke) {
|
||||
resolvePath(invoke, activity.cacheDir.absolutePath)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun getHomeDir(invoke: Invoke) {
|
||||
resolvePath(invoke, Environment.getExternalStorageDirectory().absolutePath)
|
||||
}
|
||||
}
|
||||
|
||||
fun getRealNameFromURI(activity: Activity, contentUri: Uri): String? {
|
||||
var cursor: Cursor? = null
|
||||
try {
|
||||
val projection = arrayOf(OpenableColumns.DISPLAY_NAME)
|
||||
cursor = activity.contentResolver.query(contentUri, projection, null, null, null)
|
||||
|
||||
cursor?.let {
|
||||
val columnIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
|
||||
if (it.moveToFirst()) {
|
||||
return it.getString(columnIndex)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Logger.error("failed to get real name from URI $e")
|
||||
} finally {
|
||||
cursor?.close()
|
||||
}
|
||||
|
||||
return null // Return null if no file name could be resolved
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri
|
||||
|
||||
// taken from https://github.com/ionic-team/capacitor/blob/6658bca41e78239347e458175b14ca8bd5c1d6e8/android/capacitor/src/main/java/com/getcapacitor/PermissionHelper.java
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.os.Build;
|
||||
import androidx.core.app.ActivityCompat;
|
||||
import java.util.ArrayList;
|
||||
|
||||
object PermissionHelper {
|
||||
/**
|
||||
* Checks if a list of given permissions are all granted by the user
|
||||
*
|
||||
* @param permissions Permissions to check.
|
||||
* @return True if all permissions are granted, false if at least one is not.
|
||||
*/
|
||||
fun hasPermissions(context: Context?, permissions: Array<String>): Boolean {
|
||||
for (perm in permissions) {
|
||||
if (ActivityCompat.checkSelfPermission(
|
||||
context!!,
|
||||
perm
|
||||
) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the given permission has been defined in the AndroidManifest.xml
|
||||
*
|
||||
* @param permission A permission to check.
|
||||
* @return True if the permission has been defined in the Manifest, false if not.
|
||||
*/
|
||||
fun hasDefinedPermission(context: Context, permission: String): Boolean {
|
||||
val requestedPermissions = getManifestPermissions(context)
|
||||
if (!requestedPermissions.isNullOrEmpty()) {
|
||||
val requestedPermissionsList = listOf(*requestedPermissions)
|
||||
val requestedPermissionsArrayList = ArrayList(requestedPermissionsList)
|
||||
if (requestedPermissionsArrayList.contains(permission)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether all of the given permissions have been defined in the AndroidManifest.xml
|
||||
* @param context the app context
|
||||
* @param permissions a list of permissions
|
||||
* @return true only if all permissions are defined in the AndroidManifest.xml
|
||||
*/
|
||||
fun hasDefinedPermissions(context: Context, permissions: Array<String>): Boolean {
|
||||
return permissions.all { hasDefinedPermission(context, it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the permissions defined in AndroidManifest.xml
|
||||
*
|
||||
* @return The permissions defined in AndroidManifest.xml
|
||||
*/
|
||||
private fun getManifestPermissions(context: Context): Array<String>? {
|
||||
var requestedPermissions: Array<String>? = null
|
||||
try {
|
||||
val pm = context.packageManager
|
||||
val packageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
pm.getPackageInfo(context.packageName, PackageManager.PackageInfoFlags.of(PackageManager.GET_PERMISSIONS.toLong()))
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
pm.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS)
|
||||
}
|
||||
if (packageInfo != null) {
|
||||
requestedPermissions = packageInfo.requestedPermissions
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
return requestedPermissions
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a list of permissions, return a new list with the ones not present in AndroidManifest.xml
|
||||
*
|
||||
* @param neededPermissions The permissions needed.
|
||||
* @return The permissions not present in AndroidManifest.xml
|
||||
*/
|
||||
fun getUndefinedPermissions(context: Context, neededPermissions: Array<String>): Array<String> {
|
||||
val requestedPermissions = getManifestPermissions(context)
|
||||
if (!requestedPermissions.isNullOrEmpty()) {
|
||||
val undefinedPermissions = ArrayList<String>()
|
||||
val requestedPermissionsList = listOf(*requestedPermissions)
|
||||
val requestedPermissionsArrayList = ArrayList(requestedPermissionsList)
|
||||
for (permission in neededPermissions) {
|
||||
if (!requestedPermissionsArrayList.contains(permission)) {
|
||||
undefinedPermissions.add(permission)
|
||||
}
|
||||
}
|
||||
return undefinedPermissions.toTypedArray()
|
||||
}
|
||||
return neededPermissions
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri
|
||||
|
||||
import java.util.*
|
||||
|
||||
enum class PermissionState(private val state: String) {
|
||||
GRANTED("granted"), DENIED("denied"), PROMPT("prompt"), PROMPT_WITH_RATIONALE("prompt-with-rationale");
|
||||
|
||||
override fun toString(): String {
|
||||
return state
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun byState(state: String): PermissionState {
|
||||
return valueOf(state.uppercase(Locale.ROOT).replace('-', '_'))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.annotation
|
||||
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
@Target(AnnotationTarget.FUNCTION)
|
||||
annotation class ActivityCallback
|
||||
@@ -0,0 +1,9 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.annotation
|
||||
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
@Target(AnnotationTarget.CLASS)
|
||||
annotation class InvokeArg
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.annotation
|
||||
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
annotation class Permission(
|
||||
/**
|
||||
* An array of Android permission strings.
|
||||
* Eg: {Manifest.permission.ACCESS_COARSE_LOCATION}
|
||||
* or {"android.permission.ACCESS_COARSE_LOCATION"}
|
||||
*/
|
||||
val strings: Array<String> = [],
|
||||
/**
|
||||
* An optional name to use instead of the Android permission string.
|
||||
*/
|
||||
val alias: String = ""
|
||||
)
|
||||
@@ -0,0 +1,9 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.annotation
|
||||
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
@Target(AnnotationTarget.FUNCTION)
|
||||
annotation class PermissionCallback
|
||||
@@ -0,0 +1,8 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.annotation
|
||||
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
annotation class Command
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.annotation
|
||||
|
||||
import app.tauri.annotation.Permission
|
||||
|
||||
/**
|
||||
* Base annotation for all Plugins
|
||||
*/
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
annotation class TauriPlugin(
|
||||
/**
|
||||
* Permissions this plugin needs, in order to make permission requests
|
||||
* easy if the plugin only needs basic permission prompting
|
||||
*/
|
||||
val permissions: Array<Permission> = []
|
||||
)
|
||||
@@ -0,0 +1,33 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.plugin
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser
|
||||
import com.fasterxml.jackson.databind.DeserializationContext
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
|
||||
const val CHANNEL_PREFIX = "__CHANNEL__:"
|
||||
|
||||
internal class ChannelDeserializer(val sendChannelData: (channelId: Long, data: String) -> Unit, private val objectMapper: ObjectMapper): JsonDeserializer<Channel>() {
|
||||
override fun deserialize(
|
||||
jsonParser: JsonParser?,
|
||||
deserializationContext: DeserializationContext
|
||||
): Channel {
|
||||
val channelDef = deserializationContext.readValue(jsonParser, String::class.java)
|
||||
val callback = channelDef.substring(CHANNEL_PREFIX.length).toLongOrNull() ?: throw Error("unexpected channel value $channelDef")
|
||||
return Channel(callback, { res -> sendChannelData(callback, res) }, objectMapper)
|
||||
}
|
||||
}
|
||||
|
||||
class Channel(val id: Long, private val handler: (data: String) -> Unit, private val objectMapper: ObjectMapper) {
|
||||
fun send(data: JSObject) {
|
||||
handler(PluginResult(data).toString())
|
||||
}
|
||||
|
||||
fun sendObject(data: Any) {
|
||||
handler(objectMapper.writeValueAsString(data))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.plugin
|
||||
|
||||
internal class InvalidCommandException : Exception {
|
||||
constructor(s: String?) : super(s) {}
|
||||
constructor(t: Throwable?) : super(t) {}
|
||||
constructor(s: String?, t: Throwable?) : super(s, t) {}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.plugin
|
||||
|
||||
import app.tauri.Logger
|
||||
import com.fasterxml.jackson.core.type.TypeReference
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
|
||||
class Invoke(
|
||||
val id: Long,
|
||||
val command: String,
|
||||
val callback: Long,
|
||||
val error: Long,
|
||||
private val sendResponse: (callback: Long, data: String) -> Unit,
|
||||
private val argsJson: String,
|
||||
private val jsonMapper: ObjectMapper
|
||||
) {
|
||||
fun getRawArgs(): String {
|
||||
return argsJson
|
||||
}
|
||||
|
||||
fun getArgs(): JSObject {
|
||||
return JSObject(argsJson)
|
||||
}
|
||||
|
||||
fun<T> parseArgs(cls: Class<T>): T {
|
||||
return jsonMapper.readValue(argsJson, cls)
|
||||
}
|
||||
|
||||
fun<T> parseArgs(ref: TypeReference<T>): T {
|
||||
return jsonMapper.readValue(argsJson, ref)
|
||||
}
|
||||
|
||||
fun resolve(data: JSObject?) {
|
||||
sendResponse(callback, PluginResult(data).toString())
|
||||
}
|
||||
|
||||
fun resolveObject(data: Any) {
|
||||
sendResponse(callback, jsonMapper.writeValueAsString(data))
|
||||
}
|
||||
|
||||
fun resolve() {
|
||||
sendResponse(callback, "null")
|
||||
}
|
||||
|
||||
fun reject(msg: String?, code: String?, ex: Exception?, data: JSObject?) {
|
||||
val errorResult = PluginResult()
|
||||
|
||||
if (ex != null) {
|
||||
Logger.error(Logger.tags("Plugin"), msg!!, ex)
|
||||
}
|
||||
|
||||
errorResult.put("message", msg)
|
||||
if (code != null) {
|
||||
errorResult.put("code", code)
|
||||
}
|
||||
if (data != null) {
|
||||
errorResult.put("data", data)
|
||||
}
|
||||
|
||||
sendResponse(error, errorResult.toString())
|
||||
}
|
||||
|
||||
fun reject(msg: String?, ex: Exception?, data: JSObject?) {
|
||||
reject(msg, null, ex, data)
|
||||
}
|
||||
|
||||
fun reject(msg: String?, code: String?, data: JSObject?) {
|
||||
reject(msg, code, null, data)
|
||||
}
|
||||
|
||||
fun reject(msg: String?, code: String?, ex: Exception?) {
|
||||
reject(msg, code, ex, null)
|
||||
}
|
||||
|
||||
fun reject(msg: String?, data: JSObject?) {
|
||||
reject(msg, null, null, data)
|
||||
}
|
||||
|
||||
fun reject(msg: String?, ex: Exception?) {
|
||||
reject(msg, null, ex, null)
|
||||
}
|
||||
|
||||
fun reject(msg: String?, code: String?) {
|
||||
reject(msg, code, null, null)
|
||||
}
|
||||
|
||||
fun reject(msg: String?) {
|
||||
reject(msg, null, null, null)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.plugin
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONException
|
||||
|
||||
class JSArray : JSONArray {
|
||||
constructor() : super() {}
|
||||
constructor(json: String?) : super(json) {}
|
||||
constructor(copyFrom: Collection<*>?) : super(copyFrom) {}
|
||||
constructor(array: Any?) : super(array) {}
|
||||
|
||||
@Suppress("UNCHECKED_CAST", "ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
|
||||
@Throws(JSONException::class)
|
||||
fun <E> toList(): List<E> {
|
||||
val items: MutableList<E> = ArrayList()
|
||||
var o: Any? = null
|
||||
for (i in 0 until this.length()) {
|
||||
this.get(i).also { o = it }
|
||||
try {
|
||||
items.add(this.get(i) as E)
|
||||
} catch (ex: Exception) {
|
||||
throw JSONException("Not all items are instances of the given type")
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Create a new JSArray without throwing a error
|
||||
*/
|
||||
fun from(array: Any?): JSArray? {
|
||||
try {
|
||||
return JSArray(array)
|
||||
} catch (ex: JSONException) {
|
||||
//
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.plugin
|
||||
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
|
||||
class JSObject : JSONObject {
|
||||
constructor() : super()
|
||||
constructor(json: String) : super(json)
|
||||
constructor(obj: JSONObject, names: Array<String>) : super(obj, names)
|
||||
|
||||
override fun getString(key: String): String {
|
||||
return getString(key, "")!!
|
||||
}
|
||||
|
||||
fun getString(key: String, defaultValue: String?): String? {
|
||||
try {
|
||||
if (!super.isNull(key)) {
|
||||
return super.getString(key)
|
||||
}
|
||||
} catch (_: JSONException) {
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
fun getInteger(key: String): Int? {
|
||||
return getIntegerInternal(key, null)
|
||||
}
|
||||
|
||||
fun getInteger(key: String, defaultValue: Int): Int {
|
||||
return getIntegerInternal(key, defaultValue)!!
|
||||
}
|
||||
|
||||
private fun getIntegerInternal(key: String, defaultValue: Int?): Int? {
|
||||
try {
|
||||
return super.getInt(key)
|
||||
} catch (_: JSONException) {
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
override fun getBoolean(key: String): Boolean {
|
||||
return getBooleanInternal(key, false)!!
|
||||
}
|
||||
|
||||
fun getBoolean(key: String, defaultValue: Boolean?): Boolean {
|
||||
return getBooleanInternal(key, defaultValue)!!
|
||||
}
|
||||
|
||||
private fun getBooleanInternal(key: String, defaultValue: Boolean?): Boolean? {
|
||||
try {
|
||||
return super.getBoolean(key)
|
||||
} catch (_: JSONException) {
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
fun getJSObject(name: String): JSObject? {
|
||||
try {
|
||||
return getJSObjectInternal(name, null)
|
||||
} catch (_: JSONException) {
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
fun getJSObject(name: String, defaultValue: JSObject): JSObject {
|
||||
return getJSObjectInternal(name, defaultValue)!!
|
||||
}
|
||||
|
||||
private fun getJSObjectInternal(name: String, defaultValue: JSObject?): JSObject? {
|
||||
try {
|
||||
val obj = get(name)
|
||||
if (obj is JSONObject) {
|
||||
val keysIter = obj.keys()
|
||||
val keys: MutableList<String> = ArrayList()
|
||||
while (keysIter.hasNext()) {
|
||||
keys.add(keysIter.next())
|
||||
}
|
||||
return JSObject(obj, keys.toTypedArray())
|
||||
}
|
||||
} catch (_: JSONException) {
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
override fun put(key: String, value: Boolean): JSObject {
|
||||
try {
|
||||
super.put(key, value)
|
||||
} catch (_: JSONException) {
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
override fun put(key: String, value: Int): JSObject {
|
||||
try {
|
||||
super.put(key, value)
|
||||
} catch (_: JSONException) {
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
override fun put(key: String, value: Long): JSObject {
|
||||
try {
|
||||
super.put(key, value)
|
||||
} catch (_: JSONException) {
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
override fun put(key: String, value: Double): JSObject {
|
||||
try {
|
||||
super.put(key, value)
|
||||
} catch (_: JSONException) {
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
override fun put(key: String, value: Any?): JSObject {
|
||||
try {
|
||||
super.put(key, value)
|
||||
} catch (_: JSONException) {
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
fun put(key: String, value: String?): JSObject {
|
||||
try {
|
||||
super.put(key, value)
|
||||
} catch (_: JSONException) {
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Convert a pathetic JSONObject into a JSObject
|
||||
* @param obj
|
||||
*/
|
||||
@Throws(JSONException::class)
|
||||
fun fromJSONObject(obj: JSONObject): JSObject {
|
||||
val keysIter = obj.keys()
|
||||
val keys: MutableList<String> = ArrayList()
|
||||
while (keysIter.hasNext()) {
|
||||
keys.add(keysIter.next())
|
||||
}
|
||||
return JSObject(obj, keys.toTypedArray())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,536 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.plugin
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.res.Configuration
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.webkit.WebView
|
||||
import androidx.activity.result.IntentSenderRequest
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.app.ActivityCompat
|
||||
import app.tauri.FsUtils
|
||||
import app.tauri.Logger
|
||||
import app.tauri.PermissionHelper
|
||||
import app.tauri.PermissionState
|
||||
import app.tauri.annotation.ActivityCallback
|
||||
import app.tauri.annotation.Command
|
||||
import app.tauri.annotation.InvokeArg
|
||||
import app.tauri.annotation.PermissionCallback
|
||||
import app.tauri.annotation.TauriPlugin
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import java.util.*
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
|
||||
@InvokeArg
|
||||
internal class RegisterListenerArgs {
|
||||
lateinit var event: String
|
||||
lateinit var handler: Channel
|
||||
}
|
||||
|
||||
@InvokeArg
|
||||
internal class RemoveListenerArgs {
|
||||
lateinit var event: String
|
||||
var channelId: Long = 0
|
||||
}
|
||||
|
||||
@InvokeArg internal class RequestPermissionsArgs {
|
||||
var permissions: List<String>? = null
|
||||
}
|
||||
|
||||
abstract class Plugin(private val activity: Activity) {
|
||||
var handle: PluginHandle? = null
|
||||
private val listeners: MutableMap<String, MutableList<Channel>> = mutableMapOf()
|
||||
|
||||
open fun load(webView: WebView) {}
|
||||
|
||||
fun jsonMapper(): ObjectMapper {
|
||||
return handle!!.jsonMapper
|
||||
}
|
||||
|
||||
fun<T> getConfig(cls: Class<T>): T {
|
||||
return jsonMapper().readValue(handle!!.config, cls)
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a new intent being received by the application
|
||||
*/
|
||||
open fun onNewIntent(intent: Intent) {}
|
||||
|
||||
|
||||
/**
|
||||
* This event is called just before another activity comes into the foreground.
|
||||
*/
|
||||
open fun onPause(activity: AppCompatActivity) {}
|
||||
|
||||
/**
|
||||
* This event is called just before another activity comes into the foreground.
|
||||
*/
|
||||
@Deprecated("use onPause(activity: AppCompatActivity) instead")
|
||||
open fun onPause() {}
|
||||
|
||||
/**
|
||||
* This event is called when the user returns to the activity. It is also called on cold starts.
|
||||
*/
|
||||
open fun onResume(activity: AppCompatActivity) {}
|
||||
|
||||
/**
|
||||
* This event is called when the user returns to the activity. It is also called on cold starts.
|
||||
*/
|
||||
@Deprecated("use onResume(activity: AppCompatActivity) instead")
|
||||
open fun onResume() {}
|
||||
|
||||
/**
|
||||
* This event is called after onStop() when the current activity is being re-displayed to the user (the user has navigated back to it).
|
||||
* It will be followed by onStart() and then onResume().
|
||||
*/
|
||||
open fun onRestart(activity: AppCompatActivity) {}
|
||||
|
||||
/**
|
||||
* This event is called after onStop() when the current activity is being re-displayed to the user (the user has navigated back to it).
|
||||
* It will be followed by onStart() and then onResume().
|
||||
*/
|
||||
@Deprecated("use onRestart(activity: AppCompatActivity) instead")
|
||||
open fun onRestart() {}
|
||||
|
||||
/**
|
||||
* This event is called when the app is no longer visible to the user.
|
||||
* You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.
|
||||
*/
|
||||
open fun onStop(activity: AppCompatActivity) {}
|
||||
|
||||
/**
|
||||
* This event is called when the app is no longer visible to the user.
|
||||
* You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.
|
||||
*/
|
||||
@Deprecated("use onStop(activity: AppCompatActivity) instead")
|
||||
open fun onStop() {}
|
||||
|
||||
/**
|
||||
* This event is called before the activity is destroyed.
|
||||
*/
|
||||
open fun onDestroy(activity: AppCompatActivity) {}
|
||||
/**
|
||||
* This event is called before an activity is destroyed.
|
||||
*/
|
||||
@Deprecated("use onDestroy(activity: AppCompatActivity) instead")
|
||||
open fun onDestroy() {}
|
||||
|
||||
internal fun triggerOnDestroy(activity: AppCompatActivity) {
|
||||
onDestroy(activity)
|
||||
onDestroy()
|
||||
}
|
||||
|
||||
internal fun triggerOnRestart(activity: AppCompatActivity) {
|
||||
onRestart(activity)
|
||||
onRestart()
|
||||
}
|
||||
|
||||
internal fun triggerOnPause(activity: AppCompatActivity) {
|
||||
onPause(activity)
|
||||
onPause()
|
||||
}
|
||||
|
||||
internal fun triggerOnResume(activity: AppCompatActivity) {
|
||||
onResume(activity)
|
||||
onResume()
|
||||
}
|
||||
|
||||
internal fun triggerOnStop(activity: AppCompatActivity) {
|
||||
onStop(activity)
|
||||
onStop()
|
||||
}
|
||||
|
||||
/**
|
||||
* This event is called when a configuration change occurs but the app does not recreate the activity.
|
||||
*/
|
||||
open fun onConfigurationChanged(newConfig: Configuration) {}
|
||||
|
||||
/**
|
||||
* Start activity for result with the provided Intent and resolve calling the provided callback method name.
|
||||
*
|
||||
* If there is no registered activity callback for the method name passed in, the call will
|
||||
* be rejected. Make sure a valid activity result callback method is registered using the
|
||||
* [ActivityCallback] annotation.
|
||||
*
|
||||
* @param invoke the invoke object
|
||||
* @param intent the intent used to start an activity
|
||||
* @param callbackName the name of the callback to run when the launched activity is finished
|
||||
*/
|
||||
fun startActivityForResult(invoke: Invoke, intent: Intent, callbackName: String) {
|
||||
handle!!.startActivityForResult(invoke, intent, callbackName)
|
||||
}
|
||||
|
||||
/**
|
||||
* Like startActivityForResult() but taking an IntentSender to describe the activity to be started.
|
||||
*
|
||||
* If there is no registered activity callback for the method name passed in, the call will
|
||||
* be rejected. Make sure a valid activity result callback method is registered using the
|
||||
* [ActivityCallback] annotation.
|
||||
*
|
||||
* @param invoke the invoke object
|
||||
* @param intentSender the intent used to start an activity
|
||||
* @param callbackName the name of the callback to run when the launched activity is finished
|
||||
*/
|
||||
fun startIntentSenderForResult(invoke: Invoke, intentSender: IntentSenderRequest, callbackName: String) {
|
||||
handle!!.startIntentSenderForResult(invoke, intentSender, callbackName)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the plugin log tags.
|
||||
* @param subTags
|
||||
*/
|
||||
protected fun getLogTag(vararg subTags: String): String {
|
||||
return Logger.tags(*subTags)
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a log tag with the plugin's class name as subTag.
|
||||
*/
|
||||
protected fun getLogTag(): String {
|
||||
return Logger.tags(this.javaClass.simpleName)
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an URI to an URL that can be loaded by the webview.
|
||||
*/
|
||||
fun assetUrl(u: Uri): String {
|
||||
var path = FsUtils.getFileUrlForUri(activity, u)
|
||||
if (path?.startsWith("file://") == true) {
|
||||
path = path.replace("file://", "")
|
||||
}
|
||||
return "asset://localhost$path"
|
||||
}
|
||||
|
||||
fun trigger(event: String, payload: JSObject) {
|
||||
val eventListeners = listeners[event]
|
||||
if (!eventListeners.isNullOrEmpty()) {
|
||||
val listeners = CopyOnWriteArrayList(eventListeners)
|
||||
for (channel in listeners) {
|
||||
channel.send(payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun triggerObject(event: String, payload: Any) {
|
||||
val eventListeners = listeners[event]
|
||||
if (!eventListeners.isNullOrEmpty()) {
|
||||
val listeners = CopyOnWriteArrayList(eventListeners)
|
||||
for (channel in listeners) {
|
||||
channel.sendObject(payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun hasListener(event: String): Boolean {
|
||||
return !listeners[event].isNullOrEmpty()
|
||||
}
|
||||
|
||||
@Command
|
||||
open fun registerListener(invoke: Invoke) {
|
||||
val args = invoke.parseArgs(RegisterListenerArgs::class.java)
|
||||
|
||||
val eventListeners = listeners[args.event]
|
||||
if (eventListeners.isNullOrEmpty()) {
|
||||
listeners[args.event] = mutableListOf(args.handler)
|
||||
} else {
|
||||
eventListeners.add(args.handler)
|
||||
}
|
||||
|
||||
invoke.resolve()
|
||||
}
|
||||
|
||||
@Command
|
||||
open fun removeListener(invoke: Invoke) {
|
||||
val args = invoke.parseArgs(RemoveListenerArgs::class.java)
|
||||
|
||||
val eventListeners = listeners[args.event]
|
||||
if (!eventListeners.isNullOrEmpty()) {
|
||||
val c = eventListeners.find { c -> c.id == args.channelId }
|
||||
if (c != null) {
|
||||
eventListeners.remove(c)
|
||||
}
|
||||
}
|
||||
|
||||
invoke.resolve()
|
||||
}
|
||||
|
||||
/**
|
||||
* Exported plugin method for checking the granted status for each permission
|
||||
* declared on the plugin. This plugin call responds with a mapping of permissions to
|
||||
* the associated granted status.
|
||||
*/
|
||||
@Command
|
||||
@PermissionCallback
|
||||
open fun checkPermissions(invoke: Invoke) {
|
||||
val permissionsResult: Map<String, PermissionState?> = getPermissionStates()
|
||||
if (permissionsResult.isEmpty()) {
|
||||
// if no permissions are defined on the plugin, resolve undefined
|
||||
invoke.resolve()
|
||||
} else {
|
||||
val permissionsResultJSON = JSObject()
|
||||
for ((key, value) in permissionsResult) {
|
||||
permissionsResultJSON.put(key, value)
|
||||
}
|
||||
invoke.resolve(permissionsResultJSON)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exported plugin method to request all permissions for this plugin.
|
||||
* To manually request permissions within a plugin use:
|
||||
* [.requestAllPermissions], or
|
||||
* [.requestPermissionForAlias], or
|
||||
* [.requestPermissionForAliases]
|
||||
*
|
||||
* @param invoke
|
||||
*/
|
||||
@Command
|
||||
open fun requestPermissions(invoke: Invoke) {
|
||||
val annotation = handle?.annotation
|
||||
if (annotation != null) {
|
||||
// handle permission requests for plugins defined with @TauriPlugin
|
||||
var permAliases: Array<String>? = null
|
||||
val autoGrantPerms: MutableSet<String> = HashSet()
|
||||
|
||||
val args = invoke.parseArgs(RequestPermissionsArgs::class.java)
|
||||
|
||||
args.permissions?.let {
|
||||
val aliasSet: MutableSet<String> = HashSet()
|
||||
|
||||
for (perm in annotation.permissions) {
|
||||
if (it.contains(perm.alias)) {
|
||||
aliasSet.add(perm.alias)
|
||||
}
|
||||
}
|
||||
if (aliasSet.isEmpty()) {
|
||||
invoke.reject("No valid permission alias was requested of this plugin.")
|
||||
return
|
||||
} else {
|
||||
permAliases = aliasSet.toTypedArray()
|
||||
}
|
||||
} ?: run {
|
||||
val aliasSet: MutableSet<String> = HashSet()
|
||||
|
||||
for (perm in annotation.permissions) {
|
||||
// If a permission is defined with no permission strings, separate it for auto-granting.
|
||||
// Otherwise, the alias is added to the list to be requested.
|
||||
if (perm.strings.isEmpty() || perm.strings.size == 1 && perm.strings[0]
|
||||
.isEmpty()
|
||||
) {
|
||||
if (perm.alias.isNotEmpty()) {
|
||||
autoGrantPerms.add(perm.alias)
|
||||
}
|
||||
} else {
|
||||
aliasSet.add(perm.alias)
|
||||
}
|
||||
}
|
||||
permAliases = aliasSet.toTypedArray()
|
||||
}
|
||||
|
||||
permAliases?.let {
|
||||
// request permissions using provided aliases or all defined on the plugin
|
||||
requestPermissionForAliases(it, invoke, "checkPermissions")
|
||||
} ?: run {
|
||||
if (autoGrantPerms.isNotEmpty()) {
|
||||
// if the plugin only has auto-grant permissions, return all as GRANTED
|
||||
val permissionsResults = JSObject()
|
||||
for (perm in autoGrantPerms) {
|
||||
permissionsResults.put(perm, PermissionState.GRANTED.toString())
|
||||
}
|
||||
invoke.resolve(permissionsResults)
|
||||
} else {
|
||||
// no permissions are defined on the plugin, resolve undefined
|
||||
invoke.resolve()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given permission alias is correctly declared in AndroidManifest.xml
|
||||
* @param alias a permission alias defined on the plugin
|
||||
* @return true only if all permissions associated with the given alias are declared in the manifest
|
||||
*/
|
||||
fun isPermissionDeclared(alias: String): Boolean {
|
||||
for (perm in handle?.annotation?.permissions.orEmpty()) {
|
||||
if (alias.equals(perm.alias, ignoreCase = true)) {
|
||||
var result = true
|
||||
for (permString in perm.strings) {
|
||||
result = result && PermissionHelper.hasDefinedPermission(activity, permString)
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
Logger.error(
|
||||
String.format(
|
||||
"isPermissionDeclared: No alias defined for %s " + "or missing @TauriPlugin annotation.",
|
||||
alias
|
||||
)
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
private fun permissionActivityResult(
|
||||
invoke: Invoke,
|
||||
permissionStrings: Array<String>,
|
||||
callbackName: String
|
||||
) {
|
||||
handle!!.requestPermissions(invoke, permissionStrings, callbackName)
|
||||
}
|
||||
|
||||
/**
|
||||
* Request all of the specified permissions in the TauriPlugin annotation (if any)
|
||||
*
|
||||
* If there is no registered permission callback for the Invoke passed in, the call will
|
||||
* be rejected. Make sure a valid permission callback method is registered using the
|
||||
* [PermissionCallback] annotation.
|
||||
*
|
||||
* @param invoke
|
||||
* @param callbackName the name of the callback to run when the permission request is complete
|
||||
*/
|
||||
protected fun requestAllPermissions(
|
||||
invoke: Invoke,
|
||||
callbackName: String
|
||||
) {
|
||||
val annotation = handle!!.annotation
|
||||
if (annotation != null) {
|
||||
val perms: HashSet<String> = HashSet()
|
||||
for (perm in annotation.permissions) {
|
||||
perms.addAll(perm.strings)
|
||||
}
|
||||
permissionActivityResult(invoke, perms.toArray(arrayOfNulls<String>(0)), callbackName)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Request permissions using an alias defined on the plugin.
|
||||
*
|
||||
* If there is no registered permission callback for the Invoke passed in, the call will
|
||||
* be rejected. Make sure a valid permission callback method is registered using the
|
||||
* [PermissionCallback] annotation.
|
||||
*
|
||||
* @param alias an alias defined on the plugin
|
||||
* @param invoke the invoke involved in originating the request
|
||||
* @param callbackName the name of the callback to run when the permission request is complete
|
||||
*/
|
||||
protected fun requestPermissionForAlias(
|
||||
alias: String,
|
||||
invoke: Invoke,
|
||||
callbackName: String
|
||||
) {
|
||||
requestPermissionForAliases(arrayOf(alias), invoke, callbackName)
|
||||
}
|
||||
|
||||
/**
|
||||
* Request permissions using aliases defined on the plugin.
|
||||
*
|
||||
* If there is no registered permission callback for the Invoke passed in, the call will
|
||||
* be rejected. Make sure a valid permission callback method is registered using the
|
||||
* [PermissionCallback] annotation.
|
||||
*
|
||||
* @param aliases a set of aliases defined on the plugin
|
||||
* @param invoke the invoke involved in originating the request
|
||||
* @param callbackName the name of the callback to run when the permission request is complete
|
||||
*/
|
||||
fun requestPermissionForAliases(
|
||||
aliases: Array<String>,
|
||||
invoke: Invoke,
|
||||
callbackName: String
|
||||
) {
|
||||
if (aliases.isEmpty()) {
|
||||
Logger.error("No permission alias was provided")
|
||||
return
|
||||
}
|
||||
val permissions = getPermissionStringsForAliases(aliases)
|
||||
if (permissions.isNotEmpty()) {
|
||||
permissionActivityResult(invoke, permissions, callbackName)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the Android permission strings defined on the [TauriPlugin] annotation with
|
||||
* the provided aliases.
|
||||
*
|
||||
* @param aliases aliases for permissions defined on the plugin
|
||||
* @return Android permission strings associated with the provided aliases, if exists
|
||||
*/
|
||||
private fun getPermissionStringsForAliases(aliases: Array<String>): Array<String> {
|
||||
val perms: HashSet<String> = HashSet()
|
||||
for (perm in handle?.annotation?.permissions.orEmpty()) {
|
||||
if (aliases.contains(perm.alias)) {
|
||||
perms.addAll(perm.strings)
|
||||
}
|
||||
}
|
||||
return perms.toArray(arrayOfNulls(0))
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the permission state for the provided permission alias.
|
||||
*
|
||||
* @param alias the permission alias to get
|
||||
* @return the state of the provided permission alias or null
|
||||
*/
|
||||
fun getPermissionState(alias: String): PermissionState? {
|
||||
return getPermissionStates()[alias]
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to check all permissions defined on a plugin and see the state of each.
|
||||
*
|
||||
* @return A mapping of permission aliases to the associated granted status.
|
||||
*/
|
||||
open fun getPermissionStates(): Map<String, PermissionState> {
|
||||
val permissionsResults: MutableMap<String, PermissionState> = HashMap()
|
||||
for (perm in handle?.annotation?.permissions.orEmpty()) {
|
||||
// If a permission is defined with no permission constants, return GRANTED for it.
|
||||
// Otherwise, get its true state.
|
||||
if (perm.strings.isEmpty() || perm.strings.size == 1 && perm.strings[0].isEmpty()) {
|
||||
val key = perm.alias
|
||||
if (key.isNotEmpty()) {
|
||||
val existingResult = permissionsResults[key]
|
||||
|
||||
// auto set permission state to GRANTED if the alias is empty.
|
||||
if (existingResult == null) {
|
||||
permissionsResults[key] = PermissionState.GRANTED
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (permString in perm.strings) {
|
||||
val key = perm.alias.ifEmpty { permString }
|
||||
var permissionStatus: PermissionState
|
||||
if (ActivityCompat.checkSelfPermission(
|
||||
activity,
|
||||
permString
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
permissionStatus = PermissionState.GRANTED
|
||||
} else {
|
||||
permissionStatus = PermissionState.PROMPT
|
||||
|
||||
// Check if there is a cached permission state for the "Never ask again" state
|
||||
val prefs =
|
||||
activity.getSharedPreferences("PluginPermStates", Activity.MODE_PRIVATE)
|
||||
val state = prefs.getString(permString, null)
|
||||
if (state != null) {
|
||||
permissionStatus = PermissionState.byState(state)
|
||||
}
|
||||
}
|
||||
val existingResult = permissionsResults[key]
|
||||
|
||||
// multiple permissions with the same alias must all be true, otherwise all false.
|
||||
if (existingResult == null || existingResult === PermissionState.GRANTED) {
|
||||
permissionsResults[key] = permissionStatus
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return permissionsResults
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.plugin
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.webkit.WebView
|
||||
import androidx.activity.result.IntentSenderRequest
|
||||
import androidx.core.app.ActivityCompat
|
||||
import app.tauri.PermissionHelper
|
||||
import app.tauri.PermissionState
|
||||
import app.tauri.annotation.ActivityCallback
|
||||
import app.tauri.annotation.Command
|
||||
import app.tauri.annotation.PermissionCallback
|
||||
import app.tauri.annotation.TauriPlugin
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import java.lang.reflect.Method
|
||||
import androidx.core.content.edit
|
||||
|
||||
class PluginHandle(
|
||||
private val manager: PluginManager,
|
||||
val name: String,
|
||||
val instance: Plugin,
|
||||
val config: String,
|
||||
val jsonMapper: ObjectMapper
|
||||
) {
|
||||
private val commands: HashMap<String, CommandData> = HashMap()
|
||||
private val permissionCallbackMethods: HashMap<String, Method> = HashMap()
|
||||
private val startActivityCallbackMethods: HashMap<String, Method> = HashMap()
|
||||
var annotation: TauriPlugin?
|
||||
var loaded = false
|
||||
|
||||
init {
|
||||
indexMethods()
|
||||
instance.handle = this
|
||||
annotation = instance.javaClass.getAnnotation(TauriPlugin::class.java)
|
||||
}
|
||||
|
||||
fun load(webView: WebView) {
|
||||
instance.load(webView)
|
||||
loaded = true
|
||||
}
|
||||
|
||||
fun startActivityForResult(invoke: Invoke, intent: Intent, callbackName: String) {
|
||||
manager.startActivityForResult(intent) { result ->
|
||||
val method = startActivityCallbackMethods[callbackName]
|
||||
if (method != null) {
|
||||
method.isAccessible = true
|
||||
method(instance, invoke, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun startIntentSenderForResult(
|
||||
invoke: Invoke,
|
||||
intentSender: IntentSenderRequest,
|
||||
callbackName: String
|
||||
) {
|
||||
manager.startIntentSenderForResult(intentSender) { result ->
|
||||
val method = startActivityCallbackMethods[callbackName]
|
||||
if (method != null) {
|
||||
method.isAccessible = true
|
||||
method(instance, invoke, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun requestPermissions(
|
||||
invoke: Invoke,
|
||||
permissions: Array<String>,
|
||||
callbackName: String
|
||||
) {
|
||||
manager.requestPermissions(permissions) { result ->
|
||||
if (validatePermissions(invoke, result)) {
|
||||
val method = permissionCallbackMethods[callbackName]
|
||||
if (method != null) {
|
||||
method.isAccessible = true
|
||||
method(instance, invoke)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves permission states and rejects if permissions were not correctly defined in
|
||||
* the AndroidManifest.xml file.
|
||||
*
|
||||
* @param permissions
|
||||
* @return true if permissions were saved and defined correctly, false if not
|
||||
*/
|
||||
private fun validatePermissions(
|
||||
invoke: Invoke,
|
||||
permissions: Map<String, Boolean>
|
||||
): Boolean {
|
||||
val activity = manager.activity!!
|
||||
val prefs =
|
||||
activity.getSharedPreferences("PluginPermStates", Activity.MODE_PRIVATE)
|
||||
for ((permString, isGranted) in permissions) {
|
||||
if (isGranted) {
|
||||
// Permission granted. If previously denied, remove cached state
|
||||
val state = prefs.getString(permString, null)
|
||||
if (state != null) {
|
||||
prefs.edit {
|
||||
remove(permString)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
prefs.edit {
|
||||
if (ActivityCompat.shouldShowRequestPermissionRationale(
|
||||
activity,
|
||||
permString
|
||||
)
|
||||
) {
|
||||
// Permission denied, can prompt again with rationale
|
||||
putString(permString, PermissionState.PROMPT_WITH_RATIONALE.toString())
|
||||
} else {
|
||||
// Permission denied permanently, store this state for future reference
|
||||
putString(permString, PermissionState.DENIED.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val permStrings = permissions.keys.toTypedArray()
|
||||
if (!PermissionHelper.hasDefinedPermissions(activity, permStrings)) {
|
||||
val builder = StringBuilder()
|
||||
builder.append("Missing the following permissions in AndroidManifest.xml:\n")
|
||||
val missing = PermissionHelper.getUndefinedPermissions(activity, permStrings)
|
||||
for (perm in missing) {
|
||||
builder.append(
|
||||
"""
|
||||
$perm
|
||||
|
||||
""".trimIndent()
|
||||
)
|
||||
}
|
||||
invoke.reject(builder.toString())
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@Throws(
|
||||
InvalidCommandException::class,
|
||||
IllegalAccessException::class
|
||||
)
|
||||
fun invoke(invoke: Invoke) {
|
||||
val methodMeta = commands[invoke.command]
|
||||
?: throw InvalidCommandException("No command " + invoke.command + " found for plugin " + instance.javaClass.name)
|
||||
methodMeta.method.invoke(instance, invoke)
|
||||
}
|
||||
|
||||
private fun indexMethods() {
|
||||
val methods = mutableListOf<Method>()
|
||||
var pluginCursor: Class<*> = instance.javaClass
|
||||
while (pluginCursor.name != Any::class.java.name) {
|
||||
methods.addAll(listOf(*pluginCursor.declaredMethods))
|
||||
pluginCursor = pluginCursor.superclass
|
||||
}
|
||||
|
||||
for (method in methods) {
|
||||
if (method.isAnnotationPresent(Command::class.java)) {
|
||||
val command = method.getAnnotation(Command::class.java) ?: continue
|
||||
val methodMeta = CommandData(method, command)
|
||||
commands[method.name] = methodMeta
|
||||
}
|
||||
|
||||
if (method.isAnnotationPresent(ActivityCallback::class.java)) {
|
||||
startActivityCallbackMethods[method.name] = method
|
||||
}
|
||||
|
||||
if (method.isAnnotationPresent(PermissionCallback::class.java)) {
|
||||
permissionCallbackMethods[method.name] = method
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.plugin
|
||||
|
||||
import android.content.res.Configuration
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.webkit.WebView
|
||||
import androidx.activity.result.ActivityResult
|
||||
import androidx.activity.result.ActivityResultLauncher
|
||||
import androidx.activity.result.IntentSenderRequest
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import app.tauri.annotation.InvokeArg
|
||||
import app.tauri.FsUtils
|
||||
import app.tauri.JniMethod
|
||||
import app.tauri.Logger
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect
|
||||
import com.fasterxml.jackson.annotation.PropertyAccessor
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature
|
||||
import com.fasterxml.jackson.databind.JsonNode
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule
|
||||
import java.lang.reflect.InvocationTargetException
|
||||
|
||||
object PluginManager {
|
||||
fun interface RequestPermissionsCallback {
|
||||
fun onResult(permissions: Map<String, Boolean>)
|
||||
}
|
||||
|
||||
fun interface ActivityResultCallback {
|
||||
fun onResult(result: ActivityResult)
|
||||
}
|
||||
|
||||
/** The result launchers belonging to one activity. */
|
||||
private class ResultLaunchers(
|
||||
val startActivityForResult: ActivityResultLauncher<Intent>,
|
||||
val startIntentSenderForResult: ActivityResultLauncher<IntentSenderRequest>,
|
||||
val requestPermissions: ActivityResultLauncher<Array<String>>
|
||||
)
|
||||
|
||||
// Insertion ordered, so the activity taken over when the current one goes away is the oldest
|
||||
// surviving one rather than an arbitrary member of a hash set.
|
||||
private val launchers: LinkedHashMap<AppCompatActivity, ResultLaunchers> = LinkedHashMap()
|
||||
var activity: AppCompatActivity? = null
|
||||
private val plugins: HashMap<String, PluginHandle> = HashMap()
|
||||
private var requestPermissionsCallback: RequestPermissionsCallback? = null
|
||||
private var startActivityForResultCallback: ActivityResultCallback? = null
|
||||
private var startIntentSenderForResultCallback: ActivityResultCallback? = null
|
||||
private var jsonMapper: ObjectMapper = ObjectMapper()
|
||||
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
|
||||
.enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)
|
||||
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
|
||||
|
||||
init {
|
||||
val channelDeserializer = ChannelDeserializer({ channelId, payload ->
|
||||
sendChannelData(channelId, payload)
|
||||
}, jsonMapper)
|
||||
jsonMapper
|
||||
.registerModule(SimpleModule().addDeserializer(Channel::class.java, channelDeserializer))
|
||||
// Without it, the mapper's field visibility serializes an org.json value through
|
||||
// its private fields: a `JSArray` as `{"values":[...]}` and a `JSObject` as
|
||||
// `{"nameValuePairs":{...}}`.
|
||||
.registerModule(JsonOrgModule())
|
||||
}
|
||||
|
||||
fun onCreate(activity: AppCompatActivity) {
|
||||
// Every activity gets its own launchers, and gets them here: registerForActivityResult must
|
||||
// be called before its owner reaches STARTED, so an activity that is already running can
|
||||
// never be given launchers later.
|
||||
launchers[activity] = registerResultLaunchers(activity)
|
||||
if (this.activity == null) {
|
||||
this.activity = activity
|
||||
}
|
||||
}
|
||||
|
||||
private fun registerResultLaunchers(activity: AppCompatActivity): ResultLaunchers =
|
||||
ResultLaunchers(
|
||||
activity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()
|
||||
) { result ->
|
||||
startActivityForResultCallback?.onResult(result)
|
||||
},
|
||||
|
||||
activity.registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()
|
||||
) { result ->
|
||||
startIntentSenderForResultCallback?.onResult(result)
|
||||
},
|
||||
|
||||
activity.registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()
|
||||
) { result ->
|
||||
requestPermissionsCallback?.onResult(result)
|
||||
}
|
||||
)
|
||||
|
||||
private val currentLaunchers: ResultLaunchers
|
||||
get() = launchers[activity]
|
||||
?: throw IllegalStateException("the plugin manager has no activity to launch from")
|
||||
|
||||
fun onNewIntent(intent: Intent) {
|
||||
for (plugin in plugins.values) {
|
||||
plugin.instance.onNewIntent(intent)
|
||||
}
|
||||
}
|
||||
|
||||
fun onPause(activity: AppCompatActivity) {
|
||||
for (plugin in plugins.values) {
|
||||
plugin.instance.triggerOnPause(activity)
|
||||
}
|
||||
}
|
||||
|
||||
fun onResume(activity: AppCompatActivity) {
|
||||
for (plugin in plugins.values) {
|
||||
plugin.instance.triggerOnResume(activity)
|
||||
}
|
||||
}
|
||||
|
||||
fun onRestart(activity: AppCompatActivity) {
|
||||
for (plugin in plugins.values) {
|
||||
plugin.instance.triggerOnRestart(activity)
|
||||
}
|
||||
}
|
||||
|
||||
fun onStop(activity: AppCompatActivity) {
|
||||
for (plugin in plugins.values) {
|
||||
plugin.instance.triggerOnStop(activity)
|
||||
}
|
||||
}
|
||||
|
||||
fun onDestroy(activity: AppCompatActivity) {
|
||||
for (plugin in plugins.values) {
|
||||
plugin.instance.triggerOnDestroy(activity)
|
||||
}
|
||||
|
||||
launchers.remove(activity)
|
||||
if (this.activity == activity) {
|
||||
// Whatever is left already holds its own launchers, registered when it was created. Moving
|
||||
// this activity's launchers over instead would mean registering against an activity that is
|
||||
// already running, which registerForActivityResult rejects with an IllegalStateException.
|
||||
this.activity = launchers.keys.firstOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
fun onConfigurationChanged(newConfig: Configuration) {
|
||||
for (plugin in plugins.values) {
|
||||
plugin.instance.onConfigurationChanged(newConfig)
|
||||
}
|
||||
}
|
||||
|
||||
fun startActivityForResult(intent: Intent, callback: ActivityResultCallback) {
|
||||
startActivityForResultCallback = callback
|
||||
currentLaunchers.startActivityForResult.launch(intent)
|
||||
}
|
||||
|
||||
fun startIntentSenderForResult(intent: IntentSenderRequest, callback: ActivityResultCallback) {
|
||||
startIntentSenderForResultCallback = callback
|
||||
currentLaunchers.startIntentSenderForResult.launch(intent)
|
||||
}
|
||||
|
||||
fun requestPermissions(
|
||||
permissionStrings: Array<String>,
|
||||
callback: RequestPermissionsCallback
|
||||
) {
|
||||
requestPermissionsCallback = callback
|
||||
currentLaunchers.requestPermissions.launch(permissionStrings)
|
||||
}
|
||||
|
||||
@JniMethod
|
||||
fun onWebViewCreated(webView: WebView) {
|
||||
for ((_, plugin) in plugins) {
|
||||
if (!plugin.loaded) {
|
||||
plugin.load(webView)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@JniMethod
|
||||
fun load(webView: WebView?, name: String, plugin: Plugin, config: String) {
|
||||
val handle = PluginHandle(this, name, plugin, config, jsonMapper)
|
||||
plugins[name] = handle
|
||||
if (webView != null) {
|
||||
plugin.load(webView)
|
||||
}
|
||||
}
|
||||
|
||||
@JniMethod
|
||||
fun runCommand(id: Int, pluginId: String, command: String, data: String) {
|
||||
val successId = 0L
|
||||
val errorId = 1L
|
||||
val invoke = Invoke(id.toLong(), command, successId, errorId, { fn, result ->
|
||||
var success: String? = null
|
||||
var error: String? = null
|
||||
if (fn == successId) {
|
||||
success = result
|
||||
} else {
|
||||
error = result
|
||||
}
|
||||
handlePluginResponse(id, success, error)
|
||||
}, data, jsonMapper)
|
||||
|
||||
dispatchPluginMessage(invoke, pluginId)
|
||||
}
|
||||
|
||||
private fun dispatchPluginMessage(invoke: Invoke, pluginId: String) {
|
||||
Logger.verbose(
|
||||
Logger.tags("Plugin"),
|
||||
"Tauri plugin: pluginId: $pluginId, command: ${invoke.command}"
|
||||
)
|
||||
|
||||
try {
|
||||
val plugin = plugins[pluginId]
|
||||
if (plugin == null) {
|
||||
invoke.reject("Plugin $pluginId not initialized")
|
||||
} else {
|
||||
plugins[pluginId]?.invoke(invoke)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
var exception: Throwable = e
|
||||
if (exception.message?.isEmpty() != false) {
|
||||
if (e is InvocationTargetException) {
|
||||
exception = e.targetException
|
||||
}
|
||||
}
|
||||
invoke.reject(if (exception.message?.isEmpty() != false) { exception.toString() } else { exception.message })
|
||||
}
|
||||
}
|
||||
|
||||
fun<T> loadConfig(context: Context, plugin: String, cls: Class<T>): T {
|
||||
val tauriConfigJson = FsUtils.readAsset(context.assets, "tauri.conf.json")
|
||||
val mapper = ObjectMapper()
|
||||
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
|
||||
val config = mapper.readValue(tauriConfigJson, Config::class.java)
|
||||
return mapper.readValue(config.plugins[plugin].toString(), cls)
|
||||
}
|
||||
|
||||
private external fun handlePluginResponse(id: Int, success: String?, error: String?)
|
||||
private external fun sendChannelData(id: Long, data: String)
|
||||
}
|
||||
|
||||
@InvokeArg
|
||||
internal class Config {
|
||||
lateinit var plugins: Map<String, JsonNode>
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.plugin
|
||||
|
||||
import app.tauri.annotation.Command
|
||||
import java.lang.reflect.Method
|
||||
|
||||
class CommandData(
|
||||
val method: Method, methodDecorator: Command
|
||||
) {
|
||||
|
||||
// The name of the method
|
||||
val name: String = method.name
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.plugin
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import app.tauri.Logger
|
||||
import java.text.DateFormat
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.*
|
||||
|
||||
class PluginResult @JvmOverloads constructor(json: JSObject? = JSObject()) {
|
||||
private val json: JSObject
|
||||
|
||||
init {
|
||||
this.json = json ?: JSObject()
|
||||
}
|
||||
|
||||
fun put(name: String, value: Boolean): PluginResult {
|
||||
return jsonPut(name, value)
|
||||
}
|
||||
|
||||
fun put(name: String, value: Double): PluginResult {
|
||||
return jsonPut(name, value)
|
||||
}
|
||||
|
||||
fun put(name: String, value: Int): PluginResult {
|
||||
return jsonPut(name, value)
|
||||
}
|
||||
|
||||
fun put(name: String, value: Long): PluginResult {
|
||||
return jsonPut(name, value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a date as an ISO string
|
||||
*/
|
||||
@SuppressLint("SimpleDateFormat")
|
||||
fun put(name: String, value: Date): PluginResult {
|
||||
val tz: TimeZone = TimeZone.getTimeZone("UTC")
|
||||
val df: DateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'")
|
||||
df.timeZone = tz
|
||||
return jsonPut(name, df.format(value))
|
||||
}
|
||||
|
||||
fun put(name: String, value: Any?): PluginResult {
|
||||
return jsonPut(name, value)
|
||||
}
|
||||
|
||||
fun put(name: String, value: PluginResult): PluginResult {
|
||||
return jsonPut(name, value.json)
|
||||
}
|
||||
|
||||
private fun jsonPut(name: String, value: Any?): PluginResult {
|
||||
try {
|
||||
json.put(name, value)
|
||||
} catch (ex: Exception) {
|
||||
Logger.error(Logger.tags("Plugin"), "", ex)
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
override fun toString(): String {
|
||||
return json.toString()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
import org.junit.Assert.*
|
||||
|
||||
/**
|
||||
* Example local unit test, which will execute on the development machine (host).
|
||||
*
|
||||
* See [testing documentation](http://d.android.com/tools/testing).
|
||||
*/
|
||||
class ExampleUnitTest {
|
||||
@Test
|
||||
fun addition_isCorrect() {
|
||||
assertEquals(4, 2 + 2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "fr.gastinel.connect.wireguard"
|
||||
compileSdk = 36
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 24
|
||||
consumerProguardFiles("consumer-rules.pro")
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro"
|
||||
)
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = "17"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("androidx.core:core-ktx:1.13.1")
|
||||
implementation("androidx.appcompat:appcompat:1.7.1")
|
||||
implementation(project(":tauri-android"))
|
||||
|
||||
// Composant officiel WireGuard Android (Apache-2.0, Jason A. Donenfeld / WireGuard LLC)
|
||||
implementation("com.wireguard.android:tunnel:1.0.20260102")
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# Proguard rules for tauri-plugin-wireguard
|
||||
-keep class com.wireguard.** { *; }
|
||||
-keep class fr.gastinel.connect.wireguard.** { *; }
|
||||
@@ -0,0 +1,3 @@
|
||||
# Proguard rules for tauri-plugin-wireguard
|
||||
-keep class com.wireguard.** { *; }
|
||||
-keep class fr.gastinel.connect.wireguard.** { *; }
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<application>
|
||||
<!-- VpnService interne requis par GoBackend (WireGuard Android) -->
|
||||
<service
|
||||
android:name="com.wireguard.android.backend.GoBackend$VpnService"
|
||||
android:exported="false"
|
||||
android:permission="android.permission.BIND_VPN_SERVICE">
|
||||
<intent-filter>
|
||||
<action android:name="android.net.VpnService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -0,0 +1,168 @@
|
||||
package fr.gastinel.connect.wireguard
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import androidx.activity.result.ActivityResult
|
||||
import app.tauri.annotation.ActivityCallback
|
||||
import app.tauri.annotation.Command
|
||||
import app.tauri.annotation.InvokeArg
|
||||
import app.tauri.annotation.TauriPlugin
|
||||
import app.tauri.plugin.Invoke
|
||||
import app.tauri.plugin.JSObject
|
||||
import app.tauri.plugin.Plugin
|
||||
import com.wireguard.android.backend.Backend
|
||||
import com.wireguard.android.backend.GoBackend
|
||||
import com.wireguard.android.backend.Statistics
|
||||
import com.wireguard.android.backend.Tunnel
|
||||
import com.wireguard.config.Config
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
@InvokeArg
|
||||
class ConnectArgs {
|
||||
var config: String = ""
|
||||
}
|
||||
|
||||
@TauriPlugin
|
||||
class WireGuardPlugin(private val activity: Activity) : Plugin(activity) {
|
||||
|
||||
private val backend: Backend by lazy { GoBackend(activity.applicationContext) }
|
||||
private val executor = Executors.newSingleThreadExecutor()
|
||||
|
||||
@Volatile
|
||||
private var pendingConfig: Config? = null
|
||||
|
||||
private val tunnel = object : Tunnel {
|
||||
@Volatile
|
||||
var state: Tunnel.State = Tunnel.State.DOWN
|
||||
|
||||
override fun getName(): String = "gastinel-connect"
|
||||
|
||||
override fun onStateChange(newState: Tunnel.State) {
|
||||
state = newState
|
||||
}
|
||||
}
|
||||
|
||||
@Command
|
||||
fun connect(invoke: Invoke) {
|
||||
val args = invoke.parseArgs(ConnectArgs::class.java)
|
||||
val configText = args.config
|
||||
if (configText.isBlank()) {
|
||||
invoke.reject("Configuration WireGuard vide.")
|
||||
return
|
||||
}
|
||||
|
||||
val config: Config
|
||||
try {
|
||||
val stream = ByteArrayInputStream(configText.toByteArray(StandardCharsets.UTF_8))
|
||||
config = Config.parse(stream)
|
||||
} catch (e: Exception) {
|
||||
invoke.reject("Erreur de parsing de la configuration : ${e.message}")
|
||||
return
|
||||
}
|
||||
|
||||
pendingConfig = config
|
||||
|
||||
// Vérification de la permission Android VpnService
|
||||
val prepareIntent = GoBackend.VpnService.prepare(activity)
|
||||
if (prepareIntent != null) {
|
||||
startActivityForResult(invoke, prepareIntent, "onVpnPermissionResult")
|
||||
return
|
||||
}
|
||||
|
||||
startTunnel(invoke, config)
|
||||
}
|
||||
|
||||
@ActivityCallback
|
||||
fun onVpnPermissionResult(invoke: Invoke, result: ActivityResult) {
|
||||
if (result.resultCode == Activity.RESULT_OK) {
|
||||
val config = pendingConfig
|
||||
if (config != null) {
|
||||
startTunnel(invoke, config)
|
||||
} else {
|
||||
invoke.reject("Configuration introuvable après autorisation.")
|
||||
}
|
||||
} else {
|
||||
invoke.reject("Autorisation VPN refusée par l'utilisateur.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun startTunnel(invoke: Invoke, config: Config) {
|
||||
executor.execute {
|
||||
try {
|
||||
backend.setState(tunnel, Tunnel.State.UP, config)
|
||||
val ret = JSObject()
|
||||
ret.put("status", "UP")
|
||||
invoke.resolve(ret)
|
||||
} catch (e: Exception) {
|
||||
invoke.reject("Échec de l'activation du tunnel : ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Command
|
||||
fun disconnect(invoke: Invoke) {
|
||||
executor.execute {
|
||||
try {
|
||||
backend.setState(tunnel, Tunnel.State.DOWN, null)
|
||||
val ret = JSObject()
|
||||
ret.put("status", "DOWN")
|
||||
invoke.resolve(ret)
|
||||
} catch (e: Exception) {
|
||||
invoke.reject("Échec de la fermeture du tunnel : ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Command
|
||||
fun getStatus(invoke: Invoke) {
|
||||
executor.execute {
|
||||
try {
|
||||
val state = backend.getState(tunnel)
|
||||
val ret = JSObject()
|
||||
val isUp = (state == Tunnel.State.UP)
|
||||
ret.put("state", if (isUp) "UP" else "DOWN")
|
||||
|
||||
var rxBytes: Long = 0
|
||||
var txBytes: Long = 0
|
||||
var latestHandshakeSec: Long = 0
|
||||
|
||||
if (isUp) {
|
||||
try {
|
||||
val stats: Statistics = backend.getStatistics(tunnel)
|
||||
rxBytes = stats.totalRx()
|
||||
txBytes = stats.totalTx()
|
||||
|
||||
for (key in stats.peers()) {
|
||||
val peerStat = stats.peer(key)
|
||||
if (peerStat != null) {
|
||||
val hsMillis = peerStat.latestHandshakeEpochMillis()
|
||||
val hsSec = hsMillis / 1000
|
||||
if (hsSec > latestHandshakeSec) {
|
||||
latestHandshakeSec = hsSec
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// Statistiques non disponibles pour l'instant
|
||||
}
|
||||
}
|
||||
|
||||
ret.put("rx_bytes", rxBytes)
|
||||
ret.put("tx_bytes", txBytes)
|
||||
ret.put("last_handshake", latestHandshakeSec)
|
||||
|
||||
invoke.resolve(ret)
|
||||
} catch (e: Exception) {
|
||||
val fallback = JSObject()
|
||||
fallback.put("state", "DOWN")
|
||||
fallback.put("rx_bytes", 0)
|
||||
fallback.put("tx_bytes", 0)
|
||||
fallback.put("last_handshake", 0)
|
||||
fallback.put("error", e.message ?: "Erreur inconnue")
|
||||
invoke.resolve(fallback)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
const COMMANDS: &[&str] = &[];
|
||||
|
||||
fn main() {
|
||||
tauri_plugin::Builder::new(COMMANDS)
|
||||
.android_path("android")
|
||||
.build();
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//! Module d'intégration WireGuard pour Gastinel Connect.
|
||||
//!
|
||||
//! Sur Android, ce greffon s'appuie sur le composant officiel `com.wireguard.android:tunnel`
|
||||
//! et sur l'API Android `VpnService` via un pont Kotlin minimal.
|
||||
//! Sur les cibles de test hors-Android (desktop), il fournit un bouchon sûr
|
||||
//! pour permettre la compilation et les tests unitaires.
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
use std::sync::OnceLock;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::plugin::{Builder, TauriPlugin};
|
||||
use tauri::Wry;
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
const PLUGIN_IDENTIFIER: &str = "fr.gastinel.connect.wireguard";
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
static GREFFON: OnceLock<tauri::plugin::PluginHandle<Wry>> = OnceLock::new();
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, Serialize, Deserialize)]
|
||||
pub enum VpnError {
|
||||
#[error("Le service VPN n'est pas disponible sur cette plateforme.")]
|
||||
Indisponible,
|
||||
#[error("Configuration invalide : {0}")]
|
||||
ConfigInvalide(String),
|
||||
#[error("Erreur VPN : {0}")]
|
||||
Autre(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct VpnStatus {
|
||||
pub state: String,
|
||||
pub rx_bytes: u64,
|
||||
pub tx_bytes: u64,
|
||||
pub last_handshake: u64,
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "android"))]
|
||||
static MOCK_STATE: std::sync::RwLock<Option<VpnStatus>> = std::sync::RwLock::new(None);
|
||||
|
||||
pub fn connect(config: &str) -> Result<(), VpnError> {
|
||||
#[cfg(target_os = "android")]
|
||||
{
|
||||
let handle = GREFFON.get().ok_or(VpnError::Indisponible)?;
|
||||
let args = serde_json::json!({ "config": config });
|
||||
handle.run_mobile_plugin::<serde_json::Value>("connect", args)
|
||||
.map_err(|e| VpnError::Autre(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "android"))]
|
||||
{
|
||||
if config.trim().is_empty() {
|
||||
return Err(VpnError::ConfigInvalide("Configuration vide".into()));
|
||||
}
|
||||
let mut st = MOCK_STATE.write().map_err(|e| VpnError::Autre(e.to_string()))?;
|
||||
*st = Some(VpnStatus {
|
||||
state: "UP".to_string(),
|
||||
rx_bytes: 1420,
|
||||
tx_bytes: 1420,
|
||||
last_handshake: 1,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn disconnect() -> Result<(), VpnError> {
|
||||
#[cfg(target_os = "android")]
|
||||
{
|
||||
let handle = GREFFON.get().ok_or(VpnError::Indisponible)?;
|
||||
let args = serde_json::json!({});
|
||||
handle.run_mobile_plugin::<serde_json::Value>("disconnect", args)
|
||||
.map_err(|e| VpnError::Autre(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "android"))]
|
||||
{
|
||||
let mut st = MOCK_STATE.write().map_err(|e| VpnError::Autre(e.to_string()))?;
|
||||
*st = Some(VpnStatus {
|
||||
state: "DOWN".to_string(),
|
||||
rx_bytes: 0,
|
||||
tx_bytes: 0,
|
||||
last_handshake: 0,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_status() -> Result<VpnStatus, VpnError> {
|
||||
#[cfg(target_os = "android")]
|
||||
{
|
||||
let handle = GREFFON.get().ok_or(VpnError::Indisponible)?;
|
||||
let args = serde_json::json!({});
|
||||
let res = handle.run_mobile_plugin::<serde_json::Value>("getStatus", args)
|
||||
.map_err(|e| VpnError::Autre(e.to_string()))?;
|
||||
|
||||
let state = res.get("state").and_then(|v| v.as_str()).unwrap_or("DOWN").to_string();
|
||||
let rx_bytes = res.get("rx_bytes").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let tx_bytes = res.get("tx_bytes").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let last_handshake = res.get("last_handshake").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
|
||||
Ok(VpnStatus {
|
||||
state,
|
||||
rx_bytes,
|
||||
tx_bytes,
|
||||
last_handshake,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "android"))]
|
||||
{
|
||||
let st = MOCK_STATE.read().map_err(|e| VpnError::Autre(e.to_string()))?;
|
||||
Ok(st.clone().unwrap_or_default())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init() -> TauriPlugin<Wry> {
|
||||
Builder::new("wireguard")
|
||||
.setup(|_app, _api| {
|
||||
#[cfg(target_os = "android")]
|
||||
{
|
||||
let handle = _api.register_android_plugin(PLUGIN_IDENTIFIER, "WireGuardPlugin")?;
|
||||
let _ = GREFFON.set(handle);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.build()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_mock_vpn_cycle() {
|
||||
let _ = disconnect();
|
||||
let s1 = get_status().unwrap();
|
||||
assert_eq!(s1.state, "DOWN");
|
||||
|
||||
assert!(connect("").is_err());
|
||||
assert!(connect("[Interface]\nPrivateKey=test\n").is_ok());
|
||||
|
||||
let s2 = get_status().unwrap();
|
||||
assert_eq!(s2.state, "UP");
|
||||
|
||||
assert!(disconnect().is_ok());
|
||||
let s3 = get_status().unwrap();
|
||||
assert_eq!(s3.state, "DOWN");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//! Gastinel Connect — Cœur de l'application cliente VPN.
|
||||
//!
|
||||
//! Gère l'orchestration des tunnels WireGuard, la communication avec
|
||||
//! le greffon Android et l'interface utilisateur.
|
||||
|
||||
use tauri_plugin_wireguard::VpnStatus;
|
||||
|
||||
// Configuration locale de test (sous-réseau 10.250.0.0/24, clés générées localement)
|
||||
// Endpoint par défaut : 10.0.2.2:51821 (boucle hôte vue depuis l'émulateur Android)
|
||||
const TEST_CONFIG_ANDROID: &str = r#"[Interface]
|
||||
PrivateKey = wBl9MAXjC+dtMhrGcFbKg2e9CxNB5UgJbaZnwq+P7Fo=
|
||||
Address = 10.250.0.2/24
|
||||
|
||||
[Peer]
|
||||
PublicKey = yFELe9lAqR5CVSydtRpUt+K9tmJd77xIdsteDZJ7uE4=
|
||||
Endpoint = 10.0.2.2:51821
|
||||
AllowedIPs = 10.250.0.0/24
|
||||
PersistentKeepalive = 5
|
||||
"#;
|
||||
|
||||
#[tauri::command]
|
||||
fn get_status() -> Result<VpnStatus, String> {
|
||||
tauri_plugin_wireguard::get_status().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn connect_vpn() -> Result<(), String> {
|
||||
tauri_plugin_wireguard::connect(TEST_CONFIG_ANDROID).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn disconnect_vpn() -> Result<(), String> {
|
||||
tauri_plugin_wireguard::disconnect().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_wireguard::init())
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
get_status,
|
||||
connect_vpn,
|
||||
disconnect_vpn
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("Erreur lors de l'exécution de Gastinel Connect");
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
gastinel_connect_lib::run();
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Gastinel Connect",
|
||||
"version": "0.1.0",
|
||||
"identifier": "fr.gastinel.connect",
|
||||
"build": {
|
||||
"frontendDist": "../src"
|
||||
},
|
||||
"app": {
|
||||
"withGlobalTauri": true,
|
||||
"windows": [
|
||||
{
|
||||
"label": "main",
|
||||
"title": "Gastinel Connect",
|
||||
"width": 420,
|
||||
"height": 650,
|
||||
"resizable": true,
|
||||
"center": true
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; connect-src 'self' ipc: http://ipc.localhost"
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": ["nsis"],
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.ico"
|
||||
]
|
||||
}
|
||||
}
|
||||