diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c3c97fe --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +*.iml +.gradle +**/build-publish-maven.gradle +**/build-documentation.gradle +**/build-publish-native.gradle +/local.properties +.idea +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties +/doc-generator \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e65fd45 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Simplito + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..6047ff1 --- /dev/null +++ b/README.md @@ -0,0 +1,109 @@ +# PrivMX Endpoint Java + +This repository provides a Java wrappers for the native C++ library used by PrivMX to handle +end-to-end (e2e) encryption. PrivMX is a privacy-focused platform designed to offer secure +collaboration solutions by integrating robust encryption across various data types and communication +methods. This project enables seamless integration of PrivMX’s encryption functionalities in +Java/Kotlin +applications, preserving the security and performance of the original C++ library while making its +capabilities accessible in the JVM ecosystem. + +## About PrivMX + +[PrivMX](https://privmx.dev) allows developers to build end-to-end encrypted apps used for +communication. The Platform works according to privacy-by-design mindset, so all of our solutions +are based on Zero-Knowledge architecture. This project extends PrivMX’s commitment to security by +making its encryption features accessible to developers using Java/Kotlin. + +### Key Features + +- End-to-End Encryption: Ensures that data is encrypted at the source and can only be decrypted by + the intended recipient. +- Native C++ Library Integration: Leverages the performance and security of C++ while making it + accessible in Java/Kotlin applications. +- Cross-Platform Compatibility: Designed to support PrivMX on multiple operating systems and + environments. +- Simple API: Easy-to-use interface for Java/Kotlin developers without compromising security. + +## Modules + +### 1. PrivMX Endpoint Java Extra + +PrivMX Endpoint Java Extra is the fundamental **recommended library** for utilizing the platform in +the majority of cases. +It encompasses all the essential logic that simplifies and secures the usage of our libraries. +It can be utilized on Java Virtual Machines (JVM). + +#### This library implements: + +- Enums and static fields to minimize errors while invoking the methods. +- `PrivMXEndpoint` for managing the connection and registering callbacks for any events. +- `PrivMXEndpointContainer` for managing the global session with an implemented event loop. +- Classes to simplify reading and writing to files using byte arrays and InputStream/OutputStream. + +### 2. PrivMX Endpoint Java Android + +PrivMX Endpoint Java Android is an extension of `PrivMX Endpoint Java Extra` with logic specifically +for **Android**. + +#### This library implements: + +- `PrivMXEndpointService` - an Android Service that manages the PrivMX Endpoint Java Extra library + and handles app lifecycle changes. +- `PrivMXEndpointBaseActivity` - an Android Activity that configures and binds to + `PrivMXEndpointService`. + +### 3. PrivMX Endpoint Java + +PrivMX Endpoint Java is the fundamental wrapper library, essential for the Platform’s operational +functionality. It utilizes JNI to declare native functions in Java. +As the most minimalist library available, it provides the highest degree of flexibility in +customizing the Platform to meet your specific requirements. +It is compatible with Java Virtual Machines (JVM). + +This library implements models, exception catching, and the following modules: + +- `CryptoApi` - Cryptographic methods used to encrypt/decrypt and sign your data or generate keys to + work with PrivMX Bridge. +- `Connection` - Methods for managing connection with PrivMX Bridge. +- `ThreadApi` - Methods for managing Threads and sending/reading messages. +- `StoreApi` - Methods for managing Stores and sending/reading files. +- `InboxApi` - Methods for managing Inboxes and entries. + +## Usage + +1. Add `mavenCentral()` repository to your `settings.gradle`: + +```groovy +dependencyResolutionManagement { + repositories { + mavenCentral() + } +} +``` + +2. Add dependency to `build.gradle`: + +```groovy +dependencies { + def privmxLibVersion = "2.0" // privmx-endpoint version + implementation("com.simplito.java:privmx-endpoint-extra:$privmxLibVersion") + //implementation("com.simplito.java:privmx-endpoint:$privmxLibVersion") //for base Java library + //implementation("com.simplito.java:privmx-endpoint-android:$privmxLibVersion") //for Android Java library +} +``` + +\ +For more details on PrivMX Platform, including setup guides and API reference, +visit [PrivMX documentation](https://docs.privmx.dev). + +## License information + +**PrivMX Endpoint Java**\ +Copyright © 2024 Simplito sp. z o.o. + +This project is part of the PrivMX Platform (https://privmx.dev). \ +This project is Licensed under the MIT License. + +PrivMX Endpoint and PrivMX Bridge are licensed under Licensed under the PrivMX Free License.\ +See the License for the specific language governing permissions and limitations under the License. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..d2346d3 --- /dev/null +++ b/build.gradle @@ -0,0 +1,14 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath 'com.guardsquare:proguard-gradle:7.1.0' + } +} + +plugins { +alias(libs.plugins.androidLibrary) apply false +} + diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..530cd48 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,21 @@ +# 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=-Xmx4098m -Dfile.encoding=UTF-8 +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. For more details, visit +# https://developer.android.com/r/tools/gradle-multi-project-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 +# 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 \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..524e195 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,15 @@ +[versions] +agp = "8.3.0" +junit = "4.13.2" +junitVersion = "1.1.5" +espressoCore = "3.5.1" +appcompat = "1.6.1" + +[libraries] +junit = { group = "junit", name = "junit", version.ref = "junit" } +ext-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" } +espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" } +appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" } + +[plugins] +androidLibrary = { id = "com.android.library", version.ref = "agp" } \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e708b1c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a674795 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Thu Dec 07 13:20:30 CET 2023 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..4f906e0 --- /dev/null +++ b/gradlew @@ -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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -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 diff --git a/privmx-endpoint-android/.gitignore b/privmx-endpoint-android/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/privmx-endpoint-android/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/privmx-endpoint-android/build.gradle b/privmx-endpoint-android/build.gradle new file mode 100644 index 0000000..d8e4a90 --- /dev/null +++ b/privmx-endpoint-android/build.gradle @@ -0,0 +1,81 @@ +plugins { + alias(libs.plugins.androidLibrary) + id 'maven-publish' + id 'signing' +} + +//Apply script for generating official documentation +if (file("build-documentation.gradle").exists()) { + apply from: "build-documentation.gradle" +} + +//Apply script for publishing maven dependency +if (file("build-publish-maven.gradle").exists()) { + apply from: "build-publish-maven.gradle" +} + +version="2.0" + +android { + namespace 'com.simplito.android.privmx_endpoint_wrapper' + compileSdk 34 + + defaultConfig { + minSdk 24 + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + consumerProguardFiles "consumer-rules.pro" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + publishing { + singleVariant('release') { + withSourcesJar() + withJavadocJar() + } + } +} + +dependencies { + api libs.appcompat + testImplementation libs.junit + androidTestImplementation libs.ext.junit + androidTestImplementation libs.espresso.core + api project(":privmx-endpoint-extra") +} + +sourceSets { + main { + java { + srcDirs = ["src/main/java"] + } + } +} +afterEvaluate { + sourceReleaseJar { + System.out.println("hello world") + filter(new Transformer() { + @Override + String transform(String s) { + if ( + s.trim().matches("\\* *@group.*") || + s.trim().matches("\\* *@folder.*") || + s.trim().matches("\\* *@category.*") + ) { + return null + } + return s + } + }) + } +} \ No newline at end of file diff --git a/privmx-endpoint-android/consumer-rules.pro b/privmx-endpoint-android/consumer-rules.pro new file mode 100644 index 0000000..e69de29 diff --git a/privmx-endpoint-android/proguard-rules.pro b/privmx-endpoint-android/proguard-rules.pro new file mode 100644 index 0000000..05a0d37 --- /dev/null +++ b/privmx-endpoint-android/proguard-rules.pro @@ -0,0 +1,35 @@ +# 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 + +-keepclassmembers class com.simplito.java.privmx_endpoint.modules.** { + ; + ; +} + +-keep class com.simplito.java.privmx_endpoint.model.** { + ; + ; +} + +-keepclasseswithmembernames,includedescriptorclasses class com.simplito.java.privmx_endpoint.* { + native ; +} \ No newline at end of file diff --git a/privmx-endpoint-android/src/androidTest/java/com/simplito/android/privmxendpointwrapper/ExampleInstrumentedTest.java b/privmx-endpoint-android/src/androidTest/java/com/simplito/android/privmxendpointwrapper/ExampleInstrumentedTest.java new file mode 100644 index 0000000..43149f0 --- /dev/null +++ b/privmx-endpoint-android/src/androidTest/java/com/simplito/android/privmxendpointwrapper/ExampleInstrumentedTest.java @@ -0,0 +1,47 @@ +// +// PrivMX Endpoint Java Android +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.cloud). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// +// PrivMX Endpoint Extra +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.cloud). +// This software is Licensed under the MIT Licence. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +package com.simplito.android.privmxendpointwrapper; + +import static org.junit.Assert.assertEquals; + +import android.content.Context; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.platform.app.InstrumentationRegistry; + +import org.junit.Test; +import org.junit.runner.RunWith; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); + assertEquals("com.simplito.android.privmx_endpoint_wrapper.test", appContext.getPackageName()); + } +} \ No newline at end of file diff --git a/privmx-endpoint-android/src/main/AndroidManifest.xml b/privmx-endpoint-android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..6cf7570 --- /dev/null +++ b/privmx-endpoint-android/src/main/AndroidManifest.xml @@ -0,0 +1,10 @@ + + + + + + + \ No newline at end of file diff --git a/privmx-endpoint-android/src/main/java/com/simplito/java/privmx_endpoint_android/activities/PrivmxEndpointBaseActivity.java b/privmx-endpoint-android/src/main/java/com/simplito/java/privmx_endpoint_android/activities/PrivmxEndpointBaseActivity.java new file mode 100644 index 0000000..a790249 --- /dev/null +++ b/privmx-endpoint-android/src/main/java/com/simplito/java/privmx_endpoint_android/activities/PrivmxEndpointBaseActivity.java @@ -0,0 +1,96 @@ +// +// PrivMX Endpoint Java Android. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint_android.activities; + +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.ServiceConnection; +import android.os.IBinder; +import android.util.Log; + +import androidx.appcompat.app.AppCompatActivity; + +import com.simplito.java.privmx_endpoint_android.services.PrivmxEndpointService; +import com.simplito.java.privmx_endpoint_extra.events.EventCallback; +import com.simplito.java.privmx_endpoint_extra.events.EventType; +import com.simplito.java.privmx_endpoint_extra.lib.PrivmxEndpointContainer; +import com.simplito.java.privmx_endpoint_extra.lib.PrivmxEndpoint; + +/** + * Manages {@link PrivmxEndpointService} and active connections. + */ +public abstract class PrivmxEndpointBaseActivity extends AppCompatActivity { + + private static final String TAG = "[PrivmxEndpointBaseActivity]"; + private PrivmxEndpointService privmxEndpointService = null; + + /** + * Container instance for active connections to handle PrivMX Bridge. + */ + protected PrivmxEndpointContainer privmxEndpointContainer = null; + + /** + * Starting and binding to PrivmxEndpointService with passing path to .pem certificate + * returned from {@link #getCertPath()}. + */ + @Override + protected void onStart() { + super.onStart(); + Log.d(TAG,"onStart"); + Intent intent = new Intent(this, PrivmxEndpointService.class); + intent.putExtra(PrivmxEndpointService.CERTS_PATH_EXTRA,getCertPath()); + startService(intent); + bindService(intent, privmxEndpointServiceConnection, Context.BIND_AUTO_CREATE); + } + + /** + * Unregisters all callbacks registered using {@link PrivmxEndpoint#registerCallback(Object, EventType, EventCallback)} + * identified by this instance and unbinds {@link PrivmxEndpointService}. + */ + @Override + protected void onStop() { + super.onStop(); + if (privmxEndpointService != null) { + unbindService(privmxEndpointServiceConnection); + } + } + + /** + * Method called when {@link PrivmxEndpointService} and {@link PrivmxEndpointContainer} + * have been successfully initialized. + * Override this method to safely work with {@link PrivmxEndpointBaseActivity#privmxEndpointContainer}. + */ + protected void onPrivmxEndpointStart() {} + + /** + * Override this method to set the path to your .pem certificate to create secure connection with PrivMX Bridge. + * If the passed path does not contain .pem file, the default PrivMX certificate is installed. + * @return Path to .pem certificate used to initialize {@link PrivmxEndpointService} + */ + protected abstract String getCertPath(); + + private final ServiceConnection privmxEndpointServiceConnection = new ServiceConnection() { + @Override + public void onServiceConnected(ComponentName componentName, IBinder iBinder) { + PrivmxEndpointService.PrivmxEndpointBinder binder = (PrivmxEndpointService.PrivmxEndpointBinder) iBinder; + privmxEndpointService = binder.getService(); + privmxEndpointContainer = privmxEndpointService.getContainer(); + onPrivmxEndpointStart(); + } + + @Override + public void onServiceDisconnected(ComponentName componentName) { + privmxEndpointContainer = null; + } + }; +} diff --git a/privmx-endpoint-android/src/main/java/com/simplito/java/privmx_endpoint_android/services/PrivmxEndpointService.java b/privmx-endpoint-android/src/main/java/com/simplito/java/privmx_endpoint_android/services/PrivmxEndpointService.java new file mode 100644 index 0000000..529e722 --- /dev/null +++ b/privmx-endpoint-android/src/main/java/com/simplito/java/privmx_endpoint_android/services/PrivmxEndpointService.java @@ -0,0 +1,135 @@ +// +// PrivMX Endpoint Java Android. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint_android.services; + +import android.app.Service; +import android.content.Intent; +import android.os.Binder; +import android.os.Bundle; +import android.os.IBinder; +import android.util.Log; + +import com.simplito.java.privmx_endpoint_extra.lib.PrivmxEndpointContainer; + +import java.util.ArrayList; + +/** + * Runs and manages active PrivMX Bridge connections. + */ +public class PrivmxEndpointService extends Service { + private static final String TAG = "[PrivmxEndpointService]"; + private final PrivmxEndpointBinder binder = new PrivmxEndpointBinder(); + private final PrivmxEndpointContainer privmxEndpoint = new PrivmxEndpointContainer(); + + /** + * Defines a key for Intent extras. + */ + public static final String CERTS_PATH_EXTRA = "com.simplito.android.privmx_endpoint_wrapper.services.PrivmxEndpointService.CERTS_PATH_EXTRA"; + + /** + * Implements Service Binder. + */ + public class PrivmxEndpointBinder extends Binder { + private final ArrayList onInit = new ArrayList<>(); + + /** + * @return Instance of PrivMX Endpoint Service + */ + public PrivmxEndpointService getService() { + return PrivmxEndpointService.this; + } + } + + /** + * Sets callback executed when service has been successfully prepared to use. + * @param onInit callback + */ + public void setOnInit(Runnable onInit) { + if (privmxEndpoint.initialized()) { + onInit.run(); + } else { + binder.onInit.add(onInit); + } + } + + /** + * Initializes {@link PrivmxEndpointContainer} with certsPath passed in intent extras. + * If intent does not contain the path, the default value is used. + * @see Service#onBind(Intent) + */ + @Override + public IBinder onBind(Intent intent) { + init(getCertsPath(intent)); + return binder; + } + + /** + * Initialize {@link PrivmxEndpointContainer} with certsPath passed in intent extras. + * If intent does not contain the path, the default value is used. + * @see Service#onStartCommand(Intent, int, int) + */ + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + init(getCertsPath(intent)); + return super.onStartCommand(intent, flags, startId); + } + + /** + * Disconnects active connections if any exist. + * @see Service#onDestroy() + */ + @Override + public void onDestroy() { + try { + privmxEndpoint.disconnectAll(); + privmxEndpoint.close(); + }catch (Exception e){ + System.out.println("Cannot disconnect from server, reason: " + e.getMessage()); + } + super.onDestroy(); + } + + private String getCertsPath(Intent intent) { + String certsPath = getFilesDir() + "/cacert.pem"; + if(intent != null) { + Bundle extras = intent.getExtras(); + if (extras != null) { + certsPath = extras.getString(CERTS_PATH_EXTRA); + } + } + return certsPath; + } + + /** + * Gets {@link PrivmxEndpointContainer}. + * @return Initialized container. If the service does not initialize the container successfully, it returns {@code null} + */ + public PrivmxEndpointContainer getContainer() { + return privmxEndpoint; + } + + private synchronized void init(String certsPath) { + Log.d(TAG, "PrivmxEndpoint init"); + if (privmxEndpoint.initialized()) { + return; + } + try { + privmxEndpoint.setCertsPath(certsPath); + binder.onInit.forEach(Runnable::run); + } catch (Exception e) { + Log.e(TAG, "Cannot initialize lib"); + e.printStackTrace(); + } + } + + +} diff --git a/privmx-endpoint-android/src/test/java/com/simplito/android/privmxendpointwrapper/ExampleUnitTest.java b/privmx-endpoint-android/src/test/java/com/simplito/android/privmxendpointwrapper/ExampleUnitTest.java new file mode 100644 index 0000000..4f408bc --- /dev/null +++ b/privmx-endpoint-android/src/test/java/com/simplito/android/privmxendpointwrapper/ExampleUnitTest.java @@ -0,0 +1,28 @@ +// +// PrivMX Endpoint Java Android +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.cloud). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.android.privmxendpointwrapper; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +/** + * Example local unit test, which will execute on the development machine (host). + * + * @see Testing documentation + */ +public class ExampleUnitTest { + @Test + public void addition_isCorrect() { + assertEquals(4, 2 + 2); + } +} \ No newline at end of file diff --git a/privmx-endpoint-extra/.gitignore b/privmx-endpoint-extra/.gitignore new file mode 100644 index 0000000..f9a921e --- /dev/null +++ b/privmx-endpoint-extra/.gitignore @@ -0,0 +1,3 @@ +/build +/src/main/cpp/build +/src/main/cpp/.cxx \ No newline at end of file diff --git a/privmx-endpoint-extra/build.gradle b/privmx-endpoint-extra/build.gradle new file mode 100644 index 0000000..d3edccb --- /dev/null +++ b/privmx-endpoint-extra/build.gradle @@ -0,0 +1,51 @@ +plugins { + id 'java-library' + id 'signing' + id 'maven-publish' +} + +//Apply script for generating official documentation +if (file("build-documentation.gradle").exists()) { + apply from: "build-documentation.gradle" +} + +//Apply script for publishing maven dependency +if (file("build-publish-maven.gradle").exists()) { + apply from: "build-publish-maven.gradle" +} + +version = '2.0' + +java { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + withSourcesJar() + withJavadocJar() +} + +dependencies { + testImplementation libs.junit + api project(':privmx-endpoint') +} + +javadoc { + options.tags += ["category:xt:\"Category group\""] +} + +//Removing tag @group from sources +sourcesJar { + archiveVersion.set(project.version) + filter(new Transformer() { + @Override + String transform(String s) { + if ( + s.trim().matches("\\* *@group.*") || + s.trim().matches("\\* *@folder.*") || + s.trim().matches("\\* *@category.*") + ) { + return null + } + return s + } + }) +} \ No newline at end of file diff --git a/privmx-endpoint-extra/proguard-rules.pro b/privmx-endpoint-extra/proguard-rules.pro new file mode 100644 index 0000000..f6336c5 --- /dev/null +++ b/privmx-endpoint-extra/proguard-rules.pro @@ -0,0 +1,31 @@ +# 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 + +-keepclassmembers class com.simplito.jvm.privmxendpointwrapper.modules.** { + ; + ; +} + +-keep class com.simplito.jvm.privmxendpointwrapper.model.** { + ; + ; +} \ No newline at end of file diff --git a/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/events/EventCallback.java b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/events/EventCallback.java new file mode 100644 index 0000000..b2ac7b8 --- /dev/null +++ b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/events/EventCallback.java @@ -0,0 +1,28 @@ +// +// PrivMX Endpoint Java Extra. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint_extra.events; + +/** + * Represents a callback for catching events data. + * @param type of the caught event data + * + * @category core + */ +public interface EventCallback { + + /** + * Called to pass data from a caught event. + * @param event caught event data + */ + void call(T event); + +} diff --git a/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/events/EventDispatcher.java b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/events/EventDispatcher.java new file mode 100644 index 0000000..e057248 --- /dev/null +++ b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/events/EventDispatcher.java @@ -0,0 +1,157 @@ +// +// PrivMX Endpoint Java Extra. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint_extra.events; + + +import com.simplito.java.privmx_endpoint.model.Event; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Vector; +import java.util.stream.Collectors; + +/** + * Implements a list of registered event callbacks. + * + * @category core + */ +public class EventDispatcher { + + private final Map> map = new HashMap<>(); + private final EventCallback onRemoveEntryKey; + + /** + * Creates instance of {@code EventDispatcher}. + * + * @param onRemoveEntryKey callback triggered when all events + * from channel entry have been removed + * (it can also unsubscribe from the channel) + */ + public EventDispatcher(EventCallback onRemoveEntryKey) { + this.onRemoveEntryKey = onRemoveEntryKey; + } + + private String getFormattedType(String channel, String type) { + return channel + "_" + type; + } + + /** + * Registers new event callback. + * + * @param channel channel of registered event + * @param type type of registered event + * @param context ID of registered callback + * @param callback block of code to call when the specified event has been caught + * @return {@code true} if the channel is not already subscribed + */ + public boolean register(String channel, String type, Object context, EventCallback callback) { + boolean needSubscribe = channelHasNoCallbacks(channel); + getCallbacks(getFormattedType(channel, type)).add(new Pair(context, callback)); + return needSubscribe; + } + + /** + * Emits specified event. It should only be called by event loops. + * @param type of event data + * @param event event data to emit + */ + public void emit(Event event) { + List callbacks = getCallbacks(getFormattedType(event.channel, event.type)); + for (Pair p : callbacks) { + try { + EventCallback e = (EventCallback) p.callback; + try { + e.call(event.data); + } catch (Exception error) { + error.printStackTrace(); + } + } catch (ClassCastException e) { + System.out.println("Cannot process event: issue with cast event data"); + } + } + } + + private boolean channelHasNoCallbacks(String channel) { + synchronized (map) { + return Optional.ofNullable( + map + .entrySet() + .stream() + .collect( + Collectors.groupingBy( + entry -> entry.getKey().split("_")[0], + Collectors.mapping(Map.Entry::getValue, Collectors.toList()) + ) + ).get(channel) + ).orElse(List.of()) + .stream() + .flatMap(List::stream) + .count() == 0; + } + } + + /** + * Removes all callbacks registered by {@link #register(String, String, Object, EventCallback)}. It's identified by given Context. + * + * @param context callback identifier + */ + public void unbind(Object context) { + synchronized (map) { + map.entrySet() + .stream() + .map(entry -> + Map.entry(entry.getKey().split("_")[0], entry.getValue()) + ) + .filter(entry -> !entry.getValue().isEmpty()) + .forEach(entry -> { + List list = entry.getValue(); + list.removeIf(pair -> pair.context == context); + if (channelHasNoCallbacks(entry.getKey())) { + onRemoveEntryKey.call(entry.getKey()); + } + }); + } + } + + /** + * Removes all callbacks. + */ + public void unbindAll() { + map.keySet() + .stream() + .map(it -> it.split("_")[0]) + .collect(Collectors.toSet()) + .forEach(onRemoveEntryKey::call); + map.clear(); + } + + private List getCallbacks(String type) { + synchronized (map) { + if (!map.containsKey(type)) { + map.put(type, new Vector<>()); + } + return map.get(type); + } + } + + private static class Pair { + private final Object context; + private final EventCallback callback; + + private Pair(Object context, EventCallback callback) { + this.context = context; + this.callback = callback; + } + } +} diff --git a/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/events/EventType.java b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/events/EventType.java new file mode 100644 index 0000000..2e1c131 --- /dev/null +++ b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/events/EventType.java @@ -0,0 +1,293 @@ +// +// PrivMX Endpoint Java Extra. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint_extra.events; + +import com.simplito.java.privmx_endpoint.model.File; +import com.simplito.java.privmx_endpoint.model.Inbox; +import com.simplito.java.privmx_endpoint.model.InboxEntry; +import com.simplito.java.privmx_endpoint.model.Message; +import com.simplito.java.privmx_endpoint.model.Store; +import com.simplito.java.privmx_endpoint.model.Thread; +import com.simplito.java.privmx_endpoint.model.events.InboxDeletedEventData; +import com.simplito.java.privmx_endpoint.model.events.InboxEntryDeletedEventData; +import com.simplito.java.privmx_endpoint.model.events.StoreDeletedEventData; +import com.simplito.java.privmx_endpoint.model.events.StoreFileDeletedEventData; +import com.simplito.java.privmx_endpoint.model.events.StoreStatsChangedEventData; +import com.simplito.java.privmx_endpoint.model.events.ThreadDeletedEventData; +import com.simplito.java.privmx_endpoint.model.events.ThreadDeletedMessageEventData; +import com.simplito.java.privmx_endpoint.model.events.ThreadStatsEventData; +import com.simplito.java.privmx_endpoint_extra.lib.PrivmxEndpoint; + +/** + * Defines the structure to register PrivMX Bridge event callbacks using {@link PrivmxEndpoint#registerCallback(Object, EventType, EventCallback)}. + * + * @param the type of data contained in the Event. + * @category core + */ +public class EventType{ + /** + * Channel of this event type. + */ + public final String channel; + + /** + * This event type as a string. + */ + public final String eventType; + + /** + * Type of event data. + */ + public final Class eventResultClass; + + + private EventType(String channel, String eventType, Class eventClass) { + this.channel = channel; + this.eventType = eventType; + eventResultClass = eventClass; + } + + /** + * Predefined event type that captures successful platform connection events. + */ + public static EventType ConnectedEvent = new EventType<>( + "", + "libConnected", + Void.class + ); + + /** + * Predefined event type to catch special events. + * This type could be used to emit/handle events with custom implementations (e.g. to break event loops). + */ + public static EventType LibBreakEvent = new EventType<>( + "", + "libBreak", + Void.class + ); + + /** + * Predefined event type to catch disconnection events. + */ + public static EventType DisconnectedEvent = new EventType<>( + "", + "libDisconnected", + Void.class + ); + + /** + * Predefined event type to catch created Thread events. + */ + public static EventType ThreadCreatedEvent = new EventType<>( + "thread", + "threadCreated", + Thread.class + ); + + /** + * Predefined event type to catch updated Thread events. + */ + public static EventType ThreadUpdatedEvent = new EventType<>( + "thread", + "threadUpdated", + Thread.class + ); + + /** + * Predefined event type to catch updated Thread stats events. + */ + public static EventType ThreadStatsChangedEvent = new EventType<>( + "thread", + "threadStats", + ThreadStatsEventData.class + ); + + /** + * Predefined event type to catch deleted Thread events. + */ + public static EventType ThreadDeletedEvent = new EventType<>( + "thread", + "threadDeleted", + ThreadDeletedEventData.class + ); + /** + * Predefined event type to catch created Store events. + */ + public static EventType StoreCreatedEvent = new EventType<>( + "store", + "storeCreated", + Store.class + ); + /** + * Predefined event type to catch updated Store events. + */ + public static EventType StoreUpdatedEvent = new EventType<>( + "store", + "storeUpdated", + Store.class + ); + /** + * Predefined event type to catch updated Store stats events. + */ + public static EventType StoreStatsChangedEvent = new EventType<>( + "store", + "storeStatsChanged", + StoreStatsChangedEventData.class + ); + /** + * Predefined event type to catch deleted Store stats events. + */ + public static EventType StoreDeletedEvent = new EventType<>( + "store", + "storeDeleted", + StoreDeletedEventData.class + ); + + /** + * Returns instance to register on new message Events. + * @param threadId ID of the Thread to observe + * @return Predefined event type to catch new messages in matching Thread events + */ + public static EventType ThreadNewMessageEvent(String threadId) throws NullPointerException { + if (threadId == null) throw new NullPointerException("Thread id cannot be null"); + return new EventType<>( + "thread/" + threadId + "/messages", + "threadNewMessage", + Message.class + ); + } + + /** + * Returns instance to register on message update Events. + * @param threadId ID of the Thread to observe + * @return predefined event type to catch message updates in matching Thread events + */ + public static EventType ThreadMessageUpdatedEvent(String threadId) throws NullPointerException { + if (threadId == null) throw new NullPointerException("Thread id cannot be null"); + return new EventType<>( + "thread/" + threadId + "/messages", + "threadUpdatedMessage", + Message.class + ); + } + + /** + * Returns instance to register on deleted message Events. + * @param threadId ID of the Thread to observe + * @return Predefined event type to catch deleted messages in matching Thread events + */ + public static EventType ThreadMessageDeletedEvent(String threadId) throws NullPointerException { + if (threadId == null) throw new NullPointerException("Thread id cannot be null"); + return new EventType<>( + "thread/" + threadId + "/messages", + "threadMessageDeleted", + ThreadDeletedMessageEventData.class + ); + } + + /** + * Returns instance to register on created file Events. + * @param storeId ID of the store to observe + * @return Predefined event type to catch new files in matching Store events + */ + public static EventType StoreFileCreatedEvent(String storeId) throws NullPointerException { + if (storeId == null) throw new NullPointerException("Store id cannot be null"); + return new EventType<>( + "store/" + storeId + "/files", + "storeFileCreated", + File.class + ); + } + + /** + * Returns instance to register on file update Events. + * @param storeId ID of the Store to observe + * @return Predefined event type to catch updated files in matching Store events + */ + public static EventType StoreFileUpdatedEvent(String storeId) throws NullPointerException { + if (storeId == null) throw new NullPointerException("Store id cannot be null"); + return new EventType<>( + "store/" + storeId + "/files", + "storeFileUpdated", + File.class + ); + } + + /** + * Returns instance to register on deleted file Events. + * @param storeId ID of the Store to observe + * @return Predefined event type to catch deleted files in matching Store events + */ + public static EventType StoreFileDeletedEvent(String storeId) throws NullPointerException { + if (storeId == null) throw new NullPointerException("Store id cannot be null"); + return new EventType<>( + "store/" + storeId + "/files", + "storeFileDeleted", + StoreFileDeletedEventData.class + ); + } + + /** + * Predefined event type to catch created Inbox events. + */ + public static EventType InboxCreatedEvent = new EventType<>( + "inbox", + "inboxCreated", + Inbox.class + ); + + /** + * Predefined event type to catch update Inbox events. + */ + public static EventType InboxUpdatedEvent = new EventType<>( + "inbox", + "inboxUpdated", + Inbox.class + ); + + /** + * Predefined event type to catch deleted Inbox events. + */ + public static EventType InboxDeletedEvent = new EventType<>( + "inbox", + "inboxDeleted", + InboxDeletedEventData.class + ); + + /** + * Returns instance to register on created entry Events. + * @param inboxId ID of the Inbox to observe + * @return predefined event type to catch created entries in matching Inbox events + */ + public static EventType InboxEntryCreatedEvent(String inboxId) throws NullPointerException { + if (inboxId == null) throw new NullPointerException("Inbox id cannot be null"); + return new EventType<>( + "inbox/" + inboxId + "/entries", + "inboxEntryCreated", + InboxEntry.class + ); + } + + /** + * Returns instance to register on deleting entries Events. + * @param inboxId ID of the Inbox to observe + * @return predefined event type to catch deleted entries in matching Inbox events + */ + public static EventType InboxEntryDeletedEvent(String inboxId) throws NullPointerException { + if (inboxId == null) throw new NullPointerException("Inbox id cannot be null"); + return new EventType<>( + "inbox/" + inboxId + "/entries", + "inboxEntryDeleted", + InboxEntryDeletedEventData.class + ); + } +} diff --git a/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/lib/BasicPrivmxEndpoint.java b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/lib/BasicPrivmxEndpoint.java new file mode 100644 index 0000000..b1fa822 --- /dev/null +++ b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/lib/BasicPrivmxEndpoint.java @@ -0,0 +1,95 @@ +// +// PrivMX Endpoint Java Extra. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint_extra.lib; + +import com.simplito.java.privmx_endpoint.model.exceptions.NativeException; +import com.simplito.java.privmx_endpoint.model.exceptions.PrivmxException; +import com.simplito.java.privmx_endpoint.modules.core.Connection; +import com.simplito.java.privmx_endpoint.modules.crypto.CryptoApi; +import com.simplito.java.privmx_endpoint.modules.inbox.InboxApi; +import com.simplito.java.privmx_endpoint.modules.store.StoreApi; +import com.simplito.java.privmx_endpoint.modules.thread.ThreadApi; +import com.simplito.java.privmx_endpoint_extra.model.Modules; + +import java.util.Set; + +/** + * A collection of all PrivMX Endpoint modules. It represents a single connection to PrivMX Bridge. + * + * @category core + */ +public class BasicPrivmxEndpoint implements AutoCloseable { + + /** + * Reference to Store module. + */ + public final StoreApi storeApi; + + /** + * Reference to Thread module. + */ + public final ThreadApi threadApi; + + /** + * Reference to Inbox module. + */ + public final InboxApi inboxApi; + + /** + * Reference to Connection module. + */ + public final Connection connection; + + + /** + * Initializes modules and connects to PrivMX Bridge server using given parameters. + * + * @param enableModule set of modules to initialize; should contain {@link Modules#THREAD } + * to enable Thread module or {@link Modules#STORE } to enable Store module + * @param platformUrl Platform's Endpoint URL + * @param solutionId {@code SolutionId} of the current project + * @param userPrivateKey user private key used to authorize; generated from: + * {@link CryptoApi#generatePrivateKey} or + * {@link CryptoApi#derivePrivateKey} + * @throws IllegalStateException thrown if there is an exception during init modules + * @throws PrivmxException thrown if there is a problem during login + * @throws NativeException thrown if there is an unknown problem during login + */ + public BasicPrivmxEndpoint( + Set enableModule, + String userPrivateKey, + String solutionId, + String platformUrl + ) throws IllegalStateException, PrivmxException, NativeException { + connection = Connection.platformConnect(userPrivateKey, solutionId, platformUrl); + storeApi = enableModule.contains(Modules.STORE) ? new StoreApi(connection) : null; + threadApi = enableModule.contains(Modules.THREAD) ? new ThreadApi(connection) : null; + inboxApi = enableModule.contains(Modules.INBOX) ? new InboxApi( + connection, + threadApi, + storeApi + ) : null; + } + + /** + * Disconnects from PrivMX Bridge and frees memory. + * + * @throws Exception when instance is currently closed + */ + @Override + public void close() throws Exception { + if (threadApi != null) threadApi.close(); + if (storeApi != null) storeApi.close(); + if (inboxApi != null) inboxApi.close(); + if (connection != null) connection.close(); + } +} diff --git a/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/lib/PrivmxEndpoint.java b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/lib/PrivmxEndpoint.java new file mode 100644 index 0000000..b9a1271 --- /dev/null +++ b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/lib/PrivmxEndpoint.java @@ -0,0 +1,240 @@ +// +// PrivMX Endpoint Java Extra. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint_extra.lib; + +import com.simplito.java.privmx_endpoint.model.Event; +import com.simplito.java.privmx_endpoint.model.exceptions.NativeException; +import com.simplito.java.privmx_endpoint.model.exceptions.PrivmxException; +import com.simplito.java.privmx_endpoint.modules.crypto.CryptoApi; +import com.simplito.java.privmx_endpoint_extra.events.EventCallback; +import com.simplito.java.privmx_endpoint_extra.events.EventDispatcher; +import com.simplito.java.privmx_endpoint_extra.events.EventType; +import com.simplito.java.privmx_endpoint_extra.model.Modules; + +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Extends {@link BasicPrivmxEndpoint} with event callbacks dispatcher. + * + * @category core + */ +public class PrivmxEndpoint extends BasicPrivmxEndpoint implements AutoCloseable { + private final EventCallback onRemoveChannel = (channel) -> { + try { + unsubscribeChannel(channel); + } catch (Exception e) { + System.out.println("Cannot unsubscribe channel"); + } + }; + private final EventDispatcher eventDispatcher = new EventDispatcher(onRemoveChannel); + + /** + * Calls {@link BasicPrivmxEndpoint#BasicPrivmxEndpoint(Set, String, String, String)}. + * + * @param enableModule set of modules to initialize; should contain {@link Modules#THREAD } + * to enable Thread module or {@link Modules#STORE } to enable Store module + * @param platformUrl Platform's Endpoint URL + * @param solutionId {@code SolutionId} of the current project + * @param userPrivateKey user private key used to authorize; generated from: + * {@link CryptoApi#generatePrivateKey} or + * {@link CryptoApi#derivePrivateKey} + * @throws IllegalStateException thrown if there is an exception during init modules + * @throws PrivmxException thrown if there is a problem during login + * @throws NativeException thrown if there is an unknown problem during login + */ + public PrivmxEndpoint( + Set enableModule, + String userPrivateKey, + String solutionId, + String platformUrl + ) throws IllegalStateException, PrivmxException, NativeException { + super(enableModule, userPrivateKey, solutionId, platformUrl); + } + + /** + * Registers callbacks with the specified type. + * @param context an object that identifies callbacks in the list + * @param eventType type of event to listen to + * @param callback a block of code to execute when event was handled + * @param type of data passed to callback + * @throws RuntimeException thrown when method encounters an exception during subscribing on channel. + */ + public final void registerCallback(Object context, EventType eventType, EventCallback callback) throws RuntimeException { + if (eventDispatcher.register(eventType.channel, eventType.eventType, context, callback)) { + try { + subscribeChannel(eventType.channel); + } catch (Exception e) { + throw new RuntimeException("Cannot subscribe event channel for this event (detail message: " + e.getMessage() + ")"); + } + } + } + + /** + * Unregisters all callbacks registered by {@link #registerCallback(Object, EventType, EventCallback)} and identified with given Context. + * @param context an object that identifies callbacks in the list. + */ + public void unregisterCallbacks(Object context) { + eventDispatcher.unbind(context); + } + + /** + * Unregisters all callbacks registered by {@link #registerCallback(Object, EventType, EventCallback)}. + */ + public void unregisterAll() { + eventDispatcher.unbindAll(); + } + + /** + * Handles event and invokes all related callbacks. It should only be called by event loops. + * @param event event to handle + */ + public void handleEvent(Event event) { + eventDispatcher.emit(event); + } + + private void subscribeChannel(String channelStr) { + Channel channel = Channel.fromString(channelStr); + if (channel == null) { + System.out.println("Cannot subscribe on events channel (pattern not found)"); + return; + } + if (channel.module.startsWith("thread") && threadApi != null) { + if (channel.type != null && channel.type.equals("messages")) { + if (channel.instanceId != null) { + threadApi.subscribeForMessageEvents(channel.instanceId); + } else { + System.out.println("No threadId to subscribeChannel: " + channelStr); + } + return; + } + threadApi.subscribeForThreadEvents(); + return; + } + + if (channel.module.startsWith("store") && storeApi != null) { + if (channel.type != null && channel.type.equals("files")) { + if (channel.instanceId != null) { + storeApi.subscribeForFileEvents(channel.instanceId); + } else { + System.out.println("No storeId to subscribeChannel: " + channelStr); + } + return; + } + storeApi.subscribeForStoreEvents(); + return; + } + + if (channel.module.startsWith("inbox") && inboxApi != null) { + if (channel.type != null && channel.type.equals("entries")) { + if (channel.instanceId != null) { + inboxApi.subscribeForEntryEvents(channel.instanceId); + } else { + System.out.println("No inboxId to subscribeChannel: " + channelStr); + } + return; + } + inboxApi.subscribeForInboxEvents(); + return; + } + } + + private void unsubscribeChannel(String channelStr) { + Channel channel = Channel.fromString(channelStr); + if (channel == null) { + System.out.println("Cannot unsubscribe on events channel (pattern not found)"); + return; + } + if (channel.module.startsWith("thread") && threadApi != null) { + if (channel.type != null && channel.type.equals("messages")) { + if (channel.instanceId != null) { + threadApi.unsubscribeFromMessageEvents(channel.instanceId); + } else { + System.out.println("No threadId to unsubscribeChannel: " + channelStr); + } + return; + } + threadApi.unsubscribeFromThreadEvents(); + return; + } + + if (channel.module.startsWith("store") && storeApi != null) { + if (channel.type != null && channel.type.equals("files")) { + if (channel.instanceId != null) { + storeApi.unsubscribeFromFileEvents(channel.instanceId); + } else { + System.out.println("No storeId to unsubscribeChannel: " + channelStr); + } + return; + } + storeApi.unsubscribeFromStoreEvents(); + return; + } + + if (channel.module.startsWith("inbox") && inboxApi != null) { + if (channel.type != null && channel.type.equals("entries")) { + if (channel.instanceId != null) { + inboxApi.unsubscribeFromEntryEvents(channel.instanceId); + } else { + System.out.println("No inboxId to unsubscribeChannel: " + channelStr); + } + return; + } + inboxApi.unsubscribeFromInboxEvents(); + return; + } + } + + private static class Channel { + private final String module; + private final String instanceId; + private final String type; + + private Channel( + String module, + String instanceID, + String type + ) { + this.module = module; + this.instanceId = instanceID; + this.type = type; + } + + private static Channel fromString(String channel) { + Matcher matcher = Pattern + .compile("(?(?:(?!/).)*)(/(?(?:(?!/).)*)/(?(?:(?!/).)*))?") + .matcher(channel); + if (!matcher.find()) { + return null; + } + String module = matcher.group("module"); + String instanceId = matcher.group("instanceId"); + String type = matcher.group("type"); + return new Channel( + module, + instanceId, + type + ); + } + } + + /** + * Disconnects from PrivMX Bridge and frees memory. + * + * @throws Exception when instance is currently closed + */ + @Override + public void close() throws Exception { + super.close(); + } +} diff --git a/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/lib/PrivmxEndpointContainer.java b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/lib/PrivmxEndpointContainer.java new file mode 100644 index 0000000..4873cf2 --- /dev/null +++ b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/lib/PrivmxEndpointContainer.java @@ -0,0 +1,249 @@ +// +// PrivMX Endpoint Java Extra. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint_extra.lib; + +import com.simplito.java.privmx_endpoint.model.Event; +import com.simplito.java.privmx_endpoint.model.exceptions.NativeException; +import com.simplito.java.privmx_endpoint.model.exceptions.PrivmxException; +import com.simplito.java.privmx_endpoint.modules.core.Connection; +import com.simplito.java.privmx_endpoint.modules.core.EventQueue; +import com.simplito.java.privmx_endpoint.modules.crypto.CryptoApi; +import com.simplito.java.privmx_endpoint_extra.events.EventType; +import com.simplito.java.privmx_endpoint_extra.model.Modules; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + + +/** + * Manages certificates, Platform sessions, and active connections. + * Implements event loop that can be started using {@link #startListening()}. + * Contains instance of {@link CryptoApi}. + * + * @category core + */ +public class PrivmxEndpointContainer implements AutoCloseable { + private static final String TAG = "[PrivmxEndpointContainer]"; + private final Map privmxEndpoints = new HashMap<>(); + private boolean isInitialized = false; + + /** + * Instance of {@link CryptoApi}. + */ + public final CryptoApi cryptoApi = new CryptoApi(); + //Event loop + private final ExecutorService eventExecutor = Executors.newSingleThreadExecutor(); + private Future currentTask; + + /** + * Creates instance of {@code PrivmxEndpointContainer}. + */ + public PrivmxEndpointContainer(){} + + /** + * Returns initialization state. + * @return {@code true} if path to certificate is set successfully + */ + public boolean initialized() { + return isInitialized; + } + + private boolean eventLoopStarted = false; + + /** + * Stops event loop. + */ + public void stopListening() { + EventQueue.emitBreakEvent(); + } + + /** + * Returns connection matching given {@code connectionId}. + * @param connectionId Id of connection + * @return Active connection + * @throws IllegalStateException if certificate is not set successfully + */ + public PrivmxEndpoint getEndpoint(Long connectionId) throws IllegalStateException { + if (!isInitialized) { + throw new IllegalStateException(); + } + return privmxEndpoints.get(connectionId); + } + + /** + * Returns set of all active connection's IDs. + * @return set of all active connection's IDs + * @throws IllegalStateException if certificate is not set successfully + */ + public Set getEndpointIDs() throws IllegalStateException { + if (!isInitialized) { + throw new IllegalStateException(); + } + return privmxEndpoints.keySet(); + } + + /** + * Sets path to the certificate used to create a secure connection to PrivMX Bridge. + * It checks whether a .pem file with certificate exists in {@code certsPath} and uses it if it does. + * If it does not, it installs the default PrivMX certificate. + * + * @param certsPath path to file with .pem certificate + * @throws PrivmxException if there is an error while setting {@code certsPath} + * @throws NativeException if there is an unknown error during set {@code certsPath} + */ + public void setCertsPath(String certsPath) throws IllegalArgumentException, PrivmxException, NativeException { + if(!new java.io.File(certsPath).exists()) throw new IllegalArgumentException("Certs file does not exists"); + Connection.setCertsPath(certsPath); + isInitialized = true; + } + + /** + * Creates a new connection. + * + * @param enableModule set of modules to initialize + * @param platformUrl Platform's Endpoint URL + * @param solutionId {@code SolutionId} of the current project + * @param userPrivateKey user private key used to authorize; generated from: + * {@link CryptoApi#generatePrivateKey} or + * {@link CryptoApi#derivePrivateKey} + * @return Created connection + * @throws IllegalStateException when certPath is not set up + * @throws PrivmxException if there is a problem during login + * @throws NativeException if there is an unknown problem during login + */ + public PrivmxEndpoint connect( + Set enableModule, + String userPrivateKey, + String solutionId, + String platformUrl + ) throws IllegalStateException, PrivmxException, NativeException { + if (!isInitialized) throw new IllegalStateException("Certs path is not set"); + PrivmxEndpoint privmxEndpoint = new PrivmxEndpoint( + enableModule, + userPrivateKey, + solutionId, + platformUrl + ); + synchronized (privmxEndpoints) { + privmxEndpoints.put(privmxEndpoint.connection.getConnectionId(), privmxEndpoint); + } + return privmxEndpoint; + } + + /** + * Disconnects connection matching given {@code connectionId} and removes it from the container. + * This method is recommended for disconnecting connections by their ID from the container. + * @param connectionId ID of the connection + */ + public void disconnect(Long connectionId){ + if (!isInitialized) throw new IllegalStateException("Certs path is not set"); + PrivmxEndpoint endpoint = privmxEndpoints.get(connectionId); + if ( endpoint == null) throw new IllegalStateException("No connection with specified id"); + try{ + endpoint.close(); + }catch (Exception ignored){} + } + + /** + * Disconnects all connections and removes them from the container. + */ + public void disconnectAll(){ + if (!isInitialized) throw new IllegalStateException("Certs path is not set"); + synchronized (privmxEndpoints){ + privmxEndpoints.values().forEach(endpoint -> { + try{ + endpoint.close(); + }catch (Exception ignored){} + }); + privmxEndpoints.clear(); + } + } + + /** + * Starts event handling Thread. + */ + public void startListening() { + eventLoopStarted = true; + if (currentTask == null) waitForNextEvent(); + } + + private void waitForNextEvent() { + synchronized (this) { + if (currentTask == null && eventLoopStarted && !eventExecutor.isShutdown()) { + currentTask = eventExecutor.submit(() -> { + try { + Event result = EventQueue.waitEvent(); + currentTask = null; + onNewEvent(result); + } catch (IllegalStateException e) { + currentTask = null; + } catch (Exception e) { + System.out.println("Catch event exception: " + e.getMessage()); + currentTask = null; + waitForNextEvent(); + } + }); + } + } + } + + private void onNewEvent(Event event) { + if(event.type.equals("libPlatformDisconnected")){ + waitForNextEvent(); + return; + } + if(event.connectionId != null && event.connectionId != -1) { + synchronized (privmxEndpoints) { + PrivmxEndpoint endpoint = privmxEndpoints.get(event.connectionId); + if (endpoint != null) { + endpoint.handleEvent(event); + if (event.type.equals(EventType.DisconnectedEvent.eventType)) { + try { + PrivmxEndpoint closedConnection = privmxEndpoints.remove(event.connectionId); + closedConnection.close(); + } catch (Exception ignore) { + } + } + } + } + } + + if (event.type.equals(EventType.LibBreakEvent.eventType)) { + eventLoopStarted = false; + return; + } + waitForNextEvent(); + } + + /** + * Closes event loop. + */ + @Override + public void close() throws Exception { + stopListening(); + synchronized (privmxEndpoints) { + privmxEndpoints.forEach((key, value) -> { + try { + value.close(); + } catch (Exception ignore) { + } + }); + privmxEndpoints.clear(); + } + eventExecutor.shutdown(); + } + +} diff --git a/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/model/Modules.java b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/model/Modules.java new file mode 100644 index 0000000..466e3d8 --- /dev/null +++ b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/model/Modules.java @@ -0,0 +1,32 @@ +// +// PrivMX Endpoint Java Extra. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint_extra.model; + +/** + * Available modules for PrivMX Endpoint. + * + * @category core + */ +public enum Modules { + /** + * Thread module case. + */ + THREAD, + /** + * Store module case. + */ + STORE, + /** + * Inbox module case. + */ + INBOX, +} diff --git a/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/model/SortOrder.java b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/model/SortOrder.java new file mode 100644 index 0000000..dac40ad --- /dev/null +++ b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/model/SortOrder.java @@ -0,0 +1,33 @@ +// +// PrivMX Endpoint Java Extra. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint_extra.model; + + +/** + * Constant values for sort order to use in PrivmxEnpoint lists methods. + * + * @category core + */ +public class SortOrder { + + /** + * Value for ascending sort order. + */ + public static final String ASC = "asc"; + + /** + * Value for descending sort order. + */ + public static final String DESC = "desc"; + + private SortOrder(){} +} diff --git a/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/storeFileStream/StoreFileStream.java b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/storeFileStream/StoreFileStream.java new file mode 100644 index 0000000..43d5bf9 --- /dev/null +++ b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/storeFileStream/StoreFileStream.java @@ -0,0 +1,141 @@ +// +// PrivMX Endpoint Java Extra. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint_extra.storeFileStream; + +import com.simplito.java.privmx_endpoint.model.exceptions.NativeException; +import com.simplito.java.privmx_endpoint.model.exceptions.PrivmxException; +import com.simplito.java.privmx_endpoint.modules.store.StoreApi; + +/** + * Base class for Store file streams. Implements progress listeners. + * + * @category store + */ +public abstract class StoreFileStream { + private Long processedBytes = 0L; + private ProgressListener progressListener; + private Boolean closed = false; + + /** + * Reference to file handle. + */ + protected final Long handle; + + /** + * Reference to {@link StoreApi}. + */ + protected final StoreApi storeApi; + + /** + * Constant value with optimal size of reading/sending data. + */ + public static final long OPTIMAL_SEND_SIZE = 128 * 1024L; + + /** + * Creates instance of {@code StoreFileStream}. + * @param handle handle to Store file + * @param storeApi {@link StoreApi} instance that calls read/write methods on files + */ + protected StoreFileStream( + Long handle, + StoreApi storeApi + ) { + this.handle = handle; + this.storeApi = storeApi; + } + + /** + * Sets listening for single chunk sent/read. + * @param progressListener callback triggered when chunk is sent/read + */ + public void setProgressListener(ProgressListener progressListener) { + this.progressListener = progressListener; + } + + /** + * Increases the size of current sent/read data by chunkSize and calls {@link ProgressListener#onChunkProcessed(Long)}. + * @param chunkSize size of processed chunk + */ + protected void callChunkProcessed(Long chunkSize){ + processedBytes += chunkSize; + if(progressListener != null){ + progressListener.onChunkProcessed(processedBytes); + } + } + + /** + * Interface to listen to progress of sending/reading files. + */ + public interface ProgressListener{ + /** + * A callback called after each successful read/write operation. + * @param processedBytes full size of current sent/read data + */ + void onChunkProcessed(Long processedBytes); + } + + /** + * Returns information whether the instance is closed. + * + * @return {@code true} if file handle is closed + */ + public Boolean isClosed(){return closed;} + + /** + * Closes file handle. + * @return ID of the closed file + * @throws PrivmxException if there is an error while closing file + * @throws NativeException if there is an unknown error while closing file + * @throws IllegalStateException when {@code storeApi} is not initialized or there's no connection + */ + public String close() throws PrivmxException, NativeException, IllegalStateException{ + closed = true; + return (/*closedFileId =*/ storeApi.closeFile(handle)); + } + + /** + * Manages sending/reading files using {@link java.io.InputStream}/{@link java.io.OutputStream}. + */ + public static class Controller implements ProgressListener{ + private boolean isStopped = false; + + /** + * Stops reading/writing file after processing the current chunk. + */ + public final void stop(){ + isStopped = true; + } + + /** + * Returns information whether the stream should be stopped. + * @return {@code true} if controller is set to stop + */ + public final boolean isStopped(){ + return isStopped; + } + + /** + * Override this method to handle event when each chunk was sent successfully. + * + * @param processedBytes full size of current sent/read data + */ + @Override + public void onChunkProcessed(Long processedBytes) { + + } + + /** + * Creates instance of Controller. + */ + public Controller(){} + } +} diff --git a/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/storeFileStream/StoreFileStreamReader.java b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/storeFileStream/StoreFileStreamReader.java new file mode 100644 index 0000000..8b97350 --- /dev/null +++ b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/storeFileStream/StoreFileStreamReader.java @@ -0,0 +1,143 @@ +// +// PrivMX Endpoint Java Extra. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint_extra.storeFileStream; + +import com.simplito.java.privmx_endpoint.model.exceptions.NativeException; +import com.simplito.java.privmx_endpoint.model.exceptions.PrivmxException; +import com.simplito.java.privmx_endpoint.modules.store.StoreApi; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadPoolExecutor; + + +/** + * Manages handle for file reading. + * + * @category store + */ +public class StoreFileStreamReader extends StoreFileStream { + + + private StoreFileStreamReader( + Long handle, + StoreApi api + ) { + super(handle, api); + } + + /** + * Opens Store file. + * + * @param api reference to Store API + * @param fileId ID of the file to open + * @return Instance ready to read from the Store file + * @throws IllegalStateException when {@code storeApi} is not initialized or there's no connection + * @throws PrivmxException if there is an error while opening Store file + * @throws NativeException if there is an unknown error while opening Store file + */ + public static StoreFileStreamReader openFile( + StoreApi api, + String fileId + ) throws IllegalStateException, PrivmxException, NativeException { + return new StoreFileStreamReader( + api.openFile(fileId), + api + ); + } + + /** + * Opens Store file and writes it into {@link OutputStream}. + * + * @param api reference to Store API + * @param fileId ID of the file to open + * @param outputStream stream to write downloaded data with optimized chunk size {@link StoreFileStream#OPTIMAL_SEND_SIZE} + * @return ID of the read file + * @throws IOException if there is an error while writing the stream + * @throws IllegalStateException when storeApi is not initialized or there's no connection + * @throws PrivmxException if there is an error while opening Store file + * @throws NativeException if there is an unknown error while opening Store file + */ + public static String openFile( + StoreApi api, + String fileId, + OutputStream outputStream + ) throws IOException, IllegalStateException, PrivmxException, NativeException { + return StoreFileStreamReader.openFile(api, fileId, outputStream, null); + } + + /** + * Opens Store file and writes it into {@link OutputStream}. + * + * @param api reference to Store API + * @param fileId ID of the file to open + * @param outputStream stream to write downloaded data with optimized chunk size {@link StoreFileStream#OPTIMAL_SEND_SIZE} + * @param streamController controls the process of reading file + * @return ID of the read file + * @throws IOException if there is an error while writing stream + * @throws IllegalStateException when storeApi is not initialized or there's no connection + * @throws PrivmxException if there is an error while reading Store file + * @throws NativeException if there is an unknown error while reading Store file + */ + public static String openFile( + StoreApi api, + String fileId, + OutputStream outputStream, + Controller streamController + ) throws IOException, IllegalStateException, PrivmxException, NativeException { + StoreFileStreamReader input = StoreFileStreamReader.openFile(api,fileId); + if (streamController != null) { + input.setProgressListener(streamController); + } + byte[] chunk; + do { + if (streamController != null && streamController.isStopped()) { + input.close(); + } + chunk = input.read(StoreFileStream.OPTIMAL_SEND_SIZE); + outputStream.write(chunk); + } while (chunk.length == StoreFileStream.OPTIMAL_SEND_SIZE); + + return input.close(); + } + + /** + * Reads file data and moves the cursor. If read data size is less than length, then EOF. + * + * @param size size of data to read (the recommended size is {@link StoreFileStream#OPTIMAL_SEND_SIZE}) + * @return Read data + * @throws IOException when {@code this} is closed + * @throws PrivmxException when method encounters an exception + * @throws NativeException when method encounters an unknown exception + * @throws IllegalStateException when {@link #storeApi} is closed + */ + public byte[] read(Long size) throws IOException, PrivmxException, NativeException, IllegalStateException { + if (isClosed()) throw new IOException("File handle is closed"); + byte[] result = storeApi.readFromFile(handle, size); + callChunkProcessed((long) result.length); + return result; + } + + /** + * Moves read cursor. + * + * @param position new cursor position + * @throws IllegalStateException if {@code storeApi} is not initialized or connected + * @throws PrivmxException if there is an error while seeking + * @throws NativeException if there is an unknown error while seeking + */ + public void seek(long position) throws IllegalStateException, PrivmxException, NativeException { + storeApi.seekInFile(handle,position); + ((ThreadPoolExecutor) Executors.newSingleThreadExecutor()).getQueue().clear(); + } +} diff --git a/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/storeFileStream/StoreFileStreamWriter.java b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/storeFileStream/StoreFileStreamWriter.java new file mode 100644 index 0000000..59fcd7a --- /dev/null +++ b/privmx-endpoint-extra/src/main/java/com/simplito/java/privmx_endpoint_extra/storeFileStream/StoreFileStreamWriter.java @@ -0,0 +1,250 @@ +// +// PrivMX Endpoint Java Extra. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint_extra.storeFileStream; + +import com.simplito.java.privmx_endpoint.model.exceptions.NativeException; +import com.simplito.java.privmx_endpoint.model.exceptions.PrivmxException; +import com.simplito.java.privmx_endpoint.modules.store.StoreApi; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; + +/** + * Manages handle for file writing. + * + * @category store + */ +public class StoreFileStreamWriter extends StoreFileStream { + + private StoreFileStreamWriter(Long handle, StoreApi storeApi) { + super(handle, storeApi); + } + + /** + * Creates a new file in given Store. + * + * @param api reference to Store API + * @param storeId ID of the Store + * @param publicMeta byte array of any arbitrary metadata that can be read by anyone + * @param privateMeta byte array of any arbitrary metadata that will be encrypted before sending + * @param size size of data to write + * @return Instance ready to write to the created Store file + * @throws IllegalStateException when storeApi is not initialized or there's no connection + * @throws PrivmxException if there is an error while creating Store file metadata + * @throws NativeException if there is an unknown error while creating store file metadata + */ + public static StoreFileStreamWriter createFile( + StoreApi api, + String storeId, + byte[] publicMeta, + byte[] privateMeta, + long size + ) throws PrivmxException, NativeException, IllegalStateException { + if (api == null) throw new NullPointerException("api could not be null"); + return new StoreFileStreamWriter( + api.createFile(storeId, publicMeta, privateMeta, size), + api + ); + } + + + /** + * Updates an existing file. + * + * @param api reference to Store API + * @param fileId ID of the file to update + * @param publicMeta new public metadata for the matching file + * @param privateMeta new private (encrypted) metadata for the matching file + * @param size size of data to write + * @return {@link StoreFileStreamWriter} instance prepared for writing + * @throws IllegalStateException when {@code storeApi} is not initialized or there's no connection + * @throws PrivmxException if there is an error while updating Store file metadata + * @throws NativeException if there is an unknown error while updating Store file metadata + */ + public static StoreFileStreamWriter updateFile( + StoreApi api, + String fileId, + byte[] publicMeta, + byte[] privateMeta, + long size + ) throws PrivmxException, NativeException, IllegalStateException { + if (api == null) throw new NullPointerException("api could not be null"); + return new StoreFileStreamWriter( + api.updateFile(fileId, publicMeta, privateMeta, size), + api + ); + } + + /** + * Creates a new file in given Store and writes data from given {@link InputStream}. + * + * @param api reference to Store API + * @param storeId ID of the Store + * @param publicMeta byte array of any arbitrary metadata that can be read by anyone + * @param privateMeta byte array of any arbitrary metadata that will be encrypted before sending + * @param size size of data to write + * @param inputStream stream with data to write to the file using optimal chunk size {@link StoreFileStream#OPTIMAL_SEND_SIZE} + * @return ID of the created file + * @throws IOException if there is an error while reading stream or {@code this} is closed + * @throws IllegalStateException when storeApi is not initialized or there's no connection + * @throws PrivmxException if there is an error while creating Store file metadata + * @throws NativeException if there is an unknown error while creating Store file metadata + */ + public static String createFile( + StoreApi api, + String storeId, + byte[] publicMeta, + byte[] privateMeta, + long size, + InputStream inputStream + ) throws IOException, PrivmxException, NativeException, IllegalStateException { + return StoreFileStreamWriter.createFile(api, storeId, publicMeta, privateMeta, size, inputStream, null); + } + + /** + * Creates new file in given Store and writes data from given {@link InputStream}. + * + * @param api reference to Store API + * @param storeId ID of the Store + * @param publicMeta byte array of any arbitrary metadata that can be read by anyone + * @param privateMeta byte array of any arbitrary metadata that will be encrypted before sending + * @param size size of data to write + * @param inputStream stream with data to write to the file using optimal chunk size {@link StoreFileStream#OPTIMAL_SEND_SIZE} + * @param streamController controls the process of writing file + * @return ID of the created file + * @throws IOException if there is an error while reading stream or {@code this} is closed + * @throws IllegalStateException when {@code storeApi} is not initialized or there's no connection + * @throws PrivmxException if there is an error while creating Store file metadata + * @throws NativeException if there is an unknown error while creating Store file metadata + */ + public static String createFile( + StoreApi api, + String storeId, + byte[] publicMeta, + byte[] privateMeta, + long size, + InputStream inputStream, + Controller streamController + ) throws IOException, PrivmxException, NativeException, IllegalStateException { + if (api == null) throw new NullPointerException("api could not be null"); + StoreFileStreamWriter output = StoreFileStreamWriter.createFile( + api, + storeId, + publicMeta, + privateMeta, + size + ); + + if (streamController != null) { + output.setProgressListener(streamController); + } + byte[] chunk = new byte[(int) StoreFileStream.OPTIMAL_SEND_SIZE]; + int readed; + while ((readed = inputStream.read(chunk)) >= 0) { + if(streamController != null && streamController.isStopped()){ + output.close(); + } + output.write(Arrays.copyOf(chunk, readed)); + } + return output.close(); + } + + /** + * Updates existing file and writes data from passed {@link InputStream}. + * + * @param api reference to Store API + * @param fileId ID of the file to update + * @param publicMeta new public metadata for the matching file + * @param privateMeta new private (encrypted) metadata for the matching file + * @param size size of data to write + * @param inputStream stream with data to write to the file using optimal chunk size {@link StoreFileStream#OPTIMAL_SEND_SIZE} + * @return Updated file ID + * @throws IOException if there is an error while reading stream or {@code this} is closed + * @throws IllegalStateException when {@code storeApi} is not initialized or there's no connection + * @throws PrivmxException if there is an error while updating Store file metadata + * @throws NativeException if there is an unknown error while updating Store file metadata + */ + public static String updateFile( + StoreApi api, + String fileId, + byte[] publicMeta, + byte[] privateMeta, + long size, + InputStream inputStream + ) throws IOException, PrivmxException, NativeException, IllegalStateException { + return StoreFileStreamWriter.updateFile(api, fileId, publicMeta, privateMeta, size, inputStream, null); + } + + /** + * Updates existing file and writes data from passed {@link InputStream}. + * + * @param api reference to Store API + * @param fileId ID of the file to update + * @param publicMeta new public metadata for the matching file + * @param privateMeta new private (encrypted) metadata for the matching file + * @param size size of data to write + * @param inputStream stream with data to write to the file using optimal chunk size {@link StoreFileStream#OPTIMAL_SEND_SIZE} + * @param streamController controls the process of writing file + * @return Updated file ID + * @throws IOException if there is an error while reading stream or {@code this} is closed + * @throws IllegalStateException when {@code storeApi} is not initialized or there's no connection + * @throws PrivmxException if there is an error while updating Store file metadata + * @throws NativeException if there is an unknown error while updating Store file metadata + */ + public static String updateFile( + StoreApi api, + String fileId, + byte[] publicMeta, + byte[] privateMeta, + long size, + InputStream inputStream, + Controller streamController + ) throws IOException, PrivmxException, NativeException, IllegalStateException { + if (api == null) throw new NullPointerException("api could not be null"); + StoreFileStreamWriter output = StoreFileStreamWriter.updateFile(api, fileId, publicMeta, privateMeta, size); + if (streamController != null) { + output.setProgressListener(streamController); + } + byte[] chunk = new byte[(int)StoreFileStream.OPTIMAL_SEND_SIZE]; + int readed; + while (true) { + if(streamController != null && streamController.isStopped()){ + output.close(); + } + if((readed = inputStream.read(chunk)) <= 0){ + break; + } + output.write(Arrays.copyOf(chunk, readed)); + } + return output.close(); + } + + + /** + * Writes data to Store file. + * + * @param data data to write (the recommended size of data chunk is {@link StoreFileStream#OPTIMAL_SEND_SIZE}) + * @throws PrivmxException if there is an error while writing chunk + * @throws NativeException if there is an unknown error while writing chunk + * @throws IllegalStateException when storeApi is not initialized or there's no connection + * @throws IOException when {@code this} is closed + * @throws PrivmxException when method encounters an exception + * @throws NativeException when method encounters an unknown exception + * @throws IllegalStateException when {@link #storeApi} is closed + */ + public void write(byte[] data) throws PrivmxException, NativeException, IllegalStateException, IOException { + if (isClosed()) throw new IOException("File handle is closed"); + storeApi.writeToFile(handle, data); + callChunkProcessed((long) data.length); + } +} diff --git a/privmx-endpoint-extra/src/main/resources/cacert.pem b/privmx-endpoint-extra/src/main/resources/cacert.pem new file mode 100644 index 0000000..cc55128 --- /dev/null +++ b/privmx-endpoint-extra/src/main/resources/cacert.pem @@ -0,0 +1,90 @@ +-----BEGIN CERTIFICATE----- +MIIE7DCCA9SgAwIBAgISBCxas4Z0ghNX9dmL0JRes+aEMA0GCSqGSIb3DQEBCwUA +MDIxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MQswCQYDVQQD +EwJSMzAeFw0yNDAzMjAxMTU2MDFaFw0yNDA2MTgxMTU2MDBaMBoxGDAWBgNVBAMT +D2MxLnByaXZteC5jbG91ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +AN9/D4pQxtvXriqkdWh8bmu7lvNgdIW6liHgmAW73rDd7NtmKKt0Ec+ddgqa05aC +b7V7NQBbRY0bGFRkMW1kCs634Hn1jzK3iCr7cDqwRPiC3rUUFdkccU/7FvD61501 +tPu6nG6WGCnMXY08N9sXqIGuEZTcZX7kAOTvzDEfNnqi7Ofns2zba0AG3v8F2Z73 +Niw084OdbRIS+HvqEhnmpBBDNORdPh0mrLF+cm+d25IM8gRwKGwUQpCrcYr43Rkv +mSgHVRXymHeD6aYyAYy4SCelAn3bg3HtFIW9W5wRHjVR+1tW1WjeXQyc9wnC6D6h +l172O3sua2z9Iv+2/eSNjWcCAwEAAaOCAhIwggIOMA4GA1UdDwEB/wQEAwIFoDAd +BgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDAYDVR0TAQH/BAIwADAdBgNV +HQ4EFgQU4ISnM32GmtwRKKefX15TihpAfpowHwYDVR0jBBgwFoAUFC6zF7dYVsuu +UAlA5h+vnYsUwsYwVQYIKwYBBQUHAQEESTBHMCEGCCsGAQUFBzABhhVodHRwOi8v +cjMuby5sZW5jci5vcmcwIgYIKwYBBQUHMAKGFmh0dHA6Ly9yMy5pLmxlbmNyLm9y +Zy8wGgYDVR0RBBMwEYIPYzEucHJpdm14LmNsb3VkMBMGA1UdIAQMMAowCAYGZ4EM +AQIBMIIBBQYKKwYBBAHWeQIEAgSB9gSB8wDxAHcAO1N3dT4tuYBOizBbBv5AO2fY +T8P0x70ADS1yb+H61BcAAAGOW+7RWwAABAMASDBGAiEAwMr97KeyBZw1YAqhQjpg +SNaWAWYMd1KvGYqqUInxqCMCIQCWF685H62w1J6ICJjl6JPY7cj4WxQUxXaFPdvw +TBDnugB2AKLiv9Ye3i8vB6DWTm03p9xlQ7DGtS6i2reK+Jpt9RfYAAABjlvu0WQA +AAQDAEcwRQIhANq2PbyjsO3DFAKscUktOn5zSFO27IfZt5zL+Nd0htnRAiAOmQH9 +/Xe5eCUa8X97KDlQBN0B8LavaiV8ix/851Tw1DANBgkqhkiG9w0BAQsFAAOCAQEA +mFuJGkS+vv7Zy7FHdtkbJ8SeW5FqhEQ1noxmlb61IPYjkrRRYYAtDZWHksfpIaul +XT6pwIUOTwiLQ6clZYTbqqheXqfuatWWWl/7OFdRwzcrBDdCQX+yLER8fFN8XzRj +agQzaU0kTjRI72i6D+omHm7z69bc2VjVggamo4G6QmkhcZC4IGDzmRxcYBxX6THw +eGhjP6OIBc2GmvCgoAowzEF1GHrQf54urkw2XzSLzBiHkSFw//VsGOjiMl/cw5uJ +CgHyuy1+lOXUAlAXnWtczSHbgiXKsfd4dhbtW99/E0/YVKYTjzGdf78JE2lofaYZ +b4k0Wk359EQpriwQwZDV5Q== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIFFjCCAv6gAwIBAgIRAJErCErPDBinU/bWLiWnX1owDQYJKoZIhvcNAQELBQAw +TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh +cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMjAwOTA0MDAwMDAw +WhcNMjUwOTE1MTYwMDAwWjAyMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNTGV0J3Mg +RW5jcnlwdDELMAkGA1UEAxMCUjMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK +AoIBAQC7AhUozPaglNMPEuyNVZLD+ILxmaZ6QoinXSaqtSu5xUyxr45r+XXIo9cP +R5QUVTVXjJ6oojkZ9YI8QqlObvU7wy7bjcCwXPNZOOftz2nwWgsbvsCUJCWH+jdx +sxPnHKzhm+/b5DtFUkWWqcFTzjTIUu61ru2P3mBw4qVUq7ZtDpelQDRrK9O8Zutm +NHz6a4uPVymZ+DAXXbpyb/uBxa3Shlg9F8fnCbvxK/eG3MHacV3URuPMrSXBiLxg +Z3Vms/EY96Jc5lP/Ooi2R6X/ExjqmAl3P51T+c8B5fWmcBcUr2Ok/5mzk53cU6cG +/kiFHaFpriV1uxPMUgP17VGhi9sVAgMBAAGjggEIMIIBBDAOBgNVHQ8BAf8EBAMC +AYYwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMBMBIGA1UdEwEB/wQIMAYB +Af8CAQAwHQYDVR0OBBYEFBQusxe3WFbLrlAJQOYfr52LFMLGMB8GA1UdIwQYMBaA +FHm0WeZ7tuXkAXOACIjIGlj26ZtuMDIGCCsGAQUFBwEBBCYwJDAiBggrBgEFBQcw +AoYWaHR0cDovL3gxLmkubGVuY3Iub3JnLzAnBgNVHR8EIDAeMBygGqAYhhZodHRw +Oi8veDEuYy5sZW5jci5vcmcvMCIGA1UdIAQbMBkwCAYGZ4EMAQIBMA0GCysGAQQB +gt8TAQEBMA0GCSqGSIb3DQEBCwUAA4ICAQCFyk5HPqP3hUSFvNVneLKYY611TR6W +PTNlclQtgaDqw+34IL9fzLdwALduO/ZelN7kIJ+m74uyA+eitRY8kc607TkC53wl +ikfmZW4/RvTZ8M6UK+5UzhK8jCdLuMGYL6KvzXGRSgi3yLgjewQtCPkIVz6D2QQz +CkcheAmCJ8MqyJu5zlzyZMjAvnnAT45tRAxekrsu94sQ4egdRCnbWSDtY7kh+BIm +lJNXoB1lBMEKIq4QDUOXoRgffuDghje1WrG9ML+Hbisq/yFOGwXD9RiX8F6sw6W4 +avAuvDszue5L3sz85K+EC4Y/wFVDNvZo4TYXao6Z0f+lQKc0t8DQYzk1OXVu8rp2 +yJMC6alLbBfODALZvYH7n7do1AZls4I9d1P4jnkDrQoxB3UqQ9hVl3LEKQ73xF1O +yK5GhDDX8oVfGKF5u+decIsH4YaTw7mP3GFxJSqv3+0lUFJoi5Lc5da149p90Ids +hCExroL1+7mryIkXPeFM5TgO9r0rvZaBFOvV2z0gp35Z0+L4WPlbuEjN/lxPFin+ +HlUjr8gRsI3qfJOQFy/9rKIJR0Y/8Omwt/8oTWgy1mdeHmmjk7j1nYsvC9JSQ6Zv +MldlTTKB3zhThV1+XWYp6rjd5JW1zbVWEkLNxE7GJThEUG3szgBVGP7pSWTUTsqX +nLRbwHOoq7hHwg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw +TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh +cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4 +WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu +ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY +MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc +h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+ +0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U +A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW +T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH +B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC +B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv +KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn +OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn +jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw +qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI +rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq +hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL +ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ +3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK +NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5 +ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur +TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC +jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc +oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq +4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA +mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d +emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc= +-----END CERTIFICATE----- diff --git a/privmx-endpoint-extra/src/test/java/com/simplito/privmxendpointwrapper/ExampleUnitTest.java b/privmx-endpoint-extra/src/test/java/com/simplito/privmxendpointwrapper/ExampleUnitTest.java new file mode 100644 index 0000000..cee034a --- /dev/null +++ b/privmx-endpoint-extra/src/test/java/com/simplito/privmxendpointwrapper/ExampleUnitTest.java @@ -0,0 +1,28 @@ +// +// PrivMX Endpoint Java Extra +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.cloud). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.privmxendpointwrapper; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +/** + * Example local unit test, which will execute on the development machine (host). + * + * @see Testing documentation + */ +public class ExampleUnitTest { + @Test + public void addition_isCorrect() { + assertEquals(4, 2 + 2); + } +} \ No newline at end of file diff --git a/privmx-endpoint/.gitignore b/privmx-endpoint/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/privmx-endpoint/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/privmx-endpoint/build.gradle b/privmx-endpoint/build.gradle new file mode 100644 index 0000000..9b20f0b --- /dev/null +++ b/privmx-endpoint/build.gradle @@ -0,0 +1,63 @@ +plugins { + id 'java-library' + id 'signing' + id 'maven-publish' +} + +//Apply script for publishing native libraries +if (file("build-publish-native.gradle").exists()) { + apply from: "build-publish-native.gradle" +} + +//Apply script for generating official documentation +if (file("build-documentation.gradle").exists()) { + apply from: "build-documentation.gradle" +} + +//Apply script for publishing maven dependency +if (file("build-publish-maven.gradle").exists()) { + apply from: "build-publish-maven.gradle" +} + +version = '2.0' + +java { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + withSourcesJar() + withJavadocJar() +} + +//Removing tag @group +sourcesJar { + filter(new Transformer() { + @Override + String transform(String s) { + if ( + s.trim().matches("\\* *@group.*") || + s.trim().matches("\\* *@folder.*") || + s.trim().matches("\\* *@category.*") + ) { + return null + } + return s + } + }) +} + +javadoc { + options.tags += [ + "category:xt:\"Category group\"", + "folder:xt:\"Class folder\"", + "event:xm:\"Method event\"", + "group:xt:\"Class group\"" + ] +} + +dependencies { + testImplementation libs.junit +} + +compileJava { + options.compilerArgs += "-parameters" +} \ No newline at end of file diff --git a/privmx-endpoint/src/main/cpp/.gitignore b/privmx-endpoint/src/main/cpp/.gitignore new file mode 100644 index 0000000..19f2c15 --- /dev/null +++ b/privmx-endpoint/src/main/cpp/.gitignore @@ -0,0 +1,6 @@ +build +deployer/ +libs/ +.cxx +buildScript.sh +build.gradle \ No newline at end of file diff --git a/privmx-endpoint/src/main/cpp/CMakeLists.txt b/privmx-endpoint/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000..2f03373 --- /dev/null +++ b/privmx-endpoint/src/main/cpp/CMakeLists.txt @@ -0,0 +1,118 @@ +# For more information about using CMake with Android Studio, read the +# documentation: https://d.android.com/studio/projects/add-native-code.html. +# For more examples on how to use CMake, see https://github.com/android/ndk-samples. + +# Sets the minimum CMake version required for this project. +cmake_minimum_required(VERSION 3.22.1) + +# Declares the project name. The project name can be accessed via ${ PROJECT_NAME}, +# Since this is the top level CMakeLists.txt, the project name is also accessible +# with ${CMAKE_PROJECT_NAME} (both CMake variables are in-sync within the top level +# build script scope). +project("privmx-endpoint-java") + +set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -s") +set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -s") + +if( NOT DEFINED CMAKE_DESTINATION_OS ) + set(CMAKE_DESTINATION_OS ${CMAKE_SYSTEM_NAME}) +endif () + +if( NOT DEFINED CMAKE_DESTINATION_ARCHITECTURE) + if(CMAKE_DESTINATION_OS STREQUAL "Android" AND DEFINED CMAKE_ANDROID_ARCH_ABI) + set(CMAKE_DESTINATION_ARCHITECTURE ${CMAKE_ANDROID_ARCH_ABI}) + else() + set(CMAKE_DESTINATION_ARCHITECTURE ${CMAKE_SYSTEM_PROCESSOR}) + endif () +endif() + +if("${CMAKE_DESTINATION_OS}" STREQUAL "Darwin") + set(file_extension "dylib") + set(CMAKE_MACOSX_RPATH 1) + set(CMAKE_INSTALL_RPATH "@loader_path") +elseif ("${CMAKE_DESTINATION_OS}" STREQUAL "Windows") + set(file_extension "dll") +else () + set(file_extension "so") +endif () + +message(DEBUG "CMAKE DEST OS ${CMAKE_DESTINATION_OS}") +message(DEBUG "CMAKE DEST PROCESSOR ${CMAKE_DESTINATION_ARCHITECTURE}") + +add_library(ssl SHARED IMPORTED GLOBAL) +set_target_properties(ssl PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libssl.${file_extension}) + +add_library(crypto SHARED IMPORTED GLOBAL) +set_target_properties(crypto PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libcrypto.${file_extension}) + +add_library(gmp SHARED IMPORTED GLOBAL) +set_target_properties(gmp PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libgmp.${file_extension}) + +add_library(PocoFoundation SHARED IMPORTED GLOBAL) +set_target_properties(PocoFoundation PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libPocoFoundation.${file_extension}) + +add_library(PocoJSON SHARED IMPORTED GLOBAL) +set_target_properties(PocoJSON PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libPocoJSON.${file_extension}) + +add_library(PocoNet SHARED IMPORTED GLOBAL) +set_target_properties(PocoNet PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libPocoNet.${file_extension}) + +add_library(PocoCrypto SHARED IMPORTED GLOBAL) +set_target_properties(PocoCrypto PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libPocoCrypto.${file_extension}) + +add_library(PocoXML SHARED IMPORTED GLOBAL) +set_target_properties(PocoXML PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libPocoXML.${file_extension}) + +add_library(PocoNetSSL SHARED IMPORTED GLOBAL) +set_target_properties(PocoNetSSL PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libPocoNetSSL.${file_extension}) + +add_library(PocoUtil SHARED IMPORTED GLOBAL) +set_target_properties(PocoUtil PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libPocoUtil.${file_extension}) + +add_library(Pson SHARED IMPORTED GLOBAL) +set_target_properties(Pson PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libPson.${file_extension}) + +add_library(libprivmx SHARED IMPORTED GLOBAL) +set_target_properties(libprivmx PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libprivmx.${file_extension}) + +add_library(privmxendpointcore SHARED IMPORTED GLOBAL) +set_target_properties(privmxendpointcore PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libprivmxendpointcore.${file_extension}) + +add_library(privmxendpointcrypto SHARED IMPORTED GLOBAL) +set_target_properties(privmxendpointcrypto PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libprivmxendpointcrypto.${file_extension}) + +add_library(privmxendpointstore SHARED IMPORTED GLOBAL) +set_target_properties(privmxendpointstore PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libprivmxendpointstore.${file_extension}) + +add_library(privmxendpointthread SHARED IMPORTED GLOBAL) +set_target_properties(privmxendpointthread PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libprivmxendpointthread.${file_extension}) + +add_library(privmxendpointinbox SHARED IMPORTED GLOBAL) +set_target_properties(privmxendpointinbox PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${CMAKE_DESTINATION_OS}/${CMAKE_DESTINATION_ARCHITECTURE}/lib/libprivmxendpointinbox.${file_extension}) + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/libs/include ${JAVA_HOME}/include ${JAVA_HOME}/include/darwin) + +add_library(${CMAKE_PROJECT_NAME} SHARED + ${CMAKE_CURRENT_SOURCE_DIR}/parser.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/utils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/model_native_initializers.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/modules/Connection.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/modules/CryptoApi.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/modules/ThreadApi.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/modules/StoreApi.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/modules/InboxApi.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/modules/EventQueue.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/exceptions.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/modules/BackendRequester.cpp +) + +# Android Debugging +#find_library( log-lib log ) +#target_link_libraries(${CMAKE_PROJECT_NAME} ${log-lib} ${log}) +target_link_libraries(${CMAKE_PROJECT_NAME} ssl crypto) +target_link_libraries(${CMAKE_PROJECT_NAME} gmp) +target_link_libraries(${CMAKE_PROJECT_NAME} PocoFoundation PocoXML PocoJSON PocoNet PocoNetSSL PocoUtil PocoCrypto) +target_link_libraries(${CMAKE_PROJECT_NAME} Pson libprivmx privmxendpointcore privmxendpointcrypto privmxendpointstore privmxendpointthread privmxendpointinbox) +message(DEBUG "Install to ${CMAKE_INSTALL_PREFIX}") +install(TARGETS ${CMAKE_PROJECT_NAME} DESTINATION ${CMAKE_INSTALL_PREFIX}) +install(IMPORTED_RUNTIME_ARTIFACTS crypto ssl gmp PocoFoundation PocoXML PocoJSON PocoNet PocoNetSSL PocoUtil PocoCrypto Pson libprivmx privmxendpointcore privmxendpointcrypto privmxendpointstore privmxendpointthread privmxendpointinbox DESTINATION ${CMAKE_INSTALL_PREFIX}) \ No newline at end of file diff --git a/privmx-endpoint/src/main/cpp/exceptions.cpp b/privmx-endpoint/src/main/cpp/exceptions.cpp new file mode 100644 index 0000000..ad75e41 --- /dev/null +++ b/privmx-endpoint/src/main/cpp/exceptions.cpp @@ -0,0 +1,22 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#include "exceptions.h" + +IllegalStateException::IllegalStateException(const char *message) { + this->message = message; +} + +const char *IllegalStateException::what() const noexcept { + return this->message; +} + + diff --git a/privmx-endpoint/src/main/cpp/exceptions.h b/privmx-endpoint/src/main/cpp/exceptions.h new file mode 100644 index 0000000..ab03831 --- /dev/null +++ b/privmx-endpoint/src/main/cpp/exceptions.h @@ -0,0 +1,25 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#ifndef PRIVMXENDPOINTWRAPPER_EXCEPTIONS_H +#define PRIVMXENDPOINTWRAPPER_EXCEPTIONS_H + +#include + +class IllegalStateException: public std::exception { +private: + const char *message; +public: + IllegalStateException(const char *message); + const char* what() const noexcept override; +}; + +#endif //PRIVMXENDPOINTWRAPPER_EXCEPTIONS_H diff --git a/privmx-endpoint/src/main/cpp/model_native_initializers.cpp b/privmx-endpoint/src/main/cpp/model_native_initializers.cpp new file mode 100644 index 0000000..15de309 --- /dev/null +++ b/privmx-endpoint/src/main/cpp/model_native_initializers.cpp @@ -0,0 +1,614 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#include "model_native_initializers.h" + +namespace privmx { + namespace wrapper { + //Context + jobject context2Java( + JniContextUtils &ctx, + privmx::endpoint::core::Context context_c + ) { + jclass contextCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/Context"); + jmethodID initThreadDataMID = ctx->GetMethodID( + contextCls, + "", + "(Ljava/lang/String;Ljava/lang/String;)V" + ); + return ctx->NewObject( + contextCls, + initThreadDataMID, + ctx->NewStringUTF(context_c.userId.c_str()), + ctx->NewStringUTF(context_c.contextId.c_str()) + ); + } + + //Threads + jobject thread2Java(JniContextUtils &ctx, privmx::endpoint::thread::Thread thread_c) { + jclass threadCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/Thread"); + jmethodID initThreadMID = ctx->GetMethodID( + threadCls, + "", + "(" + "Ljava/lang/String;" + "Ljava/lang/String;" + "Ljava/lang/Long;" + "Ljava/lang/String;" + "Ljava/lang/Long;" + "Ljava/lang/String;" + "Ljava/util/List;" + "Ljava/util/List;" + "Ljava/lang/Long;" + "Ljava/lang/Long;" + "[B" + "[B" + "Ljava/lang/Long;" + "Ljava/lang/Long;" + ")V" + ); + jclass arrayCls = ctx->FindClass("java/util/ArrayList"); + jmethodID initArrayMID = ctx->GetMethodID( + arrayCls, + "", + "()V"); + jmethodID addToArrayMID = ctx->GetMethodID( + arrayCls, + "add", + "(Ljava/lang/Object;)Z" + ); + jstring threadId = ctx->NewStringUTF(thread_c.threadId.c_str()); + jstring contextId = ctx->NewStringUTF(thread_c.contextId.c_str()); + jstring creator = ctx->NewStringUTF(thread_c.creator.c_str()); + jstring lastModifier = ctx->NewStringUTF(thread_c.lastModifier.c_str()); + jobject users = ctx->NewObject(arrayCls, initArrayMID); + jobject managers = ctx->NewObject(arrayCls, initArrayMID); + jbyteArray publicMeta = ctx->NewByteArray(thread_c.publicMeta.size()); + jbyteArray privateMeta = ctx->NewByteArray(thread_c.privateMeta.size()); + ctx->SetByteArrayRegion(publicMeta, 0, thread_c.publicMeta.size(), + (jbyte *) thread_c.publicMeta.data()); + ctx->SetByteArrayRegion(privateMeta, 0, thread_c.privateMeta.size(), + (jbyte *) thread_c.privateMeta.data()); + for (auto &user: thread_c.users) { + ctx->CallBooleanMethod(users, + addToArrayMID, + ctx->NewStringUTF(user.c_str())); + } + for (auto &manager: thread_c.managers) { + ctx->CallBooleanMethod(managers, + addToArrayMID, + ctx->NewStringUTF(manager.c_str())); + } + return ctx->NewObject( + threadCls, + initThreadMID, + contextId, + threadId, + ctx.long2jLong(thread_c.createDate), + creator, + ctx.long2jLong(thread_c.lastModificationDate), + lastModifier, + users, + managers, + ctx.long2jLong(thread_c.version), + ctx.long2jLong(thread_c.lastMsgDate), + publicMeta, + privateMeta, + ctx.long2jLong(thread_c.messagesCount), + ctx.long2jLong(thread_c.statusCode) + ); + } + + //Messages + jobject serverMessageInfo2Java(JniContextUtils &ctx, + privmx::endpoint::thread::ServerMessageInfo serverMessageInfo_c) { + jclass messageCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/ServerMessageInfo"); + jmethodID initMessageMID = ctx->GetMethodID( + messageCls, + "", + "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;)V" + ); + return ctx->NewObject( + messageCls, + initMessageMID, + ctx->NewStringUTF(serverMessageInfo_c.threadId.c_str()), + ctx->NewStringUTF(serverMessageInfo_c.messageId.c_str()), + ctx.long2jLong(serverMessageInfo_c.createDate), + ctx->NewStringUTF(serverMessageInfo_c.author.c_str()) + ); + } + + jobject message2Java(JniContextUtils &ctx, privmx::endpoint::thread::Message message_c) { + jclass messageCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/Message"); + jmethodID initMessageMID = ctx->GetMethodID( + messageCls, + "", + "(Lcom/simplito/java/privmx_endpoint/model/ServerMessageInfo;[B[B[BLjava/lang/String;Ljava/lang/Long;)V" + ); + + jbyteArray publicMeta = ctx->NewByteArray(message_c.publicMeta.size()); + jbyteArray privateMeta = ctx->NewByteArray(message_c.privateMeta.size()); + jbyteArray data = ctx->NewByteArray(message_c.data.size()); + ctx->SetByteArrayRegion(publicMeta, 0, message_c.publicMeta.size(), + (jbyte *) message_c.publicMeta.data()); + + ctx->SetByteArrayRegion(privateMeta, 0, message_c.privateMeta.size(), + (jbyte *) message_c.privateMeta.data()); + + ctx->SetByteArrayRegion(data, 0, message_c.data.size(), + (jbyte *) message_c.data.data()); + + return ctx->NewObject( + messageCls, + initMessageMID, + serverMessageInfo2Java(ctx, message_c.info), + publicMeta, + privateMeta, + data, + ctx->NewStringUTF(message_c.authorPubKey.c_str()), + ctx.long2jLong(message_c.statusCode) + ); + } + + //Store + jobject store2Java(JniContextUtils &ctx, privmx::endpoint::store::Store store_c) { + jclass arrayCls = ctx->FindClass("java/util/ArrayList"); + jmethodID initArrayMID = ctx->GetMethodID( + arrayCls, + "", + "()V"); + jmethodID addToArrayMID = ctx->GetMethodID( + arrayCls, + "add", + "(Ljava/lang/Object;)Z" + ); + + jclass storeCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/Store"); + jmethodID initStoreMID = ctx->GetMethodID( + storeCls, + "", + "(" + "Ljava/lang/String;" //storeId + "Ljava/lang/String;" //contextId + "Ljava/lang/Long;" //createDate + "Ljava/lang/String;" //creator + "Ljava/lang/Long;" //lastModificationDate + "Ljava/lang/Long;" //lastFileDate + "Ljava/lang/String;" //lastModifier + "Ljava/util/List;" //users + "Ljava/util/List;" //managers + "Ljava/lang/Long;" //version + "[B" //publicMeta + "[B" //privateMeta + "Ljava/lang/Long;" //filesCount + "Ljava/lang/Long;" + ")V" + ); + + jobject users = ctx->NewObject(arrayCls, initArrayMID); + jobject managers = ctx->NewObject(arrayCls, initArrayMID); + jbyteArray publicMeta = ctx->NewByteArray(store_c.publicMeta.size()); + jbyteArray privateMeta = ctx->NewByteArray(store_c.privateMeta.size()); + ctx->SetByteArrayRegion(publicMeta, 0, store_c.publicMeta.size(), + (jbyte *) store_c.publicMeta.data()); + ctx->SetByteArrayRegion(privateMeta, 0, store_c.privateMeta.size(), + (jbyte *) store_c.privateMeta.data()); + for (auto &user: store_c.users) { + ctx->CallBooleanMethod(users, + addToArrayMID, + ctx->NewStringUTF(user.c_str())); + } + for (auto &manager: store_c.managers) { + ctx->CallBooleanMethod(managers, + addToArrayMID, + ctx->NewStringUTF(manager.c_str())); + } + + return ctx->NewObject( + storeCls, + initStoreMID, + ctx->NewStringUTF(store_c.storeId.c_str()), + ctx->NewStringUTF(store_c.contextId.c_str()), + ctx.long2jLong(store_c.createDate), + ctx->NewStringUTF(store_c.creator.c_str()), + ctx.long2jLong(store_c.lastModificationDate), + ctx.long2jLong(store_c.lastFileDate), + ctx->NewStringUTF(store_c.lastModifier.c_str()), + users, + managers, + ctx.long2jLong(store_c.version), + publicMeta, + privateMeta, + ctx.long2jLong(store_c.filesCount), + ctx.long2jLong(store_c.statusCode) + ); + } + + //Inbox + jobject inbox2Java(JniContextUtils &ctx, privmx::endpoint::inbox::Inbox inbox_c) { + jclass inboxCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/Inbox"); + jmethodID initInboxMID = ctx->GetMethodID( + inboxCls, + "", + "(" + "Ljava/lang/String;" //inboxId + "Ljava/lang/String;" //contextId + "Ljava/lang/Long;" //createDate + "Ljava/lang/String;" //creator + "Ljava/lang/Long;" //lastModificationDate + "Ljava/lang/String;" //lastModifier + "Ljava/util/List;" //users + "Ljava/util/List;" //managers + "Ljava/lang/Long;" //version + "[B" //publicMeta + "[B" //privateMeta + "Lcom/simplito/java/privmx_endpoint/model/FilesConfig;" //filesConfig + "Ljava/lang/Long;" //statusCode + ")V" + ); + jclass arrayCls = ctx->FindClass("java/util/ArrayList"); + jmethodID initArrayMID = ctx->GetMethodID( + arrayCls, + "", + "()V"); + jmethodID addToArrayMID = ctx->GetMethodID( + arrayCls, + "add", + "(Ljava/lang/Object;)Z" + ); + jobject users = ctx->NewObject(arrayCls, initArrayMID); + jobject managers = ctx->NewObject(arrayCls, initArrayMID); + jbyteArray publicMeta = ctx->NewByteArray(inbox_c.publicMeta.size()); + jbyteArray privateMeta = ctx->NewByteArray(inbox_c.privateMeta.size()); + ctx->SetByteArrayRegion(publicMeta, 0, inbox_c.publicMeta.size(), + (jbyte *) inbox_c.publicMeta.data()); + ctx->SetByteArrayRegion(privateMeta, 0, inbox_c.privateMeta.size(), + (jbyte *) inbox_c.privateMeta.data()); + for (auto &user: inbox_c.users) { + ctx->CallBooleanMethod(users, + addToArrayMID, + ctx->NewStringUTF(user.c_str())); + } + for (auto &manager: inbox_c.managers) { + ctx->CallBooleanMethod(managers, + addToArrayMID, + ctx->NewStringUTF(manager.c_str())); + } + + jobject filesConfig = nullptr; + if (inbox_c.filesConfig.has_value()) { + filesConfig = filesConfig2Java(ctx, inbox_c.filesConfig.value()); + } + + return ctx->NewObject( + inboxCls, + initInboxMID, + ctx->NewStringUTF(inbox_c.inboxId.c_str()), + ctx->NewStringUTF(inbox_c.contextId.c_str()), + ctx.long2jLong(inbox_c.createDate), + ctx->NewStringUTF(inbox_c.creator.c_str()), + ctx.long2jLong(inbox_c.lastModificationDate), + ctx->NewStringUTF(inbox_c.lastModifier.c_str()), + users, + managers, + ctx.long2jLong(inbox_c.version), + publicMeta, + privateMeta, + filesConfig, + ctx.long2jLong(inbox_c.statusCode) + ); + } + + jobject + inboxEntry2Java(JniContextUtils &ctx, privmx::endpoint::inbox::InboxEntry inboxEntry_c) { + jclass inboxEntryCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/InboxEntry"); + jmethodID initEntryViewMID = ctx->GetMethodID( + inboxEntryCls, + "", + "(" + "Ljava/lang/String;" //entryId + "Ljava/lang/String;" //inboxId + "[B" //data + "Ljava/util/List;" //files + "Ljava/lang/String;" //authorPubKey + "Ljava/lang/Long;" // createDate + "Ljava/lang/Long;" // statusCode + ")V" + ); + jclass arrayCls = ctx->FindClass("java/util/ArrayList"); + jmethodID initArrayMID = ctx->GetMethodID( + arrayCls, + "", + "()V"); + jmethodID addToArrayMID = ctx->GetMethodID( + arrayCls, + "add", + "(Ljava/lang/Object;)Z" + ); + jbyteArray data = ctx->NewByteArray(inboxEntry_c.data.size()); + ctx->SetByteArrayRegion(data, 0, inboxEntry_c.data.size(), + (jbyte *) inboxEntry_c.data.data()); + jobject files = ctx->NewObject(arrayCls, initArrayMID); + for (auto &file: inboxEntry_c.files) { + ctx->CallBooleanMethod(files, + addToArrayMID, + file2Java(ctx, file)); + } + return ctx->NewObject( + inboxEntryCls, + initEntryViewMID, + ctx->NewStringUTF(inboxEntry_c.entryId.c_str()), + ctx->NewStringUTF(inboxEntry_c.inboxId.c_str()), + data, + files, + ctx->NewStringUTF(inboxEntry_c.authorPubKey.c_str()), + ctx.long2jLong(inboxEntry_c.createDate), + ctx.long2jLong(inboxEntry_c.statusCode) + ); + } + + jobject inboxPublicView2Java(JniContextUtils &ctx, + privmx::endpoint::inbox::InboxPublicView inboxPublicView_c) { + jclass inboxPublicViewCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/InboxPublicView"); + jmethodID initInboxPublicViewMID = ctx->GetMethodID( + inboxPublicViewCls, + "", + "(" + "Ljava/lang/String;" + "Ljava/lang/Long;" + "[B" + ")V" + ); + jbyteArray publicMeta = ctx->NewByteArray(inboxPublicView_c.publicMeta.size()); + ctx->SetByteArrayRegion(publicMeta, 0, inboxPublicView_c.publicMeta.size(), + (jbyte *) inboxPublicView_c.publicMeta.data()); + return ctx->NewObject( + inboxPublicViewCls, + initInboxPublicViewMID, + ctx->NewStringUTF(inboxPublicView_c.inboxId.c_str()), + ctx.long2jLong(inboxPublicView_c.version), + publicMeta + ); + } + + jobject + filesConfig2Java(JniContextUtils &ctx, privmx::endpoint::inbox::FilesConfig filesConfig_c) { + jclass filesConfigCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/FilesConfig"); + jmethodID initFilesConfigMID = ctx->GetMethodID( + filesConfigCls, + "", + "(" + "Ljava/lang/Long;" + "Ljava/lang/Long;" + "Ljava/lang/Long;" + "Ljava/lang/Long;" + ")V" + ); + return ctx->NewObject( + filesConfigCls, + initFilesConfigMID, + ctx.long2jLong(filesConfig_c.minCount), + ctx.long2jLong(filesConfig_c.maxCount), + ctx.long2jLong(filesConfig_c.maxFileSize), + ctx.long2jLong(filesConfig_c.maxWholeUploadSize) + ); + } + + //Files + jobject serverFileInfo2Java(JniContextUtils &ctx, + privmx::endpoint::store::ServerFileInfo serverFileInfo_c) { + jclass serverFileInfoCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/ServerFileInfo"); + jmethodID initServerFileInfoMID = ctx->GetMethodID( + serverFileInfoCls, + "", + "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;)V" + ); + return ctx->NewObject( + serverFileInfoCls, + initServerFileInfoMID, + ctx->NewStringUTF(serverFileInfo_c.storeId.c_str()), + ctx->NewStringUTF(serverFileInfo_c.fileId.c_str()), + ctx.long2jLong(serverFileInfo_c.createDate), + ctx->NewStringUTF(serverFileInfo_c.author.c_str()) + ); + } + + jobject file2Java(JniContextUtils &ctx, privmx::endpoint::store::File file_c) { + jclass fileCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/File"); + jmethodID initFileMID = ctx->GetMethodID( + fileCls, + "", + "(" + "Lcom/simplito/java/privmx_endpoint/model/ServerFileInfo;" + "[B" + "[B" + "Ljava/lang/Long;" + "Ljava/lang/String;" + "Ljava/lang/Long;" + ")V" + ); + + jbyteArray publicMeta = ctx->NewByteArray(file_c.publicMeta.size()); + jbyteArray privateMeta = ctx->NewByteArray(file_c.privateMeta.size()); + ctx->SetByteArrayRegion(publicMeta, 0, file_c.publicMeta.size(), + (jbyte *) file_c.publicMeta.data()); + + ctx->SetByteArrayRegion(privateMeta, 0, file_c.privateMeta.size(), + (jbyte *) file_c.privateMeta.data()); + + return ctx->NewObject( + fileCls, + initFileMID, + serverFileInfo2Java(ctx, file_c.info), + publicMeta, + privateMeta, + ctx.long2jLong(file_c.size), + ctx->NewStringUTF(file_c.authorPubKey.c_str()), + ctx.long2jLong(file_c.statusCode) + ); + } + + //Event + jobject storeFileDeletedEventData2Java(JniContextUtils &ctx, + privmx::endpoint::store::StoreFileDeletedEventData storeFileDeletedEventData_c) { + jclass storeFileDeletedEventDataCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/events/StoreFileDeletedEventData"); + jmethodID initStoreFileDeletedEventDataMID = ctx->GetMethodID( + storeFileDeletedEventDataCls, + "", + "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V" + ); + return ctx->NewObject( + storeFileDeletedEventDataCls, + initStoreFileDeletedEventDataMID, + ctx->NewStringUTF(storeFileDeletedEventData_c.fileId.c_str()), + ctx->NewStringUTF(storeFileDeletedEventData_c.contextId.c_str()), + ctx->NewStringUTF(storeFileDeletedEventData_c.storeId.c_str()) + ); + } + + jobject storeStatsChangedEventData2Java(JniContextUtils &ctx, + privmx::endpoint::store::StoreStatsChangedEventData storeStatsChangedEventData_c) { + jclass storeStatsChangedEventDataCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/events/StoreStatsChangedEventData"); + jmethodID initStoreStatsChangedEventDataMID = ctx->GetMethodID( + storeStatsChangedEventDataCls, + "", + "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/Long;)V" + ); + return ctx->NewObject( + storeStatsChangedEventDataCls, + initStoreStatsChangedEventDataMID, + ctx->NewStringUTF(storeStatsChangedEventData_c.storeId.c_str()), + ctx->NewStringUTF(storeStatsChangedEventData_c.contextId.c_str()), + ctx.long2jLong(storeStatsChangedEventData_c.lastFileDate), + ctx.long2jLong(storeStatsChangedEventData_c.filesCount) + ); + } + + jobject threadDeletedEventData2Java(JniContextUtils &ctx, + privmx::endpoint::thread::ThreadDeletedEventData threadDeletedEventData_c) { + jclass threadDeletedEventDataCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/events/ThreadDeletedEventData"); + jmethodID initThreadDeletedEventDataMID = ctx->GetMethodID( + threadDeletedEventDataCls, + "", + "(Ljava/lang/String;)V" + ); + return ctx->NewObject( + threadDeletedEventDataCls, + initThreadDeletedEventDataMID, + ctx->NewStringUTF(threadDeletedEventData_c.threadId.c_str()) + ); + } + + jobject threadDeletedMessageEventData2Java(JniContextUtils &ctx, + privmx::endpoint::thread::ThreadDeletedMessageEventData threadDeletedMessageEventData) { + jclass threadDeletedMessageEventDataCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/events/ThreadDeletedMessageEventData"); + jmethodID initThreadDeletedMessageEventDataMID = ctx->GetMethodID( + threadDeletedMessageEventDataCls, + "", + "(Ljava/lang/String;Ljava/lang/String;)V" + ); + return ctx->NewObject( + threadDeletedMessageEventDataCls, + initThreadDeletedMessageEventDataMID, + ctx->NewStringUTF(threadDeletedMessageEventData.threadId.c_str()), + ctx->NewStringUTF(threadDeletedMessageEventData.messageId.c_str()) + ); + } + + jobject storeDeletedEventData2Java(JniContextUtils &ctx, + privmx::endpoint::store::StoreDeletedEventData storeDeletedEventData_c) { + jclass storeDeletedEventDataCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/events/StoreDeletedEventData"); + jmethodID initStoreDeletedEventDataMID = ctx->GetMethodID( + storeDeletedEventDataCls, + "", + "(Ljava/lang/String;)V" + ); + return ctx->NewObject( + storeDeletedEventDataCls, + initStoreDeletedEventDataMID, + ctx->NewStringUTF(storeDeletedEventData_c.storeId.c_str()) + ); + } + + jobject threadStatsEventData2Java( + JniContextUtils &ctx, + privmx::endpoint::thread::ThreadStatsEventData threadStatsEventData_c + ) { + jclass threadStatsEventDataCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/events/ThreadStatsEventData"); + jmethodID initThreadStatsEventDataMID = ctx->GetMethodID( + threadStatsEventDataCls, + "", + "(Ljava/lang/String;Ljava/lang/Long;Ljava/lang/Long;)V" + ); + return ctx->NewObject( + threadStatsEventDataCls, + initThreadStatsEventDataMID, + ctx->NewStringUTF(threadStatsEventData_c.threadId.c_str()), + ctx.long2jLong(threadStatsEventData_c.lastMsgDate), + ctx.long2jLong(threadStatsEventData_c.messagesCount) + ); + } + + jobject inboxDeletedEventData2Java( + JniContextUtils &ctx, + privmx::endpoint::inbox::InboxDeletedEventData inboxDeletedEventData_c + ) { + jclass inboxDeletedEventDataCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/events/InboxDeletedEventData"); + jmethodID initInboxDeletedEventDataMID = ctx->GetMethodID( + inboxDeletedEventDataCls, + "", + "(Ljava/lang/String;)V" + ); + return ctx->NewObject( + inboxDeletedEventDataCls, + initInboxDeletedEventDataMID, + ctx->NewStringUTF(inboxDeletedEventData_c.inboxId.c_str()) + ); + } + + jobject inboxEntryDeletedEventData2Java( + JniContextUtils &ctx, + privmx::endpoint::inbox::InboxEntryDeletedEventData inboxEntryDeletedEventData_c + ) { + jclass inboxEntryDeletedEventDataCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/events/InboxEntryDeletedEventData"); + jmethodID initInboxEntryDeletedEventDataMID = ctx->GetMethodID( + inboxEntryDeletedEventDataCls, + "", + "(Ljava/lang/String;Ljava/lang/String;)V" + ); + return ctx->NewObject( + inboxEntryDeletedEventDataCls, + initInboxEntryDeletedEventDataMID, + ctx->NewStringUTF(inboxEntryDeletedEventData_c.inboxId.c_str()), + ctx->NewStringUTF(inboxEntryDeletedEventData_c.entryId.c_str()) + ); + } + } // wrapper +} // privmx \ No newline at end of file diff --git a/privmx-endpoint/src/main/cpp/model_native_initializers.h b/privmx-endpoint/src/main/cpp/model_native_initializers.h new file mode 100644 index 0000000..ae85a67 --- /dev/null +++ b/privmx-endpoint/src/main/cpp/model_native_initializers.h @@ -0,0 +1,67 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#ifndef PRIVMXENDPOINTWRAPPER_MODEL_NATIVE_INITIALIZERS_H +#define PRIVMXENDPOINTWRAPPER_MODEL_NATIVE_INITIALIZERS_H +#include +#include "utils.hpp" +#include "privmx/endpoint/core/Connection.hpp" +#include "privmx/endpoint/core/Types.hpp" +#include "privmx/endpoint/core/Events.hpp" +#include "privmx/endpoint/thread/ThreadApi.hpp" +#include "privmx/endpoint/thread/Types.hpp" +#include "privmx/endpoint/thread/Events.hpp" +#include "privmx/endpoint/store/StoreApi.hpp" +#include "privmx/endpoint/store/Types.hpp" +#include "privmx/endpoint/store/Events.hpp" +#include "privmx/endpoint/inbox/InboxApi.hpp" +#include "privmx/endpoint/inbox/Types.hpp" +#include "privmx/endpoint/inbox/Events.hpp" + +namespace privmx { +namespace wrapper{ + //Context + jobject context2Java(JniContextUtils &ctx, privmx::endpoint::core::Context context_c); + + //Threads + jobject thread2Java(JniContextUtils &ctx, privmx::endpoint::thread::Thread thread_c); + + //Messages + jobject serverMessageInfo2Java(JniContextUtils &ctx, privmx::endpoint::thread::ServerMessageInfo serverMessageInfo_c); + jobject message2Java(JniContextUtils &ctx, privmx::endpoint::thread::Message message_c); + + //Store + jobject store2Java(JniContextUtils &ctx, privmx::endpoint::store::Store store_c); + + //Inbox + jobject filesConfig2Java(JniContextUtils &ctx, privmx::endpoint::inbox::FilesConfig filesConfig_c); + jobject inbox2Java(JniContextUtils &ctx, privmx::endpoint::inbox::Inbox inbox_c); + jobject inboxEntry2Java(JniContextUtils &ctx, privmx::endpoint::inbox::InboxEntry inboxEntry_c); + jobject inboxPublicView2Java(JniContextUtils &ctx, privmx::endpoint::inbox::InboxPublicView inboxPublicView_c); + + //Files + jobject serverFileInfo2Java(JniContextUtils &ctx, privmx::endpoint::store::ServerFileInfo serverFileInfo_c); + jobject file2Java(JniContextUtils &ctx, privmx::endpoint::store::File file_c); + + //Event + jobject storeDeletedEventData2Java(JniContextUtils &ctx, privmx::endpoint::store::StoreDeletedEventData storeDeletedEventData_c); + jobject storeFileDeletedEventData2Java(JniContextUtils &ctx, privmx::endpoint::store::StoreFileDeletedEventData storeFileDeletedEventData_c); + jobject storeStatsChangedEventData2Java(JniContextUtils &ctx, privmx::endpoint::store::StoreStatsChangedEventData storeStatsChangedEventData_c); + jobject threadDeletedEventData2Java(JniContextUtils &ctx, privmx::endpoint::thread::ThreadDeletedEventData threadDeletedEventData_c); + jobject threadDeletedMessageEventData2Java(JniContextUtils &ctx, privmx::endpoint::thread::ThreadDeletedMessageEventData threadDeletedMessageEventData_c); + jobject threadStatsEventData2Java(JniContextUtils &ctx, privmx::endpoint::thread::ThreadStatsEventData threadStatsEventData_c); + jobject inboxDeletedEventData2Java(JniContextUtils &ctx, privmx::endpoint::inbox::InboxDeletedEventData inboxDeletedEventData_c); + jobject inboxEntryDeletedEventData2Java(JniContextUtils &ctx, privmx::endpoint::inbox::InboxEntryDeletedEventData inboxEntryDeletedEventData_c); + +} // wrapper +} // privmx + +#endif //PRIVMXENDPOINTWRAPPER_MODEL_NATIVE_INITIALIZERS_H diff --git a/privmx-endpoint/src/main/cpp/modules/BackendRequester.cpp b/privmx-endpoint/src/main/cpp/modules/BackendRequester.cpp new file mode 100644 index 0000000..2159aa2 --- /dev/null +++ b/privmx-endpoint/src/main/cpp/modules/BackendRequester.cpp @@ -0,0 +1,149 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#include +#include "../exceptions.h" +#include "../utils.hpp" +#include +#include + +extern "C" +JNIEXPORT jstring JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_core_BackendRequester_backendRequest__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_String_2( + JNIEnv *env, + jclass clazz, + jstring server_url, + jstring access_token, + jstring method, + jstring params_as_json +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(server_url, "Server URL") || + ctx.nullCheck(access_token, "Access token") || + ctx.nullCheck(method, "Method") || + ctx.nullCheck(params_as_json, "Params as json")) { + return nullptr; + } + try { + return ctx->NewStringUTF( + privmx::endpoint::core::BackendRequester::backendRequest( + ctx.jString2string(server_url), + ctx.jString2string(access_token), + ctx.jString2string(method), + ctx.jString2string(params_as_json) + ).c_str() + ); + } catch (const privmx::endpoint::core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} +extern "C" +JNIEXPORT jstring JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_core_BackendRequester_backendRequest__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_String_2( + JNIEnv *env, + jclass clazz, + jstring server_url, + jstring method, + jstring params_as_json +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(server_url, "Server URL") || + ctx.nullCheck(method, "Method") || + ctx.nullCheck(params_as_json, "Params as json")) { + return nullptr; + } + try { + return ctx->NewStringUTF( + privmx::endpoint::core::BackendRequester::backendRequest( + ctx.jString2string(server_url), + ctx.jString2string(method), + ctx.jString2string(params_as_json) + ).c_str() + ); + } catch (const privmx::endpoint::core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT jstring JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_core_BackendRequester_backendRequest__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_String_2JLjava_lang_String_2Ljava_lang_String_2( + JNIEnv *env, + jclass clazz, + jstring server_url, + jstring api_key_id, + jstring api_key_secret, + jlong mode, + jstring method, + jstring params_as_json +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(server_url, "Server URL") || + ctx.nullCheck(api_key_id, "Api key ID") || + ctx.nullCheck(api_key_secret, "Api key secret") || + ctx.nullCheck(method, "Method") || + ctx.nullCheck(params_as_json, "Params as json")) { + return nullptr; + } + try { + return ctx->NewStringUTF( + privmx::endpoint::core::BackendRequester::backendRequest( + ctx.jString2string(server_url), + ctx.jString2string(api_key_id), + ctx.jString2string(api_key_secret), + mode, + ctx.jString2string(method), + ctx.jString2string(params_as_json) + ).c_str() + ); + } catch (const privmx::endpoint::core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} \ No newline at end of file diff --git a/privmx-endpoint/src/main/cpp/modules/Connection.cpp b/privmx-endpoint/src/main/cpp/modules/Connection.cpp new file mode 100644 index 0000000..12b3a5d --- /dev/null +++ b/privmx-endpoint/src/main/cpp/modules/Connection.cpp @@ -0,0 +1,281 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#include +#include +#include "privmx/endpoint/core/Config.hpp" +#include +#include "Connection.h" +#include "../utils.hpp" +#include "../parser.h" +#include "../exceptions.h" + +privmx::endpoint::core::Connection *getConnection(JNIEnv *env, jobject thiz) { + JniContextUtils ctx(env); + jclass cls = ctx->GetObjectClass(thiz); + jfieldID apiFID = ctx->GetFieldID(cls, "api", "Ljava/lang/Long;"); + jobject apiLong = ctx->GetObjectField(thiz, apiFID); + if (apiLong == nullptr) { + throw IllegalStateException("Platform is not connected. Connect to platform first."); + } + return (privmx::endpoint::core::Connection *) ctx.getObject(apiLong).getLongValue(); +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_core_Connection_deinit(JNIEnv *env, jobject thiz) { + try { + //if null go to catch + auto api = getConnection(env, thiz); + delete api; + jclass cls = env->GetObjectClass(thiz); + jfieldID apiFID = env->GetFieldID(cls, "api", "Ljava/lang/Long;"); + env->SetObjectField(thiz, apiFID, (jobject) nullptr); + } catch (const IllegalStateException &e) { + env->ThrowNew( + env->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_core_Connection_platformConnect( + JNIEnv *env, + jclass clazz, + jstring user_priv_key, + jstring solution_id, + jstring platform_url +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(user_priv_key, "User Private Key") || + ctx.nullCheck(solution_id, "Solution ID") || + ctx.nullCheck(platform_url, "Platform URL")) { + return nullptr; + } + try { + jmethodID initMID = ctx->GetMethodID(clazz, "", "(Ljava/lang/Long;Ljava/lang/Long;)V"); + privmx::endpoint::core::Connection connection = privmx::endpoint::core::Connection::platformConnect( + ctx.jString2string(user_priv_key), + ctx.jString2string(solution_id), + ctx.jString2string(platform_url) + ); + privmx::endpoint::core::Connection *api = new privmx::endpoint::core::Connection(); + *api = connection; + jobject result = ctx->NewObject( + clazz, + initMID, + ctx.long2jLong((jlong) api), + ctx.long2jLong(api->getConnectionId()) + ); + return result; + } catch (const privmx::endpoint::core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_core_Connection_listContexts( + JNIEnv *env, + jobject thiz, + jlong skip, + jlong limit, + jstring sort_order, + jstring last_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(sort_order, "Sort Order")) { + return nullptr; + } + try { + auto query = privmx::endpoint::core::PagingQuery(); + query.skip = skip; + query.limit = limit; + query.sortOrder = ctx.jString2string(sort_order); + if (last_id != nullptr) { + query.lastId = ctx.jString2string(last_id); + } + privmx::endpoint::core::PagingList infos = getConnection( + env, thiz)->listContexts( + query + ); + jclass pagingListCls = env->FindClass( + "com/simplito/java/privmx_endpoint/model/PagingList" + ); + jmethodID pagingListInitMID = env->GetMethodID( + pagingListCls, + "", + "(Ljava/lang/Long;Ljava/util/List;)V" + ); + jclass arrayListCls = env->FindClass("java/util/ArrayList"); + jmethodID initMID = env->GetMethodID(arrayListCls, "", "()V"); + jmethodID addToListMID = env->GetMethodID(arrayListCls, "add", "(Ljava/lang/Object;)Z"); + jobject array = env->NewObject(arrayListCls, initMID); + for (auto &context: infos.readItems) { + env->CallBooleanMethod( + array, + addToListMID, + privmx::wrapper::context2Java(ctx, context) + ); + } + return ctx->NewObject( + pagingListCls, + pagingListInitMID, + ctx.long2jLong(infos.totalAvailable), + array + ); + } catch (const privmx::endpoint::core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_core_Connection_disconnect( + JNIEnv *env, + jobject thiz +) { + JniContextUtils ctx(env); + try { + getConnection(env, thiz)->disconnect(); + Java_com_simplito_java_privmx_1endpoint_modules_core_Connection_deinit(env, thiz); + } catch (const privmx::endpoint::core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_core_Connection_setCertsPath( + JNIEnv *env, + jclass clazz, + jstring certs_path +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(certs_path, "Certs path")) { + return; + } + try { + privmx::endpoint::core::Config::setCertsPath( + ctx.jString2string(certs_path) + ); + } catch (const privmx::endpoint::core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_core_Connection_platformConnectPublic( + JNIEnv *env, + jclass clazz, + jstring solution_id, + jstring platform_url +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(solution_id, "Solution ID") || + ctx.nullCheck(platform_url, "Platform URL")) { + return nullptr; + } + try { + jmethodID initMID = ctx->GetMethodID(clazz, "", "(Ljava/lang/Long;Ljava/lang/Long;)V"); + privmx::endpoint::core::Connection connection = privmx::endpoint::core::Connection::platformConnectPublic( + ctx.jString2string(solution_id), + ctx.jString2string(platform_url) + ); + privmx::endpoint::core::Connection *api = new privmx::endpoint::core::Connection(); + *api = connection; + jobject result = ctx->NewObject( + clazz, + initMID, + ctx.long2jLong((jlong) api), + ctx.long2jLong(api->getConnectionId()) + ); + return result; + } catch (const privmx::endpoint::core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} \ No newline at end of file diff --git a/privmx-endpoint/src/main/cpp/modules/Connection.h b/privmx-endpoint/src/main/cpp/modules/Connection.h new file mode 100644 index 0000000..fb6a789 --- /dev/null +++ b/privmx-endpoint/src/main/cpp/modules/Connection.h @@ -0,0 +1,19 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +#include +#include + +#ifndef PRIVMXENDPOINTWRAPPER_CONNECTION_H +#define PRIVMXENDPOINTWRAPPER_CONNECTION_H + +#endif //PRIVMXENDPOINTWRAPPER_CONNECTION_H + +privmx::endpoint::core::Connection *getConnection(JNIEnv *env, jobject thiz); \ No newline at end of file diff --git a/privmx-endpoint/src/main/cpp/modules/CryptoApi.cpp b/privmx-endpoint/src/main/cpp/modules/CryptoApi.cpp new file mode 100644 index 0000000..12d926c --- /dev/null +++ b/privmx-endpoint/src/main/cpp/modules/CryptoApi.cpp @@ -0,0 +1,452 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#include +#include +#include +#include "../utils.hpp" +#include "../parser.h" +#include "../exceptions.h" + +using namespace privmx::endpoint; + +crypto::CryptoApi *getCryptoApi(JNIEnv *env, jobject thiz) { + JniContextUtils ctx(env); + jclass cls = ctx->GetObjectClass(thiz); + jfieldID apiFID = ctx->GetFieldID(cls, "api", "Ljava/lang/Long;"); + jobject apiLong = ctx->GetObjectField(thiz, apiFID); + if (apiLong == nullptr) { + throw IllegalStateException("CryptoApi cannot be used"); + } + return (crypto::CryptoApi *) ctx.getObject(apiLong).getLongValue(); +} + + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_crypto_CryptoApi_init(JNIEnv *env, jobject thiz) { + JniContextUtils ctx(env); + try { + auto cryptoApi = crypto::CryptoApi::create(); + auto cryptoApi_ptr = new crypto::CryptoApi(); + *cryptoApi_ptr = cryptoApi; + return ctx.long2jLong((jlong) cryptoApi_ptr); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_crypto_CryptoApi_deinit(JNIEnv *env, jobject thiz) { + try { + //if null go to catch + auto api = getCryptoApi(env, thiz); + delete api; + jclass cls = env->GetObjectClass(thiz); + jfieldID apiFID = env->GetFieldID(cls, "api", "Ljava/lang/Long;"); + env->SetObjectField(thiz, apiFID, (jobject) nullptr); + } catch (const IllegalStateException &e) { + env->ThrowNew( + env->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } +} +extern "C" +JNIEXPORT jstring JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_crypto_CryptoApi_generatePrivateKey( + JNIEnv *env, + jobject thiz, + jstring random_seed +) { + JniContextUtils ctx(env); + try { + std::optional random_seed_c = std::nullopt; + if (random_seed != nullptr) { + random_seed_c = ctx.jString2string(random_seed); + } + return env->NewStringUTF( + getCryptoApi(env, thiz)->generatePrivateKey( + random_seed_c + ).c_str() + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} +extern "C" +JNIEXPORT jstring JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_crypto_CryptoApi_derivePublicKey( + JNIEnv *env, + jobject thiz, + jstring private_key +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(private_key, "Private key")) { + return nullptr; + } + try { + return env->NewStringUTF( + getCryptoApi(env, thiz)->derivePublicKey( + ctx.jString2string(private_key) + ).c_str() + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} +extern "C" +JNIEXPORT jbyteArray JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_crypto_CryptoApi_encryptDataSymmetric( + JNIEnv *env, + jobject thiz, + jbyteArray data, + jbyteArray symmetric_key +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(data, "Data") || + ctx.nullCheck(symmetric_key, "Symmetric key")) { + return nullptr; + } + try { + auto response = getCryptoApi(env, thiz)->encryptDataSymmetric( + core::Buffer::from(ctx.jByteArray2String(data)), + core::Buffer::from(ctx.jByteArray2String(symmetric_key)) + ); + jbyteArray result = env->NewByteArray(response.size()); + env->SetByteArrayRegion(result, 0, response.size(), (jbyte *) response.data()); + + return result; + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} +extern "C" +JNIEXPORT jbyteArray JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_crypto_CryptoApi_decryptDataSymmetric( + JNIEnv *env, + jobject thiz, + jbyteArray data, + jbyteArray symmetric_key +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(data, "Data") || + ctx.nullCheck(symmetric_key, "Symmetric key")) { + return nullptr; + } + try { + auto response = getCryptoApi(env, thiz)->decryptDataSymmetric( + core::Buffer::from(ctx.jByteArray2String(data)), + core::Buffer::from(ctx.jByteArray2String(symmetric_key)) + ); + jbyteArray result = env->NewByteArray(response.size()); + env->SetByteArrayRegion(result, 0, response.size(), (jbyte *) response.data()); + return result; + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT jbyteArray JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_crypto_CryptoApi_signData( + JNIEnv *env, + jobject thiz, + jbyteArray data, + jstring private_key +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(data, "Data") || + ctx.nullCheck(private_key, "Private key")) { + return nullptr; + } + try { + auto response = getCryptoApi(env, thiz)->signData( + core::Buffer::from(ctx.jByteArray2String(data)), + ctx.jString2string(private_key) + ); + + jbyteArray result = env->NewByteArray(response.size()); + env->SetByteArrayRegion(result, 0, response.size(), (jbyte *) response.data()); + return result; + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + + return nullptr; +} + +extern "C" +JNIEXPORT jstring JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_crypto_CryptoApi_convertPEMKeyToWIFKey( + JNIEnv *env, + jobject thiz, + jstring pem_key +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(pem_key, "Pem key")) { + return nullptr; + } + try { + std::string convertedKey = getCryptoApi(env, thiz)->convertPEMKeytoWIFKey( + ctx.jString2string(pem_key)); + return env->NewStringUTF(convertedKey.c_str()); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} +extern "C" +JNIEXPORT jstring JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_crypto_CryptoApi_derivePrivateKey( + JNIEnv *env, + jobject thiz, + jstring password, + jstring salt +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(password, "Password") || + ctx.nullCheck(salt, "Salt")) { + return nullptr; + } + try { + auto result = getCryptoApi(env, thiz)->derivePrivateKey( + ctx.jString2string(password), + ctx.jString2string(salt) + ); + return env->NewStringUTF(result.c_str()); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT jbyteArray JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_crypto_CryptoApi_generateKeySymmetric( + JNIEnv *env, + jobject thiz +) { + JniContextUtils ctx(env); + try { + auto response = getCryptoApi(env, thiz)->generateKeySymmetric(); + jbyteArray result = env->NewByteArray(response.size()); + env->SetByteArrayRegion(result, 0, response.size(), (jbyte *) response.data()); + return result; + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} +extern "C" +JNIEXPORT jboolean JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_crypto_CryptoApi_verifySignature( + JNIEnv *env, + jobject thiz, + jbyteArray data, + jbyteArray signature, + jstring public_key +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(data, "Data") || + ctx.nullCheck(signature, "Signature") || + ctx.nullCheck(public_key, "Public key") + ) { + return JNI_FALSE; + } + try { + auto response = getCryptoApi(env, thiz)->verifySignature( + core::Buffer::from(ctx.jByteArray2String(data)), + core::Buffer::from(ctx.jByteArray2String(signature)), + ctx.jString2string(public_key) + ); + return response ? JNI_TRUE : JNI_FALSE; + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + + return JNI_FALSE; +} \ No newline at end of file diff --git a/privmx-endpoint/src/main/cpp/modules/EventQueue.cpp b/privmx-endpoint/src/main/cpp/modules/EventQueue.cpp new file mode 100644 index 0000000..29f1355 --- /dev/null +++ b/privmx-endpoint/src/main/cpp/modules/EventQueue.cpp @@ -0,0 +1,101 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#include + +// +// Created by Dawid Jenczewski on 29/08/2024. +// +#include +#include "../utils.hpp" +#include "../parser.h" + +using namespace privmx::endpoint::core; + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_core_EventQueue_emitBreakEvent( + JNIEnv *env, + jclass clazz +) { + JniContextUtils ctx(env); + try { + EventQueue::getInstance().emitBreakEvent(); + } catch (const privmx::endpoint::core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_core_EventQueue_waitEvent( + JNIEnv *env, + jclass clazz +) { + JniContextUtils ctx(env); + try { + return parseEvent(ctx,EventQueue::getInstance().waitEvent().get()); + } catch (const privmx::endpoint::core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_core_EventQueue_getEvent( + JNIEnv *env, + jclass clazz +) { + JniContextUtils ctx(env); + try { + auto eventHolder = EventQueue::getInstance().getEvent(); + if(!eventHolder.has_value()) return nullptr; + return parseEvent(ctx,eventHolder.value().get()); + } catch (const privmx::endpoint::core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} \ No newline at end of file diff --git a/privmx-endpoint/src/main/cpp/modules/InboxApi.cpp b/privmx-endpoint/src/main/cpp/modules/InboxApi.cpp new file mode 100644 index 0000000..464629e --- /dev/null +++ b/privmx-endpoint/src/main/cpp/modules/InboxApi.cpp @@ -0,0 +1,1039 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#include +#include +#include +#include "Connection.h" +#include "ThreadApi.h" +#include "StoreApi.h" +#include "../utils.hpp" +#include "../parser.h" +#include "../model_native_initializers.h" +#include "../exceptions.h" +#include "privmx/endpoint/core/Exception.hpp" + +using namespace privmx::endpoint; + +inbox::InboxApi *getInboxApi(JniContextUtils &ctx, jobject inboxApiInstance) { + jclass cls = ctx->GetObjectClass(inboxApiInstance); + jfieldID apiFID = ctx->GetFieldID(cls, "api", "Ljava/lang/Long;"); + jobject apiLong = ctx->GetObjectField(inboxApiInstance, apiFID); + if (apiLong == nullptr) { + throw IllegalStateException("InboxApi cannot be used"); + } + return (inbox::InboxApi *) ctx.getObject(apiLong).getLongValue(); +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_init( + JNIEnv *env, jobject thiz, + jobject connection, + jobject thread_api, + jobject store_api +) { + JniContextUtils ctx(env); + try { + auto connection_c = getConnection(env, connection); + auto threadApi_c = getThreadApi(ctx, thread_api); + auto storeApi_c = getStoreApi(ctx, store_api); + auto inboxApi = inbox::InboxApi::create( + *connection_c, + *threadApi_c, + *storeApi_c + ); + auto inboxApi_ptr = new inbox::InboxApi(); + *inboxApi_ptr = inboxApi; + return ctx.long2jLong((jlong) inboxApi_ptr); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_deinit(JNIEnv *env, jobject thiz) { + try { + JniContextUtils ctx(env); + auto api = getInboxApi(ctx, thiz); + delete api; + jclass cls = env->GetObjectClass(thiz); + jfieldID apiFID = env->GetFieldID(cls, "api", "Ljava/lang/Long;"); + env->SetObjectField(thiz, apiFID, (jobject) nullptr); + } catch (const IllegalStateException &e) { + env->ThrowNew( + env->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } +} + +extern "C" +JNIEXPORT jstring JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_createInbox( + JNIEnv *env, + jobject thiz, + jstring context_id, + jobject users, + jobject managers, + jbyteArray public_meta, + jbyteArray private_meta, + jobject files_config +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(context_id, "Context ID") || + ctx.nullCheck(users, "Users list") || + ctx.nullCheck(managers, "Managers list") || + ctx.nullCheck(public_meta, "Public meta") || + ctx.nullCheck(private_meta, "Private meta")) { + return nullptr; + } + + try { + std::optional files_config_c = std::nullopt; + if (files_config != nullptr) { + files_config_c = parseFilesConfig(ctx, files_config); + } + std::vector users_c = usersToVector( + ctx, + ctx.jObject2jArray(users) + ); + std::vector managers_c = usersToVector( + ctx, + ctx.jObject2jArray(managers) + ); + return ctx->NewStringUTF( + getInboxApi(ctx, thiz)->createInbox( + ctx.jString2string(context_id), + users_c, + managers_c, + core::Buffer::from(ctx.jByteArray2String(public_meta)), + core::Buffer::from(ctx.jByteArray2String(private_meta)), + files_config_c + ).c_str() + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_updateInbox( + JNIEnv *env, + jobject thiz, + jstring inbox_id, + jobject users, + jobject managers, + jbyteArray public_meta, + jbyteArray private_meta, + jobject files_config, + jlong version, + jboolean force, + jboolean force_generate_new_key +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(inbox_id, "Inbox ID") || + ctx.nullCheck(users, "Users list") || + ctx.nullCheck(managers, "Managers list") || + ctx.nullCheck(public_meta, "Public meta") || + ctx.nullCheck(private_meta, "Private meta")) { + return; + } + + try { + std::optional files_config_c = std::nullopt; + if (files_config != nullptr) { + files_config_c = parseFilesConfig(ctx, files_config); + } + std::vector users_c = usersToVector( + ctx, + ctx.jObject2jArray(users) + ); + std::vector managers_c = usersToVector( + ctx, + ctx.jObject2jArray(managers) + ); + getInboxApi(ctx, thiz)->updateInbox( + ctx.jString2string(inbox_id), + users_c, + managers_c, + core::Buffer::from(ctx.jByteArray2String(public_meta)), + core::Buffer::from(ctx.jByteArray2String(private_meta)), + files_config_c, + version, + force == JNI_TRUE, + force_generate_new_key == JNI_TRUE + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_getInbox( + JNIEnv *env, + jobject thiz, + jstring inbox_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(inbox_id, "Inbox ID")) { + return nullptr; + } + try { + return privmx::wrapper::inbox2Java( + ctx, + getInboxApi(ctx, thiz)->getInbox( + ctx.jString2string(inbox_id) + ) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_listInboxes( + JNIEnv *env, + jobject thiz, + jstring context_id, + jlong skip, + jlong limit, + jstring sort_order, + jstring last_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(context_id, "Context ID") || + ctx.nullCheck(sort_order, "Sort order")) { + return nullptr; + } + + jclass pagingListCls = env->FindClass( + "com/simplito/java/privmx_endpoint/model/PagingList"); + jmethodID pagingListInitMID = env->GetMethodID(pagingListCls, "", + "(Ljava/lang/Long;Ljava/util/List;)V"); + jclass arrayCls = env->FindClass("java/util/ArrayList"); + jmethodID initArrayMID = env->GetMethodID(arrayCls, "", "()V"); + jmethodID addToArrayMID = env->GetMethodID(arrayCls, "add", "(Ljava/lang/Object;)Z"); + auto query = core::PagingQuery(); + query.skip = skip; + query.limit = limit; + query.sortOrder = ctx.jString2string(sort_order); + if (last_id != nullptr) { + query.lastId = ctx.jString2string(last_id); + } + try { + auto inboxes_c( + getInboxApi(ctx, thiz)->listInboxes( + ctx.jString2string(context_id), + query + ) + ); + jobject array = env->NewObject(arrayCls, initArrayMID); + for (auto &inbox_c: inboxes_c.readItems) { + env->CallBooleanMethod(array, + addToArrayMID, + privmx::wrapper::inbox2Java(ctx, inbox_c) + ); + } + return ctx->NewObject( + pagingListCls, + pagingListInitMID, + ctx.long2jLong(inboxes_c.totalAvailable), + array + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_getInboxPublicView( + JNIEnv *env, + jobject thiz, + jstring inbox_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(inbox_id, "Inbox ID")) { + return nullptr; + } + try { + return privmx::wrapper::inboxPublicView2Java( + ctx, + getInboxApi(ctx, thiz)->getInboxPublicView( + ctx.jString2string(inbox_id) + ) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_deleteInbox( + JNIEnv *env, + jobject thiz, + jstring inbox_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(inbox_id, "Inbox ID")) { + return; + } + try { + getInboxApi(ctx, thiz)->deleteInbox( + ctx.jString2string(inbox_id) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_prepareEntry( + JNIEnv *env, + jobject thiz, + jstring inbox_id, + jbyteArray data, + jobject inbox_file_handles, + jstring user_priv_key +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(inbox_id, "Inbox ID") || + ctx.nullCheck(data, "Data") || + ctx.nullCheck(inbox_file_handles, "File handles list")) { + return nullptr; + } + try { + std::optional user_priv_key_c = std::nullopt; + if (user_priv_key != nullptr) { + user_priv_key_c = ctx.jString2string(user_priv_key); + } + auto files_handles_arr = ctx.jObject2jArray(inbox_file_handles); + auto file_handles_c = std::vector(); + for (int i = 0; i < ctx->GetArrayLength(files_handles_arr); i++) { + jobject arrayElement = ctx->GetObjectArrayElement(files_handles_arr, i); + file_handles_c.push_back(ctx.getObject(arrayElement).getLongValue()); + } + return ctx.long2jLong( + getInboxApi(ctx, thiz)->prepareEntry( + ctx.jString2string(inbox_id), + core::Buffer::from(ctx.jByteArray2String(data)), + file_handles_c, + user_priv_key_c + ) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_sendEntry( + JNIEnv *env, + jobject thiz, + jlong inbox_handle +) { + JniContextUtils ctx(env); + try { + getInboxApi(ctx, thiz)->sendEntry(inbox_handle); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_readEntry( + JNIEnv *env, + jobject thiz, + jstring inbox_entry_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(inbox_entry_id, "Inbox Entry ID")) { + return nullptr; + } + try { + return privmx::wrapper::inboxEntry2Java( + ctx, + getInboxApi(ctx, thiz)->readEntry( + ctx.jString2string(inbox_entry_id) + ) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_listEntries( + JNIEnv *env, + jobject thiz, + jstring inbox_id, + jlong skip, + jlong limit, + jstring sort_order, + jstring last_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(inbox_id, "Inbox ID") || + ctx.nullCheck(sort_order, "Sort order")) { + return nullptr; + } + jclass pagingListCls = env->FindClass( + "com/simplito/java/privmx_endpoint/model/PagingList"); + jmethodID pagingListInitMID = env->GetMethodID(pagingListCls, "", + "(Ljava/lang/Long;Ljava/util/List;)V"); + jclass arrayCls = env->FindClass("java/util/ArrayList"); + jmethodID initArrayMID = env->GetMethodID(arrayCls, "", "()V"); + jmethodID addToArrayMID = env->GetMethodID(arrayCls, "add", "(Ljava/lang/Object;)Z"); + auto query = core::PagingQuery(); + query.skip = skip; + query.limit = limit; + query.sortOrder = ctx.jString2string(sort_order); + if (last_id != nullptr) { + query.lastId = ctx.jString2string(last_id); + } + try { + auto entries_c( + getInboxApi(ctx, thiz)->listEntries( + ctx.jString2string(inbox_id), + query + ) + ); + jobject array = env->NewObject(arrayCls, initArrayMID); + for (auto &entry_c: entries_c.readItems) { + env->CallBooleanMethod(array, + addToArrayMID, + privmx::wrapper::inboxEntry2Java(ctx, entry_c) + ); + } + return ctx->NewObject( + pagingListCls, + pagingListInitMID, + ctx.long2jLong(entries_c.totalAvailable), + array + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_deleteEntry( + JNIEnv *env, + jobject thiz, + jstring inbox_entry_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(inbox_entry_id, "Inbox Entry ID")) { + return; + } + try { + getInboxApi(ctx, thiz)->deleteEntry(ctx.jString2string(inbox_entry_id)); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_createFileHandle( + JNIEnv *env, + jobject thiz, + jbyteArray public_meta, + jbyteArray private_meta, + jlong file_size +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(public_meta, "Public Meta") || + ctx.nullCheck(private_meta, "Private Meta")) { + return nullptr; + } + try { + return ctx.long2jLong( + getInboxApi(ctx, thiz)->createFileHandle( + core::Buffer::from(ctx.jByteArray2String(public_meta)), + core::Buffer::from(ctx.jByteArray2String(private_meta)), + file_size + ) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_writeToFile( + JNIEnv *env, + jobject thiz, + jlong inbox_handle, + jlong inbox_file_handle, + jbyteArray data_chunk +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(data_chunk, "Data chunk")) { + return; + } + try { + auto data_chunk_c = ctx.jByteArray2String(data_chunk); + getInboxApi(ctx, thiz)->writeToFile( + inbox_handle, + inbox_file_handle, + core::Buffer::from(data_chunk_c) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_openFile( + JNIEnv *env, + jobject thiz, + jstring file_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(file_id, "File ID")) { + return nullptr; + } + try { + return ctx.long2jLong( + (jlong) getInboxApi(ctx, thiz)->openFile( + ctx.jString2string(file_id) + ) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT jbyteArray JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_readFromFile( + JNIEnv *env, + jobject thiz, + jlong file_handle, + jlong length +) { + JniContextUtils ctx(env); + try { + auto data_c = getInboxApi(ctx, thiz)->readFromFile(file_handle, length).stdString(); + jbyteArray data = ctx->NewByteArray(data_c.length()); + ctx->SetByteArrayRegion( + data, + 0, + data_c.length(), + (jbyte *) data_c.c_str() + ); + return data; + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_seekInFile( + JNIEnv *env, + jobject thiz, + jlong file_handle, + jlong position +) { + JniContextUtils ctx(env); + try { + getInboxApi(ctx, thiz)->seekInFile( + file_handle, + position + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT jstring JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_closeFile( + JNIEnv *env, + jobject thiz, + jlong file_handle +) { + JniContextUtils ctx(env); + try { + return ctx->NewStringUTF( + getInboxApi(ctx, thiz)->closeFile(file_handle) + .c_str() + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_subscribeForInboxEvents( + JNIEnv *env, + jobject thiz +) { + JniContextUtils ctx(env); + try { + getInboxApi(ctx, thiz)->subscribeForInboxEvents(); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_unsubscribeFromInboxEvents( + JNIEnv *env, + jobject thiz +) { + JniContextUtils ctx(env); + try { + getInboxApi(ctx, thiz)->unsubscribeFromInboxEvents(); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_subscribeForEntryEvents( + JNIEnv *env, + jobject thiz, + jstring inbox_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(inbox_id, "Inbox ID")) { + return; + } + try { + getInboxApi(ctx, thiz)->subscribeForEntryEvents( + ctx.jString2string(inbox_id) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_inbox_InboxApi_unsubscribeFromEntryEvents( + JNIEnv *env, + jobject thiz, + jstring inbox_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(inbox_id, "Inbox ID")) { + return; + } + try { + getInboxApi(ctx, thiz)->unsubscribeFromEntryEvents( + ctx.jString2string(inbox_id) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} \ No newline at end of file diff --git a/privmx-endpoint/src/main/cpp/modules/StoreApi.cpp b/privmx-endpoint/src/main/cpp/modules/StoreApi.cpp new file mode 100644 index 0000000..399f164 --- /dev/null +++ b/privmx-endpoint/src/main/cpp/modules/StoreApi.cpp @@ -0,0 +1,985 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#include +#include +#include +#include "Connection.h" +#include "StoreApi.h" +#include "../utils.hpp" +#include "../parser.h" +#include "../exceptions.h" + +using namespace privmx::endpoint; + +store::StoreApi *getStoreApi(JniContextUtils &ctx, jobject storeApiInstance) { + jclass cls = ctx->GetObjectClass(storeApiInstance); + jfieldID apiFID = ctx->GetFieldID(cls, "api", "Ljava/lang/Long;"); + jobject apiLong = ctx->GetObjectField(storeApiInstance, apiFID); + if (apiLong == nullptr) { + throw IllegalStateException("StoreApi cannot be used"); + } + return (store::StoreApi *) ctx.getObject(apiLong).getLongValue(); +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_init( + JNIEnv *env, + jobject thiz, + jobject connection +) { + JniContextUtils ctx(env); + try { + auto connection_c = getConnection(env, connection); + auto storeApi = store::StoreApi::create(*connection_c); + auto storeApi_ptr = new store::StoreApi(); + *storeApi_ptr = storeApi; + return ctx.long2jLong((jlong) storeApi_ptr); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_deinit( + JNIEnv *env, + jobject thiz +) { + try { + JniContextUtils ctx(env); + //if null go to catch + auto api = getStoreApi(ctx, thiz); + delete api; + jclass cls = env->GetObjectClass(thiz); + jfieldID apiFID = env->GetFieldID(cls, "api", "Ljava/lang/Long;"); + env->SetObjectField(thiz, apiFID, (jobject) nullptr); + } catch (const IllegalStateException &e) { + env->ThrowNew( + env->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_listStores( + JNIEnv *env, + jobject thiz, + jstring context_id, + jlong skip, + jlong limit, + jstring sort_order, + jstring last_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(sort_order, "Sort order") || + ctx.nullCheck(context_id, "Context ID")) { + return nullptr; + } + jclass pagingListCls = env->FindClass( + "com/simplito/java/privmx_endpoint/model/PagingList"); + jmethodID pagingListInitMID = env->GetMethodID(pagingListCls, "", + "(Ljava/lang/Long;Ljava/util/List;)V" + ); + jclass arrayCls = env->FindClass("java/util/ArrayList"); + jmethodID initArrayMID = env->GetMethodID(arrayCls, "", "()V"); + jmethodID addToArrayMID = env->GetMethodID(arrayCls, "add", "(Ljava/lang/Object;)Z"); + auto query = core::PagingQuery(); + query.skip = skip; + query.limit = limit; + query.sortOrder = ctx.jString2string(sort_order); + if (last_id != nullptr) { + query.lastId = ctx.jString2string(last_id); + } + try { + auto stores_c( + getStoreApi(ctx, thiz)->listStores( + ctx.jString2string(context_id), + query + ) + ); + jobject array = env->NewObject(arrayCls, initArrayMID); + for (auto &store_c: stores_c.readItems) { + env->CallBooleanMethod(array, + addToArrayMID, + privmx::wrapper::store2Java(ctx, store_c) + ); + } + return ctx->NewObject( + pagingListCls, + pagingListInitMID, + ctx.long2jLong(stores_c.totalAvailable), + array + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_getStore( + JNIEnv *env, + jobject thiz, + jstring store_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(store_id, "Store ID")) { + return nullptr; + } + try { + auto store_c( + getStoreApi(ctx, thiz)->getStore( + ctx.jString2string(store_id) + ) + ); + return privmx::wrapper::store2Java(ctx, store_c); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + + +extern "C" +JNIEXPORT jstring JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_createStore( + JNIEnv *env, + jobject thiz, + jstring context_id, + jobject users, + jobject managers, + jbyteArray public_meta, + jbyteArray private_meta +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(context_id, "Context ID") || + ctx.nullCheck(users, "Users list") || + ctx.nullCheck(managers, "Managers list") || + ctx.nullCheck(public_meta, "Public meta") || + ctx.nullCheck(private_meta, "Private meta")) { + return nullptr; + } + try { + std::vector managers_c = usersToVector( + ctx, + ctx.jObject2jArray(managers) + ); + std::vector users_c = usersToVector( + ctx, + ctx.jObject2jArray(users) + ); + return env->NewStringUTF( + getStoreApi(ctx, thiz)->createStore( + ctx.jString2string(context_id), + users_c, + managers_c, + core::Buffer::from(ctx.jByteArray2String(public_meta)), + core::Buffer::from(ctx.jByteArray2String(private_meta)) + ).c_str() + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_getFile( + JNIEnv *env, + jobject thiz, + jstring file_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(file_id, "File ID")) { + return nullptr; + } + try { + auto file_c( + getStoreApi(ctx, thiz)->getFile( + ctx.jString2string(file_id) + ) + ); + return privmx::wrapper::file2Java(ctx, file_c); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_listFiles( + JNIEnv *env, + jobject thiz, + jstring store_id, + jlong skip, + jlong limit, + jstring sort_order, + jstring last_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(store_id, "Store ID") || + ctx.nullCheck(sort_order, "Sort order")) { + return nullptr; + } + + jclass pagingListCls = env->FindClass( + "com/simplito/java/privmx_endpoint/model/PagingList"); + jmethodID pagingListInitMID = env->GetMethodID(pagingListCls, "", + "(Ljava/lang/Long;Ljava/util/List;)V" + ); + jclass arrayCls = env->FindClass("java/util/ArrayList"); + jmethodID initArrayMID = env->GetMethodID(arrayCls, "", "()V"); + jmethodID addToArrayMID = env->GetMethodID(arrayCls, "add", "(Ljava/lang/Object;)Z"); + auto query = core::PagingQuery(); + query.skip = skip; + query.limit = limit; + query.sortOrder = ctx.jString2string(sort_order); + if (last_id != nullptr) { + query.lastId = ctx.jString2string(last_id); + } + try { + auto files_c( + getStoreApi(ctx, thiz)->listFiles( + ctx.jString2string(store_id), + query + ) + ); + jobject array = env->NewObject(arrayCls, initArrayMID); + for (auto &file_c: files_c.readItems) { + env->CallBooleanMethod(array, + addToArrayMID, + privmx::wrapper::file2Java(ctx, file_c) + ); + } + return ctx->NewObject( + pagingListCls, + pagingListInitMID, + ctx.long2jLong(files_c.totalAvailable), + array + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_deleteFile( + JNIEnv *env, + jobject thiz, + jstring file_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(file_id, "File ID")) { + return; + } + try { + return getStoreApi(ctx, thiz)->deleteFile( + ctx.jString2string(file_id) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_deleteStore( + JNIEnv *env, + jobject thiz, + jstring store_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(store_id, "Store ID")) { + return; + } + try { + getStoreApi(ctx, thiz)->deleteStore( + ctx.jString2string(store_id) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_createFile( + JNIEnv *env, jobject thiz, + jstring store_id, + jbyteArray public_meta, + jbyteArray private_meta, + jlong size +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(store_id, "Store ID") || + ctx.nullCheck(public_meta, "Public meta") || + ctx.nullCheck(private_meta, "Private meta")) { + return nullptr; + } + try { + return ctx.long2jLong( + (jlong) getStoreApi(ctx, thiz)->createFile( + ctx.jString2string(store_id), + core::Buffer::from(ctx.jByteArray2String(public_meta)), + core::Buffer::from(ctx.jByteArray2String(private_meta)), + size + ) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_updateFile( + JNIEnv *env, + jobject thiz, + jstring file_id, + jbyteArray public_meta, + jbyteArray private_meta, + jlong size +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(file_id, "File ID") || + ctx.nullCheck(public_meta, "Public meta") || + ctx.nullCheck(private_meta, "Private meta")) { + return nullptr; + } + try { + return ctx.long2jLong( + (jlong) getStoreApi(ctx, thiz)->updateFile( + ctx.jString2string(file_id), + core::Buffer::from(ctx.jByteArray2String(public_meta)), + core::Buffer::from(ctx.jByteArray2String(private_meta)), + size + ) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_updateFileMeta( + JNIEnv *env, + jobject thiz, + jstring file_id, + jbyteArray public_meta, + jbyteArray private_meta +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(file_id, "File ID") || + ctx.nullCheck(public_meta, "Public meta") || + ctx.nullCheck(private_meta, "Private meta")) { + return; + } + try { + getStoreApi(ctx, thiz)->updateFileMeta( + ctx.jString2string(file_id), + core::Buffer::from(ctx.jByteArray2String(public_meta)), + core::Buffer::from(ctx.jByteArray2String(private_meta)) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_writeToFile( + JNIEnv *env, + jobject thiz, + jlong file_handle, + jbyteArray data_chunk +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(data_chunk, "Data chunk")) { + return; + } + try { + auto data_chunk_c = ctx.jByteArray2String(data_chunk); + getStoreApi(ctx, thiz)->writeToFile( + file_handle, + core::Buffer::from(data_chunk_c) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_updateStore( + JNIEnv *env, + jobject thiz, + jstring store_id, + jobject users, + jobject managers, + jbyteArray public_meta, + jbyteArray private_meta, + jlong version, + jboolean force, + jboolean force_generate_new_key +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(store_id, "Store ID") || + ctx.nullCheck(users, "Users list") || + ctx.nullCheck(managers, "Managers list") || + ctx.nullCheck(public_meta, "Public meta") || + ctx.nullCheck(private_meta, "Private meta")) { + return; + } + try { + std::vector users_c = usersToVector( + ctx, + ctx.jObject2jArray(users) + ); + std::vector managers_c = usersToVector( + ctx, + ctx.jObject2jArray(managers) + ); + + getStoreApi(ctx, thiz)->updateStore( + ctx.jString2string(store_id), + users_c, + managers_c, + core::Buffer::from(ctx.jByteArray2String(public_meta)), + core::Buffer::from(ctx.jByteArray2String(private_meta)), + version, + force == JNI_TRUE, + force_generate_new_key == JNI_TRUE + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_openFile( + JNIEnv *env, + jobject thiz, + jstring file_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(file_id, "File ID")) { + return nullptr; + } + try { + return ctx.long2jLong( + (jlong) getStoreApi(ctx, thiz)->openFile( + ctx.jString2string(file_id) + ) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT jbyteArray JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_readFromFile( + JNIEnv *env, + jobject thiz, + jlong file_handle, + jlong length +) { + JniContextUtils ctx(env); + try { + auto data_c = getStoreApi(ctx, thiz)->readFromFile(file_handle, length).stdString(); + jbyteArray data = ctx->NewByteArray(data_c.length()); + ctx->SetByteArrayRegion( + data, + 0, + data_c.length(), + (jbyte *) data_c.c_str() + ); + return data; + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_seekInFile( + JNIEnv *env, + jobject thiz, + jlong file_handle, + jlong position +) { + JniContextUtils ctx(env); + try { + getStoreApi(ctx, thiz)->seekInFile( + file_handle, + position + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT jstring JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_closeFile( + JNIEnv *env, + jobject thiz, + jlong file_handle +) { + JniContextUtils ctx(env); + try { + return ctx->NewStringUTF( + getStoreApi(ctx, thiz)->closeFile(file_handle) + .c_str() + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_subscribeForStoreEvents( + JNIEnv *env, + jobject thiz +) { + JniContextUtils ctx(env); + try { + getStoreApi(ctx, thiz)->subscribeForStoreEvents(); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_unsubscribeFromStoreEvents( + JNIEnv *env, + jobject thiz +) { + JniContextUtils ctx(env); + try { + getStoreApi(ctx, thiz)->unsubscribeFromStoreEvents(); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_subscribeForFileEvents( + JNIEnv *env, + jobject thiz, + jstring store_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(store_id, "Store ID")) { + return; + } + try { + getStoreApi(ctx, thiz)->subscribeForFileEvents( + ctx.jString2string(store_id) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_store_StoreApi_unsubscribeFromFileEvents( + JNIEnv *env, + jobject thiz, + jstring store_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(store_id, "Store ID")) { + return; + } + try { + getStoreApi(ctx, thiz)->unsubscribeFromFileEvents( + ctx.jString2string(store_id) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} \ No newline at end of file diff --git a/privmx-endpoint/src/main/cpp/modules/StoreApi.h b/privmx-endpoint/src/main/cpp/modules/StoreApi.h new file mode 100644 index 0000000..3399a5f --- /dev/null +++ b/privmx-endpoint/src/main/cpp/modules/StoreApi.h @@ -0,0 +1,21 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#include +#include +#include "../utils.hpp" + +#ifndef PRIVMXENDPOINT_STOREAPI_H +#define PRIVMXENDPOINT_STOREAPI_H + +#endif //PRIVMXENDPOINT_STOREAPI_H + +privmx::endpoint::store::StoreApi *getStoreApi(JniContextUtils &ctx, jobject storeApiInstance); \ No newline at end of file diff --git a/privmx-endpoint/src/main/cpp/modules/ThreadApi.cpp b/privmx-endpoint/src/main/cpp/modules/ThreadApi.cpp new file mode 100644 index 0000000..e383537 --- /dev/null +++ b/privmx-endpoint/src/main/cpp/modules/ThreadApi.cpp @@ -0,0 +1,747 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#include +#include +#include +#include "Connection.h" +#include "ThreadApi.h" +#include "../utils.hpp" +#include "../parser.h" +#include "../exceptions.h" +#include "Connection.h" + +using namespace privmx::endpoint; + +thread::ThreadApi *getThreadApi(JniContextUtils &ctx, jobject threadApiInstance) { + jclass cls = ctx->GetObjectClass(threadApiInstance); + jfieldID apiFID = ctx->GetFieldID(cls, "api", "Ljava/lang/Long;"); + jobject apiLong = ctx->GetObjectField(threadApiInstance, apiFID); + if (apiLong == nullptr) { + throw IllegalStateException("ThreadApi cannot be used"); + } + return (thread::ThreadApi *) ctx.getObject(apiLong).getLongValue(); +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_thread_ThreadApi_init( + JNIEnv *env, + jobject thiz, + jobject connection +) { + JniContextUtils ctx(env); + try { + auto connection_c = getConnection(env, connection); + auto threadApi = thread::ThreadApi::create(*connection_c); + auto threadApi_ptr = new thread::ThreadApi(); + *threadApi_ptr = threadApi; + return ctx.long2jLong((jlong) threadApi_ptr); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_thread_ThreadApi_deinit(JNIEnv *env, + jobject thiz) { + try { + JniContextUtils ctx(env); + //if null go to catch + auto api = getThreadApi(ctx, thiz); + delete api; + jclass cls = env->GetObjectClass(thiz); + jfieldID apiFID = env->GetFieldID(cls, "api", "Ljava/lang/Long;"); + env->SetObjectField(thiz, apiFID, (jobject) nullptr); + } catch (const IllegalStateException &e) { + env->ThrowNew( + env->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } +} + +extern "C" +JNIEXPORT jstring JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_thread_ThreadApi_createThread( + JNIEnv *env, jobject thiz, + jstring context_id, + jobject users, + jobject managers, + jbyteArray public_meta, + jbyteArray private_meta +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(context_id, "Context ID") || + ctx.nullCheck(users, "Users list") || + ctx.nullCheck(managers, "Managers list") || + ctx.nullCheck(public_meta, "Public meta") || + ctx.nullCheck(private_meta, "Private meta")) { + return nullptr; + } + try { + std::vector users_c = usersToVector( + ctx, + ctx.jObject2jArray(users) + ); + std::vector managers_c = usersToVector( + ctx, + ctx.jObject2jArray(managers) + ); + return ctx->NewStringUTF( + getThreadApi(ctx, thiz)->createThread( + ctx.jString2string(context_id), + users_c, + managers_c, + core::Buffer::from(ctx.jByteArray2String(public_meta)), + core::Buffer::from(ctx.jByteArray2String(private_meta)) + ).c_str() + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_thread_ThreadApi_getThread( + JNIEnv *env, + jobject thiz, + jstring thread_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(thread_id, "Thread ID")) { + return nullptr; + } + try { + thread::Thread thread_c = getThreadApi(ctx, thiz)->getThread( + ctx.jString2string(thread_id) + ); + return privmx::wrapper::thread2Java(ctx, thread_c); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_thread_ThreadApi_listThreads( + JNIEnv *env, + jobject thiz, + jstring context_id, + jlong skip, + jlong limit, + jstring sort_order, + jstring last_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(context_id, "Context ID") || + ctx.nullCheck(sort_order, "Sort order")) { + return nullptr; + } + + jclass pagingListCls = env->FindClass( + "com/simplito/java/privmx_endpoint/model/PagingList"); + jmethodID pagingListInitMID = env->GetMethodID(pagingListCls, "", + "(Ljava/lang/Long;Ljava/util/List;)V" + ); + jclass arrayCls = env->FindClass("java/util/ArrayList"); + jmethodID initArrayMID = env->GetMethodID( + arrayCls, + "", + "()V" + ); + jmethodID addToArrayMID = env->GetMethodID( + arrayCls, + "add", + "(Ljava/lang/Object;)Z" + ); + try { + auto query = core::PagingQuery(); + query.skip = skip; + query.limit = limit; + query.sortOrder = ctx.jString2string(sort_order); + if (last_id != nullptr) { + query.lastId = ctx.jString2string(last_id); + } + core::PagingList + threads_c = getThreadApi(ctx, thiz)->listThreads( + ctx.jString2string(context_id), + query + ); + jobject array = env->NewObject(arrayCls, initArrayMID); + for (auto &thread_c: threads_c.readItems) { + env->CallBooleanMethod( + array, + addToArrayMID, + privmx::wrapper::thread2Java(ctx, thread_c) + ); + } + return ctx->NewObject( + pagingListCls, + pagingListInitMID, + ctx.long2jLong(threads_c.totalAvailable), + array + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT jstring JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_thread_ThreadApi_sendMessage( + JNIEnv *env, + jobject thiz, + jstring thread_id, + jbyteArray public_meta, + jbyteArray private_meta, + jbyteArray data +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(thread_id, "Thread ID") || + ctx.nullCheck(public_meta, "Public meta") || + ctx.nullCheck(private_meta, "Private meta") || + ctx.nullCheck(data, "Data")) { + return nullptr; + } + try { + return env->NewStringUTF( + getThreadApi(ctx, thiz)->sendMessage( + ctx.jString2string(thread_id), + core::Buffer::from(ctx.jByteArray2String(public_meta)), + core::Buffer::from(ctx.jByteArray2String(private_meta)), + core::Buffer::from(ctx.jByteArray2String(data)) + ).c_str() + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_thread_ThreadApi_listMessages( + JNIEnv *env, + jobject thiz, + jstring thread_id, + jlong skip, + jlong limit, + jstring sort_order, + jstring last_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(thread_id, "Thread ID") || + ctx.nullCheck(sort_order, "Sort order")) { + return nullptr; + } + try { + jclass pagingListCls = env->FindClass( + "com/simplito/java/privmx_endpoint/model/PagingList"); + jmethodID pagingListInitMID = env->GetMethodID(pagingListCls, "", + "(Ljava/lang/Long;Ljava/util/List;)V" + ); + jclass arrayCls = env->FindClass("java/util/ArrayList"); + jmethodID initArrayMID = env->GetMethodID(arrayCls, "", "()V"); + jmethodID addToArrayMID = env->GetMethodID(arrayCls, "add", "(Ljava/lang/Object;)Z"); + auto query = core::PagingQuery(); + query.skip = skip; + query.limit = limit; + query.sortOrder = ctx.jString2string(sort_order); + if (last_id != nullptr) { + query.lastId = ctx.jString2string(last_id); + } + core::PagingList messages_c = getThreadApi(ctx, thiz)->listMessages( + ctx.jString2string(thread_id), + query + ); + jobject array = env->NewObject(arrayCls, initArrayMID); + for (auto &threadMessage_c: messages_c.readItems) { + env->CallBooleanMethod(array, + addToArrayMID, + privmx::wrapper::message2Java(ctx, threadMessage_c) + ); + } + return ctx->NewObject( + pagingListCls, + pagingListInitMID, + ctx.long2jLong(messages_c.totalAvailable), + array + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_thread_ThreadApi_deleteThread( + JNIEnv *env, + jobject thiz, + jstring thread_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(thread_id, "Thread ID")) { + return; + } + try { + getThreadApi(ctx, thiz)->deleteThread( + ctx.jString2string(thread_id) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_thread_ThreadApi_deleteMessage( + JNIEnv *env, + jobject thiz, + jstring message_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(message_id, "Message ID")) { + return; + } + try { + getThreadApi(ctx, thiz)->deleteMessage( + ctx.jString2string(message_id) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_thread_ThreadApi_updateThread( + JNIEnv *env, + jobject thiz, + jstring thread_id, + jobject users, + jobject managers, + jbyteArray public_meta, + jbyteArray private_meta, + jlong version, + jboolean force, + jboolean force_generate_new_key +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(thread_id, "Thread ID") || + ctx.nullCheck(users, "Users list") || + ctx.nullCheck(managers, "Managers list") || + ctx.nullCheck(public_meta, "Public meta") || + ctx.nullCheck(private_meta, "Private meta")) { + return; + } + try { + std::vector users_c = usersToVector( + ctx, + ctx.jObject2jArray(users) + ); + std::vector managers_c = usersToVector( + ctx, + ctx.jObject2jArray(managers) + ); + getThreadApi(ctx, thiz)->updateThread( + ctx.jString2string(thread_id), + users_c, + managers_c, + core::Buffer::from(ctx.jByteArray2String(public_meta)), + core::Buffer::from(ctx.jByteArray2String(private_meta)), + version, + force == JNI_TRUE, + force_generate_new_key == JNI_TRUE + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_thread_ThreadApi_getMessage( + JNIEnv *env, + jobject thiz, + jstring message_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(message_id, "Message ID")) { + return nullptr; + } + try { + return privmx::wrapper::message2Java( + ctx, + getThreadApi(ctx, thiz)->getMessage( + ctx.jString2string(message_id) + ) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } + return nullptr; +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_thread_ThreadApi_updateMessage( + JNIEnv *env, + jobject thiz, + jstring message_id, + jbyteArray public_meta, + jbyteArray private_meta, + jbyteArray data +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(message_id, "Message ID") || + ctx.nullCheck(public_meta, "Public meta") || + ctx.nullCheck(private_meta, "Private meta") || + ctx.nullCheck(data, "Data")) { + return; + } + try { + getThreadApi(ctx, thiz)->updateMessage( + ctx.jString2string(message_id), + core::Buffer::from(ctx.jByteArray2String(public_meta)), + core::Buffer::from(ctx.jByteArray2String(private_meta)), + core::Buffer::from(ctx.jByteArray2String(data)) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_thread_ThreadApi_subscribeForThreadEvents( + JNIEnv *env, + jobject thiz +) { + JniContextUtils ctx(env); + try { + getThreadApi(ctx, thiz)->subscribeForThreadEvents(); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_thread_ThreadApi_unsubscribeFromThreadEvents( + JNIEnv *env, + jobject thiz +) { + JniContextUtils ctx(env); + try { + getThreadApi(ctx, thiz)->unsubscribeFromThreadEvents(); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_thread_ThreadApi_subscribeForMessageEvents( + JNIEnv *env, + jobject thiz, + jstring thread_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(thread_id, "Thread ID")) { + return; + } + try { + getThreadApi(ctx, thiz)->subscribeForMessageEvents( + ctx.jString2string(thread_id) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} +extern "C" +JNIEXPORT void JNICALL +Java_com_simplito_java_privmx_1endpoint_modules_thread_ThreadApi_unsubscribeFromMessageEvents( + JNIEnv *env, + jobject thiz, + jstring thread_id +) { + JniContextUtils ctx(env); + if (ctx.nullCheck(thread_id, "Thread ID")) { + return; + } + try { + getThreadApi(ctx, thiz)->unsubscribeFromMessageEvents( + ctx.jString2string(thread_id) + ); + } catch (const core::Exception &e) { + env->Throw(ctx.coreException2jthrowable(e)); + } catch (const IllegalStateException &e) { + ctx->ThrowNew( + ctx->FindClass("java/lang/IllegalStateException"), + e.what() + ); + } catch (const std::exception &e) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + e.what() + ); + } catch (...) { + env->ThrowNew( + env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/NativeException"), + "Unknown exception" + ); + } +} \ No newline at end of file diff --git a/privmx-endpoint/src/main/cpp/modules/ThreadApi.h b/privmx-endpoint/src/main/cpp/modules/ThreadApi.h new file mode 100644 index 0000000..68c8848 --- /dev/null +++ b/privmx-endpoint/src/main/cpp/modules/ThreadApi.h @@ -0,0 +1,21 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#include +#include +#include "../utils.hpp" + +#ifndef PRIVMXENDPOINT_THREADAPI_H +#define PRIVMXENDPOINT_THREADAPI_H + +#endif //PRIVMXENDPOINT_THREADAPI_H + +privmx::endpoint::thread::ThreadApi *getThreadApi(JniContextUtils &ctx, jobject threadApiInstance); \ No newline at end of file diff --git a/privmx-endpoint/src/main/cpp/parser.cpp b/privmx-endpoint/src/main/cpp/parser.cpp new file mode 100644 index 0000000..4ab9894 --- /dev/null +++ b/privmx-endpoint/src/main/cpp/parser.cpp @@ -0,0 +1,365 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#include "parser.h" + +using namespace privmx::endpoint; + +std::vector +usersToVector(JniContextUtils &ctx, jobjectArray users) { + std::vector users_c; + for (int i = 0; i < ctx->GetArrayLength(users); i++) { + + jobject arrayElement = ctx->GetObjectArrayElement(users, i); + jclass arrayElementCls = ctx->GetObjectClass(arrayElement); + + jfieldID pubKeyFID = ctx->GetFieldID(arrayElementCls, "pubKey", "Ljava/lang/String;"); + jfieldID userIdFID = ctx->GetFieldID(arrayElementCls, "userId", "Ljava/lang/String;"); + privmx::endpoint::core::UserWithPubKey user = privmx::endpoint::core::UserWithPubKey(); + user.userId = ctx.jString2string( + (jstring) ctx->GetObjectField(arrayElement, userIdFID)); + user.pubKey = ctx.jString2string( + (jstring) ctx->GetObjectField(arrayElement, pubKeyFID)); + + users_c.push_back(user); + } + return users_c; +} + +//privmx::endpoint::inbox::InboxCreateMeta +//parseInboxCreateMeta(JniContextUtils &ctx, jobject inboxCreateMeta) { +// auto result = privmx::endpoint::inbox::InboxCreateMeta(); +// jclass inboxCreateMetaCls = ctx->FindClass( +// "com/simplito/java/privmx_endpoint/model/InboxCreateMeta"); +// jfieldID nameFID = ctx->GetFieldID(inboxCreateMetaCls, "name", "Ljava/lang/String;"); +// jfieldID customDataFID = ctx->GetFieldID(inboxCreateMetaCls, "customData", "[B"); +// result.name = ctx.jString2string( +// (jstring) ctx->GetObjectField(inboxCreateMeta, nameFID) +// ); +// result.customData = core::Buffer::from( +// ctx.jByteArray2String( +// (jbyteArray) ctx->GetObjectField(inboxCreateMeta, customDataFID) +// ) +// ); +// return result; +//} +// +//privmx::endpoint::inbox::InboxOptions +//parseInboxOptions(JniContextUtils &ctx, jobject inboxOptions) { +// auto result = privmx::endpoint::inbox::InboxOptions(); +// jclass inboxCreateMetaCls = ctx->FindClass( +// "com/simplito/java/privmx_endpoint/model/InboxOptions"); +// jfieldID fileConfigFID = ctx->GetFieldID(inboxCreateMetaCls, "fileConfig", +// "Lcom/simplito/java/privmx_endpoint/model/FileConfig;"); +// jfieldID publicCustomDataFID = ctx->GetFieldID(inboxCreateMetaCls, "publicCustomData", "[B"); +// result.fileConfig = parseFileConfig(ctx, ctx->GetObjectField( +// inboxOptions, fileConfigFID) +// ); +// result.publicCustomData = ctx.jByteArray2String( +// (jbyteArray) ctx->GetObjectField(inboxOptions, publicCustomDataFID) +// ); +// return result; +//} + +privmx::endpoint::inbox::FilesConfig parseFilesConfig(JniContextUtils &ctx, jobject filesConfig) { + auto result = privmx::endpoint::inbox::FilesConfig(); + jclass filesConfigCls = ctx->FindClass( + "com/simplito/java/privmx_endpoint/model/FilesConfig"); + jfieldID minCountFID = ctx->GetFieldID(filesConfigCls, "minCount", "Ljava/lang/Long;"); + jfieldID maxCountFID = ctx->GetFieldID(filesConfigCls, "maxCount", "Ljava/lang/Long;"); + jfieldID maxFileSizeFID = ctx->GetFieldID(filesConfigCls, "maxFileSize", "Ljava/lang/Long;"); + jfieldID maxWholeUploadSizeFID = ctx->GetFieldID(filesConfigCls, "maxWholeUploadSize", + "Ljava/lang/Long;"); + result.minCount = (jlong) ctx->GetObjectField(filesConfig, minCountFID); + result.maxCount = (jlong) ctx->GetObjectField(filesConfig, maxCountFID); + result.maxFileSize = (jlong) ctx->GetObjectField(filesConfig, maxFileSizeFID); + result.maxWholeUploadSize = (jlong) ctx->GetObjectField(filesConfig, maxWholeUploadSizeFID); + return result; +} + +jobject initEvent(JniContextUtils &ctx, std::string type, std::string channel, int64_t connectionId, + jobject data_j) { + if (type.empty()) return nullptr; + jclass eventCls = ctx->FindClass("com/simplito/java/privmx_endpoint/model/Event"); + jmethodID eventInitMID = ctx->GetMethodID(eventCls, "", "()V"); + jfieldID eventTypeFieldID = ctx->GetFieldID(eventCls, "type", "Ljava/lang/String;"); + jfieldID eventDataFieldID = ctx->GetFieldID(eventCls, "data", "Ljava/lang/Object;"); + jfieldID eventConnectionIdFieldID = ctx->GetFieldID(eventCls, "connectionId", + "Ljava/lang/Long;"); + jfieldID eventChannelFieldID = ctx->GetFieldID(eventCls, "channel", "Ljava/lang/String;"); + jobject event_j = ctx->NewObject(eventCls, eventInitMID); + ctx->SetObjectField( + event_j, + eventTypeFieldID, + ctx->NewStringUTF(type.c_str()) + ); + ctx->SetObjectField( + event_j, + eventDataFieldID, + data_j + ); + ctx->SetObjectField( + event_j, + eventConnectionIdFieldID, + ctx.long2jLong(connectionId) + ); + ctx->SetObjectField( + event_j, + eventChannelFieldID, + ctx->NewStringUTF(channel.c_str()) + ); + return event_j; +} + +jobject +parseEvent(JniContextUtils &ctx, std::shared_ptr event) { + try { + if (thread::Events::isThreadCreatedEvent(event)) { + privmx::endpoint::thread::ThreadCreatedEvent event_cast = thread::Events::extractThreadCreatedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::thread2Java(ctx, event_cast.data) + ); + } else if (thread::Events::isThreadUpdatedEvent(event)) { + privmx::endpoint::thread::ThreadUpdatedEvent event_cast = thread::Events::extractThreadUpdatedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::thread2Java(ctx, event_cast.data) + ); + } else if (thread::Events::isThreadStatsEvent(event)) { + privmx::endpoint::thread::ThreadStatsChangedEvent event_cast = thread::Events::extractThreadStatsEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::threadStatsEventData2Java(ctx, event_cast.data) + ); + } else if (thread::Events::isThreadDeletedEvent(event)) { + privmx::endpoint::thread::ThreadDeletedEvent event_cast = thread::Events::extractThreadDeletedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::threadDeletedEventData2Java(ctx, event_cast.data) + ); + } else if (thread::Events::isThreadNewMessageEvent(event)) { + privmx::endpoint::thread::ThreadNewMessageEvent event_cast = thread::Events::extractThreadNewMessageEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::message2Java(ctx, event_cast.data) + ); + return nullptr; + } else if (thread::Events::isThreadMessageUpdatedEvent(event)) { + privmx::endpoint::thread::ThreadMessageUpdatedEvent event_cast = thread::Events::extractThreadMessageUpdatedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::message2Java(ctx, event_cast.data) + ); + return nullptr; + } else if (thread::Events::isThreadDeletedMessageEvent(event)) { + privmx::endpoint::thread::ThreadMessageDeletedEvent event_cast = thread::Events::extractThreadMessageDeletedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::threadDeletedMessageEventData2Java(ctx, event_cast.data) + ); + } else if (store::Events::isStoreCreatedEvent(event)) { + privmx::endpoint::store::StoreCreatedEvent event_cast = store::Events::extractStoreCreatedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::store2Java(ctx, event_cast.data) + ); + } else if (store::Events::isStoreUpdatedEvent(event)) { + privmx::endpoint::store::StoreUpdatedEvent event_cast = store::Events::extractStoreUpdatedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::store2Java(ctx, event_cast.data) + ); + } else if (store::Events::isStoreStatsChangedEvent(event)) { + privmx::endpoint::store::StoreStatsChangedEvent event_cast = store::Events::extractStoreStatsChangedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::storeStatsChangedEventData2Java(ctx, event_cast.data) + ); + } else if (store::Events::isStoreUpdatedEvent(event)) { + privmx::endpoint::store::StoreUpdatedEvent event_cast = store::Events::extractStoreUpdatedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::store2Java(ctx, event_cast.data) + ); + } else if (store::Events::isStoreDeletedEvent(event)) { + privmx::endpoint::store::StoreDeletedEvent event_cast = store::Events::extractStoreDeletedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::storeDeletedEventData2Java(ctx, event_cast.data) + ); + } else if (store::Events::isStoreFileCreatedEvent(event)) { + privmx::endpoint::store::StoreFileCreatedEvent event_cast = store::Events::extractStoreFileCreatedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::file2Java(ctx, event_cast.data) + ); + } else if (store::Events::isStoreFileUpdatedEvent(event)) { + privmx::endpoint::store::StoreFileUpdatedEvent event_cast = store::Events::extractStoreFileUpdatedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::file2Java(ctx, event_cast.data) + ); + } else if (store::Events::isStoreFileDeletedEvent(event)) { + privmx::endpoint::store::StoreFileDeletedEvent event_cast = store::Events::extractStoreFileDeletedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::storeFileDeletedEventData2Java(ctx, event_cast.data) + ); + } else if (inbox::Events::isInboxCreatedEvent(event)) { + privmx::endpoint::inbox::InboxCreatedEvent event_cast = inbox::Events::extractInboxCreatedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::inbox2Java(ctx, event_cast.data) + ); + } else if (inbox::Events::isInboxUpdatedEvent(event)) { + privmx::endpoint::inbox::InboxUpdatedEvent event_cast = inbox::Events::extractInboxUpdatedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::inbox2Java(ctx, event_cast.data) + ); + } else if (inbox::Events::isInboxDeletedEvent(event)) { + privmx::endpoint::inbox::InboxDeletedEvent event_cast = inbox::Events::extractInboxDeletedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::inboxDeletedEventData2Java(ctx, event_cast.data) + ); + } else if (inbox::Events::isInboxEntryCreatedEvent(event)) { + privmx::endpoint::inbox::InboxEntryCreatedEvent event_cast = inbox::Events::extractInboxEntryCreatedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::inboxEntry2Java(ctx, event_cast.data) + ); + } else if (inbox::Events::isInboxEntryDeletedEvent(event)) { + privmx::endpoint::inbox::InboxEntryDeletedEvent event_cast = inbox::Events::extractInboxEntryDeletedEvent( + event); + return initEvent( + ctx, + event_cast.type, + event_cast.channel, + event_cast.connectionId, + privmx::wrapper::inboxEntryDeletedEventData2Java(ctx, event_cast.data) + ); + } else { + return initEvent( + ctx, + event->type, + event->channel, + event->connectionId, + nullptr + ); + } + +// else if (core::Events::isLibPlatformDisconnectedEvent(event)) { +// return initEvent( +// ctx, +// event->type, +// event->channel, +// nullptr +// ); +// } +// else if (core::Events::libs(event)) { +// return initEvent( +// ctx, +// event->type, +// event->channel, +// nullptr +// ); +// } else if (event->type == "libDisconnected") { +// return initEvent( +// ctx, +// event->type, +// event->channel, +// nullptr +// ); +// } + } catch (const std::exception &e) { + throw e; +// return nullptr; + } + return nullptr; +} \ No newline at end of file diff --git a/privmx-endpoint/src/main/cpp/parser.h b/privmx-endpoint/src/main/cpp/parser.h new file mode 100644 index 0000000..f8bf4b4 --- /dev/null +++ b/privmx-endpoint/src/main/cpp/parser.h @@ -0,0 +1,27 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#ifndef PRIVMX_POCKET_LIB_PARSER_H +#define PRIVMX_POCKET_LIB_PARSER_H + +#include "utils.hpp" + +#include +#include "model_native_initializers.h" + +std::vector usersToVector(JniContextUtils &ctx, jobjectArray users); +//privmx::endpoint::inbox::InboxCreateMeta parseInboxCreateMeta(JniContextUtils &ctx, jobject inboxCreateMeta); +//privmx::endpoint::inbox::InboxOptions parseInboxOptions(JniContextUtils &ctx, jobject inboxOptions); +privmx::endpoint::inbox::FilesConfig parseFilesConfig(JniContextUtils &ctx, jobject filesConfig); +jobject parseEvent(JniContextUtils &ctx, std::shared_ptr event); + + +#endif //PRIVMX_POCKET_LIB_PARSER_H diff --git a/privmx-endpoint/src/main/cpp/utils.cpp b/privmx-endpoint/src/main/cpp/utils.cpp new file mode 100644 index 0000000..eee2497 --- /dev/null +++ b/privmx-endpoint/src/main/cpp/utils.cpp @@ -0,0 +1,113 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#include "utils.hpp" + +std::string JniContextUtils::jString2string(jstring str) { + if (str == nullptr) return nullptr; + const char *tmp = _env->GetStringUTFChars(str, NULL); + std::string result(tmp); + _env->ReleaseStringUTFChars(str, tmp); + return result; +} + +std::string JniContextUtils::jByteArray2String(jbyteArray arr) { + jsize size = _env->GetArrayLength(arr); + jbyte *bytes = _env->GetByteArrayElements(arr, NULL); + std::string result((const char *) bytes, size); + _env->ReleaseByteArrayElements(arr, bytes, JNI_ABORT); + return result; +} + +jobjectArray JniContextUtils::jObject2jArray(jobject obj) { + jclass objClass = _env->GetObjectClass(obj); + if (_env->IsInstanceOf(obj, _env->FindClass("java/util/List"))) { + jmethodID mToArray = _env->GetMethodID(objClass, "toArray", "()[Ljava/lang/Object;"); + + if (mToArray == nullptr) return nullptr; + return (jobjectArray) _env->CallObjectMethod(obj, mToArray); + } else return nullptr; +} + +jobject JniContextUtils::long2jLong(long long value) { + jclass longCls = _env->FindClass("java/lang/Long"); + jmethodID longInitMethodID = _env->GetMethodID(longCls, "", "(J)V"); + return _env->NewObject(longCls, longInitMethodID, (jlong) value); +} + +jobject JniContextUtils::bool2jBoolean(bool value) { + jclass longCls = _env->FindClass("java/lang/Boolean"); + jmethodID longInitMethodID = _env->GetMethodID(longCls, "", "(Z)V"); + return _env->NewObject(longCls, longInitMethodID, (jboolean) value); +} + +jobject JniContextUtils::int2jInteger(int value) { + jclass longCls = _env->FindClass("java/lang/Integer"); + jmethodID longInitMethodID = _env->GetMethodID(longCls, "", "(I)V"); + return _env->NewObject(longCls, longInitMethodID, (jint) value); +} + +JniContextUtils::Object JniContextUtils::getObject(jobject obj) { + return JniContextUtils::Object(*this, obj); +} + +jthrowable +JniContextUtils::coreException2jthrowable(privmx::endpoint::core::Exception exception_c) { + jclass exceptionCls = _env->FindClass( + "com/simplito/java/privmx_endpoint/model/exceptions/PrivmxException"); + jmethodID initExceptionMID = _env->GetMethodID(exceptionCls, "", + "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V"); + return (jthrowable) _env->NewObject( + exceptionCls, + initExceptionMID, + _env->NewStringUTF(exception_c.what()), + _env->NewStringUTF(exception_c.getDescription().c_str()), + _env->NewStringUTF(exception_c.getScope().c_str()), + (int) exception_c.getCode() + ); +} + +JniContextUtils::Object::Object(JniContextUtils &env, jobject obj) : _env(env), _obj(obj) { + _objCls = _env->GetObjectClass(obj); +} + +JniContextUtils::Object::~Object() { + _env->DeleteLocalRef(_objCls); +} + +std::string JniContextUtils::Object::getFieldAsString(const std::string &name) { + jstring jValue = (jstring) _env->GetObjectField(_obj, _env->GetFieldID(_objCls, name.c_str(), + "Ljava/lang/String;")); + std::string value = _env.jString2string(jValue); + _env->DeleteLocalRef(jValue); + return value; +} + +jlong JniContextUtils::Object::getLongValue() { + jmethodID longValue = _env->GetMethodID(_objCls, "longValue", "()J"); + return _env->CallLongMethod(_obj, longValue); +} + +jboolean JniContextUtils::Object::getBooleanValue() { + jmethodID booleanValue = _env->GetMethodID(_objCls, "booleanValue", "()Z"); + return _env->CallBooleanMethod(_obj, booleanValue); +} + +bool JniContextUtils::nullCheck(void *value, std::string value_name) { + if (value == nullptr) { + _env->ThrowNew( + _env->FindClass("java/lang/NullPointerException"), + (value_name + " cannot be null").c_str() + ); + return true; + } + return false; +} diff --git a/privmx-endpoint/src/main/cpp/utils.hpp b/privmx-endpoint/src/main/cpp/utils.hpp new file mode 100644 index 0000000..76fe89a --- /dev/null +++ b/privmx-endpoint/src/main/cpp/utils.hpp @@ -0,0 +1,56 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#ifndef PRIVMX_PRIVMXPOCKETLIB_UTILS_HPP +#define PRIVMX_PRIVMXPOCKETLIB_UTILS_HPP + +#include +#include + +#include +#include "privmx/endpoint/core/Exception.hpp" + +class JniContextUtils +{ +public: + class Object + { + public: + Object(JniContextUtils& env, jobject obj); + ~Object(); + std::string getFieldAsString(const std::string& name); + jlong getLongValue(); + jboolean getBooleanValue(); + + private: + jobject _obj; + jclass _objCls; + JniContextUtils& _env; + }; + + JniContextUtils(JNIEnv* env) : _env(env) {} + JNIEnv* operator->() { return _env; } + std::string jString2string(jstring str); + std::string jByteArray2String(jbyteArray arr); + jobjectArray jObject2jArray(jobject obj); + Object getObject(jobject obj); + jthrowable coreException2jthrowable(privmx::endpoint::core::Exception exception_c); + jobject long2jLong(long long value); + jobject bool2jBoolean(bool value); + jobject int2jInteger(int value); + bool nullCheck(void *value, std::string value_name); + + +private: + JNIEnv* _env; +}; + +#endif //PRIVMX_PRIVMXPOCKETLIB_UTILS_HPP diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Context.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Context.java new file mode 100644 index 0000000..7c09a3d --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Context.java @@ -0,0 +1,40 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model; + +/** + * + * Contains base Context information. + * @category core + * @group Core + */ +public class Context { + /** + * ID of the user requesting information. + */ + public final String userId; + + /** + * ID of the Context. + */ + public final String contextId; + + /** + * Creates instance of {@code Context} + * @param userId ID of the user requesting information. + * @param contextId ID of Context. + */ + public Context(String userId, String contextId){ + this.userId = userId; + this.contextId = contextId; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Event.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Event.java new file mode 100644 index 0000000..1245b31 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Event.java @@ -0,0 +1,69 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model; + +/** + * Represents a generic event caught by PrivMX Endpoint. + * @param The type of data associated with the event. + * + * @category core + * @group Events + */ +public class Event { + /** + * Type of the event. + */ + public String type; + + /** + * The event channel. + */ + public String channel; + + + /** + * ID of connection for this event. + */ + public Long connectionId; + + /** + * The data payload associated with the event. + * The type of this data is determined by the generic type parameter {@code T}. + */ + public T data; + + /** + * Creates instance of Event model. + */ + Event() { + } + + /** + * Creates instance of Event model. + * + * @param type type of event as text + * @param channel event channel + * @param connectionId ID of connection for this event + * @param data event data + */ + public Event( + String type, + String channel, + Long connectionId, + T data + ) { + this.type = type; + this.channel = channel; + this.connectionId = connectionId; + this.data = data; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/File.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/File.java new file mode 100644 index 0000000..ea91f0e --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/File.java @@ -0,0 +1,75 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model; + +/** + * Holds information about the file. + * @category store + * @group Store + */ +public class File { + + /** + * File's information created by server. + */ + public ServerFileInfo info; + + /** + * File's public metadata. + */ + public byte[] publicMeta; + + /** + * File's private metadata. + */ + public byte[] privateMeta; + + /** + * File's size. + */ + public Long size; + + /** + * Public key of the author of the file. + */ + public String authorPubKey; + + /** + * Status code of retrieval and decryption of the file. + */ + public Long statusCode; + + /** + * Creates instance of {@code File}. + * @param info File's information created by server. + * @param publicMeta File's public metadata. + * @param privateMeta File's private metadata. + * @param size File's size. + * @param authorPubKey Public key of the author of the file. + * @param statusCode Status code of retrieval and decryption of the file. + */ + public File( + ServerFileInfo info, + byte[] publicMeta, + byte[] privateMeta, + Long size, + String authorPubKey, + Long statusCode + ) { + this.info = info; + this.publicMeta = publicMeta; + this.privateMeta = privateMeta; + this.size = size; + this.authorPubKey = authorPubKey; + this.statusCode = statusCode; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/FilesConfig.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/FilesConfig.java new file mode 100644 index 0000000..6d816ef --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/FilesConfig.java @@ -0,0 +1,54 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model; + +/** + * Holds Inbox files configuration. + * @category inbox + * @group Inbox + */ +public class FilesConfig { + + /** + * Minimum number of files required when sending Inbox entry. + */ + public Long minCount; + + /** + * Maximum number of files allowed when sending Inbox entry. + */ + public Long maxCount; + + /** + * Maximum file size allowed when sending Inbox entry. + */ + public Long maxFileSize; + + /** + * Maximum size of all files in total allowed when sending Inbox entry. + */ + public Long maxWholeUploadSize; + + /** + * Creates instance of {@code FilesConfig}. + * @param minCount Minimum number of files required when sending Inbox entry. + * @param maxCount Maximum number of files allowed when sending Inbox entry. + * @param maxFileSize Maximum file size allowed when sending Inbox entry. + * @param maxWholeUploadSize Maximum size of all files in total allowed when sending Inbox entry. + */ + public FilesConfig(Long minCount, Long maxCount, Long maxFileSize, Long maxWholeUploadSize) { + this.minCount = minCount; + this.maxCount = maxCount; + this.maxFileSize = maxFileSize; + this.maxWholeUploadSize = maxWholeUploadSize; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Inbox.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Inbox.java new file mode 100644 index 0000000..9e98670 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Inbox.java @@ -0,0 +1,134 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model; + +import java.util.List; + +/** + * Holds all available information about an Inbox. + * + * @category inbox + * @group Inbox + */ +public class Inbox { + + /** + * ID of the Inbox. + */ + public String inboxId; + + /** + * ID of the Context. + */ + public String contextId; + + /** + * Inbox creation timestamp. + */ + public Long createDate; + + /** + * ID of the user who created the Inbox. + */ + public String creator; + + /** + * Inbox last modification timestamp. + */ + public Long lastModificationDate; + + /** + * ID of the user who last modified the Inbox. + */ + public String lastModifier; + + /** + * List of users (their IDs) with access to the Inbox. + */ + public List users; + + /** + * List of users (their IDs) with management rights. + */ + public List managers; + + /** + * Version number (changes on updates). + */ + public Long version; + + /** + * Inbox public metadata. + */ + public byte[] publicMeta; + + /** + * Inbox private metadata. + */ + public byte[] privateMeta; + + /** + * Inbox files configuration. + */ + public FilesConfig filesConfig; + + /** + * Status code of retrieval and decryption of the {@code Inbox}. + */ + public Long statusCode; + + /** + * Creates instance of {@code Inbox}. + * @param inboxId ID of the Inbox. + * @param contextId ID of the Context. + * @param createDate Inbox creation timestamp. + * @param creator ID of the user who created the Inbox. + * @param lastModificationDate Inbox last modification timestamp. + * @param lastModifier ID of the user who last modified the Inbox. + * @param users List of users (their IDs) with access to the Inbox. + * @param managers List of users (their IDs) with management rights. + * @param version Version number (changes on updates). + * @param publicMeta Inbox public metadata. + * @param privateMeta Inbox private metadata. + * @param filesConfig Inbox files configuration. + * @param statusCode Status code of retrieval and decryption of the {@code Inbox}. + */ + public Inbox( + String inboxId, + String contextId, + Long createDate, + String creator, + Long lastModificationDate, + String lastModifier, + List users, + List managers, + Long version, + byte[] publicMeta, + byte[] privateMeta, + FilesConfig filesConfig, + Long statusCode + ) { + this.inboxId = inboxId; + this.contextId = contextId; + this.createDate = createDate; + this.creator = creator; + this.lastModificationDate = lastModificationDate; + this.lastModifier = lastModifier; + this.users = users; + this.managers = managers; + this.version = version; + this.publicMeta = publicMeta; + this.privateMeta = privateMeta; + this.filesConfig = filesConfig; + this.statusCode = statusCode; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/InboxEntry.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/InboxEntry.java new file mode 100644 index 0000000..10a2cbe --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/InboxEntry.java @@ -0,0 +1,85 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model; + +import java.util.List; + +/** + * Holds information about Inbox entry. + * @category inbox + * @group Inbox + */ +public class InboxEntry { + + /** + * ID of the entry. + */ + public String entryId; + + /** + * ID of the Inbox. + */ + public String inboxId; + + /** + * Entry data. + */ + public byte[] data; + + /** + * List of files attached to the entry. + */ + public List files; + + /** + * Public key of the author of an entry. + */ + public String authorPubKey; + + /** + * Inbox entry creation timestamp. + */ + public Long createDate; + + /** + * Status code of retrieval and decryption of the {@code Inbox} entry. + */ + public Long statusCode; + + /** + * Creates instance of {@code InboxEntry}. + * @param entryId ID of the entry. + * @param inboxId ID of the Inbox. + * @param data Entry data. + * @param files List of files attached to the entry. + * @param authorPubKey Public key of the author of an entry. + * @param createDate Inbox entry creation timestamp. + * @param statusCode Status code of retrieval and decryption of the {@code Inbox} entry. + */ + public InboxEntry( + String entryId, + String inboxId, + byte[] data, + List files, + String authorPubKey, + Long createDate, + Long statusCode + ) { + this.entryId = entryId; + this.inboxId = inboxId; + this.data = data; + this.files = files; + this.authorPubKey = authorPubKey; + this.createDate = createDate; + this.statusCode = statusCode; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/InboxPublicView.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/InboxPublicView.java new file mode 100644 index 0000000..cf105a6 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/InboxPublicView.java @@ -0,0 +1,52 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model; + +/** + * Holds Inbox public information. + * + * @category inbox + * @group Inbox + */ +public class InboxPublicView { + + /** + * ID of the Inbox. + */ + public String inboxId; + + /** + * Version of the Inbox. + */ + public Long version; + + /** + * Inbox public metadata. + */ + public byte[] publicMeta; + + /** + * Creates instance of {@code InboxPublicView}. + * @param inboxId ID of the Inbox. + * @param version Version of the Inbox. + * @param publicMeta Inbox public metadata. + */ + public InboxPublicView( + String inboxId, + Long version, + byte[] publicMeta + ) { + this.inboxId = inboxId; + this.version = version; + this.publicMeta = publicMeta; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Message.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Message.java new file mode 100644 index 0000000..33b4e5a --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Message.java @@ -0,0 +1,76 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model; + +/** + * Holds information about the Message. + * + * @category thread + * @group Thread + */ +public class Message { + + /** + * Message's information created by server. + */ + public ServerMessageInfo info; + + /** + * Message's public metadata. + */ + public byte[] publicMeta; + + /** + * Message's private metadata. + */ + public byte[] privateMeta; + + /** + * Message's data. + */ + public byte[] data; + + /** + * Public key of the author of the message. + */ + public String authorPubKey; + + /** + * Status code of retrieval and decryption of the {@code Message}. + */ + public Long statusCode; + + /** + * Creates instance of {@code Message}. + * @param info Message's information created by server. + * @param publicMeta Message's public metadata. + * @param privateMeta Message's private metadata. + * @param data Message's data. + * @param authorPubKey Public key of the author of the message. + * @param statusCode Status code of retrieval and decryption of the {@code Message}. + */ + public Message( + ServerMessageInfo info, + byte[] publicMeta, + byte[] privateMeta, + byte[] data, + String authorPubKey, + Long statusCode + ) { + this.info = info; + this.publicMeta = publicMeta; + this.privateMeta = privateMeta; + this.authorPubKey = authorPubKey; + this.data = data; + this.statusCode = statusCode; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/PagingList.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/PagingList.java new file mode 100644 index 0000000..39569b0 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/PagingList.java @@ -0,0 +1,43 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model; + +import java.util.List; + +/** + * Contains results of listing methods. + * @param type of items stored in list. + * + * @category core + * @group Core + */ +public class PagingList { + /** + * Total items available to get. + */ + public Long totalAvailable; + + /** + * List of items read during single method call. + */ + public List readItems; + + /** + * Creates instance of {@code PagingList}. + * @param totalAvailable Total items available to get. + * @param items List of items read during single method call. + */ + public PagingList(Long totalAvailable, List items){ + this.totalAvailable = totalAvailable; + this.readItems = items; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/ServerFileInfo.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/ServerFileInfo.java new file mode 100644 index 0000000..a55abe2 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/ServerFileInfo.java @@ -0,0 +1,61 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model; + +/** + * Holds file's information created by server. + * + * @category store + * @group Store + */ +public class ServerFileInfo { + + /** + * ID of the Store. + */ + public String storeId; + + /** + * ID of the file. + */ + public String fileId; + + /** + * File's creation timestamp. + */ + public Long createDate; + + /** + * ID of the user who created the file. + */ + public String author; + + + /** + * Creates instance of {@code ServerFileInfo}. + * @param storeId ID of the Store. + * @param fileId ID of the file. + * @param createDate File's creation timestamp. + * @param author ID of the user who created the file. + */ + public ServerFileInfo( + String storeId, + String fileId, + Long createDate, + String author + ) { + this.storeId = storeId; + this.fileId = fileId; + this.createDate = createDate; + this.author = author; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/ServerMessageInfo.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/ServerMessageInfo.java new file mode 100644 index 0000000..88e0386 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/ServerMessageInfo.java @@ -0,0 +1,60 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model; + +/** + * Holds message's information created by server. + * + * @category thread + * @group Thread + */ +public class ServerMessageInfo { + + /** + * ID of the message's Thread. + */ + public String threadId; + + /** + * ID of the message. + */ + public String messageId; + + /** + * Message's creation timestamp. + */ + public Long createDate; + + /** + * ID of the user who created the message. + */ + public String author; + + /** + * Creates instance of {@code ServerMessageInfo}. + * @param threadId ID of the message's Thread. + * @param messageId ID of the message. + * @param createDate Message's creation timestamp. + * @param author ID of the user who created the message. + */ + public ServerMessageInfo( + String threadId, + String messageId, + Long createDate, + String author + ) { + this.threadId = threadId; + this.messageId = messageId; + this.createDate = createDate; + this.author = author; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Store.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Store.java new file mode 100644 index 0000000..4a17390 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Store.java @@ -0,0 +1,140 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model; + +import java.util.List; + +/** + * Holds all available information about a Store. + * @category store + * @group Store + */ +public class Store { + /** + * ID of the Store. + */ + public String storeId; + + /** + * ID of the Context. + */ + public String contextId; + + /** + * Store creation timestamp. + */ + public Long createDate; + + /** + * ID of the user who created the Store. + */ + public String creator; + + /** + * Store last modification timestamp. + */ + public Long lastModificationDate; + + /** + * Timestamp of the last created file. + */ + public Long lastFileDate; + + /** + * ID of the user who last modified the Store. + */ + public String lastModifier; + + /** + * List of users (their IDs) with access to the Store. + */ + public List users; + + /** + * List of users (their IDs) with management rights. + */ + public List managers; + + /** + * Version number (changes on updates). + */ + public Long version; + + /** + * Store's public metadata. + */ + public byte[] publicMeta; + + /** + * Store's private metadata. + */ + public byte[] privateMeta; + + /** + * Total number of files in the Store. + */ + public Long filesCount; + + /** + * Status code of retrieval and decryption of the {@code Store}. + */ + public Long statusCode; + + /** + * Creates instance of {@code Store}. + * @param storeId ID of the Store. + * @param contextId ID of the Context. + * @param createDate Store creation timestamp. + * @param creator ID of the user who created the Store. + * @param lastModificationDate Store last modification timestamp. + * @param lastFileDate Timestamp of the last created file. + * @param lastModifier ID of the user who last modified the Store. + * @param users List of users (their IDs) with access to the Store. + * @param managers List of users (their IDs) with management rights. + * @param version Version number (changes on updates). + * @param publicMeta Store's public metadata. + * @param privateMeta Store's private metadata. + * @param filesCount Total number of files in the Store. + * @param statusCode Status code of retrieval and decryption of the {@code Store}. + */ + public Store( + String storeId, + String contextId, + Long createDate, + String creator, + Long lastModificationDate, + Long lastFileDate, + String lastModifier, + List users, + List managers, + Long version, + byte[] publicMeta, + byte[] privateMeta, + Long filesCount, + Long statusCode + ) { + this.storeId = storeId; + this.contextId = contextId; + this.createDate = createDate; + this.creator = creator; + this.lastModificationDate = lastModificationDate; + this.lastFileDate = lastFileDate; + this.lastModifier = lastModifier; + this.users = users; + this.managers = managers; + this.version = version; + this.publicMeta = publicMeta; + this.privateMeta = privateMeta; + this.filesCount = filesCount; + this.statusCode = statusCode; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Thread.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Thread.java new file mode 100644 index 0000000..2fd3e30 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/Thread.java @@ -0,0 +1,142 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model; + +import java.util.List; + +/** + * Holds all available information about a Thread. + * @category thread + * @group Thread + */ +public class Thread { + + /** + * ID of the Thread's Context. + */ + public String contextId; + + /** + * ID of the Thread. + */ + public String threadId; + + /** + * Thread creation timestamp. + */ + public Long createDate; + + /** + * ID of the user who created the Thread. + */ + public String creator; + + /** + * Thread last modification timestamp. + */ + public Long lastModificationDate; + + /** + * ID of the user who last modified the Thread. + */ + public String lastModifier; + + /** + * List of users (their IDs) with access to the Thread. + */ + public List users; + + /** + * List of users (their IDs) with management rights. + */ + public List managers; + + /** + * Version number (changes on updates). + */ + public Long version; + + /** + * Timestamp of the last posted message. + */ + public Long lastMsgDate; + + /** + * Total number of messages in the Thread. + */ + public Long messagesCount; + + /** + * Thread's public metadata. + */ + public byte[] publicMeta; + + /** + * Thread's private metadata. + */ + public byte[] privateMeta; + + /** + * Status code of retrieval and decryption of the {@code Thread}. + */ + public Long statusCode; + + + /** + * Creates instance of {@code Thread}. + * @param contextId ID of the Context. + * @param threadId ID of the Thread. + * @param createDate Thread creation timestamp. + * @param creator ID of the user who created the Thread. + * @param lastModificationDate Thread last modification timestamp. + * @param lastModifier ID of the user who last modified the Thread. + * @param users List of users (their IDs) with access to the Thread. + * @param managers List of users (their IDs) with management rights. + * @param version Version number (changes on updates). + * @param lastMsgDate Timestamp of the last posted message. + * @param publicMeta Total number of messages in the Thread. + * @param privateMeta Thread's public metadata. + * @param messagesCount Thread's private metadata. + * @param statusCode Status code of retrieval and decryption of the {@code Thread}. + */ + public Thread( + String contextId, + String threadId, + Long createDate, + String creator, + Long lastModificationDate, + String lastModifier, + List users, + List managers, + Long version, + Long lastMsgDate, + byte[] publicMeta, + byte[] privateMeta, + Long messagesCount, + Long statusCode + ) { + this.contextId = contextId; + this.threadId = threadId; + this.createDate = createDate; + this.creator = creator; + this.lastModificationDate = lastModificationDate; + this.lastModifier = lastModifier; + this.users = users; + this.managers = managers; + this.version = version; + this.lastMsgDate = lastMsgDate; + this.publicMeta = publicMeta; + this.privateMeta = privateMeta; + this.messagesCount = messagesCount; + this.statusCode = statusCode; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/UserWithPubKey.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/UserWithPubKey.java new file mode 100644 index 0000000..1e9f285 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/UserWithPubKey.java @@ -0,0 +1,50 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model; + +/** + * Contains ID of user and the corresponding public key. + * + * @category core + * @group Core + */ +public class UserWithPubKey { + + /** + * ID of the user. + */ + public String userId; + + /** + * User's public key. + */ + public String pubKey; + + /** + * Creates instance of {@code UserWithPubKey}. + */ + public UserWithPubKey() {} + + /** + * Creates instance of {@code UserWithPubKey}. + * @param userId ID of the user. + * @param pubKey User's public key. + */ + public UserWithPubKey( + String userId, + String pubKey + ) { + this.userId = userId; + this.pubKey = pubKey; + } + +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/InboxDeletedEventData.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/InboxDeletedEventData.java new file mode 100644 index 0000000..6cb1259 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/InboxDeletedEventData.java @@ -0,0 +1,36 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model.events; + +/** + * Holds information about deleted Inbox. + * + * @category core + * @group Events + */ +public class InboxDeletedEventData { + + /** + * ID of the deleted Inbox. + */ + public final String inboxId; + + /** + * Creates instance of {@code InboxDeletedEventData}. + * @param inboxId ID of the deleted Inbox. + */ + public InboxDeletedEventData( + String inboxId + ) { + this.inboxId = inboxId; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/InboxEntryDeletedEventData.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/InboxEntryDeletedEventData.java new file mode 100644 index 0000000..dfc4855 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/InboxEntryDeletedEventData.java @@ -0,0 +1,43 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model.events; + +/** + * Holds information about a entry deleted from Inbox. + * + * @category core + * @group Events + */ +public class InboxEntryDeletedEventData { + /** + * ID of the deleted entry's Inbox. + */ + public final String inboxId; + + /** + * ID of the deleted entry. + */ + public final String entryId; + + /** + * Creates instance of {@code InboxEntryDeletedEventData}. + * @param inboxId ID of the deleted entry's Inbox. + * @param entryId ID of the deleted entry. + */ + public InboxEntryDeletedEventData( + String inboxId, + String entryId + ) { + this.inboxId = inboxId; + this.entryId = entryId; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/StoreDeletedEventData.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/StoreDeletedEventData.java new file mode 100644 index 0000000..cb2990b --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/StoreDeletedEventData.java @@ -0,0 +1,34 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model.events; + +/** + * Holds information about deleted Store. + * @category core + * @group Events + */ +public class StoreDeletedEventData { + /** + * ID of the deleted Store. + */ + public final String storeId; + + /** + * Creates instance of {@code StoreDeletedEventData}. + * @param storeId ID of the deleted Store. + */ + public StoreDeletedEventData( + String storeId + ){ + this.storeId = storeId; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/StoreFileDeletedEventData.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/StoreFileDeletedEventData.java new file mode 100644 index 0000000..8e24268 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/StoreFileDeletedEventData.java @@ -0,0 +1,50 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model.events; + +/** + * Holds information about a file deleted from Store. + * @category core + * @group Events + */ +public class StoreFileDeletedEventData { + /** + * ID of the deleted file. + */ + public final String fileId; + + /** + * ID of the Store's Context. + */ + public final String contextId; + + /** + * ID of the deleted file's Store. + */ + public final String storeId; + + /** + * Creates instance of {@code StoreFileDeletedEventData}. + * @param fileId ID of the deleted file. + * @param contextId ID of the Store's Context. + * @param storeId ID of the Store of the deleted file. + */ + public StoreFileDeletedEventData( + String fileId, + String contextId, + String storeId + ) { + this.fileId = fileId; + this.contextId = contextId; + this.storeId = storeId; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/StoreStatsChangedEventData.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/StoreStatsChangedEventData.java new file mode 100644 index 0000000..65a3cc1 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/StoreStatsChangedEventData.java @@ -0,0 +1,58 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model.events; + +/** + * Holds information about changes in a Store's statistics. + * @category core + * @group Events + */ +public class StoreStatsChangedEventData { + /** + * ID of the changed Store's Context. + */ + public final String contextId; + + /** + * ID of the changed Store. + */ + public final String storeId; + + /** + * Updated date of the last file in the Store. + */ + public final Long lastFileDate; + + /** + * Updated number of files in the Store. + */ + public final Long filesCount; + + /** + * Creates instance of {@code StoreStatsChangedEventData}. + * @param storeId ID of the changed Store's Context. + * @param contextId ID of the changed Store. + * @param lastFileDate Updated date of the last file in the Store. + * @param filesCount Updated number of files in the Store. + */ + public StoreStatsChangedEventData( + String storeId, + String contextId, + Long lastFileDate, + Long filesCount + ){ + this.storeId = storeId; + this.contextId = contextId; + this.lastFileDate = lastFileDate; + this.filesCount = filesCount; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/ThreadDeletedEventData.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/ThreadDeletedEventData.java new file mode 100644 index 0000000..dd3a7d4 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/ThreadDeletedEventData.java @@ -0,0 +1,36 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model.events; + +/** + * Holds information about a deleted Thread. + * + * @category core + * @group Events + */ +public class ThreadDeletedEventData { + + /** + * ID of the deleted Thread. + */ + public final String threadId; + + /** + * Creates instance of {@code ThreadDeletedEventData}. + * @param threadId ID of the deleted Thread. + */ + public ThreadDeletedEventData( + String threadId + ){ + this.threadId = threadId; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/ThreadDeletedMessageEventData.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/ThreadDeletedMessageEventData.java new file mode 100644 index 0000000..c379455 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/ThreadDeletedMessageEventData.java @@ -0,0 +1,43 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model.events; + +/** + * Holds information about a message deleted from a Thread. + * @category core + * @group Events + */ +public class ThreadDeletedMessageEventData { + + /** + * ID of the deleted message's Thread. + */ + public final String threadId; + + /** + * ID of the deleted Message. + */ + public final String messageId; + + /** + * Creates instance of {@code ThreadDeletedMessageEventData}. + * @param threadId ID of the deleted message's Thread. + * @param messageId ID of the deleted Message. + */ + ThreadDeletedMessageEventData( + String threadId, + String messageId + ){ + this.threadId = threadId; + this.messageId = messageId; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/ThreadStatsEventData.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/ThreadStatsEventData.java new file mode 100644 index 0000000..b930695 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/events/ThreadStatsEventData.java @@ -0,0 +1,51 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model.events; + +/** + * Holds information about changes in a Thread's statistics. + * @category core + * @group Events + */ +public class ThreadStatsEventData { + + /** + * ID of the changed Thread. + */ + public final String threadId; + + /** + * Timestamp of the most recent Thread message. + */ + public final Long lastMsgDate; + + /** + * Updated number of messages in the Thread. + */ + public final Long messagesCount; + + /** + * Creates instance of {@code ThreadStatsEventData}. + * @param threadId ID of the changed Thread. + * @param lastMsgDate Timestamp of the most recent Thread message. + * @param messagesCount Updated number of messages in the Thread. + */ + public ThreadStatsEventData( + String threadId, + Long lastMsgDate, + Long messagesCount + ) { + this.threadId = threadId; + this.lastMsgDate = lastMsgDate; + this.messagesCount = messagesCount; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/exceptions/NativeException.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/exceptions/NativeException.java new file mode 100644 index 0000000..a3aacf1 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/exceptions/NativeException.java @@ -0,0 +1,26 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model.exceptions; + +/** + * Thrown when a PrivMX Endpoint method encounters an unknown exception. + * @category errors + */ +public class NativeException extends RuntimeException{ + /** + * Initialize exception with passed message. + * @param message information about the exception + */ + NativeException(String message){ + super(message); + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/exceptions/PrivmxException.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/exceptions/PrivmxException.java new file mode 100644 index 0000000..5237831 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/model/exceptions/PrivmxException.java @@ -0,0 +1,109 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.model.exceptions; + +/** + * Thrown when a PrivMX Endpoint method encounters an exception. + * @category errors + */ +public class PrivmxException extends RuntimeException { + + /** + * Code of the exception. + */ + private final int code; + + /** + * Scope of the exception. + */ + public final String scope; + + /** + * Detailed description of the exception. + */ + public final String description; + + /** + * Native Exception name. + */ + public final String name; + + /** + * Creates instance of {@code PrivmxException}. + * @param message short information about exception + * @param scope scope of this exception + * @param code unique code of this exception + */ + PrivmxException(String message, String scope, int code){ + this(message,null,scope,code, ""); + } + + /** + * Creates instance of {@code PrivmxException}. + * @param message short information about exception + * @param description information about exception + * @param scope scope of this exception + * @param code unique code of this exception + */ + PrivmxException(String message, String description , String scope, int code){ + this(message,description,scope,code, ""); + } + + /** + * Creates instance of {@code PrivmxException}. + * @param message brief information about exception + * @param description detailed information about exception + * @param scope scope of this exception + * @param code unique code of this exception + * @param name special name for this exception + */ + PrivmxException(String message, String description , String scope, int code, String name){ + super(message); + this.scope = scope; + this.code = code; + this.description = description; + this.name = name; + } + + /** + * Returns full information about the exception. + *

