diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..d52715d --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,34 @@ +# Control Hub · GitHub Copilot + +## Dansk + +Læs [projektreglerne](../AGENTS.md) og [bidragsvejledningen](../CONTRIBUTING.md). Svar ejeren på dansk. Opdatér brugerflade og dokumentation på dansk og engelsk i samme ændring. Første prioritet er Stream Deck sammen med PowerPoint og OBS Studio, derefter AndroidRemote. + +Læg pluginimplementationer og aktiver under `Plugins/`. Genbrug protokol v1 og den fælles dispatcher til styringskommandoer. Styr det eksisterende PowerPoint-slideshow via COM. Præsentationsfiler må aldrig ændres, og styringen må aldrig afhænge af tastaturfokus. Hold tokens, OBS-adgangskoder og parringsbeviser ude af kode, logfiler og PR-tekst. + +Arbejd på den valgte arbejdsbranch og brug PR til review. Følg [versionsreglerne](../docs/versioning.md). Release og tag kræver ejerens godkendelse. Hver .100-grænse og overgangen til 0.1.000 kræver særskilt godkendelse. + +## English + +Read the [project rules](../AGENTS.md) and [contribution guide](../CONTRIBUTING.md). Reply to the owner in Danish. Update user-facing text and documentation in Danish and English in the same change. Prioritize Stream Deck with PowerPoint and OBS Studio, followed by AndroidRemote. + +Keep plugin implementations and assets under `Plugins/`. Reuse protocol v1 and the shared dispatcher for control commands. Control the existing PowerPoint slideshow through COM. Never modify presentation files or use focus-dependent shortcuts. Keep tokens, OBS passwords and pairing invitations out of code, logs and pull request text. + +Work on the selected development branch and use a pull request for review. Follow the [version policy](../docs/versioning.md). Releases and tags require owner approval. Each .100 boundary and the transition to 0.1.000 require separate approval. + +## Build og test / Build and test + +Brug .NET 10 SDK og Node.js 24 fra repositoryets rod. / Use the .NET 10 SDK and Node.js 24 from the repository root. + +```sh +dotnet restore ControlHub.slnx +dotnet build ControlHub.slnx --no-restore --configuration Release +dotnet test ControlHub.slnx --no-build --configuration Release +node --test tests/streamdeck.test.cjs tests/inspector.test.cjs +node tests/host-smoke.cjs +node scripts/check-policy.cjs +``` + +Se [CI](workflows/ci.yml) for Windows-installationen, Elgato-validering og APK-prøven på Android-emulatoren. Beskriv i PR’en, hvilke kontroller du kørte, hvad de viste, og hvilke fysiske prøver der stadig afventer. + +See [CI](workflows/ci.yml) for Windows packaging, Elgato validation and the Android APK emulator trial. Report the checks you ran, their results and any outstanding physical hardware trials in the pull request. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f546728 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,65 @@ +name: Build and tests / Byg og test +on: + push: + branches: [main, 'feature/**'] + pull_request: + branches: [main] +permissions: + contents: read +jobs: + verify: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + - uses: actions/setup-node@v4 + with: + node-version: '24' + - run: dotnet restore ControlHub.slnx + - run: dotnet build ControlHub.slnx --no-restore --configuration Release + - run: dotnet test ControlHub.slnx --no-build --configuration Release --logger trx + - run: node --test tests/streamdeck.test.cjs tests/inspector.test.cjs + - run: npx --yes --package=@elgato/cli@1.10.3 streamdeck validate --no-update-check Plugins/StreamDeck/dk.thebonden.controlhub.sdPlugin + - run: node tests/host-smoke.cjs + - run: node scripts/check-policy.cjs + - name: Build Windows installers / Byg Windows-installation + if: runner.os == 'Windows' + shell: pwsh + run: | + $iscc = "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" + ./scripts/package-windows.ps1 -IsccPath $iscc -OutputDirectory "$env:GITHUB_WORKSPACE\artifacts\windows" + ./scripts/verify-package.ps1 -PackageDirectory "$env:GITHUB_WORKSPACE\artifacts\windows" + - uses: actions/upload-artifact@v4 + if: runner.os == 'Windows' + with: + name: ControlHub-0.0.001-windows-development + path: artifacts/windows/files/* + retention-days: 14 + if-no-files-found: error + android: + name: Android APK and emulator / APK og emulator + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + - run: bash scripts/android-emulator-ci.sh + - uses: actions/upload-artifact@v4 + with: + name: ControlHub-AndroidRemote-0.0.001-development + path: ${{ runner.temp }}/controlhub-android/ControlHub-AndroidRemote-0.0.001.apk + retention-days: 14 + if-no-files-found: error diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ec0a0f1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +**/bin/ +**/obj/ +.vs/ +TestResults/ +artifacts/ +.env +*.user +*.streamDeckPlugin +*.apk +*.p12 +*.jks +*.controlhub +__pycache__/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..dec341f --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,12 @@ +# Projektregler / Project rules + +- Dansk: Kommunikér med ejeren på dansk. Dokumentation og brugervendte tekster skal være på dansk og engelsk. +- English: Communicate with the owner in Danish. Documentation and user-facing text must be Danish and English. +- Dansk: Prioritér Stream Deck sammen med PowerPoint og OBS Studio; derefter AndroidRemote. +- English: Prioritize Stream Deck with PowerPoint and OBS Studio, followed by AndroidRemote. +- Dansk: Alle pluginimplementationer og aktiver under Plugins/. Ingen ændring af præsentationsfiler eller fokusafhængige genveje. +- English: All plugin implementations and assets belong under Plugins/. Never modify presentation files or use focus-dependent shortcuts. +- Dansk: Brug arbejdsbranch og PR mod main. Byg og test. Rapportér faktisk implementering og resterende hardwaretest. +- English: Use a working branch and PR to main. Build and test. Report actual implementation and remaining hardware tests. +- Dansk: Ingen release eller tag uden ejerens godkendelse. Hver .100-grænse og skiftet til 0.1.000 kræver særskilt godkendelse. Følg docs/versioning.md. +- English: No release or tag without owner approval. Each .100 boundary and transition to 0.1.000 needs separate approval. Follow docs/versioning.md. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..6be5b62 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,51 @@ +# Ændringslog / Changelog + +## 0.0.001 — udviklingsversion / development version + +### Dansk +- AndroidRemote til Android 8 og nyere med parret HTTPS, certifikatkontrol, krypteret enhedsnøgle, slides, OBS-scene og status. APK-knapperne er prøvet på en Android 15-emulator med bogførte kommandoer, afbrydelse og tilbagekaldelse. +- Nyt Windows-vindue **Administrér telefonadgang**: vælg rettigheder, opret et to-minutters bevis, se ventende/parrede enheder og tilbagekald adgang. Lokale ejerruter kræver en separat nøgle for hver opstart; Stream Deck-nøglen alene er utilstrækkelig. +- AndroidRemote-bibliotek med enkeltbrugsparring, enhedsrettigheder, udløb og tilbagekaldelse. +- Adgang kontrolleres igen efter kommandokøen; kommandosvar holdes adskilt pr. parret enhed. +- Host-smoketest bruger en separat lokal port, så den åbne Control Hub kan fortsætte. +- Konkrete forbindelsesårsager for PowerPoint og OBS i status og Stream Deck, med sikre dansk/engelske tekster. +- Afbrudte OBS-kommandoer efter påbegyndt afsendelse rapporteres som ukendt udfald; aldrig automatisk genafsendelse. +- Rettet forbindelsessvar, når Stream Decks indstillingsvindue og knap har forskellige id'er; dækket af en regressionstest. +- Windows x64-installation med inkluderet .NET og officiel Stream Deck-installationspakke. +- Dansk/engelsk kontrolvindue med start/stop, forbindelsesstatus, kopiering af vedvarende token og DPAPI-krypterede OBS-indstillinger. +- Pakketest af konfiguration, lokal host og stop; Windows-artefakter i CI uden release/tag. +- Forbindelsestest i Stream Deck-indstillingerne med separat status for Control Hub, PowerPoint og OBS. +- Beskyttelse mod forsinket knapfeedback efter profil-/indstillingsskift. +- Hovedikon i krævet PNG-format og officiel Elgato-validering i CI. +- C#/.NET 10-kontrakter, dispatcher og lokal autentificeret HTTP-host. +- Eksplicit pluginsystem med ærlig status for ikke-implementerede integrationer. +- PowerPoint COM-navigation på STA-tråd, uden filredigering eller tastaturgenveje. +- OBS WebSocket v5-klient med godkendelse og konkrete handlinger. +- Stream Deck-kildeplugin med 12 handlinger, dansk/engelsk opsætning og statusfeedback. +- Forberedte integrationsplaner for AndroidRemote, lyd, Logitech, Android Live, fysisk fjernkontrol og Flux Keyboard. +- Automatiske tests, CI på Windows/Linux og projektbeskrivelse på begge sprog. +- Fysisk test i det aktive miljø afventer. Ingen release eller tag. + +### English +- AndroidRemote for Android 8 and later with paired HTTPS, certificate verification, encrypted device credentials, slides, OBS scene and status. Android 15 emulator tests exercise the APK controls, counted commands, disconnection and revocation. +- New Windows **Manage phone access** dialog: select permissions, create a two-minute invitation, list pending/paired devices and revoke access. Local owner routes require a separate key for each launch; the Stream Deck key alone is insufficient. +- AndroidRemote library with single-use pairing, device permissions, expiry and revocation. +- Authorization is rechecked after queueing; command results are isolated per paired device. +- Host smoke tests use a separate local port so the open Control Hub can keep running. +- Specific PowerPoint/OBS connection reasons in status and Stream Deck, with safe Danish/English messages. +- OBS commands interrupted after transmission starts report an unknown outcome; no automatic retries. +- Fixed connection replies when the Stream Deck inspector and key have different IDs; covered by a regression test. +- Windows x64 installer with included .NET and an official Stream Deck installation package. +- Danish/English control window with start/stop, connection status, persistent token copying and DPAPI-encrypted OBS settings. +- Package checks for configuration, local host and shutdown; Windows CI artifacts without a release/tag. +- Connection check in Stream Deck settings with separate Control Hub, PowerPoint and OBS status. +- Protection against late key feedback after profile/settings changes. +- Main icon in the required PNG format and official Elgato validation in CI. +- C#/.NET 10 contracts, dispatcher and authenticated local HTTP host. +- Explicit plugin system with truthful status for unimplemented integrations. +- PowerPoint COM navigation on an STA thread without file editing or keyboard shortcuts. +- OBS WebSocket v5 client with authentication and concrete actions. +- Stream Deck source plugin with 12 actions, Danish/English settings and status feedback. +- Prepared integration plans for AndroidRemote, audio, Logitech, Android Live, physical remote and Flux Keyboard. +- Automated tests, Windows/Linux CI and project description in both languages. +- Physical testing in the active environment remains pending. No release or tag. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..0cbc0f4 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,37 @@ +# Bidrag / Contributing + +## Dansk + +Arbejd på en branch fra `main`, og åbn en PR mod `main`. Hold alle pluginimplementationer og deres aktiver under `Plugins/`. Bevar danske og engelske dokumenter samt UI-tekster i samme ændring; protokol- og kodeidentifikatorer forbliver engelske. + +Kør build, C#-tests, Stream Deck-tests, host-smoketest og kildekoderegler som beskrevet i installationsvejledningen. Beskriv præcist, om en integration er implementeret, simuleret, planlagt eller fysisk afprøvet. Brug ikke grønne enhedstests som bevis for hardwarefunktion. + +Ændr aldrig præsentationsfiler, og tilføj ingen fokusafhængige genveje. Gem aldrig tokens eller adgangskoder i kode, eksempler, testlogs eller profiler. Følg [versionsreglerne](docs/versioning.md). Release, tags og .100-grænser kræver ejerens eksplicitte godkendelse. + +### Kod med GitHub Copilot + +Mens [PR #1](https://github.com/thebonden/Control_Hub/pull/1) er åben, kan du skrive `@copilot` i PR’ens samtale og beskrive én konkret kodeændring. Copilot kan tilføje commits direkte på `feature/control-hub-0.0.001`. Gennemgå diffen og testresultaterne i samme PR. Hvis du starter en separat opgave i [Copilot Agents](https://github.com/copilot/agents), så vælg `thebonden/Control_Hub` og den branch, som indeholder koden, opgaven skal bygge videre på. + +Eksempel på en opgave: + +> @copilot Vis optagelses- og streamingstatus fra OBS på AndroidRemotes statusskærm. Vis “Ukendt” eller “Unknown”, når oplysningerne mangler. Opdatér den relevante emulatortest, og beskriv resultatet på dansk. + +Brug en GitHub-konto med skriveadgang og adgang til Copilot cloud agent i repositoriet. Hvis agenten ikke kan vælges, så kontrollér repositoryadgangen i [Copilot-indstillingerne](https://github.com/settings/copilot/features). [GitHubs vejledning](https://docs.github.com/en/copilot/how-tos/use-copilot-agents/cloud-agent/use-cloud-agent-on-github#continuing-work-on-a-pull-request) + +## English + +Work on a branch from `main` and open a PR targeting `main`. Keep all plugin implementations and assets under `Plugins/`. Update Danish and English documentation and UI text together; protocol and code identifiers remain English. + +Run the build, C# tests, Stream Deck tests, host smoke test and source policy checks described in setup. State precisely whether an integration is implemented, simulated, planned or physically tested. Green unit tests do not prove hardware functionality. + +Never modify presentation files or add focus-dependent shortcuts. Never commit tokens or passwords in code, examples, test logs or profiles. Follow the [version policy](docs/versioning.md). Releases, tags and .100 boundaries require explicit owner approval. + +### Code with GitHub Copilot + +While [PR #1](https://github.com/thebonden/Control_Hub/pull/1) is open, mention `@copilot` in its conversation and describe one concrete code change. Copilot can add commits directly to `feature/control-hub-0.0.001`. Review the diff and test results in the same PR. When starting a separate task in [Copilot Agents](https://github.com/copilot/agents), select `thebonden/Control_Hub` and the branch containing the code the task should build on. + +Example task: + +> @copilot Show OBS recording and streaming status on AndroidRemote’s status screen. Display “Ukendt” or “Unknown” when the data is missing. Update the relevant emulator test and report the result in Danish. + +Use a GitHub account with write access and Copilot cloud agent access to the repository. If the agent is unavailable, check repository access in [Copilot settings](https://github.com/settings/copilot/features). [GitHub guide](https://docs.github.com/en/copilot/how-tos/use-copilot-agents/cloud-agent/use-cloud-agent-on-github#continuing-work-on-a-pull-request) diff --git a/ControlHub.slnx b/ControlHub.slnx new file mode 100644 index 0000000..ea2b8e7 --- /dev/null +++ b/ControlHub.slnx @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..4f588a5 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,13 @@ + + + net10.0 + enable + enable + true + 0.0.1 + 0.0.1.0 + 0.0.1.0 + 0.0.001 + true + + diff --git a/Plugins/AndroidLive/README.md b/Plugins/AndroidLive/README.md new file mode 100644 index 0000000..87918f6 --- /dev/null +++ b/Plugins/AndroidLive/README.md @@ -0,0 +1,17 @@ +# Android Live / Android Live + +## Dansk + +Status i 0.0.001: **planlagt, ikke implementeret**. Plugin-id: `android-live`. Hosten registrerer en fælles `PlannedPlugin` med tom handlingsliste og `not_implemented`-status. Der er ingen driver, transport eller app i denne mappe endnu. + +Afklar om integrationen omfatter kamera, status eller styring. Fastlæg transport, parring og adgang. Denne integration er adskilt fra AndroidRemote. + +Accept kræver en dokumenteret protokol, fejl- og forbindelsestests, hardwaretest og danske/engelske brugertekster. Implementationskode skal placeres i denne mappe under `Plugins/`. + +## English + +0.0.001 status: **planned, not implemented**. Plugin ID: `android-live`. The host registers a shared `PlannedPlugin` with an empty action list and `not_implemented` status. No driver, transport or app exists in this directory yet. + +Establish whether the integration covers a camera, status or control. Define transport, pairing and access. This integration is separate from AndroidRemote. + +Acceptance requires a documented protocol, error and connection tests, hardware testing and Danish/English user text. Implementation code must be placed in this directory under `Plugins/`. diff --git a/Plugins/AndroidRemote/Android/AndroidManifest.xml b/Plugins/AndroidRemote/Android/AndroidManifest.xml new file mode 100644 index 0000000..83598e8 --- /dev/null +++ b/Plugins/AndroidRemote/Android/AndroidManifest.xml @@ -0,0 +1,10 @@ + + + + + + + + + diff --git a/Plugins/AndroidRemote/Android/build.py b/Plugins/AndroidRemote/Android/build.py new file mode 100644 index 0000000..0f00771 --- /dev/null +++ b/Plugins/AndroidRemote/Android/build.py @@ -0,0 +1,65 @@ +"""Build and verify the development APK with the Android SDK and a JDK.""" +import argparse +import os +from pathlib import Path +import subprocess +import tempfile +import zipfile + +ROOT = Path(__file__).resolve().parent +APP_ID = "dk.thebonden.controlhub.remote" + + +def build(source, manifest, output, android_sdk, jdk, keystore): + sdk = android_sdk / "build-tools" / "36.0.0" + platform = android_sdk / "platforms" / "android-35" / "android.jar" + executable = ".exe" if os.name == "nt" else "" + java = jdk / "bin" / ("java" + executable) + + def run(*args): + subprocess.run([str(arg) for arg in args], check=True) + + output.parent.mkdir(parents=True, exist_ok=True) + keystore.parent.mkdir(parents=True, exist_ok=True) + if not keystore.exists(): + run(jdk / "bin" / ("keytool" + executable), "-genkeypair", "-keystore", keystore, + "-storepass", "android", "-keypass", "android", "-alias", "androiddebugkey", + "-keyalg", "RSA", "-keysize", "2048", "-validity", "3650", "-dname", "CN=Control Hub Development") + + with tempfile.TemporaryDirectory(dir=output.parent) as temp: + work = Path(temp) + classes = work / "classes" + classes.mkdir() + run(jdk / "bin" / ("javac" + executable), "-encoding", "UTF-8", "-source", "8", "-target", "8", + "-classpath", platform, "-d", classes, *sorted(source.rglob("*.java"))) + jar = work / "classes.jar" + with zipfile.ZipFile(jar, "w") as archive: + for entry in classes.rglob("*.class"): + archive.write(entry, entry.relative_to(classes).as_posix()) + run(java, "-cp", sdk / "lib/d8.jar", "com.android.tools.r8.D8", "--min-api", "26", + "--lib", platform, "--output", work, jar) + unsigned = work / "unsigned.apk" + run(sdk / ("aapt2" + executable), "link", "-o", unsigned, "-I", platform, "--manifest", manifest) + with zipfile.ZipFile(unsigned, "a", compression=zipfile.ZIP_DEFLATED) as archive: + archive.write(work / "classes.dex", "classes.dex") + aligned = work / "aligned.apk" + run(sdk / ("zipalign" + executable), "-f", "4", unsigned, aligned) + signed = work / "signed.apk" + signer = sdk / "lib/apksigner.jar" + run(java, "-jar", signer, "sign", "--ks", keystore, "--ks-pass", "pass:android", + "--ks-key-alias", "androiddebugkey", "--out", signed, aligned) + run(java, "-jar", signer, "verify", "--verbose", signed) + signed.replace(output) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--sdk", type=Path, required=True) + parser.add_argument("--jdk", type=Path, required=True) + parser.add_argument("--keystore", type=Path, required=True, help="Development signing key outside the repository") + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--ui-test", action="store_true") + args = parser.parse_args() + module = ROOT.parents[2] / "tests" / "android-ui" if args.ui_test else ROOT + build(module / "src", module / "AndroidManifest.xml", args.out.resolve(), + args.sdk.resolve(), args.jdk.resolve(), args.keystore.resolve()) diff --git a/Plugins/AndroidRemote/Android/src/PinnedChannel.java b/Plugins/AndroidRemote/Android/src/PinnedChannel.java new file mode 100644 index 0000000..2b6f6b4 --- /dev/null +++ b/Plugins/AndroidRemote/Android/src/PinnedChannel.java @@ -0,0 +1,101 @@ +package dk.thebonden.controlhub.remote; + +import java.io.*; +import java.net.*; +import java.nio.charset.StandardCharsets; +import java.security.*; +import java.security.cert.*; +import javax.net.ssl.*; +import org.json.*; + +final class PinnedChannel { + static final class Denied extends IOException { + final int status; + Denied(int status) { super("HTTP " + status); this.status = status; } + } + private final URI endpoint; + private final SSLSocketFactory sockets; + + PinnedChannel(JSONObject transport) throws Exception { + endpoint = new URI(transport.getString("endpoint")); + String host = endpoint.getHost(); + if (!"https".equals(endpoint.getScheme()) || host == null || !privateIPv4(host) + || endpoint.getPort() < 1 || endpoint.getPort() > 65535 || endpoint.getRawUserInfo() != null + || endpoint.getRawQuery() != null || endpoint.getRawFragment() != null + || !(endpoint.getPath().isEmpty() || "/".equals(endpoint.getPath()))) + throw new IllegalArgumentException("endpoint"); + String pin = transport.getString("certificateSha256"); + if (!pin.matches("[0-9A-Fa-f]{64}")) throw new IllegalArgumentException("pin"); + byte[] expected = new byte[32]; + for (int i = 0; i < expected.length; i++) expected[i] = (byte)Integer.parseInt(pin.substring(i*2, i*2+2),16); + X509TrustManager trust = new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } + public void checkClientTrusted(X509Certificate[] chain, String auth) throws CertificateException { + throw new CertificateException("client"); + } + public void checkServerTrusted(X509Certificate[] chain, String auth) throws CertificateException { + if (chain == null || chain.length == 0) throw new CertificateException("empty"); + chain[0].checkValidity(); + try { + byte[] actual = MessageDigest.getInstance("SHA-256").digest(chain[0].getEncoded()); + if (!MessageDigest.isEqual(expected, actual)) throw new CertificateException("identity"); + } catch (NoSuchAlgorithmException e) { throw new CertificateException(e); } + } + }; + SSLContext tls = SSLContext.getInstance("TLS"); + tls.init(null,new TrustManager[]{trust},null); + sockets = tls.getSocketFactory(); + } + + private static boolean privateIPv4(String host) { + String[] parts = host.split("\\.", -1); + if (parts.length != 4) return false; + int[] bytes = new int[4]; + for (int i=0; i<4; i++) { + if (!parts[i].matches("0|[1-9][0-9]{0,2}")) return false; + bytes[i] = Integer.parseInt(parts[i]); + if (bytes[i] > 255) return false; + } + return host.equals("127.0.0.1") || bytes[0]==10 || (bytes[0]==172 && bytes[1]>=16 && bytes[1]<=31) + || (bytes[0]==192 && bytes[1]==168); + } + + JSONObject request(String route, JSONObject body, JSONObject session) throws Exception { + URL url = endpoint.resolve("/phone/v1/" + route).toURL(); + HttpsURLConnection connection = (HttpsURLConnection)url.openConnection(Proxy.NO_PROXY); + try { + connection.setSSLSocketFactory(sockets); + // Default hostname verification also checks the IP subject alternative name. + connection.setInstanceFollowRedirects(false); + connection.setUseCaches(false); + connection.setConnectTimeout(6000); + connection.setReadTimeout(35000); + if (session != null) { + connection.setRequestProperty("X-ControlHub-Device", session.getString("id")); + connection.setRequestProperty("Authorization", "Bearer " + session.getString("token")); + } + if (body != null) { + byte[] bytes = body.toString().getBytes(StandardCharsets.UTF_8); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setFixedLengthStreamingMode(bytes.length); + connection.setRequestProperty("Content-Type","application/json"); + try (OutputStream out = connection.getOutputStream()) { out.write(bytes); } + } + int status = connection.getResponseCode(); + if (status != 200) throw new Denied(status); + try (InputStream in = connection.getInputStream()) { return new JSONObject(read(in, 256 * 1024)); } + } finally { connection.disconnect(); } + } + + static String read(InputStream in, int limit) throws IOException { + if (in == null) throw new IOException("missing input"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + for (int count; (count = in.read(buffer)) != -1;) { + if (count > limit - out.size()) throw new IOException("size"); + out.write(buffer,0,count); + } + return out.toString("UTF-8"); + } +} diff --git a/Plugins/AndroidRemote/Android/src/RemoteActivity.java b/Plugins/AndroidRemote/Android/src/RemoteActivity.java new file mode 100644 index 0000000..3fe9227 --- /dev/null +++ b/Plugins/AndroidRemote/Android/src/RemoteActivity.java @@ -0,0 +1,194 @@ +package dk.thebonden.controlhub.remote; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.text.InputFilter; +import android.text.InputType; +import android.view.*; +import android.widget.*; +import java.io.InputStream; +import java.util.*; +import java.util.concurrent.*; +import org.json.*; +import javax.net.ssl.SSLException; + +public final class RemoteActivity extends Activity { + private final ExecutorService worker = Executors.newSingleThreadExecutor(); + private final ArrayList