diff --git a/README.md b/README.md index d19b0ff..b67b6aa 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ Monorepo of all my Capacitor plugins. | [`@danyalwe/capacitor-battery`](packages/battery) | [![npm](https://img.shields.io/npm/v/@danyalwe/capacitor-battery)](https://www.npmjs.com/package/@danyalwe/capacitor-battery) | Capacitor plugin for battery monitoring | | [`@danyalwe/capacitor-sensors`](packages/sensors) | [![npm](https://img.shields.io/npm/v/@danyalwe/capacitor-sensors)](https://www.npmjs.com/package/@danyalwe/capacitor-sensors) | Capacitor plugin for device sensors | | [`@danyalwe/capacitor-systeminfo`](packages/systeminfo) | [![npm](https://img.shields.io/npm/v/@danyalwe/capacitor-systeminfo)](https://www.npmjs.com/package/@danyalwe/capacitor-systeminfo) | Capacitor plugin for device system information | +| [`@danyalwe/capacitor-connection`](packages/connection) | [![npm](https://img.shields.io/npm/v/@danyalwe/capacitor-connection)](https://www.npmjs.com/package/@danyalwe/capacitor-connection) | Capacitor plugin for network connection monitoring | ## Development diff --git a/package.json b/package.json index 4967957..7163c75 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,8 @@ "docs:preview": "bun run --cwd docs preview", "release:battery": "bun run --cwd packages/battery release", "release:sensors": "bun run --cwd packages/sensors release", - "release:systeminfo": "bun run --cwd packages/systeminfo release" + "release:systeminfo": "bun run --cwd packages/systeminfo release", + "release:connection": "bun run --cwd packages/connection release" }, "devDependencies": { "@antfu/eslint-config": "^9.1.0", diff --git a/packages/battery/android/src/main/kotlin/com/danyalwe/capacitor/battery/Battery.kt b/packages/battery/android/src/main/kotlin/com/danyalwe/capacitor/battery/Battery.kt index 0aa820a..b1c692a 100644 --- a/packages/battery/android/src/main/kotlin/com/danyalwe/capacitor/battery/Battery.kt +++ b/packages/battery/android/src/main/kotlin/com/danyalwe/capacitor/battery/Battery.kt @@ -10,8 +10,6 @@ import com.getcapacitor.JSObject import java.util.Timer import java.util.TimerTask import kotlin.math.abs -import kotlin.math.max - class Battery( private val plugin: BatteryPlugin, diff --git a/packages/battery/android/src/main/kotlin/com/danyalwe/capacitor/battery/BatteryPlugin.kt b/packages/battery/android/src/main/kotlin/com/danyalwe/capacitor/battery/BatteryPlugin.kt index 402927e..e27f941 100644 --- a/packages/battery/android/src/main/kotlin/com/danyalwe/capacitor/battery/BatteryPlugin.kt +++ b/packages/battery/android/src/main/kotlin/com/danyalwe/capacitor/battery/BatteryPlugin.kt @@ -1,6 +1,6 @@ package com.danyalwe.capacitor.battery -import android.content.Intent +import android.util.Log import com.getcapacitor.JSObject import com.getcapacitor.Plugin import com.getcapacitor.PluginCall @@ -27,11 +27,13 @@ class BatteryPlugin : Plugin() { @PluginMethod fun start(call: PluginCall) { + Log.d("Start", "Battery Plugin") implementation.start() } @PluginMethod fun stop(call: PluginCall) { implementation.stop() + Log.d("Stop", "Battery Plugin") } } \ No newline at end of file diff --git a/packages/connection/.eslintignore b/packages/connection/.eslintignore new file mode 100644 index 0000000..23f8944 --- /dev/null +++ b/packages/connection/.eslintignore @@ -0,0 +1,3 @@ +build +dist +example-app diff --git a/packages/connection/.gitignore b/packages/connection/.gitignore new file mode 100644 index 0000000..df9f0c2 --- /dev/null +++ b/packages/connection/.gitignore @@ -0,0 +1,70 @@ +# node files +dist +node_modules + +# iOS files +Pods +Podfile.lock +Package.resolved +Build +xcuserdata +/.build +/Packages +xcuserdata/ +DerivedData/ +.swiftpm/configuration/registries.json +.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata +.netrc + + +# macOS files +.DS_Store + + + +# Based on Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore + +# Built application files +*.apk +*.ap_ + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin +gen +out + +# Gradle files +.gradle +build + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation + +# Android Studio captures folder +captures + +# IntelliJ +*.iml +.idea + +# Keystore files +# Uncomment the following line if you do not want to check your keystore files in. +#*.jks + +# External native build folder generated in Android Studio 2.2 and later +.externalNativeBuild diff --git a/packages/connection/.prettierignore b/packages/connection/.prettierignore new file mode 100644 index 0000000..5ab6e14 --- /dev/null +++ b/packages/connection/.prettierignore @@ -0,0 +1 @@ +example-app diff --git a/packages/connection/CHANGELOG.md b/packages/connection/CHANGELOG.md new file mode 100644 index 0000000..4e4146b --- /dev/null +++ b/packages/connection/CHANGELOG.md @@ -0,0 +1,13 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines. + +## 1.0.0 (2026-07-09) + +### ⚠ BREAKING CHANGES + +* upgraded to Capacitor v8 (peer dependency bumped to `@capacitor/core >=8.0.0`) + +### Code Refactoring + +* migrated to a Bun workspace monorepo (build, lint, and test now run from the repo root via tsdown, ESLint flat config, and vitest) diff --git a/packages/connection/CONTRIBUTING.md b/packages/connection/CONTRIBUTING.md new file mode 100644 index 0000000..9d78ae3 --- /dev/null +++ b/packages/connection/CONTRIBUTING.md @@ -0,0 +1,54 @@ +# Contributing + +This guide provides instructions for contributing to this Capacitor plugin. + +## Developing + +### Local Setup + +1. Fork and clone the repo. +1. Install the dependencies from the **repo root** (this plugin is part of a Bun workspace monorepo). + + ```shell + bun install + ``` + +1. Install SwiftLint if you're on macOS. + + ```shell + brew install swiftlint + ``` + +### Scripts + +#### `bun run build` (repo root) + +Building web assets happens once for all plugins from the **monorepo root**, not per-plugin. From the repo root, run: + +```shell +bun run build +``` + +This compiles the TypeScript code from each plugin's `src/` using [tsdown](https://tsdown.dev) in workspace mode, producing ESM (`dist/index.mjs`), CJS (`dist/index.cjs`), and type declarations (`dist/index.d.mts` / `dist/index.d.cts`). + +To generate plugin API documentation, run `bun run docgen` from the repo root (uses [`@capacitor/docgen`](https://github.com/ionic-team/capacitor-docgen)). + +#### `bun run verify` + +Validate the native iOS and Android projects build correctly. Web build/lint/test is handled by the root CI, not this script. + +#### `bun run lint` / `bun run fmt` + +Check formatting and code quality for this plugin, autoformat/autofix if possible. + +This checks Prettier and SwiftLint. Linting of TypeScript code (ESLint) is handled at the monorepo root via `bun run lint`. + +## Publishing + +Publishing is automated via GitHub Actions and is not done manually with `npm publish`. + +1. From the repo root, run this plugin's release script (e.g. `bun run release:sensors`), which uses `commit-and-tag-version` to bump the version, update `CHANGELOG.md`, and create a git tag. +1. Push the tag: `git push --follow-tags`. +1. Pushing a tag matching `capacitor-*@*` triggers the `release.yml` GitHub Actions workflow, which builds from the repo root and publishes this plugin to npm via [trusted publishing](https://docs.npmjs.com/trusted-publishers) (OIDC) — no npm token or manual `npm publish` needed. + +> **Note**: The [`files`](https://docs.npmjs.com/cli/v7/configuring-npm/package-json#files) array in `package.json` specifies which files get published. If you rename files/directories or add files elsewhere, you may need to update it. diff --git a/packages/connection/Connection.podspec b/packages/connection/Connection.podspec new file mode 100644 index 0000000..20207a7 --- /dev/null +++ b/packages/connection/Connection.podspec @@ -0,0 +1,17 @@ +require 'json' + +package = JSON.parse(File.read(File.join(__dir__, 'package.json'))) + +Pod::Spec.new do |s| + s.name = 'Battery' + s.version = package['version'] + s.summary = package['description'] + s.license = package['license'] + s.homepage = package['repository']['url'] + s.author = package['author'] + s.source = { :git => package['repository']['url'], :tag => s.version.to_s } + s.source_files = 'ios/Sources/**/*.{swift,h,m,c,cc,mm,cpp}' + s.ios.deployment_target = '15.0' + s.dependency 'Capacitor' + s.swift_version = '5.1' +end diff --git a/packages/connection/Package.swift b/packages/connection/Package.swift new file mode 100644 index 0000000..a756daf --- /dev/null +++ b/packages/connection/Package.swift @@ -0,0 +1,28 @@ +// swift-tools-version: 5.9 +import PackageDescription + +let package = Package( + name: "Connection", + platforms: [.iOS(.v15)], + products: [ + .library( + name: "Connection", + targets: ["ConnectionPlugin"]) + ], + dependencies: [ + .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "8.0.0") + ], + targets: [ + .target( + name: "ConnectionPlugin", + dependencies: [ + .product(name: "Capacitor", package: "capacitor-swift-pm"), + .product(name: "Cordova", package: "capacitor-swift-pm") + ], + path: "ios/Sources/ConnectionPlugin"), + .testTarget( + name: "ConnectionPluginTests", + dependencies: ["ConnectionPlugin"], + path: "ios/Tests/ConnectionPluginTests") + ] +) \ No newline at end of file diff --git a/packages/connection/README.md b/packages/connection/README.md new file mode 100644 index 0000000..756aebd --- /dev/null +++ b/packages/connection/README.md @@ -0,0 +1,123 @@ +# Capacitor Plugin - Battery + +Get access to every info about the device battery! + +Supported Android version: `24+`\ +Supported iOS version: `Not supported`\ +Supported Browsers: `Chromium-based` + +## Install + +```bash +npm install @danyalwe/capacitor-battery +npx cap sync +``` + +## Todos + +- [ ] Add support for iOS + +## Supported methods + +| Name | Android | iOS | Web | +| :----------------- | :------ | :-- | :-- | +| start | ✅ | ❌ | ✅ | +| stop | ✅ | ❌ | ✅ | +| addListener | ✅ | ❌ | ✅ | +| removeAllListeners | ✅ | ❌ | ✅ | + +## Supported properties + +| Property | Android | iOS | Web | +| :-------------------- | :------ | :-- | :-- | +| **`currentCapacity`** | ✅ | ❌ | ❌ | +| **`totalCapacity`** | ✅ | ❌ | ❌ | +| **`realPercentage`** | ✅ | ❌ | ❌ | +| **`technology`** | ✅ | ❌ | ❌ | +| **`temperature`** | ✅ | ❌ | ❌ | +| **`voltage`** | ✅ | ❌ | ❌ | +| **`amperage`** | ✅ | ❌ | ❌ | +| **`wattage`** | ✅ | ❌ | ❌ | +| **`health`** | ✅ | ❌ | ❌ | +| **`status`** | ✅ | ❌ | ❌ | +| **`chargeMode`** | ✅ | ❌ | ❌ | +| **`level`** | ✅ | ❌ | ✅ | +| **`hasBattery`** | ✅ | ❌ | ✅ | +| **`isCharging`** | ✅ | ❌ | ✅ | +| **`chargingTime`** | ❌ | ❌ | ✅ | +| **`dischargingTime`** | ❌ | ❌ | ✅ | + +## API + + + +* [Interfaces](#interfaces) +* [Type Aliases](#type-aliases) + + + + + + +Represents the BatteryPlugin interface. + +### Interfaces + + +#### BatteryInfo + +Represents the battery information of the device. + +| Prop | Type | Description | +| ------------------- | -------------------- | ---------------------------------------- | +| **`totalCapacity`** | number | The total battery capacity (in mAh). | +| **`technology`** | string | The technology used in the battery. | +| **`hasBattery`** | boolean | Whether the device has a battery or not. | + + +#### BatteryData + +Represents the battery data that can change over time. + +| Prop | Type | Description | +| --------------------- | --------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| **`level`** | number | The current battery level as a percentage (0-100). | +| **`isCharging`** | boolean | Whether the device is currently charging or not. | +| **`chargingTime`** | number | The estimated time remaining until the battery is fully charged (in minutes). | +| **`dischargingTime`** | number | The estimated time remaining until the battery is fully discharged (in minutes). | +| **`currentCapacity`** | number | The current battery capacity (in mAh). | +| **`realPercentage`** | number | The real battery percentage, which may differ from the reported percentage. | +| **`temperature`** | number | The current temperature of the battery (in Celsius). | +| **`voltage`** | number | The current voltage of the battery (in volts). | +| **`amperage`** | number | The current amperage of the battery (in amperes). | +| **`wattage`** | number | The current wattage of the battery (in watts). | +| **`health`** | BatteryHealth | The health status of the battery. | +| **`status`** | BatteryStatus | The status of the battery. | +| **`chargeMode`** | BatteryChargeMode | The charging mode of the battery. | + + +#### PluginListenerHandle + +| Prop | Type | +| ------------ | ----------------------------------------- | +| **`remove`** | () => Promise<void> | + + +### Type Aliases + + +#### BatteryHealth + +(typeof BatteryHealths)[number] + + +#### BatteryStatus + +(typeof BatteryStatuses)[number] + + +#### BatteryChargeMode + +(typeof BatteryChargeModes)[number] + + diff --git a/packages/connection/android/.gitignore b/packages/connection/android/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/packages/connection/android/.gitignore @@ -0,0 +1 @@ +/build diff --git a/packages/connection/android/build.gradle b/packages/connection/android/build.gradle new file mode 100644 index 0000000..4ba158c --- /dev/null +++ b/packages/connection/android/build.gradle @@ -0,0 +1,67 @@ +ext { + junitVersion = project.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2' + androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.7.1' + androidxJunitVersion = project.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.3.0' + androidxEspressoCoreVersion = project.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.7.0' + androidxCoreKTXVersion = project.hasProperty('androidxCoreKTXVersion') ? rootProject.ext.androidxCoreKTXVersion : '1.17.0' +} + +buildscript { + ext.kotlin_version = project.hasProperty("kotlin_version") ? rootProject.ext.kotlin_version : '2.2.20' + repositories { + google() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:8.13.0' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' + +android { + namespace = "com.danyalwe.capacitor.connection" + compileSdk = project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 36 + defaultConfig { + minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 24 + targetSdkVersion project.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 36 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + lintOptions { + abortOnError = false + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_21 + targetCompatibility JavaVersion.VERSION_21 + } +} + +kotlin { + jvmToolchain(21) +} + +repositories { + google() + mavenCentral() +} + + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation project(':capacitor-android') + implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion" + implementation "androidx.core:core-ktx:$androidxCoreKTXVersion" + testImplementation "junit:junit:$junitVersion" + androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion" + androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion" +} diff --git a/packages/connection/android/gradle.properties b/packages/connection/android/gradle.properties new file mode 100644 index 0000000..2e87c52 --- /dev/null +++ b/packages/connection/android/gradle.properties @@ -0,0 +1,22 @@ +# 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=-Xmx1536m + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true + +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true diff --git a/packages/connection/android/gradle/wrapper/gradle-wrapper.jar b/packages/connection/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/packages/connection/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/packages/connection/android/gradle/wrapper/gradle-wrapper.properties b/packages/connection/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..7705927 --- /dev/null +++ b/packages/connection/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/packages/connection/android/gradlew b/packages/connection/android/gradlew new file mode 100755 index 0000000..23d15a9 --- /dev/null +++ b/packages/connection/android/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original 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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# 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 + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/packages/connection/android/gradlew.bat b/packages/connection/android/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/packages/connection/android/gradlew.bat @@ -0,0 +1,94 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@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=. +@rem This is normally unused +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% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/packages/connection/android/proguard-rules.pro b/packages/connection/android/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/packages/connection/android/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/packages/connection/android/settings.gradle b/packages/connection/android/settings.gradle new file mode 100644 index 0000000..1e5b843 --- /dev/null +++ b/packages/connection/android/settings.gradle @@ -0,0 +1,2 @@ +include ':capacitor-android' +project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor') \ No newline at end of file diff --git a/packages/connection/android/src/androidTest/kotlin/com/getcapacitor/android/ExampleInstrumentedTest.kt b/packages/connection/android/src/androidTest/kotlin/com/getcapacitor/android/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..8e8e3f0 --- /dev/null +++ b/packages/connection/android/src/androidTest/kotlin/com/getcapacitor/android/ExampleInstrumentedTest.kt @@ -0,0 +1,26 @@ +package com.getcapacitor.android + +import android.content.Context +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + + @Test + @Throws(Exception::class) + fun useAppContext() { + // Context of the app under test. + val appContext: Context = InstrumentationRegistry.getInstrumentation().targetContext + + assertEquals("com.getcapacitor.android", appContext.packageName) + } +} diff --git a/packages/connection/android/src/main/AndroidManifest.xml b/packages/connection/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..7326baa --- /dev/null +++ b/packages/connection/android/src/main/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + + diff --git a/packages/connection/android/src/main/kotlin/com/danyalwe/capacitor/connection/Connection.kt b/packages/connection/android/src/main/kotlin/com/danyalwe/capacitor/connection/Connection.kt new file mode 100644 index 0000000..d92a476 --- /dev/null +++ b/packages/connection/android/src/main/kotlin/com/danyalwe/capacitor/connection/Connection.kt @@ -0,0 +1,97 @@ +package com.danyalwe.capacitor.connection + +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.net.ConnectivityManager +import android.net.ConnectivityManager.NetworkCallback +import android.net.Network +import android.net.NetworkCapabilities +import android.net.NetworkRequest +import android.net.wifi.WifiManager +import android.os.Build +import android.telephony.TelephonyManager +import android.util.Log +import com.getcapacitor.JSArray +import com.getcapacitor.JSObject + +class Connection( + private val plugin: ConnectionPlugin, + private val context: Context +) : NetworkCallback() { + private val intentFilter = IntentFilter() + private var connectivityManager: ConnectivityManager? = null + private var networkRequest: NetworkRequest? = null + + init { + intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION) + intentFilter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED) + connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + networkRequest = NetworkRequest.Builder() + .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) + .addTransportType(NetworkCapabilities.TRANSPORT_BLUETOOTH) + .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) + .addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET) + .addTransportType(NetworkCapabilities.TRANSPORT_VPN) + .build() + } + + fun start() { + networkRequest?.let { connectivityManager?.registerNetworkCallback(it, this) } + Log.d("Start", "Connection Plugin") + } + + fun stop() { + connectivityManager?.unregisterNetworkCallback(this) + Log.d("Stop", "Connection Plugin") + } + + fun getInfos(): JSObject { + val obj = JSObject() + return obj + } + + private fun getSimData(): JSArray { + val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager + + val totSim = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + telephonyManager.activeModemCount + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + telephonyManager.phoneCount + } else 1 + + val sims = JSArray() + + if (totSim > 1 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + for (i in 0 until totSim) { + val sim = JSObject() + sim.put("state", telephonyManager.getSimState(i)) + sims.put(sim) + } + } else { + val sim = JSObject() + sim.put("state", telephonyManager.simState) + sims.put(sim) + } + + return sims + } + + override fun onUnavailable() { + val content = JSObject() + content.put("sims", getSimData()) + this.plugin.notify("connectionChange", content, true) + } + + override fun onAvailable(network: Network) { + val content = JSObject() + content.put("sims", getSimData()) + this.plugin.notify("connectionChange", content, true) + } + + override fun onLost(network: Network) { + val content = JSObject() + content.put("sims", getSimData()) + this.plugin.notify("connectionChange", content, true) + } +} \ No newline at end of file diff --git a/packages/connection/android/src/main/kotlin/com/danyalwe/capacitor/connection/ConnectionPlugin.kt b/packages/connection/android/src/main/kotlin/com/danyalwe/capacitor/connection/ConnectionPlugin.kt new file mode 100644 index 0000000..d9b4288 --- /dev/null +++ b/packages/connection/android/src/main/kotlin/com/danyalwe/capacitor/connection/ConnectionPlugin.kt @@ -0,0 +1,77 @@ +package com.danyalwe.capacitor.connection + +import android.Manifest +import android.os.Build +import com.getcapacitor.PermissionState +import com.getcapacitor.JSObject +import com.getcapacitor.Plugin +import com.getcapacitor.PluginCall +import com.getcapacitor.PluginMethod +import com.getcapacitor.annotation.CapacitorPlugin +import com.getcapacitor.annotation.Permission +import com.getcapacitor.annotation.PermissionCallback + +@CapacitorPlugin( + name = "Connection", + permissions = [ + Permission( + alias = "connectionAboveOreo", + strings = arrayOf( + Manifest.permission.ACCESS_FINE_LOCATION, + Manifest.permission.READ_PHONE_STATE + ) + ), + Permission( + alias = "connectionUnderOreo", + strings = arrayOf( + Manifest.permission.READ_PHONE_STATE + ) + ) + ] +) +class ConnectionPlugin : Plugin() { + private lateinit var implementation: Connection + + override fun load() { + super.load() + implementation = Connection(this, context) + } + + fun notify(eventName: String, data: JSObject, retainUntilConsumed: Boolean): Unit { + return notifyListeners(eventName, data, retainUntilConsumed) + } + + @PluginMethod + fun getInfos(call: PluginCall) { + call.resolve(implementation.getInfos()) + } + + private fun hasPermissions(call: PluginCall): Boolean { + if (getPermissionState("connectionAboveOreo") != PermissionState.GRANTED + && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + requestPermissionForAlias("connectionAboveOreo", call, "permissionsCallback") + return false + } else if (getPermissionState("connectionUnderOreo") != PermissionState.GRANTED + && Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + requestPermissionForAlias("connectionUnderOreo", call, "permissionsCallback") + return false + } + return true + } + + @PluginMethod + override fun requestPermissions(call: PluginCall) { + hasPermissions(call) + } + + override fun removeAllListeners(call: PluginCall) { + implementation.stop() + super.removeAllListeners(call) + } + + @PermissionCallback + private fun permissionsCallback(call: PluginCall) { + if (hasPermissions(call)) implementation.start() + else call.reject("Permission is required to access connection information.") + } +} \ No newline at end of file diff --git a/packages/connection/android/src/main/res/.gitkeep b/packages/connection/android/src/main/res/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/packages/connection/android/src/test/kotlin/com/getcapacitor/ExampleUnitTest.kt b/packages/connection/android/src/test/kotlin/com/getcapacitor/ExampleUnitTest.kt new file mode 100644 index 0000000..ba1894e --- /dev/null +++ b/packages/connection/android/src/test/kotlin/com/getcapacitor/ExampleUnitTest.kt @@ -0,0 +1,18 @@ +package com.getcapacitor + +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * Example local unit test, which will execute on the development machine (host). + * + * @see Testing documentation + */ +class ExampleUnitTest { + + @Test + @Throws(Exception::class) + fun addition_isCorrect() { + assertEquals(4, 2 + 2) + } +} diff --git a/packages/connection/ios/.gitignore b/packages/connection/ios/.gitignore new file mode 100644 index 0000000..afb34f8 --- /dev/null +++ b/packages/connection/ios/.gitignore @@ -0,0 +1,8 @@ +.DS_Store +.build +/Packages +xcuserdata/ +DerivedData/ +.swiftpm/configuration/registries.json +.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata +.netrc \ No newline at end of file diff --git a/packages/connection/ios/Sources/ConnectionPlugin/Connection.swift b/packages/connection/ios/Sources/ConnectionPlugin/Connection.swift new file mode 100644 index 0000000..36c2bbe --- /dev/null +++ b/packages/connection/ios/Sources/ConnectionPlugin/Connection.swift @@ -0,0 +1,8 @@ +import Foundation + +@objc public class Connection: NSObject { + @objc public func echo(_ value: String) -> String { + print(value) + return value + } +} diff --git a/packages/connection/ios/Sources/ConnectionPlugin/ConnectionPlugin.swift b/packages/connection/ios/Sources/ConnectionPlugin/ConnectionPlugin.swift new file mode 100644 index 0000000..781dd08 --- /dev/null +++ b/packages/connection/ios/Sources/ConnectionPlugin/ConnectionPlugin.swift @@ -0,0 +1,23 @@ +import Foundation +import Capacitor + +/** + * Please read the Capacitor iOS Plugin Development Guide + * here: https://capacitorjs.com/docs/plugins/ios + */ +@objc(ConnectionPlugin) +public class ConnectionPlugin: CAPPlugin, CAPBridgedPlugin { + public let identifier = "ConnectionPlugin" + public let jsName = "Connection" + public let pluginMethods: [CAPPluginMethod] = [ + CAPPluginMethod(name: "echo", returnType: CAPPluginReturnPromise) + ] + private let implementation = Connection() + + @objc func echo(_ call: CAPPluginCall) { + let value = call.getString("value") ?? "" + call.resolve([ + "value": implementation.echo(value) + ]) + } +} diff --git a/packages/connection/ios/Tests/ConnectionPluginTests/ConnectionTests.swift b/packages/connection/ios/Tests/ConnectionPluginTests/ConnectionTests.swift new file mode 100644 index 0000000..cd4bf25 --- /dev/null +++ b/packages/connection/ios/Tests/ConnectionPluginTests/ConnectionTests.swift @@ -0,0 +1,12 @@ +import XCTest +@testable import ConnectionPlugin + +class ConnectionTests: XCTestCase { + func testEcho() { + let implementation = Connection() + let value = "Hello, World!" + let result = implementation.echo(value) + + XCTAssertEqual(value, result) + } +} diff --git a/packages/connection/package.json b/packages/connection/package.json new file mode 100644 index 0000000..44a7576 --- /dev/null +++ b/packages/connection/package.json @@ -0,0 +1,71 @@ +{ + "name": "@danyalwe/capacitor-connection", + "version": "1.0.0", + "description": "Capacitor plugin for network connection monitoring", + "author": "zAlweNy26", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/zAlweNy26/capacitor-plugins.git" + }, + "bugs": { + "url": "https://github.com/zAlweNy26/capacitor-plugins/issues" + }, + "keywords": [ + "capacitor", + "plugin", + "native" + ], + "main": "dist/index.cjs", + "module": "dist/index.mjs", + "types": "dist/index.d.mts", + "files": [ + "Connection.podspec", + "Package.swift", + "android/", + "dist/", + "ios/" + ], + "publishConfig": { + "access": "public" + }, + "scripts": { + "verify": "bun run verify:ios && bun run verify:android", + "verify:ios": "xcodebuild -scheme Connection -destination generic/platform=iOS", + "verify:android": "cd android && ./gradlew clean build test && cd ..", + "lint": "bun run prettier -- --check && bun run swiftlint -- lint", + "fmt": "bun run prettier -- --write && bun run swiftlint -- --fix --format", + "prettier": "prettier \"**/*.{css,html,ts,js,java}\" --plugin=prettier-plugin-java", + "swiftlint": "node-swiftlint", + "docgen": "docgen --api ConnectionPlugin --output-readme README.md --output-json dist/docs.json", + "test": "vitest run", + "watch": "tsc --watch", + "release": "commit-and-tag-version --path . --tag-prefix \"capacitor-connection@\"" + }, + "peerDependencies": { + "@capacitor/core": ">=8.0.0" + }, + "devDependencies": { + "@capacitor/android": "^8.4.1", + "@capacitor/core": "^8.4.1", + "@capacitor/docgen": "^0.3.1", + "@capacitor/ios": "^8.4.1", + "@ionic/prettier-config": "^4.0.0", + "@ionic/swiftlint-config": "^2.0.0", + "prettier": "^3.9.5", + "prettier-plugin-java": "^2.10.2", + "swiftlint": "^2.0.0", + "typescript": "^5.9.3", + "vitest": "^4.1.10" + }, + "prettier": "@ionic/prettier-config", + "swiftlint": "@ionic/swiftlint-config", + "capacitor": { + "ios": { + "src": "ios" + }, + "android": { + "src": "android" + } + } +} diff --git a/packages/connection/src/__tests__/index.test.ts b/packages/connection/src/__tests__/index.test.ts new file mode 100644 index 0000000..8cfc1e8 --- /dev/null +++ b/packages/connection/src/__tests__/index.test.ts @@ -0,0 +1,8 @@ +import { describe, expect, it } from 'vitest' + +describe('connection', () => { + it('should be importable', async () => { + const mod = await import('../index') + expect(mod.Connection).toBeDefined() + }) +}) diff --git a/packages/connection/src/definitions.ts b/packages/connection/src/definitions.ts new file mode 100644 index 0000000..800e691 --- /dev/null +++ b/packages/connection/src/definitions.ts @@ -0,0 +1,47 @@ +import type { PluginListenerHandle } from '@capacitor/core' + +/** + * Array of possible SIM states. + */ +export const SimStates = ['UNKNOWN', 'ABSENT', 'PIN_REQUIRED', 'PUK_REQUIRED', 'NETWORK_LOCKED', 'READY', 'NOT_READY', 'PERMANENTLY_DISABLED', 'IO_ERROR', 'RESTRICTED'] as const + +export type SimState = (typeof SimStates)[number] + +export interface SimData { + state: SimState +} + +export interface ConnectionListenerResult { + sims: SimData[] +} + +/** Represents the ConnectionPlugin interface. */ +export interface ConnectionPlugin { + /** + * Returns a Promise that resolves with an object containing connection information. + * @returns ConnectionInfo + */ + getInfos: () => Promise + /** + * Checks the permissions for the connection data. + * @returns A Promise that resolves to the permission status. + */ + checkPermissions: () => Promise + /** + * Requests permission for the connection data. + * @returns A Promise that resolves to the permission status. + */ + requestPermissions: () => Promise + /** + * Adds a listener for the given connection event. + * @param eventName The name of the event to listen for. + * @param listenerFunc The function to call when the event is triggered. + * @returns A Promise that resolves to a handle for the listener. + */ + addListener: (eventName: 'connectionChange', listenerFunc: (event: ConnectionListenerResult) => void) => Promise + /** + * Removes all listeners for the connection plugin. + * @returns A Promise that resolves when all listeners have been removed. + */ + removeAllListeners: () => Promise +} diff --git a/packages/connection/src/index.ts b/packages/connection/src/index.ts new file mode 100644 index 0000000..6319cc3 --- /dev/null +++ b/packages/connection/src/index.ts @@ -0,0 +1,10 @@ +import type { ConnectionPlugin } from './definitions' + +import { registerPlugin } from '@capacitor/core' + +const Connection = registerPlugin('Connection', { + web: () => import('./web').then(m => new m.ConnectionWeb()), +}) + +export * from './definitions' +export { Connection } diff --git a/packages/connection/src/web.ts b/packages/connection/src/web.ts new file mode 100644 index 0000000..38a8637 --- /dev/null +++ b/packages/connection/src/web.ts @@ -0,0 +1,17 @@ +import type { ConnectionPlugin, SimData } from './definitions' + +import { WebPlugin } from '@capacitor/core' + +export class ConnectionWeb extends WebPlugin implements ConnectionPlugin { + async getInfos(): Promise { + throw this.unavailable('Connection information is not available in the browser.') + } + + async checkPermissions(): Promise { + throw this.unavailable('Permission information is not available in the browser.') + } + + async requestPermissions(): Promise { + throw this.unavailable('Permission information is not available in the browser.') + } +} diff --git a/packages/connection/tsconfig.json b/packages/connection/tsconfig.json new file mode 100644 index 0000000..c8dc7d5 --- /dev/null +++ b/packages/connection/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist" + }, + "files": ["src/index.ts"], + "include": ["src"] +} diff --git a/packages/connection/vitest.config.ts b/packages/connection/vitest.config.ts new file mode 100644 index 0000000..d87fc4a --- /dev/null +++ b/packages/connection/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + globals: true, + environment: 'node', + }, +}) diff --git a/packages/sensors/android/src/main/kotlin/com/danyalwe/capacitor/sensors/SensorsPlugin.kt b/packages/sensors/android/src/main/kotlin/com/danyalwe/capacitor/sensors/SensorsPlugin.kt index 86c0fb1..41555fb 100644 --- a/packages/sensors/android/src/main/kotlin/com/danyalwe/capacitor/sensors/SensorsPlugin.kt +++ b/packages/sensors/android/src/main/kotlin/com/danyalwe/capacitor/sensors/SensorsPlugin.kt @@ -1,5 +1,6 @@ package com.danyalwe.capacitor.sensors +import android.util.Log import android.Manifest import android.content.Context import android.hardware.Sensor @@ -121,6 +122,7 @@ class SensorsPlugin : Plugin() { return } + Log.d("Start", "Sensors Plugin") sensorInstance.start() call.resolve() } @@ -143,5 +145,6 @@ class SensorsPlugin : Plugin() { sensorInstance.stop() call.resolve() + Log.d("Stop", "Sensors Plugin") } } \ No newline at end of file diff --git a/packages/systeminfo/android/src/main/kotlin/com/danyalwe/capacitor/systeminfo/SystemInfo.kt b/packages/systeminfo/android/src/main/kotlin/com/danyalwe/capacitor/systeminfo/SystemInfo.kt index bc1815c..db10fa9 100644 --- a/packages/systeminfo/android/src/main/kotlin/com/danyalwe/capacitor/systeminfo/SystemInfo.kt +++ b/packages/systeminfo/android/src/main/kotlin/com/danyalwe/capacitor/systeminfo/SystemInfo.kt @@ -10,7 +10,6 @@ import com.getcapacitor.JSArray import com.getcapacitor.JSObject import java.util.TimeZone - class SystemInfo( private val plugin: SystemInfoPlugin, private val context: Context diff --git a/packages/systeminfo/android/src/main/kotlin/com/danyalwe/capacitor/systeminfo/SystemInfoPlugin.kt b/packages/systeminfo/android/src/main/kotlin/com/danyalwe/capacitor/systeminfo/SystemInfoPlugin.kt index 36963d9..395f31f 100644 --- a/packages/systeminfo/android/src/main/kotlin/com/danyalwe/capacitor/systeminfo/SystemInfoPlugin.kt +++ b/packages/systeminfo/android/src/main/kotlin/com/danyalwe/capacitor/systeminfo/SystemInfoPlugin.kt @@ -4,7 +4,6 @@ import android.util.Log import com.getcapacitor.Plugin import com.getcapacitor.PluginCall import com.getcapacitor.PluginMethod -import com.getcapacitor.JSObject import com.getcapacitor.annotation.CapacitorPlugin import java.util.Timer import java.util.TimerTask @@ -26,7 +25,7 @@ class SystemInfoPlugin : Plugin() { @PluginMethod fun start(call: PluginCall) { - Log.d("SystemInfo Plugin", "Start listening") + Log.d("Start", "SystemInfo Plugin") timer?.cancel() timer?.purge() timer = Timer("CheckUsage") @@ -42,8 +41,8 @@ class SystemInfoPlugin : Plugin() { @PluginMethod fun stop(call: PluginCall) { - Log.d("SystemInfo Plugin", "Stop listening") timer?.cancel() timer?.purge() + Log.d("Stop", "SystemInfo Plugin") } } \ No newline at end of file diff --git a/playground/package.json b/playground/package.json index f4b21d5..c3d2cab 100644 --- a/playground/package.json +++ b/playground/package.json @@ -14,7 +14,8 @@ "@capacitor/core": "^8.4.1", "@danyalwe/capacitor-battery": "workspace:*", "@danyalwe/capacitor-sensors": "workspace:*", - "@danyalwe/capacitor-systeminfo": "workspace:*" + "@danyalwe/capacitor-systeminfo": "workspace:*", + "@danyalwe/capacitor-connection": "workspace:*" }, "devDependencies": { "@capacitor/android": "^8.4.1", diff --git a/playground/vite.config.ts b/playground/vite.config.ts index 78f0c7a..06e5023 100644 --- a/playground/vite.config.ts +++ b/playground/vite.config.ts @@ -2,6 +2,6 @@ import { defineConfig } from 'vite' export default defineConfig({ ssr: { - noExternal: ['@danyalwe/capacitor-battery', '@danyalwe/capacitor-sensors', '@danyalwe/capacitor-systeminfo'], + noExternal: ['@danyalwe/capacitor-battery', '@danyalwe/capacitor-sensors', '@danyalwe/capacitor-systeminfo', '@danyalwe/capacitor-connection'], }, })