+ * See: {@link #getFull}. + * @return Full information about exception + */ + @Override + public String toString() { + return getFull(); + } + + /** + * Returns exception code as {@code unsigned int} converted to {@code long}. + * @return Exception code + */ + public long getCode(){ + return Integer.toUnsignedLong(code); + } + + /** + * Returns full information about exception. + * @return Full information about exception + */ + public String getFull(){ + return "{\n" + + "\"name\" : \"" + name + "\",\n" + + "\"scope\" : \"" + scope + "\",\n" + + "\"msg\" : \"" + getMessage() + "\",\n" + + "\"code\" : " + getCode() + ",\n" + + "\"description\" : \"" + description + "\"\n" + + "}\n"; + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/core/BackendRequester.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/core/BackendRequester.java new file mode 100644 index 0000000..6851fb6 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/core/BackendRequester.java @@ -0,0 +1,76 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.modules.core; + +import com.simplito.java.privmx_endpoint.model.exceptions.NativeException; +import com.simplito.java.privmx_endpoint.model.exceptions.PrivmxException; + +/** + * Defines methods sending requests to PrivMX Bridge API. + */ +public class BackendRequester { + /** + * Sends a request to PrivMX Bridge API using access token for authorization. + * + * @param serverUrl PrivMX Bridge server URL + * @param accessToken token for authorization (see PrivMX Bridge API for more details) + * @param method API method to call + * @param paramsAsJson API method's parameters in JSON format + * @return JSON string representing raw server response + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public static native String backendRequest( + String serverUrl, + String accessToken, + String method, + String paramsAsJson + ) throws PrivmxException, NativeException; + + + /** + * Sends request to PrivMX Bridge API. + * + * @param serverUrl PrivMX Bridge server URL + * @param method API method to call + * @param paramsAsJson API method's parameters in JSON format + * @return JSON string representing raw server response + */ + public static native String backendRequest( + String serverUrl, + String method, + String paramsAsJson + ); + + /** + * Sends a request to PrivMX Bridge API using pair of API KEY ID and API KEY SECRET for authorization. + * + * @param serverUrl PrivMX Bridge server URL + * @param apiKeyId API KEY ID (see PrivMX Bridge API for more details) + * @param apiKeySecret API KEY SECRET (see PrivMX Bridge API for more details) + * @param mode allows you to set whether the request should be signed (mode = 1) or plain (mode = 0) + * @param method API method to call + * @param paramsAsJson API method's parameters in JSON format + * @return JSON string representing raw server response + */ + public static native String backendRequest( + String serverUrl, + String apiKeyId, + String apiKeySecret, + long mode, + String method, + String paramsAsJson + ); + + private BackendRequester() { + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/core/Connection.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/core/Connection.java new file mode 100644 index 0000000..a6a094a --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/core/Connection.java @@ -0,0 +1,144 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.modules.core; + +import com.simplito.java.privmx_endpoint.model.Context; +import com.simplito.java.privmx_endpoint.model.PagingList; +import com.simplito.java.privmx_endpoint.model.exceptions.NativeException; +import com.simplito.java.privmx_endpoint.model.exceptions.PrivmxException; + +/** + * Manages a connection between the Endpoint and the Bridge server. + * + * @category core + */ +public class Connection implements AutoCloseable { + static { + System.loadLibrary("crypto"); + System.loadLibrary("ssl"); + System.loadLibrary("privmx-endpoint-java"); + } + + private final Long api; + private final Long connectionId; + + private Connection(Long api, Long connectionId) { + this.api = api; + this.connectionId = connectionId; + } + + private native void deinit() throws IllegalStateException, PrivmxException, NativeException; + + /** + * Allows to set path to the SSL certificate file. + * + * @param certsPath path to file + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public static native void setCertsPath(String certsPath) throws PrivmxException, NativeException; + + /** + * Connects to the PrivMX Bridge server. + * + * @param userPrivKey user's private key + * @param solutionId ID of the Solution + * @param platformUrl Platform's Endpoint URL + * @return Connection object + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + * @event type: libConnected + * channel: - + * payload: {@link Void} + */ + public static native Connection platformConnect(String userPrivKey, String solutionId, String platformUrl) throws PrivmxException, NativeException; + + /** + * Connects to the PrivMX Bridge server as a guest user. + * + * @param solutionId ID of the Solution + * @param platformUrl Platform's Endpoint URL + * @return Connection object + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + * @event type: libConnected + * channel: - + * payload: {@link Void} + */ + public static native Connection platformConnectPublic(String solutionId, String platformUrl) throws PrivmxException, NativeException; + + /** + * Disconnects from the PrivMX Bridge server. + * + * @throws IllegalStateException thrown when instance is not connected or closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + * @event type: libDisconnected + * channel: - + * payload: {@link Void} + * @event type: libPlatformDisconnected + * channel: - + * payload: {@link Void} + */ + public native void disconnect() throws IllegalStateException, PrivmxException, NativeException; + + /** + * Gets a list of Contexts available for the user. + * + * @param skip skip number of elements to skip from result + * @param limit limit of elements to return for query + * @param sortOrder order of elements in result ("asc" for ascending, "desc" for descending) + * @return list of Contexts + * @throws IllegalStateException thrown when instance is not connected. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public PagingList listContexts(long skip, long limit, String sortOrder) throws IllegalStateException, PrivmxException, NativeException { + return listContexts(skip, limit, sortOrder, null); + } + + /** + * Gets a list of Contexts available for the user. + * + * @param skip skip number of elements to skip from result + * @param limit limit of elements to return for query + * @param sortOrder order of elements in result ("asc" for ascending, "desc" for descending) + * @param lastId ID of the element from which query results should start + * @return list of Contexts + * @throws IllegalStateException thrown when instance is not connected. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native PagingList listContexts(long skip, long limit, String sortOrder, String lastId) throws IllegalStateException, PrivmxException, NativeException; + + + /** + * Gets the ID of the current connection. + * + * @return ID of the connection + */ + public Long getConnectionId() { + return this.connectionId; + } + + + /** + * If there is an active connnection then it + * disconnects from PrivMX Bridge and frees memory making this instance not reusable. + */ + @Override + public void close() { + if (api != null) { + disconnect(); + } + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/core/EventQueue.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/core/EventQueue.java new file mode 100644 index 0000000..6e47079 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/core/EventQueue.java @@ -0,0 +1,50 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.modules.core; + +import com.simplito.java.privmx_endpoint.model.Event; +import com.simplito.java.privmx_endpoint.model.exceptions.NativeException; +import com.simplito.java.privmx_endpoint.model.exceptions.PrivmxException; + +/** + * Defines methods to working with Events queue. + */ +public class EventQueue { + /** + * Puts the break event on the events queue. + * You can use it to break the {@link #waitEvent()}. + * + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public static native void emitBreakEvent() throws PrivmxException, NativeException; + + /** + * Waits for event on current thread. + * + * @return Caught event + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public static native Event waitEvent() throws PrivmxException, NativeException; + + /** + * Gets the first event from the events queue. + * + * @return Event data if any available otherwise return null + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public static native Event getEvent() throws PrivmxException, NativeException; + + private EventQueue(){}; +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/crypto/CryptoApi.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/crypto/CryptoApi.java new file mode 100644 index 0000000..78fd60c --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/crypto/CryptoApi.java @@ -0,0 +1,121 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.modules.crypto; + +import com.simplito.java.privmx_endpoint.model.exceptions.NativeException; +import com.simplito.java.privmx_endpoint.model.exceptions.PrivmxException; + +/** + * Defines cryptographic methods. + * + * @category crypto + */ +public class CryptoApi implements AutoCloseable { + static { + System.loadLibrary("crypto"); + System.loadLibrary("ssl"); + System.loadLibrary("privmx-endpoint-java"); + } + private final Long api; + + /** + * Create instance of {@code CryptoApi}. + */ + public CryptoApi(){ + api = init(); + } + + private native Long init(); + private native void deinit() throws IllegalStateException; + + /** + * Generates a new private ECC key. + * + * @param randomSeed optional string used as the base to generate the new key + * @return Generated ECC key in WIF format + */ + public native String generatePrivateKey(String randomSeed) throws PrivmxException, NativeException; + + /** + * Generates a new private ECC key from a password using pbkdf2. + * + * @param password the password used to generate the new key + * @param salt random string (additional input for the hashing function) + + * @return Generated ECC key in WIF format + */ + public native String derivePrivateKey(String password, String salt) throws PrivmxException, NativeException; + + /** + * Generates a new public ECC key as a pair for an existing private key. + * + * @param privateKey private ECC key in WIF format + * @return Generated ECC key in BASE58DER format + */ + public native String derivePublicKey(String privateKey) throws PrivmxException, NativeException; + + /** + * Encrypts buffer with a given key using AES. + * + * @param data buffer to encrypt + * @param symmetricKey key used to encrypt data + * @return Encrypted data buffer + */ + public native byte[] encryptDataSymmetric(byte[] data, byte[] symmetricKey) throws PrivmxException, NativeException; + + /** + * Decrypts buffer with a given key using AES. + * + * @param data buffer to decrypt + * @param symmetricKey key used to decrypt data + * @return Plain (decrypted) data buffer + */ + public native byte[] decryptDataSymmetric(byte[] data, byte[] symmetricKey) throws PrivmxException, NativeException; + + /** + * Creates a signature of data using given key. + * + * @param data data the buffer to sign + * @param privateKey the key used to sign data + * @return Signature of data + */ + public native byte[] signData(byte[] data, String privateKey) throws PrivmxException, NativeException; + + /** + * Validate a signature of data using given key. + * + * @param data buffer + * @param signature of data + * @param publicKey public ECC key in BASE58DER format used to validate data + * @return data validation result + */ + public native boolean verifySignature(byte[] data, byte[] signature, String publicKey); + + /** + * Converts given private key in PEM format to its WIF format. + * + * @param pemKey private key to convert + * @return Private key in WIF format + */ + public native String convertPEMKeyToWIFKey(String pemKey) throws PrivmxException, NativeException; + + /** + * Generates a new symmetric key. + * @return Generated key + */ + public native byte[] generateKeySymmetric(); + + @Override + public void close() throws Exception { + deinit(); + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/inbox/InboxApi.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/inbox/InboxApi.java new file mode 100644 index 0000000..020f25c --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/inbox/InboxApi.java @@ -0,0 +1,397 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.modules.inbox; + +import com.simplito.java.privmx_endpoint.model.FilesConfig; +import com.simplito.java.privmx_endpoint.model.Inbox; +import com.simplito.java.privmx_endpoint.model.InboxEntry; +import com.simplito.java.privmx_endpoint.model.InboxPublicView; +import com.simplito.java.privmx_endpoint.model.PagingList; +import com.simplito.java.privmx_endpoint.model.UserWithPubKey; +import com.simplito.java.privmx_endpoint.model.events.InboxDeletedEventData; +import com.simplito.java.privmx_endpoint.model.events.InboxEntryDeletedEventData; +import com.simplito.java.privmx_endpoint.modules.core.Connection; +import com.simplito.java.privmx_endpoint.modules.store.StoreApi; +import com.simplito.java.privmx_endpoint.modules.thread.ThreadApi; + +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** + * Manages PrivMX Bridge Inboxes and Entries. + * + * @category inbox + */ +public class InboxApi implements AutoCloseable{ + static { + System.loadLibrary("crypto"); + System.loadLibrary("ssl"); + System.loadLibrary("privmx-endpoint-java"); + } + + private final Long api; + + /** + * Creates Inbox from existing {@link Connection}. + * @param connection current connection + * @throws IllegalStateException when one of the passed parameters is closed. + */ + public InboxApi( + Connection connection + ) throws IllegalStateException { + this(connection,null,null); + } + + + /** + * Creates Inbox from existing {@link Connection}, {@link ThreadApi}, {@link StoreApi}. + * @param connection active connection to PrivMX Bridge + * @param threadApi instance of {@link ThreadApi} created on passed Connection + * @param storeApi instance of {@link StoreApi} created on passed Connection + * @throws IllegalStateException when one of the passed parameters is closed. + */ + public InboxApi( + Connection connection, + ThreadApi threadApi, + StoreApi storeApi + ) throws IllegalStateException { + Objects.requireNonNull(connection); + StoreApi tmpStoreApi = storeApi == null ? new StoreApi(connection) : null; + ThreadApi tmpThreadApi = threadApi == null ? new ThreadApi(connection) : null; + this.api = init( + connection, + Optional.ofNullable(threadApi).orElse(tmpThreadApi), + Optional.ofNullable(storeApi).orElse(tmpStoreApi) + ); + try { + if(tmpThreadApi != null) tmpThreadApi.close(); + if(tmpStoreApi != null) tmpStoreApi.close(); + }catch (Exception ignore){} + } + + private native Long init( + Connection connection, + ThreadApi threadApi, + StoreApi storeApi + ) throws IllegalStateException; + + private native void deinit() throws IllegalStateException; + + + /** + * Creates a new Inbox. + * + * @param contextId ID of the Context of the new Inbox + * @param users vector of {@link UserWithPubKey} structs which indicates who will have access to the created Inbox + * @param managers vector of {@link UserWithPubKey} structs which indicates who will have access (and management rights) to + * the created Inbox + * @param publicMeta public (unencrypted) metadata + * @param privateMeta private (encrypted) metadata + * @return ID of the created Inbox + * @event type: inboxCreated + * channel: inbox + * payload: {@link Inbox} + */ + public String createInbox(String contextId, List users, List managers, byte[] publicMeta, byte[] privateMeta) { + return createInbox(contextId, users, managers, publicMeta, privateMeta, null); + } + + /** + Creates a new Inbox. + * + * @param contextId ID of the Context of the new Inbox + * @param users list of {@link UserWithPubKey} structs which indicates who will have access to the created Inbox + * @param managers list of {@link UserWithPubKey} structs which indicates who will have access (and management rights) to + * the created Inbox + * @param publicMeta public (unencrypted) metadata + * @param privateMeta private (encrypted) metadata + * @param filesConfig overrides default file configuration + * @return ID of the created Inbox + * @event type: inboxCreated + * channel: inbox + * payload: {@link Inbox} + */ + public native String createInbox(String contextId, List users, List managers, byte[] publicMeta, byte[] privateMeta, FilesConfig filesConfig); + + /** + * Updates an existing Inbox. + * + * @param inboxId ID of the Inbox to update + * @param users vector of UserWithPubKey structs which indicates who will have access to the created Inbox + * @param managers vector of UserWithPubKey structs which indicates who will have access (and have manage rights) to + * the created Inbox + * @param publicMeta public (unencrypted) metadata + * @param privateMeta private (encrypted) metadata + * @param filesConfig struct to override default files configuration + * @param version current version of the updated Inbox + * @param force force update (without checking version) + * @event type: inboxUpdated + * channel: inbox + * payload: {@link Inbox} + */ + public void updateInbox(String inboxId, List users, List managers, byte[] publicMeta, byte[] privateMeta, FilesConfig filesConfig, long version, boolean force){ + updateInbox(inboxId,users,managers,publicMeta,privateMeta,filesConfig,version,force,true); + } + + /** + * Updates an existing Inbox. + * + * @param inboxId ID of the Inbox to update + * @param users list of {@link UserWithPubKey} structs which indicates who will have access to the created Inbox + * @param managers list of {@link UserWithPubKey} structs which indicates who will have access (and management rights) to + * the created Inbox + * @param publicMeta public (unencrypted) metadata + * @param privateMeta private (encrypted) metadata + * @param filesConfig overrides default file configuration + * @param version current version of the updated Inbox + * @param force force update (without checking version) + * @param forceGenerateNewKey force to regenerate a key for the Inbox + * @event type: inboxUpdated + * channel: inbox + * payload: {@link Inbox} + */ + public native void updateInbox(String inboxId, List users, List managers, byte[] publicMeta, byte[] privateMeta, FilesConfig filesConfig, long version, boolean force, boolean forceGenerateNewKey); + + /** + * Gets a single Inbox by given Inbox ID. + * + * @param inboxId ID of the Inbox to get + * @return Information about the Inbox + */ + public native Inbox getInbox(String inboxId); + + /** + * Gets a list of Inboxes in given Context. + * + * @param contextId ID of the Context to get Inboxes from + * @param skip skip number of elements to skip from result + * @param limit limit of elements to return for query + * @param sortOrder order of elements in result ("asc" for ascending, "desc" for descending) + * @return list of Inboxes + */ + public PagingList listInboxes(String contextId, long skip, long limit, String sortOrder) { + return listInboxes(contextId, skip, limit, sortOrder, null); + } + + /** + * Gets s list of Inboxes in given Context. + * + * @param contextId ID of the Context to get Inboxes from + * @param skip skip number of elements to skip from result + * @param limit limit of elements to return for query + * @param sortOrder order of elements in result ("asc" for ascending, "desc" for descending) + * @param lastId ID of the element from which query results should start + * @return list of Inboxes + */ + public native PagingList listInboxes(String contextId, long skip, long limit, String sortOrder, String lastId); + + + /** + * Gets public data of given Inbox. + * You do not have to be logged in to call this function. + * + * @param inboxId ID of the Inbox to get + * @return Public accessible information about the Inbox + */ + public native InboxPublicView getInboxPublicView(String inboxId); + + /** + * Deletes an Inbox by given Inbox ID. + * + * @param inboxId ID of the Inbox to delete + * @event type: inboxDeleted + * channel: inbox + * payload: {@link InboxDeletedEventData} + */ + public native void deleteInbox(String inboxId); + + /** + * Prepares a request to send data to an Inbox. + * You do not have to be logged in to call this function. + * + * + * @param inboxId ID of the Inbox to which the request applies + * @param data entry data to send + * @return Inbox handle + */ + public Long /*inboxHandle*/ prepareEntry(String inboxId, byte[] data) { + return prepareEntry(inboxId, data, Collections.emptyList(), null); + } + + /** + * Prepares a request to send data to an Inbox. + * You do not have to be logged in to call this function. + * + * + * @param inboxId ID of the Inbox to which the request applies + * @param data entry data to send + * @param inboxFileHandles optional list of file handles that will be sent with the request + * @return Inbox handle + */ + public Long /*inboxHandle*/ prepareEntry(String inboxId, byte[] data, List inboxFileHandles) { + return prepareEntry(inboxId, data, inboxFileHandles, null); + } + + /** + * Prepares a request to send data to an Inbox. + * You do not have to be logged in to call this function. + * + * + * @param inboxId ID of the Inbox to which the request applies + * @param data entry data to send + * @param inboxFileHandles optional list of file handles that will be sent with the request + * @param userPrivKey optional sender's private key which can be used later to encrypt data for that sender + * @return Inbox handle + */ + public native Long /*inboxHandle*/ prepareEntry(String inboxId, byte[] data, List inboxFileHandles, String userPrivKey); + + /** + * Sends data to an Inbox. + * You do not have to be logged in to call this function. + * + * @param inboxHandle ID of the Inbox to which the request applies + * @event type: inboxEntryCreated + * channel: inbox/<inboxId>/entries + * payload: {@link InboxEntry} + */ + public native void sendEntry(long inboxHandle); + + /** + * Gets an entry from an Inbox. + * + * @param inboxEntryId ID of an entry to read from the Inbox + * @return Data of the selected entry stored in the Inbox + */ + public native InboxEntry readEntry(String inboxEntryId); + + /** + * Gets list of entries in given Inbox. + * + * @param inboxId ID of the Inbox + * @param skip skip number of elements to skip from result + * @param limit limit of elements to return for query + * @param sortOrder order of elements in result ("asc" for ascending, "desc" for descending) + * @return list of entries + */ + public PagingList listEntries(String inboxId, long skip, long limit, String sortOrder){ + return listEntries(inboxId, skip, limit, sortOrder, null); + } + + /** + * Gets list of entries of given Inbox. + * + * @param inboxId ID of the Inbox + * @param skip skip number of elements to skip from result + * @param limit limit of elements to return for query + * @param sortOrder order of elements in result ("asc" for ascending, "desc" for descending) + * @param lastId ID of the element from which query results should start + * @return list of entries + */ + public native PagingList listEntries(String inboxId, long skip, long limit, String sortOrder, String lastId); + + /** + * Deletes an entry from an Inbox. + * + * @param inboxEntryId ID of an entry to delete + * @event type: inboxEntryDeleted + * channel: inbox/<inboxId>/entries + * payload: {@link InboxEntryDeletedEventData} + */ + public native void deleteEntry(String inboxEntryId); + + /** + * Creates a file handle to send a file to an Inbox. + * You do not have to be logged in to call this function. + * + * @param publicMeta public file's metadata + * @param privateMeta private file's metadata + * @param fileSize size of the file to send + * @return File handle + */ + public native Long /*inboxFileHandle*/ createFileHandle(byte[] publicMeta, byte[] privateMeta, long fileSize); + + /** + * Sends a file's data chunk to an Inbox. + * To send the entire file - divide it into pieces of the desired size and call the function for each fragment. + * You do not have to be logged in to call this function. + * + * @param inboxHandle ID of the Inbox to which the request applies + * @param inboxFileHandle handle to the file where the uploaded chunk belongs + * @param dataChunk file chunk to send + */ + public native void writeToFile(long inboxHandle, long inboxFileHandle, byte[] dataChunk); + + + /** + * Opens a file to read. + * + * @param fileId ID of the file to read + * @return Handle to read file data + */ + public native Long openFile(String fileId); + + /** + * Reads file data. + * + * @param fileHandle handle to the file + * @param length size of data to read + * @return File data chunk + */ + public native byte[] readFromFile(long fileHandle, long length); + + /** + * Moves file's read cursor. + * + * @param fileHandle handle to the file + * @param position sets new cursor position + */ + public native void seekInFile(long fileHandle, long position); + + /** + * Closes a file by given handle. + * + * @param fileHandle handle to the file + * @return ID of closed file + */ + public native String closeFile(long fileHandle); + + /** + * Subscribes for the Inbox module main events. + */ + public native void subscribeForInboxEvents(); + + /** + * Subscribes for the Inbox module main events. + */ + public native void unsubscribeFromInboxEvents(); + + /** + * Subscribes for events in given Inbox. + * + * @param inboxId ID of the Inbox to subscribe + */ + public native void subscribeForEntryEvents(String inboxId); + + /** + * Unsubscribes from events in given Inbox. + * + * @param inboxId ID of the Inbox to unsubscribe + */ + public native void unsubscribeFromEntryEvents(String inboxId); + + @Override + public void close() throws Exception { + deinit(); + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/store/StoreApi.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/store/StoreApi.java new file mode 100644 index 0000000..b8adcb2 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/store/StoreApi.java @@ -0,0 +1,384 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.modules.store; + +import com.simplito.java.privmx_endpoint.model.File; +import com.simplito.java.privmx_endpoint.model.PagingList; +import com.simplito.java.privmx_endpoint.model.Store; +import com.simplito.java.privmx_endpoint.model.UserWithPubKey; +import com.simplito.java.privmx_endpoint.model.events.StoreDeletedEventData; +import com.simplito.java.privmx_endpoint.model.events.StoreFileDeletedEventData; +import com.simplito.java.privmx_endpoint.model.events.StoreStatsChangedEventData; +import com.simplito.java.privmx_endpoint.model.exceptions.NativeException; +import com.simplito.java.privmx_endpoint.model.exceptions.PrivmxException; +import com.simplito.java.privmx_endpoint.modules.core.Connection; + +import java.util.List; +import java.util.Objects; + +/** + * Manages PrivMX Bridge Stores and Files. + * + * @category store + */ +public class StoreApi implements AutoCloseable { + static { + System.loadLibrary("crypto"); + System.loadLibrary("ssl"); + System.loadLibrary("privmx-endpoint-java"); + } + + private final Long api; + + /** + * Initialize Store module on passed active connection. + * + * @param connection active connection to PrivMX Bridge + * @throws IllegalStateException when passed {@link Connection} is not connected. + */ + public StoreApi(Connection connection) throws IllegalStateException { + Objects.requireNonNull(connection); + this.api = init(connection); + } + + private native Long init(Connection connection) throws IllegalStateException; + + private native void deinit() throws IllegalStateException; + + /** + * Creates a new Store in given Context. + * + * @param contextId ID of the Context to create the Store in + * @param users list of {@link UserWithPubKey} which indicates who will have access to the created Store + * @param managers list of {@link UserWithPubKey} which indicates who will have access (and management rights) to the + * created Store + * @param publicMeta public (unencrypted) metadata + * @param privateMeta private (encrypted) metadata + * @return Created Store ID + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + * @event type: storeCreated + * channel: store + * payload: {@link Store} + */ + public native String createStore(String contextId, List users, List managers, byte[] publicMeta, byte[] privateMeta) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Updates an existing Store. + * + * @param storeId ID of the Store to update + * @param users list of {@link UserWithPubKey} which indicates who will have access to the updated Store + * @param managers list of {@link UserWithPubKey} which indicates who will have access (and management rights) to the + * updated Store + * @param publicMeta public (unencrypted) metadata + * @param privateMeta private (encrypted) metadata + * @param version current version of the updated Store + * @param force force update (without checking version) + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + * @event type: storeUpdated + * channel: store + * payload: {@link Store} + */ + public void updateStore(String storeId, List users, List managers, byte[] publicMeta, byte[] privateMeta, long version, boolean force) throws PrivmxException, NativeException, IllegalStateException { + updateStore(storeId, users, managers, publicMeta, privateMeta, version, force, true); + } + + /** + * Updates an existing Store. + * + * @param storeId ID of the Store to update + * @param users list of {@link UserWithPubKey} which indicates who will have access to the updated Store + * @param managers list of {@link UserWithPubKey} which indicates who will have access (and management rights) to the + * updated Store + * @param publicMeta public (unencrypted) metadata + * @param privateMeta private (encrypted) metadata + * @param version current version of the updated Store + * @param force force update (without checking version) + * @param forceGenerateNewKey force to regenerate a key for the Store + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + * @event type: storeUpdated + * channel: store + * payload: {@link Store} + */ + public native void updateStore(String storeId, List users, List managers, byte[] publicMeta, byte[] privateMeta, long version, boolean force, boolean forceGenerateNewKey) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Gets a single Store by given Store ID. + * + * @param storeId ID of the Store to get + * @return Information about the Store + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native Store getStore(String storeId) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Gets a list of Stores in given Context. + * + * @param contextId ID of the Context to get the Stores from + * @param skip skip number of elements to skip from result + * @param limit limit of elements to return for query + * @param sortOrder order of elements in result ("asc" for ascending, "desc" for descending) + * @return list of Stores + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public PagingList listStores(String contextId, long skip, long limit, String sortOrder) throws PrivmxException, NativeException, IllegalStateException { + return listStores(contextId, skip, limit, sortOrder, null); + } + + /** + * Gets a list of Stores in given Context. + * + * @param contextId ID of the Context to get the Stores from + * @param skip skip number of elements to skip from result + * @param limit limit of elements to return for query + * @param sortOrder order of elements in result ("asc" for ascending, "desc" for descending) + * @param lastId ID of the element from which query results should start + * @return list of Stores + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native PagingList listStores(String contextId, long skip, long limit, String sortOrder, String lastId) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Deletes a Store by given Store ID. + * + * @param storeId ID of the Store to delete + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + * @event type: storeDeleted + * channel: store + * payload: {@link StoreDeletedEventData} + */ + public native void deleteStore(String storeId) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Creates a new file in a Store. + * + * @param storeId ID of the Store to create the file in + * @param publicMeta public file metadata + * @param privateMeta private file metadata + * @param size size of the file + * @return Handle to write data + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native Long createFile(String storeId, byte[] publicMeta, byte[] privateMeta, long size) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Updates an existing file in a Store. + * + * @param fileId ID of the file to update + * @param publicMeta public file metadata + * @param privateMeta private file metadata + * @param size size of the file + * @return Handle to write file data + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native Long updateFile(String fileId, byte[] publicMeta, byte[] privateMeta, long size) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Updates metadata of an existing file in a Store. + * + * @param fileId ID of the file to update + * @param publicMeta public file metadata + * @param privateMeta private file metadata + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + * @event type: storeFileUpdated + * channel: store/<storeId>/files + * payload: {@link File} + */ + public native void updateFileMeta(String fileId, byte[] publicMeta, byte[] privateMeta) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Writes a file data. + * + * @param fileHandle handle to write file data + * @param dataChunk file data chunk + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native void writeToFile(long fileHandle, byte[] dataChunk) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Deletes a file by given ID. + * + * @param fileId ID of the file to delete + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + * @event type: storeFileDeleted + * channel: store/<storeId>/files + * payload: {@link StoreFileDeletedEventData} + */ + public native void deleteFile(String fileId) throws PrivmxException, NativeException, IllegalStateException; + + + /** + * Gets a single file by the given file ID. + * + * @param fileId ID of the file to get + * @return Information about the file + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native File getFile(String fileId) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Gets a list of files in given Store. + * @param storeId ID of the Store to get files from + * @param skip skip number of elements to skip from result + * @param limit limit of elements to return for query + * @param sortOrder order of elements in result ("asc" for ascending, "desc" for descending) + * @return list of files + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public PagingList listFiles(String storeId, long skip, long limit, String sortOrder) throws PrivmxException, NativeException, IllegalStateException { + return listFiles(storeId, skip, limit, sortOrder, null); + } + + /** + * Gets a list of files in given Store. + * @param storeId ID of the Store to get files from + * @param skip skip number of elements to skip from result + * @param limit limit of elements to return for query + * @param sortOrder order of elements in result ("asc" for ascending, "desc" for descending) + * @param lastId ID of the element from which query results should start + * @return list of files + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native PagingList listFiles(String storeId, long skip, long limit, String sortOrder, String lastId) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Opens a file to read. + * + * @param fileId ID of the file to read + * @return Handle to read file data + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native Long openFile(String fileId) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Reads file data. + * + * @param fileHandle handle to read file data + * @param length size of data to read + * @return File data chunk + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native byte[] readFromFile(long fileHandle, long length) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Moves read cursor. + * + * @param fileHandle handle to read/write file data + * @param position new cursor position + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native void seekInFile(long fileHandle, long position) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Closes the file handle. + * + * @param fileHandle handle to read/write file data + * @return ID of closed file + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + * @event type: storeStatsChanged + * channel: store + * payload: {@link StoreStatsChangedEventData} + * @event type: storeFileCreated + * channel: store/<storeId>/files + * payload: {@link File} + * @event type: storeFileUpdated + * channel: store/<storeId>/files + * payload: {@link File} + */ + public native String closeFile(long fileHandle) throws PrivmxException, NativeException, IllegalStateException; + + + /** + * Subscribes for the Store module main events. + * + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native void subscribeForStoreEvents() throws PrivmxException, NativeException, IllegalStateException; + + /** + * Unsubscribes from the Store module main events. + * + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native void unsubscribeFromStoreEvents() throws PrivmxException, NativeException, IllegalStateException; + + /** + * Subscribes for events in given Store. + * + * @param storeId ID of the Store to subscribe + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native void subscribeForFileEvents(String storeId) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Unsubscribes from events in given Store. + * + * @param storeId ID of the {@code Store} to unsubscribe + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native void unsubscribeFromFileEvents(String storeId) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Frees memory. + * + * @throws Exception when instance is currently closed. + */ + @Override + public void close() throws Exception { + deinit(); + } +} diff --git a/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/thread/ThreadApi.java b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/thread/ThreadApi.java new file mode 100644 index 0000000..7be6f33 --- /dev/null +++ b/privmx-endpoint/src/main/java/com/simplito/java/privmx_endpoint/modules/thread/ThreadApi.java @@ -0,0 +1,311 @@ +// +// PrivMX Endpoint Java. +// Copyright © 2024 Simplito sp. z o.o. +// +// This file is part of the PrivMX Platform (https://privmx.dev). +// This software is Licensed under the MIT License. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package com.simplito.java.privmx_endpoint.modules.thread; + +import com.simplito.java.privmx_endpoint.model.Message; +import com.simplito.java.privmx_endpoint.model.PagingList; +import com.simplito.java.privmx_endpoint.model.Thread; +import com.simplito.java.privmx_endpoint.model.UserWithPubKey; +import com.simplito.java.privmx_endpoint.model.events.ThreadDeletedEventData; +import com.simplito.java.privmx_endpoint.model.events.ThreadDeletedMessageEventData; +import com.simplito.java.privmx_endpoint.model.events.ThreadStatsEventData; +import com.simplito.java.privmx_endpoint.model.exceptions.NativeException; +import com.simplito.java.privmx_endpoint.model.exceptions.PrivmxException; +import com.simplito.java.privmx_endpoint.modules.core.Connection; + +import java.util.List; +import java.util.Objects; + +/** + * Manages Threads and messages. + * + * @category thread + */ +public class ThreadApi implements AutoCloseable { + static { + System.loadLibrary("crypto"); + System.loadLibrary("ssl"); + System.loadLibrary("privmx-endpoint-java"); + } + + private final Long api; + + /** + * Initialize Thread module on given active connection. + * + * @param connection active connection to PrivMX Bridge + * @throws IllegalStateException when given {@link Connection} is not connected + */ + public ThreadApi(Connection connection) throws IllegalStateException { + Objects.requireNonNull(connection); + this.api = init(connection); + } + + private native Long init(Connection connection) throws IllegalStateException; + + private native void deinit() throws IllegalStateException; + + /** + * Creates a new Thread in given Context. + * + * @param contextId ID of the Context to create the Thread in + * @param users list of {@link UserWithPubKey} which indicates who will have access to the created Thread + * @param managers list of {@link UserWithPubKey} which indicates who will have access (and management rights) to + * the created Thread + * @param publicMeta public (unencrypted) metadata + * @param privateMeta private (encrypted) metadata + * @return ID of the created Thread + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + * @event type: threadCreated + * channel: thread + * payload: {@link Thread} + */ + public native String createThread(String contextId, List users, List managers, byte[] publicMeta, byte[] privateMeta) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Updates an existing Thread. + * + * @param threadId ID of the Thread to update + * @param users list of {@link UserWithPubKey} which indicates who will have access to the updated Thread + * @param managers list of {@link UserWithPubKey} which indicates who will have access (and management rights) to + * the updated Thread + * @param publicMeta public (unencrypted) metadata + * @param privateMeta private (encrypted) metadata + * @param version current version of the updated Thread + * @param force force update (without checking version) + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + * @event type: threadUpdated + * channel: thread + * payload: {@link Thread} + */ + public void updateThread(String threadId, List users, List managers, byte[] publicMeta, byte[] privateMeta, long version, boolean force) throws PrivmxException, NativeException, IllegalStateException { + updateThread(threadId, users, managers, publicMeta, privateMeta, version, force, true); + } + + /** + * Updates an existing Thread. + * + * @param threadId ID of the Thread to update + * @param users list of {@link UserWithPubKey} which indicates who will have access to the updated Thread + * @param managers list of {@link UserWithPubKey} which indicates who will have access (and management rights) to + * the updated Thread + * @param publicMeta public (unencrypted) metadata + * @param privateMeta private (encrypted) metadata + * @param version current version of the updated Thread + * @param force force update (without checking version) + * @param forceGenerateNewKey force to regenerate a key for the Thread + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + * @event type: threadUpdated + * channel: thread + * payload: {@link Thread} + */ + public native void updateThread(String threadId, List users, List managers, byte[] publicMeta, byte[] privateMeta, long version, boolean force, boolean forceGenerateNewKey) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Gets a Thread by given Thread ID. + * + * @param threadId ID of Thread to get + * @return Information about the Thread + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native Thread getThread(String threadId) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Gets a list of Threads in given Context. + * + * @param contextId ID of the Context to get the Threads from + * @param skip skip number of elements to skip from result + * @param limit limit of elements to return for query + * @param sortOrder order of elements in result ("asc" for ascending, "desc" for descending) + * @return list of Threads + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception + * @throws NativeException thrown when method encounters an unknown exception + */ + public PagingList listThreads(String contextId, long skip, long limit, String sortOrder) throws PrivmxException, NativeException, IllegalStateException { + return listThreads(contextId, skip, limit, sortOrder, null); + } + + /** + * Gets a list of Threads in given Context. + * @param contextId ID of the Context to get the Threads from + * @param skip skip number of elements to skip from result + * @param limit limit of elements to return for query + * @param sortOrder order of elements in result ("asc" for ascending, "desc" for descending) + * @param lastId ID of the element from which query results should start + * @return list of Threads + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception + * @throws NativeException thrown when method encounters an unknown exception + */ + public native PagingList listThreads(String contextId, long skip, long limit, String sortOrder, String lastId) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Deletes a Thread by given Thread ID. + * + * @param threadId ID of the Thread to delete + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + * @event type: threadDeleted + * channel: thread + * payload: {@link ThreadDeletedEventData} + */ + public native void deleteThread(String threadId) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Sends a message in a Thread. + * + * @param threadId ID of the Thread to send message to + * @param publicMeta public message metadata + * @param privateMeta private message metadata + * @param data content of the message + * @return ID of the new message + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + * @event type: threadNewMessage + * channel: thread/<threadId>/messages + * payload: {@link Message} + * @event type: threadStats + * channel: thread + * payload: {@link ThreadStatsEventData} + */ + public native String sendMessage(String threadId, byte[] publicMeta, byte[] privateMeta, byte[] data) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Gets a message by given message ID. + * + * @param messageId ID of the message to get + * @return Message with matching id + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native Message getMessage(String messageId) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Gets a list of messages from a Thread. + * + * @param threadId ID of the Thread to list messages from + * @param skip skip number of elements to skip from result + * @param limit limit of elements to return for query + * @param sortOrder order of elements in result ("asc" for ascending, "desc" for descending) + * @return list of messages + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public PagingList listMessages(String threadId, long skip, long limit, String sortOrder) throws PrivmxException, NativeException, IllegalStateException { + return listMessages(threadId, skip, limit, sortOrder, null); + } + + /** + * Gets a list of messages from a Thread. + * + * @param threadId ID of the Thread to list messages from + * @param skip skip number of elements to skip from result + * @param limit limit of elements to return for query + * @param sortOrder order of elements in result ("asc" for ascending, "desc" for descending) + * @param lastId ID of the element from which query results should start + * @return list of messages + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native PagingList listMessages(String threadId, long skip, long limit, String sortOrder, String lastId) throws PrivmxException, NativeException, IllegalStateException; + + + /** + * Deletes a message by given message ID. + * + * @param messageId ID of the message to delete + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + * @event type: threadMessageDeleted + * channel: thread/<threadId>/messages + * payload: {@link ThreadDeletedMessageEventData} + */ + public native void deleteMessage(String messageId) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Updates message in a Thread. + * @param messageId ID of the message to update + * @param publicMeta public message metadata + * @param privateMeta private message metadata + * @param data new content of the message + * @event type: threadUpdatedMessage + * channel: thread/<threadId>/messages + * payload: {@link Message} + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native void updateMessage(String messageId, byte[] publicMeta, byte[] privateMeta, byte[] data) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Subscribes for the Thread module main events. + * + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native void subscribeForThreadEvents() throws PrivmxException, NativeException, IllegalStateException; + + /** + * Unsubscribes from the Thread module main events. + * + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native void unsubscribeFromThreadEvents() throws PrivmxException, NativeException, IllegalStateException; + + /** + * Subscribes for events in given Thread. + * @param threadId ID of the Thread to subscribe + * + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native void subscribeForMessageEvents(String threadId) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Unsubscribes from events in given Thread. + * @param threadId ID of the Thread to unsubscribe + * + * @throws IllegalStateException thrown when instance is closed. + * @throws PrivmxException thrown when method encounters an exception. + * @throws NativeException thrown when method encounters an unknown exception. + */ + public native void unsubscribeFromMessageEvents(String threadId) throws PrivmxException, NativeException, IllegalStateException; + + /** + * Frees memory. + * + * @throws Exception when instance is currently closed. + */ + @Override + public void close() throws Exception { + deinit(); + } +} diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..720cd61 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,31 @@ +pluginManagement { + repositories { + google { + content { + includeGroupByRegex("com\\.android.*") + includeGroupByRegex("com\\.google.*") + includeGroupByRegex("androidx.*") + } + } + mavenCentral() + gradlePluginPortal() + } +} +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.5.0' +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "PrivmxEndpoint" +include ':privmx-endpoint' +include ':privmx-endpoint-extra' +include ':privmx-endpoint-android' +include ':privmx-endpoint-jni' +project(':privmx-endpoint-jni').projectDir = file("privmx-endpoint/src/main/cpp") \ No newline at end of file