Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

addons: TV Hub, one live-TV guide for playlists, Dispatcharr and HDHomeRun

מקס חיים80c95602dfda
diff --git a/addons/README.md b/addons/README.md
index 7136a318a..cf6213ebf 100644
--- a/addons/README.md
+++ b/addons/README.md
@@ -15,6 +15,7 @@ the core bigger or change how it behaves. You install an add-on only if you want
| [Photo Prints](photo-prints/) | Your own photos as a screensaver: dated prints dealt in on a time-of-day sky, and a card that starts the slideshow | [@shivamsingh262](https://github.com/shivamsingh262) | Sony BRAVIA KD-65X82L (Google TV 12) | None |
| [Photo screensaver](photo-screensaver/) | Your own pictures and MP4 clips as the TV's screensaver and as a card, slowly zooming and crossfading (20 s each by default); optional time, photo dates, prints on a sky and weather | [JorickGU](https://github.com/JorickGU) | TCL 43P69K (Google TV 12) | `INTERNET` and coarse location, only with the weather option on |
| [Prayer Times](prayer-times/) | Today's prayer times for one city from Aladhan (no key), the next prayer with a countdown, Gregorian and Hijri dates | [@majnioui](https://github.com/majnioui) | Xiaomi TV (MiTV-MOOR2), Google TV 11 | `INTERNET` |
+| [TV Hub](tv-hub/) | One live-TV guide for M3U/XMLTV playlists, Dispatcharr and HDHomeRun tuners, with a Media3 player and shortcuts to installed live-TV apps | [@maxhayim](https://github.com/maxhayim) | MOKA R8G (Android TV 14) | `INTERNET` |
A widget, an info tile, a storage or smart-home card: if it can live as its own small app, it can live
here. See the rules below.
diff --git a/addons/tv-hub/.gitignore b/addons/tv-hub/.gitignore
new file mode 100644
index 000000000..b77a429a0
--- /dev/null
+++ b/addons/tv-hub/.gitignore
@@ -0,0 +1,11 @@
+.gradle/
+build/
+local.properties
+.idea/
+*.iml
+.DS_Store
+*.keystore
+*.jks
+keystore.properties
+fixtures/out/
+.kotlin/
diff --git a/addons/tv-hub/LICENSE b/addons/tv-hub/LICENSE
new file mode 100644
index 000000000..7e51dab7f
--- /dev/null
+++ b/addons/tv-hub/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 maxhayim
+
+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.
diff --git a/addons/tv-hub/README.md b/addons/tv-hub/README.md
new file mode 100644
index 000000000..079f3d346
--- /dev/null
+++ b/addons/tv-hub/README.md
@@ -0,0 +1,163 @@
+# TV Hub
+
+One live-TV guide for Android TV, Google TV and Fire TV: your M3U playlists and XMLTV guides,
+a [Dispatcharr](https://github.com/Dispatcharr/Dispatcharr) server, HDHomeRun antenna tuners, and
+shortcuts to the live-TV apps you already have, in one remote-friendly interface.
+
+A CleanYourTV add-on: a normal app you can install on any launcher, with a module card so on
+CleanYourTV it can sit in the dock as **TV Hub · Live channels** once you approve it.
+
+Free, MIT-licensed, no ads, no accounts, no tracking, no background services. It comes with no
+channels: it plays the sources you add. Only use playlists and services you are allowed to watch.
+
+## What works
+
+| | Status |
+| :- | :- |
+| M3U / M3U8 playlists over http and https | Works: `tvg-id`, `tvg-name`, `tvg-logo`, `tvg-chno`, `group-title`, `#EXTGRP`, `#EXTVLCOPT` user agent and referrer, header `x-tvg-url` / `url-tvg` |
+| XMLTV guides (.xml and .xml.gz) | Works: streamed, never loaded whole; matched by `tvg-id`, or by display name for channels without one |
+| Dispatcharr | Works through its documented `/output/m3u[/profile]` and `/output/epg[/profile]` |
+| HDHomeRun network tuners | Works: UDP discovery or a typed address, channel list from the tuner's own `lineup.json`. No guide (see below) |
+| Installed live-TV apps | Shortcuts that open the app (Pluto TV, Tubi, Plex, Kodi, Channels, HDHomeRun, YouTube TV, Sling, Philo, Haystack, Live Channels, TiviMate, or any TV app you pick) |
+| Guide | Programme grid, now and next, categories, favourites, recently watched, search, programme details |
+| Player | Media3: HLS and progressive streams (MPEG-TS, MP4 and the other containers Media3 reads), channel up/down, previous channel, number entry, audio and subtitle tracks, recovery and fallback |
+| Merging | Channels with the same `tvg-id` in several sources show once; the player falls back between their streams. Can be turned off |
+| CleanYourTV module card | Declared per spec 1 (`res/xml/module_card.xml`) |
+
+### Not done, on purpose or not yet
+
+- **No channels from streaming apps.** Pluto TV, Tubi, Plex and the rest publish no channel list or
+ guide to other apps, so TV Hub only opens them. It never shows them as channels.
+- **No HDHomeRun guide.** SiliconDust's guide comes from its cloud service with a device token;
+ TV Hub stays on your network. Add an XMLTV guide for listings (Dispatcharr can make one).
+- **No USB tuners.** That needs a vendor TV input or driver; not attempted.
+- **No Xtream Codes login.** Not implemented. Many services also give an M3U address; Dispatcharr can
+ take an Xtream account and serve it as M3U.
+- **No DASH, RTSP, RTMP or UDP multicast.** Those entries are skipped and counted on the Sources screen.
+- **No DRM.** Encrypted channels fail with a message saying so.
+- **No recording, catch-up or background guide refresh.** The guide refreshes when the app opens
+ (if older than 12 hours by default) or when you press Refresh.
+- **English only** so far; strings are in code, not yet in resources.
+- **No configuration backup or import** yet.
+
+## Install
+
+Build it (below) and install it from the repo root as with every add-on:
+
+```bash
+cd addons/tv-hub && ./gradlew assembleDebug && cd ../..
+TV_HOST=<tv ip> tools/venv/bin/python -I tools/tv.py --push addons/tv-hub/app/build/outputs/apk/debug/app-debug.apk /data/local/tmp/addon.apk
+TV_HOST=<tv ip> tools/venv/bin/python -I tools/tv.py 'pm install -r /data/local/tmp/addon.apk; rm -f /data/local/tmp/addon.apk'
+```
+
+or `adb install -r app/build/outputs/apk/debug/app-debug.apk`. It opens from the TV's app list as
+**TV Hub**; on Fire TV it is under Apps > Your Apps.
+
+The debug APK is signed with a throwaway key that changes between machines. For anything you keep,
+build a release with your own key (below): the launcher pins its approval of the card to the signing
+key, and a different key makes it ask again.
+
+## Set up
+
+On first launch TV Hub offers each source; every one is optional, and **Skip for now** goes straight to
+the hub. Later, go to **Sources > Add a source**.
+
+- **M3U playlist**: the playlist's address. If the playlist names a guide in its header, that guide is
+ read too (switch off per source). You can give a separate XMLTV address.
+- **XMLTV guide**: a guide for channels from any source.
+- **Dispatcharr**: the address you open Dispatcharr at, e.g. `http://192.168.1.10:9191`, and optionally
+ an output profile name. Dispatcharr only serves its M3U/EPG to networks you allow in its settings;
+ "refused access (HTTP 403)" means the TV's network is not on that list yet.
+- **HDHomeRun**: **Scan the network**, or type the tuner's address. Broadcast TV is often MPEG-2 video,
+ which many Android TV chips cannot decode (Chromecast with Google TV among them); on an HDHomeRun
+ EXTEND, tick **Ask the tuner for H.264**.
+- **Streaming apps**: tick the installed apps to show as shortcuts on Home.
+
+**Check** reads a source once without saving, so a wrong address shows up straight away.
+
+## Remote control
+
+| Where | Key | Does |
+| :- | :- | :- |
+| Everywhere | Back | Back to the left menu; from the menu, leaves the app |
+| Lists and guide | OK | Play the channel (a future programme opens its details) |
+| Lists and guide | Hold OK | Add to or remove from Favorites |
+| Guide | Left / Right | Previous or next programme; Left from the first one goes to the menu |
+| Guide | Info or Menu | Programme details |
+| Guide | Channel + / - | A page up or down |
+| Player | Up / Down, Channel + / - | Next or previous channel in the list you started from |
+| Player | Left or Last | Previous channel |
+| Player | Digits | Tune by channel number |
+| Player | OK | Show what is on; after an error, try again |
+| Player | Menu, Captions, or hold OK | Audio and subtitle tracks |
+| Player | Back | Back to the guide; playback stops and the player is released |
+
+## Module card
+
+`AndroidManifest.xml` puts the `com.gathin.tvhome.category.DOCK_CARD` filter and the
+`com.gathin.tvhome.card` meta-data on `MainActivity`, the same exported activity as
+`LEANBACK_LAUNCHER`, as [the spec](https://github.com/Gathin23/cleanyourtv/blob/main/docs/specs/card.md) requires:
+
+```xml
+<card spec="1" label="TV Hub" caption="Live channels" accent="#4FA3E0" />
+```
+
+The launcher finds it the next time Home comes to the front and asks once. Nothing is shown until
+you choose **Show card**, and you can change your answer by holding OK on its Settings pill. TV Hub
+changes nothing under `launcher/`. On other launchers the card is ignored and TV Hub is an ordinary app.
+
+## Permissions
+
+- `INTERNET` is the only permission: playlists, guides, logos and streams, and only to the sources you add.
+- `usesCleartextTraffic` is on because home servers (Dispatcharr, HDHomeRun, a NAS) and many playlists use plain http.
+- Package visibility: the known live-TV apps are listed in `<queries>`, and "Show every TV app" uses a
+ `LEANBACK_LAUNCHER` intent query. No `QUERY_ALL_PACKAGES`.
+- Source settings (addresses, which often hold a user name and password) are encrypted with an AES key
+ kept in the Android Keystore. On a TV whose Keystore is broken they fall back to the app's private
+ storage, unencrypted; the app logs one line saying so.
+- Backups are off, so none of this leaves the TV. Logs never include an address beyond its host.
+- No analytics, no crash reporting, no network calls except to the sources you add and the logos they name.
+- Nothing runs in the background: no services, no jobs, no alarms. Playback stops when you leave the player.
+
+## Tested on
+
+MOKA R8G (Android 14, 1080p, 2 GB RAM): sources, guide, playback, fallback, favourites and app
+shortcuts; results and what is still untested in [docs/TESTING.md](docs/TESTING.md). The card itself
+was checked in the built APK but not yet on a TV running this launcher.
+
+## Build
+
+JDK 17 and the Android SDK (platform 34), as for the launcher:
+
+```bash
+./gradlew testDebugUnitTest lintDebug assembleDebug
+# app/build/outputs/apk/debug/app-debug.apk
+```
+
+A release signed with your own key (keep the keystore out of the repo):
+
+```bash
+keytool -genkeypair -v -keystore ~/tvhub-release.jks -alias tvhub -keyalg RSA -keysize 4096 -validity 10000
+TVHUB_KEYSTORE=~/tvhub-release.jks TVHUB_KEYSTORE_PASSWORD=... TVHUB_KEY_ALIAS=tvhub TVHUB_KEY_PASSWORD=... ./gradlew assembleRelease
+apksigner verify --print-certs app/build/outputs/apk/release/app-release.apk | grep SHA-256
+```
+
+Publish that SHA-256 with every release, as CleanYourTV's module guide asks.
+
+## How it is built
+
+Kotlin, minimum Android 8.0 (API 26), target 34. Plain Android views and framework SQLite: no
+Compose, Room, WorkManager or image library, to stay small on 1 GB TVs (release APK about 1.2 MB).
+
+```
+model/ Channel, Programme, SourceConfig
+parse/ M3uParser, XmltvParser, XmltvTime, ChannelMerger (pure Kotlin, unit-tested)
+source/ Providers (M3U, XMLTV, Dispatcharr), HdHomeRun, Apps
+data/ Repository (refresh, state), Db (SQLite), SecureStore (Keystore), Http, Prefs
+ui/ MainActivity and its pages, GuideView (canvas grid), SourceEditorActivity, OnboardingActivity
+player/ PlayerActivity (Media3)
+```
+
+Testing on a TV, with demo fixtures: [docs/TESTING.md](docs/TESTING.md).
+Third-party licences: [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
+Maintained by [@maxhayim](https://github.com/maxhayim); issues about TV Hub go to them.
diff --git a/addons/tv-hub/THIRD_PARTY_NOTICES.md b/addons/tv-hub/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..b60ee0195
--- /dev/null
+++ b/addons/tv-hub/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,33 @@
+# Third-party notices
+
+TV Hub is MIT-licensed. The APK includes these libraries, all under the
+[Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0):
+
+| Library | Version | Copyright |
+| :- | :- | :- |
+| AndroidX Media3: exoplayer, exoplayer-hls, ui (and their common, datasource, extractor, container, decoder modules) | 1.4.1 | The Android Open Source Project |
+| AndroidX RecyclerView | 1.3.2 | The Android Open Source Project |
+| AndroidX Core, Annotation, Collection, Lifecycle (pulled in by the above) | various | The Android Open Source Project |
+| Kotlin standard library | 2.0.21 | JetBrains s.r.o. and Kotlin contributors |
+| kotlinx.coroutines | 1.8.1 | JetBrains s.r.o. and Kotlin contributors |
+
+Test-only dependencies, not shipped: JUnit 4 (EPL 1.0), kXML 2 (MIT-style), org.json (Public Domain / JSON licence).
+
+The same notice ships in the app under Settings > About and licences (`app/src/main/assets/licenses.txt`).
+
+## What is not included
+
+- No code from [OpenTV](https://github.com/opentvproject/opentv) (GPL-3.0),
+ [Dispatcharr](https://github.com/Dispatcharr/Dispatcharr) (AGPL-3.0) or
+ [Kodi](https://github.com/xbmc/xbmc) (GPL-2.0-or-later). They were read for how they behave and
+ what they publish; TV Hub's player, parsers and guide are written independently on Media3.
+ TV Hub talks to Dispatcharr only through its documented `/output/m3u` and `/output/epg`
+ addresses, so the AGPL does not reach this app.
+- No playlists, channels, logos or credentials. The demo fixtures in `fixtures/` are generated by
+ `tools/make_fixtures.py`: made-up listings, solid-colour logos drawn by the script, and one
+ public test stream, Big Buck Bunny (c) Blender Foundation, [CC BY 3.0](https://creativecommons.org/licenses/by/3.0/).
+- The banner and icon are drawn by `tools/make_art.py`; the wordmark was set in Outfit (SIL Open
+ Font License 1.1). No font file ships in the app.
+
+Pluto TV, Tubi, Plex, Kodi, HDHomeRun, Dispatcharr, Fire TV and Google TV are trademarks of their
+owners, named only to describe what TV Hub can open or read. TV Hub is not affiliated with them or with CleanYourTV.
diff --git a/addons/tv-hub/app/build.gradle.kts b/addons/tv-hub/app/build.gradle.kts
new file mode 100644
index 000000000..524d4b4a0
--- /dev/null
+++ b/addons/tv-hub/app/build.gradle.kts
@@ -0,0 +1,68 @@
+plugins {
+ id("com.android.application")
+ id("org.jetbrains.kotlin.android")
+}
+
+android {
+ namespace = "io.github.maxhayim.tvhub"
+ compileSdk = 34
+
+ defaultConfig {
+ applicationId = "io.github.maxhayim.tvhub"
+ minSdk = 26
+ targetSdk = 34
+ versionCode = 1
+ versionName = "0.1.0"
+ }
+
+ // Release signing comes from the environment so the keystore never sits in the repo.
+ // The launcher pins the owner's card decision to this key: sign every release with the same one.
+ val ks = System.getenv("TVHUB_KEYSTORE")
+ signingConfigs {
+ if (ks != null) {
+ create("release") {
+ storeFile = file(ks)
+ storePassword = System.getenv("TVHUB_KEYSTORE_PASSWORD")
+ keyAlias = System.getenv("TVHUB_KEY_ALIAS")
+ keyPassword = System.getenv("TVHUB_KEY_PASSWORD")
+ }
+ }
+ }
+
+ buildTypes {
+ release {
+ isMinifyEnabled = true
+ isShrinkResources = true
+ proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
+ if (ks != null) signingConfig = signingConfigs.getByName("release")
+ }
+ }
+
+ buildFeatures { buildConfig = true }
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+ kotlinOptions { jvmTarget = "17" }
+
+ lint {
+ abortOnError = true
+ // TVs have no app store review for this; the banner and leanback checks are what matter.
+ disable += setOf("GradleDependency", "NewerVersionAvailable", "AndroidGradlePluginVersion", "OldTargetApi")
+ }
+ testOptions { unitTests.isReturnDefaultValues = true }
+}
+
+dependencies {
+ val media3 = "1.4.1"
+ implementation("androidx.media3:media3-exoplayer:$media3")
+ implementation("androidx.media3:media3-exoplayer-hls:$media3")
+ implementation("androidx.media3:media3-ui:$media3")
+ implementation("androidx.recyclerview:recyclerview:1.3.2")
+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1")
+
+ testImplementation("junit:junit:4.13.2")
+ testImplementation("net.sf.kxml:kxml2:2.3.0")
+ testImplementation("org.json:json:20240303")
+}
diff --git a/addons/tv-hub/app/proguard-rules.pro b/addons/tv-hub/app/proguard-rules.pro
new file mode 100644
index 000000000..bd003d98d
--- /dev/null
+++ b/addons/tv-hub/app/proguard-rules.pro
@@ -0,0 +1 @@
+# Media3 ships its own consumer rules; nothing here is loaded by reflection.
diff --git a/addons/tv-hub/app/src/main/AndroidManifest.xml b/addons/tv-hub/app/src/main/AndroidManifest.xml
new file mode 100644
index 000000000..c95d634be
--- /dev/null
+++ b/addons/tv-hub/app/src/main/AndroidManifest.xml
@@ -0,0 +1,77 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <!-- Playlists, guides, logos and streams. The only permission TV Hub asks for. -->
+ <uses-permission android:name="android.permission.INTERNET" />
+
+ <!-- Runs on TVs only, but does not demand TV hardware so Fire TV and boxes without a tuner install it. -->
+ <uses-feature android:name="android.software.leanback" android:required="false" />
+ <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
+
+ <!--
+ Package visibility without QUERY_ALL_PACKAGES: the live-TV apps TV Hub knows by name
+ (keep in sync with Apps.KNOWN), and any app with a TV launcher entry for "Show every TV app".
+ -->
+ <queries>
+ <package android:name="tv.pluto.android" />
+ <package android:name="com.tubitv" />
+ <package android:name="com.plexapp.android" />
+ <package android:name="org.xbmc.kodi" />
+ <package android:name="com.getchannels.dvr.app" />
+ <package android:name="com.silicondust.view" />
+ <package android:name="com.google.android.youtube.tvunplugged" />
+ <package android:name="com.sling" />
+ <package android:name="com.philo.philo.google" />
+ <package android:name="com.haystack.android" />
+ <package android:name="com.google.android.tv" />
+ <package android:name="ar.tvplayer.tv" />
+ <intent>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
+ </intent>
+ </queries>
+
+ <!--
+ usesCleartextTraffic: home servers (Dispatcharr, HDHomeRun, a NAS) serve plain http on the
+ local network, and many IPTV playlists are http. allowBackup off: source settings and
+ stream addresses never leave the TV in a backup.
+ -->
+ <application
+ android:name=".TvHubApp"
+ android:allowBackup="false"
+ android:dataExtractionRules="@xml/data_extraction_rules"
+ android:fullBackupContent="false"
+ android:banner="@drawable/banner"
+ android:icon="@mipmap/ic_launcher"
+ android:label="@string/app_name"
+ android:supportsRtl="true"
+ android:theme="@style/Theme.TvHub"
+ android:usesCleartextTraffic="true">
+
+ <activity
+ android:name=".ui.MainActivity"
+ android:exported="true"
+ android:launchMode="singleTask"
+ android:configChanges="keyboard|keyboardHidden|navigation|screenSize|smallestScreenSize|screenLayout|orientation">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
+ </intent-filter>
+ <!-- CleanYourTV module card, spec 1 (docs/specs/card.md): same activity as LEANBACK_LAUNCHER. -->
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="com.gathin.tvhome.category.DOCK_CARD" />
+ </intent-filter>
+ <meta-data android:name="com.gathin.tvhome.card" android:resource="@xml/module_card" />
+ </activity>
+
+ <activity android:name=".ui.OnboardingActivity" android:exported="false" />
+ <activity android:name=".ui.SourceEditorActivity" android:exported="false" android:windowSoftInputMode="adjustResize" />
+ <activity
+ android:name=".player.PlayerActivity"
+ android:exported="false"
+ android:theme="@style/Theme.TvHub.Player"
+ android:configChanges="keyboard|keyboardHidden|navigation|screenSize|smallestScreenSize|screenLayout|orientation" />
+ </application>
+</manifest>
diff --git a/addons/tv-hub/app/src/main/assets/licenses.txt b/addons/tv-hub/app/src/main/assets/licenses.txt
new file mode 100644
index 000000000..aa1cb9f5b
--- /dev/null
+++ b/addons/tv-hub/app/src/main/assets/licenses.txt
@@ -0,0 +1,11 @@
+TV Hub is free software under the MIT licence. It has no ads, no accounts, no tracking and no telemetry, and it brings no channels of its own: it plays the sources you add. Only use playlists and services you are allowed to watch.
+
+Third-party software in this app, all under the Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0):
+
+- AndroidX Media3 (ExoPlayer, HLS, UI), Copyright The Android Open Source Project
+- AndroidX RecyclerView, Annotation and Core, Copyright The Android Open Source Project
+- Kotlin standard library and kotlinx.coroutines, Copyright JetBrains s.r.o. and Kotlin contributors
+
+Not included: no code from OpenTV (GPL-3.0), Dispatcharr (AGPL-3.0) or Kodi (GPL-2.0). TV Hub only reads Dispatcharr's documented playlist and guide addresses and the HDHomeRun tuners' local HTTP interface.
+
+Names such as Pluto TV, Tubi, Plex, Kodi, HDHomeRun and Dispatcharr belong to their owners and are used only to name the apps and devices TV Hub can open or read. TV Hub is not affiliated with them or with CleanYourTV.
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/TvHubApp.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/TvHubApp.kt
new file mode 100644
index 000000000..bdf3aaaff
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/TvHubApp.kt
@@ -0,0 +1,17 @@
+package io.github.maxhayim.tvhub
+
+import android.app.Application
+import io.github.maxhayim.tvhub.data.Repository
+import io.github.maxhayim.tvhub.ui.LogoLoader
+
+class TvHubApp : Application() {
+ lateinit var repo: Repository; private set
+ lateinit var logos: LogoLoader; private set
+
+ override fun onCreate() {
+ super.onCreate()
+ repo = Repository(this)
+ logos = LogoLoader(this)
+ repo.load()
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/Db.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/Db.kt
new file mode 100644
index 000000000..eb1a5ac79
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/Db.kt
@@ -0,0 +1,185 @@
+package io.github.maxhayim.tvhub.data
+
+import android.content.ContentValues
+import android.content.Context
+import android.database.sqlite.SQLiteDatabase
+import android.database.sqlite.SQLiteOpenHelper
+import io.github.maxhayim.tvhub.model.Programme
+import io.github.maxhayim.tvhub.model.RawChannel
+import io.github.maxhayim.tvhub.model.SourceConfig
+import io.github.maxhayim.tvhub.model.SourceStatus
+import io.github.maxhayim.tvhub.model.SourceType
+
+/** Framework SQLite: no Room, no annotation processing, nothing loaded that a TV does not need. */
+class Db(context: Context) : SQLiteOpenHelper(context, "tvhub.db", null, 2) {
+
+ override fun onConfigure(db: SQLiteDatabase) { db.enableWriteAheadLogging() }
+
+ override fun onCreate(db: SQLiteDatabase) {
+ db.execSQL("CREATE TABLE sources(id INTEGER PRIMARY KEY AUTOINCREMENT, type TEXT NOT NULL, enabled INTEGER NOT NULL, config TEXT NOT NULL, position INTEGER NOT NULL DEFAULT 0, last_refresh INTEGER NOT NULL DEFAULT 0, channel_count INTEGER NOT NULL DEFAULT 0, skipped INTEGER NOT NULL DEFAULT 0, error TEXT, epg TEXT)")
+ db.execSQL("CREATE TABLE streams(source_id INTEGER NOT NULL, idx INTEGER NOT NULL, name TEXT NOT NULL, number TEXT, tvg_id TEXT, tvg_name TEXT, logo TEXT, grp TEXT, url TEXT NOT NULL, ua TEXT, ref TEXT)")
+ db.execSQL("CREATE INDEX streams_source ON streams(source_id, idx)")
+ db.execSQL("CREATE TABLE programmes(epg_id TEXT NOT NULL, start INTEGER NOT NULL, stop INTEGER NOT NULL, title TEXT NOT NULL, sub TEXT, descr TEXT, cat TEXT)")
+ db.execSQL("CREATE INDEX programmes_channel ON programmes(epg_id, start)")
+ db.execSQL("CREATE TABLE epg_names(name TEXT PRIMARY KEY, epg_id TEXT NOT NULL)")
+ db.execSQL("CREATE TABLE favorites(channel_key TEXT PRIMARY KEY, added INTEGER NOT NULL)")
+ db.execSQL("CREATE TABLE recents(channel_key TEXT PRIMARY KEY, at INTEGER NOT NULL)")
+ }
+
+ override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
+ if (oldVersion < 2) db.execSQL("ALTER TABLE sources ADD COLUMN epg TEXT")
+ }
+
+ // ---- sources
+
+ fun sources(): List<Pair<SourceConfig, SourceStatus>> = readableDatabase.rawQuery(
+ "SELECT id, type, enabled, config, last_refresh, channel_count, skipped, error FROM sources ORDER BY position, id", null
+ ).use { c ->
+ buildList {
+ while (c.moveToNext()) {
+ val type = runCatching { SourceType.valueOf(c.getString(1)) }.getOrNull() ?: continue
+ val json = SecureStore.decrypt(c.getString(3)) ?: continue
+ val cfg = runCatching { SourceCodec.fromJson(c.getLong(0), type, c.getInt(2) != 0, json) }.getOrNull() ?: continue
+ add(cfg to SourceStatus(c.getLong(4), c.getInt(5), c.getInt(6), c.getString(7)))
+ }
+ }
+ }
+
+ fun saveSource(s: SourceConfig): Long {
+ val v = ContentValues().apply {
+ put("type", s.type.name); put("enabled", if (s.enabled) 1 else 0)
+ put("config", SecureStore.encrypt(SourceCodec.toJson(s)))
+ }
+ val db = writableDatabase
+ return if (s.id == 0L) db.insert("sources", null, v) else { db.update("sources", v, "id=?", arrayOf(s.id.toString())); s.id }
+ }
+
+ fun deleteSource(id: Long) {
+ val db = writableDatabase
+ db.beginTransaction()
+ try {
+ db.delete("sources", "id=?", arrayOf(id.toString()))
+ db.delete("streams", "source_id=?", arrayOf(id.toString()))
+ db.setTransactionSuccessful()
+ } finally { db.endTransaction() }
+ }
+
+ fun setStatus(id: Long, st: SourceStatus) {
+ writableDatabase.update("sources", ContentValues().apply {
+ put("last_refresh", st.lastRefresh); put("channel_count", st.channelCount); put("skipped", st.skipped); put("error", st.error)
+ }, "id=?", arrayOf(id.toString()))
+ }
+
+ /**
+ * The guide addresses a source named at its last successful read (its header's x-tvg-url
+ * included), encrypted like the rest of its settings. A source that fails a refresh keeps
+ * contributing them, so one unreachable playlist does not empty the guide.
+ */
+ fun setEpgUrls(id: Long, urls: List<String>) {
+ writableDatabase.update("sources", ContentValues().apply { put("epg", SecureStore.encrypt(org.json.JSONArray(urls).toString())) }, "id=?", arrayOf(id.toString()))
+ }
+
+ fun epgUrls(id: Long): List<String> = readableDatabase.rawQuery("SELECT epg FROM sources WHERE id=?", arrayOf(id.toString())).use { c ->
+ if (!c.moveToFirst() || c.isNull(0)) return emptyList()
+ val a = SecureStore.decrypt(c.getString(0))?.let { runCatching { org.json.JSONArray(it) }.getOrNull() } ?: return emptyList()
+ List(a.length()) { a.optString(it) }.filter { it.isNotBlank() }
+ }
+
+ // ---- streams
+
+ fun replaceStreams(sourceId: Long, list: List<RawChannel>) {
+ val db = writableDatabase
+ db.beginTransaction()
+ try {
+ db.delete("streams", "source_id=?", arrayOf(sourceId.toString()))
+ val st = db.compileStatement("INSERT INTO streams(source_id, idx, name, number, tvg_id, tvg_name, logo, grp, url, ua, ref) VALUES (?,?,?,?,?,?,?,?,?,?,?)")
+ list.forEachIndexed { i, r ->
+ st.clearBindings()
+ st.bindLong(1, sourceId); st.bindLong(2, i.toLong()); st.bindString(3, r.name)
+ bindOpt(st, 4, r.number); bindOpt(st, 5, r.tvgId); bindOpt(st, 6, r.tvgName); bindOpt(st, 7, r.logo); bindOpt(st, 8, r.group)
+ st.bindString(9, r.url); bindOpt(st, 10, r.userAgent); bindOpt(st, 11, r.referrer)
+ st.executeInsert()
+ }
+ db.setTransactionSuccessful()
+ } finally { db.endTransaction() }
+ }
+
+ fun streams(sourceIds: List<Long>, names: Map<Long, String>): List<RawChannel> {
+ if (sourceIds.isEmpty()) return emptyList()
+ val out = ArrayList<RawChannel>()
+ // Source order decides which source names a merged channel and gives its logo.
+ for (sid in sourceIds) {
+ readableDatabase.rawQuery("SELECT name, number, tvg_id, tvg_name, logo, grp, url, ua, ref FROM streams WHERE source_id=? ORDER BY idx", arrayOf(sid.toString())).use { c ->
+ while (c.moveToNext()) out += RawChannel(sid, names[sid].orEmpty(), c.getString(0), c.getString(1), c.getString(2), c.getString(3), c.getString(4), c.getString(5), c.getString(6), c.getString(7), c.getString(8))
+ }
+ }
+ return out
+ }
+
+ // ---- guide
+
+ /** Replaces every programme and name match in one transaction, so the guide never shows half a refresh. */
+ fun replaceGuide(fill: (insert: (Programme) -> Unit) -> Map<String, String>) {
+ val db = writableDatabase
+ db.beginTransaction()
+ try {
+ db.delete("programmes", null, null)
+ db.delete("epg_names", null, null)
+ val st = db.compileStatement("INSERT INTO programmes(epg_id, start, stop, title, sub, descr, cat) VALUES (?,?,?,?,?,?,?)")
+ val names = fill { p ->
+ st.clearBindings()
+ st.bindString(1, p.epgId); st.bindLong(2, p.start); st.bindLong(3, p.stop); st.bindString(4, p.title)
+ bindOpt(st, 5, p.subtitle); bindOpt(st, 6, p.description); bindOpt(st, 7, p.category)
+ st.executeInsert()
+ }
+ val ns = db.compileStatement("INSERT OR IGNORE INTO epg_names(name, epg_id) VALUES (?,?)")
+ names.forEach { (n, id) -> ns.bindString(1, n); ns.bindString(2, id); ns.executeInsert() }
+ db.setTransactionSuccessful()
+ } finally { db.endTransaction() }
+ }
+
+ fun epgNames(): Map<String, String> = readableDatabase.rawQuery("SELECT name, epg_id FROM epg_names", null).use { c ->
+ HashMap<String, String>().apply { while (c.moveToNext()) put(c.getString(0), c.getString(1)) }
+ }
+
+ /** Programmes of these XMLTV ids overlapping [from, to), by id. */
+ fun programmes(epgIds: Collection<String>, from: Long, to: Long, withDescription: Boolean = false): Map<String, List<Programme>> {
+ val out = HashMap<String, MutableList<Programme>>()
+ epgIds.distinct().chunked(400).forEach { chunk ->
+ val q = "SELECT epg_id, start, stop, title, sub, ${if (withDescription) "descr" else "NULL"}, cat FROM programmes WHERE epg_id IN (${chunk.joinToString(",") { "?" }}) AND stop > ? AND start < ? ORDER BY epg_id, start"
+ readableDatabase.rawQuery(q, (chunk + from.toString() + to.toString()).toTypedArray()).use { c ->
+ while (c.moveToNext()) {
+ val p = Programme(c.getString(0), c.getLong(1), c.getLong(2), c.getString(3), c.getString(4), c.getString(5), c.getString(6))
+ out.getOrPut(p.epgId) { ArrayList() } += p
+ }
+ }
+ }
+ return out
+ }
+
+ fun description(epgId: String, start: Long): String? = readableDatabase.rawQuery(
+ "SELECT descr FROM programmes WHERE epg_id=? AND start=? LIMIT 1", arrayOf(epgId, start.toString())
+ ).use { if (it.moveToFirst()) it.getString(0) else null }
+
+ fun programmeCount(): Int = readableDatabase.rawQuery("SELECT COUNT(*) FROM programmes", null).use { if (it.moveToFirst()) it.getInt(0) else 0 }
+
+ // ---- favourites and recents
+
+ fun favorites(): LinkedHashSet<String> = keys("SELECT channel_key FROM favorites ORDER BY added")
+ fun setFavorite(key: String, on: Boolean) {
+ if (on) writableDatabase.insertWithOnConflict("favorites", null, ContentValues().apply { put("channel_key", key); put("added", System.currentTimeMillis()) }, SQLiteDatabase.CONFLICT_IGNORE)
+ else writableDatabase.delete("favorites", "channel_key=?", arrayOf(key))
+ }
+
+ fun recents(limit: Int = 20): List<String> = keys("SELECT channel_key FROM recents ORDER BY at DESC LIMIT $limit").toList()
+ fun addRecent(key: String) {
+ val db = writableDatabase
+ db.insertWithOnConflict("recents", null, ContentValues().apply { put("channel_key", key); put("at", System.currentTimeMillis()) }, SQLiteDatabase.CONFLICT_REPLACE)
+ db.execSQL("DELETE FROM recents WHERE channel_key NOT IN (SELECT channel_key FROM recents ORDER BY at DESC LIMIT 50)")
+ }
+ fun clearRecents() { writableDatabase.delete("recents", null, null) }
+
+ private fun keys(sql: String) = readableDatabase.rawQuery(sql, null).use { c -> LinkedHashSet<String>().apply { while (c.moveToNext()) add(c.getString(0)) } }
+
+ private fun bindOpt(st: android.database.sqlite.SQLiteStatement, i: Int, v: String?) { if (v == null) st.bindNull(i) else st.bindString(i, v) }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/Http.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/Http.kt
new file mode 100644
index 000000000..d114ef26d
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/Http.kt
@@ -0,0 +1,78 @@
+package io.github.maxhayim.tvhub.data
+
+import java.io.BufferedInputStream
+import java.io.FilterInputStream
+import java.io.IOException
+import java.io.InputStream
+import java.net.HttpURLConnection
+import java.net.SocketTimeoutException
+import java.net.URL
+import java.net.UnknownHostException
+import java.util.zip.GZIPInputStream
+import javax.net.ssl.SSLException
+
+/** Plain HttpURLConnection: no extra library for a few GETs. Gzip is detected by its magic bytes, so .xml.gz guides work. */
+object Http {
+ class HttpError(message: String) : IOException(message)
+
+ fun open(url: String, maxBytes: Long, headers: Map<String, String> = emptyMap()): InputStream {
+ var current = url
+ repeat(6) {
+ val c = URL(current).openConnection() as HttpURLConnection
+ c.connectTimeout = 15_000
+ c.readTimeout = 30_000
+ c.instanceFollowRedirects = false
+ c.setRequestProperty("User-Agent", headers["User-Agent"] ?: "TVHub/1.0 (Android TV)")
+ c.setRequestProperty("Accept-Encoding", "gzip")
+ headers.forEach { (k, v) -> if (k != "User-Agent") c.setRequestProperty(k, v) }
+ val code = try { c.responseCode } catch (e: IOException) { c.disconnect(); throw friendly(e) }
+ if (code in 300..399) {
+ val loc = c.getHeaderField("Location")
+ c.disconnect()
+ if (loc.isNullOrEmpty()) throw HttpError("The server redirected without saying where")
+ current = URL(URL(current), loc).toString()
+ if (!current.startsWith("http://") && !current.startsWith("https://")) throw HttpError("The server redirected to an unsupported address")
+ return@repeat
+ }
+ if (code !in 200..299) {
+ c.disconnect()
+ throw HttpError(
+ when (code) {
+ 401, 403 -> "The server refused access (HTTP $code). Check the address, or the server's allowed networks"
+ 404 -> "Nothing at that address (HTTP 404)"
+ else -> "The server answered HTTP $code"
+ }
+ )
+ }
+ val raw = BufferedInputStream(Limited(c.inputStream, maxBytes), 64 * 1024)
+ raw.mark(2)
+ val b0 = raw.read(); val b1 = raw.read()
+ raw.reset()
+ return if (b0 == 0x1f && b1 == 0x8b) Limited(GZIPInputStream(raw, 64 * 1024), maxBytes * 8) else raw
+ }
+ throw HttpError("Too many redirects")
+ }
+
+ fun text(url: String, maxBytes: Long = 4L * 1024 * 1024): String = open(url, maxBytes).use { it.readBytes().toString(Charsets.UTF_8) }
+
+ fun friendly(e: Throwable): IOException = when (e) {
+ is HttpError -> e
+ is UnknownHostException -> HttpError("Can't find that server. Check the address and the TV's network")
+ is SocketTimeoutException -> HttpError("The server took too long to answer")
+ is SSLException -> HttpError("The secure connection failed (certificate or TLS problem)")
+ is java.net.ConnectException -> HttpError("Can't connect to the server. Is it running and reachable from the TV?")
+ is TooLarge -> HttpError(e.message ?: "The file is too large")
+ is IOException -> HttpError("Network error: ${e.javaClass.simpleName}")
+ else -> HttpError("Unexpected error: ${e.javaClass.simpleName}")
+ }
+
+ class TooLarge(message: String) : IOException(message)
+
+ /** Stops a download that grows past what a TV should hold. */
+ private class Limited(input: InputStream, private val max: Long) : FilterInputStream(input) {
+ private var count = 0L
+ override fun read(): Int = super.read().also { if (it >= 0) bump(1) }
+ override fun read(b: ByteArray, off: Int, len: Int): Int = super.read(b, off, len).also { if (it > 0) bump(it.toLong()) }
+ private fun bump(n: Long) { count += n; if (count > max) throw TooLarge("The file is larger than ${max / (1024 * 1024)} MB") }
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/Prefs.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/Prefs.kt
new file mode 100644
index 000000000..efa4c3e79
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/Prefs.kt
@@ -0,0 +1,34 @@
+package io.github.maxhayim.tvhub.data
+
+import android.content.Context
+
+/** Plain settings; nothing secret lives here (source settings are in the encrypted sources table). */
+class Prefs(context: Context) {
+ private val p = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
+
+ var onboarded: Boolean
+ get() = p.getBoolean("onboarded", false)
+ set(v) = p.edit().putBoolean("onboarded", v).apply()
+
+ var mergeDuplicates: Boolean
+ get() = p.getBoolean("merge", true)
+ set(v) = p.edit().putBoolean("merge", v).apply()
+
+ /** Days of guide kept after a refresh. */
+ var guideDays: Int
+ get() = p.getInt("guide_days", 2)
+ set(v) = p.edit().putInt("guide_days", v.coerceIn(1, 7)).apply()
+
+ /** Refresh when the app opens and the last refresh is older than this; 0 never refreshes on its own. */
+ var refreshHours: Int
+ get() = p.getInt("refresh_hours", 12)
+ set(v) = p.edit().putInt("refresh_hours", v).apply()
+
+ var animations: Boolean
+ get() = p.getBoolean("animations", true)
+ set(v) = p.edit().putBoolean("animations", v).apply()
+
+ var lastRefresh: Long
+ get() = p.getLong("last_refresh", 0)
+ set(v) = p.edit().putLong("last_refresh", v).apply()
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/Repository.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/Repository.kt
new file mode 100644
index 000000000..f0a0a365c
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/Repository.kt
@@ -0,0 +1,208 @@
+package io.github.maxhayim.tvhub.data
+
+import android.content.Context
+import android.util.Xml
+import io.github.maxhayim.tvhub.model.AppShortcut
+import io.github.maxhayim.tvhub.model.Channel
+import io.github.maxhayim.tvhub.model.Programme
+import io.github.maxhayim.tvhub.model.SourceConfig
+import io.github.maxhayim.tvhub.model.SourceStatus
+import io.github.maxhayim.tvhub.model.SourceType
+import io.github.maxhayim.tvhub.parse.ChannelMerger
+import io.github.maxhayim.tvhub.parse.XmltvParser
+import io.github.maxhayim.tvhub.source.Apps
+import io.github.maxhayim.tvhub.source.Providers
+import io.github.maxhayim.tvhub.util.Log
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import org.xmlpull.v1.XmlPullParser
+
+/**
+ * The app's single source of truth. Refreshing runs only while the app is open (no background
+ * service): when it starts and the last refresh is older than the setting, or when the owner asks.
+ */
+class Repository(private val context: Context) {
+ val db = Db(context)
+ val prefs = Prefs(context)
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ data class RefreshState(val running: Boolean = false, val message: String = "", val errors: Int = 0)
+
+ private val _channels = MutableStateFlow<List<Channel>>(emptyList())
+ val channels: StateFlow<List<Channel>> = _channels
+ private val _favorites = MutableStateFlow<Set<String>>(emptySet())
+ val favorites: StateFlow<Set<String>> = _favorites
+ private val _refresh = MutableStateFlow(RefreshState())
+ val refresh: StateFlow<RefreshState> = _refresh
+ private val _sources = MutableStateFlow<List<Pair<SourceConfig, SourceStatus>>>(emptyList())
+ val sources: StateFlow<List<Pair<SourceConfig, SourceStatus>>> = _sources
+ /** Bumped when the guide data changes, so open screens reload programmes. */
+ private val _guideVersion = MutableStateFlow(0)
+ val guideVersion: StateFlow<Int> = _guideVersion
+
+ private var refreshJob: Job? = null
+ @Volatile var loaded = false; private set
+
+ fun channel(key: String): Channel? = _channels.value.firstOrNull { it.key == key }
+
+ /** Reads what the last refresh stored. Cheap enough to call after every settings change. */
+ fun load(): Job = scope.launch { reload() }
+
+ private fun reload() {
+ val all = db.sources()
+ _sources.value = all
+ val enabled = all.map { it.first }.filter { it.enabled && it.type != SourceType.APPS && it.type != SourceType.XMLTV }
+ val raw = db.streams(enabled.map { it.id }, enabled.associate { it.id to it.name })
+ _channels.value = ChannelMerger.merge(raw, prefs.mergeDuplicates, db.epgNames())
+ _favorites.value = db.favorites()
+ loaded = true
+ }
+
+ fun refreshIfStale() {
+ val h = prefs.refreshHours
+ if (h > 0 && System.currentTimeMillis() - prefs.lastRefresh > h * 3_600_000L) refreshAll()
+ }
+
+ fun refreshAll() {
+ if (refreshJob?.isActive == true) return
+ refreshJob = scope.launch { runRefresh() }
+ }
+
+ private fun runRefresh() {
+ val sources = db.sources().map { it.first }.filter { it.enabled }
+ var errors = 0
+ val epgUrls = LinkedHashSet<String>()
+ for (s in sources) {
+ if (s.type == SourceType.APPS) continue
+ _refresh.value = RefreshState(true, "Reading ${s.name}…", errors)
+ try {
+ val r = Providers.forType(s.type).load(s)
+ if (s.type != SourceType.XMLTV) db.replaceStreams(s.id, r.channels)
+ epgUrls += r.epgUrls.filter { it.isNotBlank() }
+ db.setEpgUrls(s.id, r.epgUrls)
+ db.setStatus(s.id, SourceStatus(System.currentTimeMillis(), r.channels.size, r.skipped, null))
+ } catch (e: Exception) {
+ errors++
+ Log.w("Source ${s.id} (${s.type}) failed", e)
+ // The previous channels stay, so a server that is down for a moment does not empty the guide.
+ epgUrls += db.epgUrls(s.id)
+ val old = _sources.value.firstOrNull { it.first.id == s.id }?.second ?: SourceStatus()
+ db.setStatus(s.id, old.copy(error = e.message ?: "Could not read this source"))
+ }
+ }
+ reload()
+ if (epgUrls.isNotEmpty()) {
+ _refresh.value = RefreshState(true, "Reading the guide…", errors)
+ errors += readGuides(epgUrls.toList(), sources)
+ } else {
+ db.replaceGuide { emptyMap() }
+ }
+ prefs.lastRefresh = System.currentTimeMillis()
+ reload()
+ _guideVersion.value++
+ _refresh.value = RefreshState(false, if (errors == 0) "Up to date" else "$errors source${if (errors == 1) "" else "s"} could not be read", errors)
+ }
+
+ /** Returns how many guides failed. A failed guide's errors land on the XMLTV source that named it, if any. */
+ private fun readGuides(urls: List<String>, sources: List<SourceConfig>): Int {
+ val enabled = sources.filter { it.type != SourceType.APPS && it.type != SourceType.XMLTV }.map { it.id }
+ val raw = db.streams(enabled, emptyMap())
+ val wanted = raw.mapNotNull { it.tvgId?.trim()?.takeIf { s -> s.isNotEmpty() } }.toSet()
+ val namesWithoutId = raw.filter { it.tvgId.isNullOrBlank() }.map { XmltvParser.normalise(it.tvgName ?: it.name) }.filter { it.isNotEmpty() }.toSet()
+ val now = System.currentTimeMillis()
+ val from = now - 3 * 3_600_000L
+ val to = now + prefs.guideDays * 86_400_000L
+ var failed = 0
+ val names = HashMap<String, String>()
+ try { db.replaceGuide { insert ->
+ for (u in urls) {
+ val xmltvSource = sources.firstOrNull { it.type == SourceType.XMLTV && it.url.trim() == u }
+ try {
+ val parser = XmltvParser(wanted, namesWithoutId, from, to)
+ Http.open(u, 256L * 1024 * 1024).use { input ->
+ val p = Xml.newPullParser()
+ p.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
+ p.setInput(input, null)
+ parser.parse(p, insert)
+ }
+ if (parser.channelCount == 0 && parser.programmeCount == 0) throw java.io.IOException("That address did not return an XMLTV guide")
+ parser.nameMatches.forEach { (k, v) -> names.putIfAbsent(k, v) }
+ xmltvSource?.let { db.setStatus(it.id, SourceStatus(System.currentTimeMillis(), parser.channelCount, 0, null)) }
+ } catch (e: Exception) {
+ failed++
+ Log.w("Guide ${Log.redact(u)} failed", e)
+ val msg = when (e) {
+ is org.xmlpull.v1.XmlPullParserException -> "The guide is not valid XMLTV"
+ else -> Http.friendly(e).message
+ }
+ xmltvSource?.let { db.setStatus(it.id, SourceStatus(System.currentTimeMillis(), 0, 0, msg)) }
+ }
+ }
+ // Every guide failed: roll back and keep the last good one instead of an empty guide.
+ if (failed == urls.size) throw KeepOldGuide()
+ names
+ } } catch (_: KeepOldGuide) {
+ Log.i("No guide could be read; keeping the previous one")
+ }
+ return failed
+ }
+
+ // ---- sources
+
+ fun saveSource(s: SourceConfig, refresh: Boolean = true) = scope.launch {
+ db.saveSource(s)
+ reload()
+ if (refresh && s.type != SourceType.APPS) withContext(Dispatchers.Main) { refreshAll() }
+ }
+
+ fun deleteSource(id: Long) = scope.launch { db.deleteSource(id); reload(); _guideVersion.value++ }
+
+ fun appShortcuts(): List<AppShortcut> = _sources.value.map { it.first }
+ .filter { it.type == SourceType.APPS && it.enabled }
+ .flatMap { it.packages }.distinct()
+ .filter { Apps.isInstalled(context, it) }
+ .map { AppShortcut(it, Apps.label(context, it)) }
+
+ // ---- favourites, recents, guide
+
+ fun toggleFavorite(key: String): Boolean {
+ val on = key !in _favorites.value
+ _favorites.value = if (on) _favorites.value + key else _favorites.value - key
+ scope.launch { db.setFavorite(key, on) }
+ return on
+ }
+
+ fun addRecent(key: String) = scope.launch { db.addRecent(key) }
+ fun recents(): List<Channel> { val byKey = _channels.value.associateBy { it.key }; return db.recents().mapNotNull { byKey[it] } }
+ fun clearRecents() = scope.launch { db.clearRecents() }
+
+ /** Programmes for these channels overlapping [from, to), by channel key. Call off the main thread. */
+ fun programmes(channels: List<Channel>, from: Long, to: Long): Map<String, List<Programme>> {
+ val ids = channels.flatMap { it.epgIds }
+ if (ids.isEmpty()) return emptyMap()
+ val byId = db.programmes(ids, from, to)
+ return channels.associate { ch ->
+ ch.key to ch.epgIds.asSequence().mapNotNull { byId[it] }.firstOrNull { it.isNotEmpty() }.orEmpty()
+ }
+ }
+
+ /** Now and next for each channel; empty for channels without guide data. Call off the main thread. */
+ fun nowNext(channels: List<Channel>, now: Long = System.currentTimeMillis()): Map<String, Pair<Programme?, Programme?>> =
+ programmes(channels, now, now + 6 * 3_600_000L).mapValues { (_, list) ->
+ val cur = list.firstOrNull { it.isOn(now) }
+ val next = list.firstOrNull { it.start >= (cur?.stop ?: now) }
+ cur to next
+ }
+
+ fun description(p: Programme): String? = p.description ?: db.description(p.epgId, p.start)
+
+ fun setMerge(on: Boolean) { prefs.mergeDuplicates = on; load() }
+
+ private class KeepOldGuide : RuntimeException()
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/SecureStore.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/SecureStore.kt
new file mode 100644
index 000000000..a67ab7670
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/SecureStore.kt
@@ -0,0 +1,66 @@
+package io.github.maxhayim.tvhub.data
+
+import android.security.keystore.KeyGenParameterSpec
+import android.security.keystore.KeyProperties
+import android.util.Base64
+import io.github.maxhayim.tvhub.util.Log
+import java.security.KeyStore
+import javax.crypto.Cipher
+import javax.crypto.KeyGenerator
+import javax.crypto.SecretKey
+import javax.crypto.spec.GCMParameterSpec
+
+/**
+ * Encrypts source settings with an AES key kept in the Android Keystore, so the key never sits in
+ * the app's files. Some budget TVs ship a broken Keystore; there the value is kept in the app's
+ * private storage unencrypted (marked "p:"), backups being off, and the README says so.
+ */
+object SecureStore {
+ private const val ALIAS = "tvhub_sources"
+ @Volatile private var broken = false
+
+ fun encrypt(plain: String): String {
+ if (!broken) {
+ try {
+ val c = Cipher.getInstance("AES/GCM/NoPadding")
+ c.init(Cipher.ENCRYPT_MODE, key())
+ val ct = c.doFinal(plain.toByteArray(Charsets.UTF_8))
+ return "k:" + Base64.encodeToString(c.iv + ct, Base64.NO_WRAP)
+ } catch (e: Exception) {
+ broken = true
+ Log.w("Keystore unavailable, storing source settings in private storage only", e)
+ }
+ }
+ return "p:" + Base64.encodeToString(plain.toByteArray(Charsets.UTF_8), Base64.NO_WRAP)
+ }
+
+ fun decrypt(stored: String): String? = try {
+ when {
+ stored.startsWith("k:") -> {
+ val all = Base64.decode(stored.substring(2), Base64.NO_WRAP)
+ val c = Cipher.getInstance("AES/GCM/NoPadding")
+ c.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, all, 0, 12))
+ String(c.doFinal(all, 12, all.size - 12), Charsets.UTF_8)
+ }
+ stored.startsWith("p:") -> String(Base64.decode(stored.substring(2), Base64.NO_WRAP), Charsets.UTF_8)
+ else -> null
+ }
+ } catch (e: Exception) {
+ Log.w("Could not read a stored source", e)
+ null
+ }
+
+ private fun key(): SecretKey {
+ val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+ (ks.getEntry(ALIAS, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey }
+ val g = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
+ g.init(
+ KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .setKeySize(256)
+ .build()
+ )
+ return g.generateKey()
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/SourceCodec.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/SourceCodec.kt
new file mode 100644
index 000000000..63fcf44c3
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/data/SourceCodec.kt
@@ -0,0 +1,27 @@
+package io.github.maxhayim.tvhub.data
+
+import io.github.maxhayim.tvhub.model.SourceConfig
+import io.github.maxhayim.tvhub.model.SourceType
+import org.json.JSONArray
+import org.json.JSONObject
+
+/** Source settings as JSON, the form that is encrypted into the database. */
+object SourceCodec {
+ fun toJson(s: SourceConfig): String = JSONObject()
+ .put("name", s.name).put("url", s.url).put("epgUrl", s.epgUrl).put("profile", s.profile)
+ .put("useHeaderEpg", s.useHeaderEpg).put("transcode", s.transcode)
+ .put("packages", JSONArray(s.packages))
+ .toString()
+
+ fun fromJson(id: Long, type: SourceType, enabled: Boolean, json: String): SourceConfig {
+ val o = JSONObject(json)
+ val pk = o.optJSONArray("packages")
+ return SourceConfig(
+ id = id, type = type, enabled = enabled,
+ name = o.optString("name"), url = o.optString("url"), epgUrl = o.optString("epgUrl"),
+ profile = o.optString("profile"), useHeaderEpg = o.optBoolean("useHeaderEpg", true),
+ transcode = o.optBoolean("transcode", false),
+ packages = if (pk == null) emptyList() else List(pk.length()) { pk.optString(it) }.filter { it.isNotEmpty() },
+ )
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/model/Models.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/model/Models.kt
new file mode 100644
index 000000000..12571f312
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/model/Models.kt
@@ -0,0 +1,80 @@
+package io.github.maxhayim.tvhub.model
+
+/** Kinds of source the hub can read. APPS is a list of installed apps, never channels. */
+enum class SourceType { M3U, XMLTV, DISPATCHARR, HDHOMERUN, APPS }
+
+/**
+ * One configured source. Everything but id and type is stored encrypted, since playlist URLs
+ * often carry an account name and password in their query string.
+ */
+data class SourceConfig(
+ val id: Long = 0,
+ val type: SourceType,
+ val name: String,
+ /** M3U or XMLTV URL, Dispatcharr base URL, or the HDHomeRun address. */
+ val url: String = "",
+ /** XMLTV URL used with an M3U source; empty for none. */
+ val epgUrl: String = "",
+ /** Dispatcharr output profile; empty for all channels. */
+ val profile: String = "",
+ /** Also read the guide named in the playlist's #EXTM3U header (x-tvg-url). */
+ val useHeaderEpg: Boolean = true,
+ /** HDHomeRun EXTEND only: ask the tuner for H.264 instead of broadcast MPEG-2. */
+ val transcode: Boolean = false,
+ /** APPS: package names the owner picked. */
+ val packages: List<String> = emptyList(),
+ val enabled: Boolean = true,
+)
+
+/** Result of the last refresh of a source, shown on the Sources screen. */
+data class SourceStatus(val lastRefresh: Long = 0, val channelCount: Int = 0, val skipped: Int = 0, val error: String? = null)
+
+/** One playable stream as a playlist or tuner lists it. */
+data class RawChannel(
+ val sourceId: Long,
+ val sourceName: String,
+ val name: String,
+ val number: String? = null,
+ val tvgId: String? = null,
+ val tvgName: String? = null,
+ val logo: String? = null,
+ val group: String? = null,
+ val url: String,
+ val userAgent: String? = null,
+ val referrer: String? = null,
+)
+
+data class StreamRef(val url: String, val userAgent: String?, val referrer: String?, val sourceName: String)
+
+/**
+ * A channel as the guide shows it. With duplicates merged, one channel can hold the streams of
+ * several sources that share a tvg-id; the player falls back to the next one if a stream fails.
+ */
+data class Channel(
+ /** Stable across refreshes; favourites and recents are stored by it. */
+ val key: String,
+ val name: String,
+ val number: String?,
+ val logo: String?,
+ val group: String?,
+ /** XMLTV channel ids whose programmes belong to this channel. Empty: no guide data. */
+ val epgIds: List<String>,
+ val streams: List<StreamRef>,
+) {
+ val sourceNames: List<String> get() = streams.map { it.sourceName }.distinct()
+}
+
+data class Programme(
+ val epgId: String,
+ val start: Long,
+ val stop: Long,
+ val title: String,
+ val subtitle: String? = null,
+ val description: String? = null,
+ val category: String? = null,
+) {
+ fun isOn(now: Long) = now in start until stop
+}
+
+/** An installed app offered as a source. It opens the app; it has no channels or guide. */
+data class AppShortcut(val pkg: String, val label: String)
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/parse/ChannelMerger.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/parse/ChannelMerger.kt
new file mode 100644
index 000000000..66eb8dbac
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/parse/ChannelMerger.kt
@@ -0,0 +1,77 @@
+package io.github.maxhayim.tvhub.parse
+
+import io.github.maxhayim.tvhub.model.Channel
+import io.github.maxhayim.tvhub.model.RawChannel
+import io.github.maxhayim.tvhub.model.StreamRef
+
+/**
+ * Turns the streams of every source into the channel list. Two streams are the same channel only
+ * when they carry the same tvg-id, the one identifier playlists share reliably; names alone are
+ * never merged. With merging off, every source keeps its own copy.
+ */
+object ChannelMerger {
+
+ fun merge(raw: List<RawChannel>, mergeDuplicates: Boolean, epgByName: Map<String, String> = emptyMap()): List<Channel> {
+ val byKey = LinkedHashMap<String, Builder>()
+ val seen = HashMap<String, Int>()
+ for (r in raw) {
+ val tvg = r.tvgId?.trim()?.takeIf { it.isNotEmpty() }
+ val base = if (mergeDuplicates && tvg != null) "tvg:" + tvg.lowercase()
+ else "src:${r.sourceId}:" + (tvg?.lowercase() ?: XmltvParser.normalise(r.name))
+ // Two entries of one source with the same key (the same channel listed twice in a group
+ // each) stay separate channels, numbered by order so the key is stable across refreshes.
+ val key = if (base.startsWith("tvg:") && byKey.containsKey(base)) {
+ base
+ } else {
+ val n = seen.merge(base, 1, Int::plus)!!
+ if (n == 1) base else "$base#$n"
+ }
+ val b = byKey.getOrPut(key) { Builder(key, r) }
+ val s = StreamRef(r.url, r.userAgent, r.referrer, r.sourceName)
+ if (b.streams.none { it.url == s.url }) b.streams += s
+ if (b.logo == null) b.logo = r.logo
+ if (b.number == null) b.number = r.number
+ if (b.group == null) b.group = r.group
+ if (tvg != null) b.epgIds += tvg
+ else {
+ val byName = epgByName[XmltvParser.normalise(r.tvgName ?: r.name)]
+ if (byName != null) b.epgIds += byName
+ }
+ }
+ return byKey.values.map { it.build() }.sortedWith(ORDER)
+ }
+
+ /** Channels with a number first, by number ("4.1" before "4.10" before "12"), then by name. */
+ val ORDER: Comparator<Channel> = Comparator { a, b ->
+ val an = a.number; val bn = b.number
+ when {
+ an != null && bn != null -> compareNumbers(an, bn).takeIf { it != 0 } ?: a.name.compareTo(b.name, true)
+ an != null -> -1
+ bn != null -> 1
+ else -> a.name.compareTo(b.name, true)
+ }
+ }
+
+ internal fun compareNumbers(a: String, b: String): Int {
+ val pa = a.split('.', '-'); val pb = b.split('.', '-')
+ for (i in 0 until maxOf(pa.size, pb.size)) {
+ val x = pa.getOrNull(i); val y = pb.getOrNull(i)
+ if (x == null) return -1
+ if (y == null) return 1
+ val xi = x.toLongOrNull(); val yi = y.toLongOrNull()
+ val c = if (xi != null && yi != null) xi.compareTo(yi) else x.compareTo(y, true)
+ if (c != 0) return c
+ }
+ return 0
+ }
+
+ private class Builder(val key: String, first: RawChannel) {
+ val name = first.name
+ var number = first.number
+ var logo = first.logo
+ var group = first.group
+ val epgIds = LinkedHashSet<String>()
+ val streams = ArrayList<StreamRef>()
+ fun build() = Channel(key, name, number, logo, group, epgIds.toList(), streams.toList())
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/parse/M3uParser.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/parse/M3uParser.kt
new file mode 100644
index 000000000..a47584dab
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/parse/M3uParser.kt
@@ -0,0 +1,128 @@
+package io.github.maxhayim.tvhub.parse
+
+import io.github.maxhayim.tvhub.model.RawChannel
+import java.io.BufferedReader
+
+/**
+ * Reads M3U and M3U8 playlists (the extended IPTV form with #EXTINF attributes, and plain lists
+ * of URLs). Only http and https streams are kept; anything else is counted as skipped, so the
+ * Sources screen can say how many entries this player cannot open.
+ */
+object M3uParser {
+ const val MAX_CHANNELS = 50_000
+ private const val MAX_LINE = 16 * 1024
+
+ data class Result(val channels: List<RawChannel>, val epgUrls: List<String>, val skipped: Int, val isPlaylist: Boolean)
+
+ fun parse(reader: BufferedReader, sourceId: Long, sourceName: String): Result {
+ val out = ArrayList<RawChannel>()
+ val epg = LinkedHashSet<String>()
+ var skipped = 0
+ var sawHeader = false
+ var info: Map<String, String> = emptyMap()
+ var title: String? = null
+ var group: String? = null
+ var ua: String? = null
+ var ref: String? = null
+ var first = true
+ while (true) {
+ var line = reader.readLine() ?: break
+ if (first) { line = line.removePrefix("\uFEFF"); first = false }
+ if (line.length > MAX_LINE) { skipped++; continue }
+ line = line.trim()
+ if (line.isEmpty()) continue
+ when {
+ line.startsWith("#EXTM3U") -> {
+ sawHeader = true
+ val a = attributes(line.removePrefix("#EXTM3U"))
+ listOfNotNull(a["x-tvg-url"], a["url-tvg"]).forEach { v ->
+ v.split(',').map { it.trim() }.filter { isHttp(it) }.forEach { epg += it }
+ }
+ }
+ line.startsWith("#EXTINF:") -> {
+ val body = line.removePrefix("#EXTINF:")
+ val comma = titleComma(body)
+ info = attributes(if (comma >= 0) body.substring(0, comma) else body)
+ title = if (comma >= 0) body.substring(comma + 1).trim() else null
+ }
+ line.startsWith("#EXTGRP:") -> group = line.removePrefix("#EXTGRP:").trim()
+ line.startsWith("#EXTVLCOPT:") -> {
+ val opt = line.removePrefix("#EXTVLCOPT:")
+ when {
+ opt.startsWith("http-user-agent=") -> ua = opt.substringAfter('=').trim()
+ opt.startsWith("http-referrer=") -> ref = opt.substringAfter('=').trim()
+ }
+ }
+ line.startsWith("#") -> Unit
+ else -> {
+ if (!isHttp(line) || out.size >= MAX_CHANNELS) {
+ skipped++
+ } else {
+ val name = title?.takeIf { it.isNotEmpty() } ?: info["tvg-name"]?.takeIf { it.isNotBlank() } ?: nameFromUrl(line)
+ out += RawChannel(
+ sourceId = sourceId,
+ sourceName = sourceName,
+ name = name,
+ number = (info["tvg-chno"] ?: info["channel-number"] ?: info["tvg-num"])?.trim()?.takeIf { it.isNotEmpty() },
+ tvgId = info["tvg-id"]?.trim()?.takeIf { it.isNotEmpty() },
+ tvgName = info["tvg-name"]?.trim()?.takeIf { it.isNotEmpty() },
+ logo = info["tvg-logo"]?.trim()?.takeIf { isHttp(it) },
+ group = (info["group-title"] ?: group)?.trim()?.takeIf { it.isNotEmpty() },
+ url = line,
+ userAgent = ua ?: info["http-user-agent"],
+ referrer = ref ?: info["http-referrer"],
+ )
+ }
+ info = emptyMap(); title = null; group = null; ua = null; ref = null
+ }
+ }
+ }
+ return Result(out, epg.toList(), skipped, sawHeader || out.isNotEmpty())
+ }
+
+ fun isHttp(s: String): Boolean {
+ val l = s.lowercase()
+ return (l.startsWith("http://") || l.startsWith("https://")) && s.length > 8 && s.none { it == ' ' || it.code < 0x20 }
+ }
+
+ /** The comma that starts the title: the first one outside a quoted attribute value. */
+ internal fun titleComma(s: String): Int {
+ var quoted = false
+ for (i in s.indices) {
+ when (s[i]) {
+ '"' -> quoted = !quoted
+ ',' -> if (!quoted) return i
+ }
+ }
+ return -1
+ }
+
+ /** key="value" pairs; keys are lower-cased, the first occurrence of a key wins. */
+ internal fun attributes(s: String): Map<String, String> {
+ val m = HashMap<String, String>()
+ var i = 0
+ val n = s.length
+ while (i < n) {
+ while (i < n && !(s[i].isLetterOrDigit())) i++
+ val ks = i
+ while (i < n && (s[i].isLetterOrDigit() || s[i] == '-' || s[i] == '_')) i++
+ val key = s.substring(ks, i).lowercase()
+ if (i < n && s[i] == '=' && i + 1 < n && s[i + 1] == '"') {
+ val vs = i + 2
+ val ve = s.indexOf('"', vs)
+ if (ve < 0) break
+ if (key.isNotEmpty() && key !in m) m[key] = s.substring(vs, ve)
+ i = ve + 1
+ } else if (i == ks) {
+ i++
+ }
+ }
+ return m
+ }
+
+ private fun nameFromUrl(url: String): String {
+ val path = url.substringAfter("://").substringBefore('?').trimEnd('/')
+ val last = path.substringAfterLast('/')
+ return if (last.isNotEmpty() && last != path) last else path.substringBefore('/')
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/parse/XmltvParser.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/parse/XmltvParser.kt
new file mode 100644
index 000000000..50c1a3752
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/parse/XmltvParser.kt
@@ -0,0 +1,86 @@
+package io.github.maxhayim.tvhub.parse
+
+import io.github.maxhayim.tvhub.model.Programme
+import org.xmlpull.v1.XmlPullParser
+
+/**
+ * Streams an XMLTV guide without holding it in memory. Guides list their channels before their
+ * programmes, so a channel element can add its id to the wanted set (matched by display name)
+ * before the programmes for it arrive.
+ */
+class XmltvParser(
+ /** XMLTV ids some channel already names through its tvg-id. */
+ wantedIds: Set<String>,
+ /** Normalised names of channels without a tvg-id, for matching by display name. */
+ private val namesWithoutId: Set<String>,
+ private val windowStart: Long,
+ private val windowEnd: Long,
+) {
+ private val wanted = HashSet(wantedIds)
+
+ /** Display-name matches found: normalised name to XMLTV id. */
+ val nameMatches = HashMap<String, String>()
+ var channelCount = 0; private set
+ var programmeCount = 0; private set
+
+ fun parse(p: XmlPullParser, onProgramme: (Programme) -> Unit) {
+ var ev = p.eventType
+ while (ev != XmlPullParser.END_DOCUMENT) {
+ if (ev == XmlPullParser.START_TAG) {
+ when (p.name) {
+ "channel" -> readChannel(p)
+ "programme" -> readProgramme(p)?.let { programmeCount++; onProgramme(it) }
+ }
+ }
+ ev = p.next()
+ }
+ }
+
+ private fun readChannel(p: XmlPullParser) {
+ val id = p.getAttributeValue(null, "id")?.trim().orEmpty()
+ val depth = p.depth
+ channelCount++
+ while (true) {
+ val ev = p.next()
+ if (ev == XmlPullParser.END_DOCUMENT || (ev == XmlPullParser.END_TAG && p.depth == depth)) return
+ if (ev == XmlPullParser.START_TAG && p.name == "display-name" && id.isNotEmpty()) {
+ val n = normalise(p.nextText())
+ if (n.isNotEmpty() && n in namesWithoutId && n !in nameMatches) {
+ nameMatches[n] = id
+ wanted += id
+ }
+ }
+ }
+ }
+
+ private fun readProgramme(p: XmlPullParser): Programme? {
+ val ch = p.getAttributeValue(null, "channel")?.trim().orEmpty()
+ val start = XmltvTime.parse(p.getAttributeValue(null, "start"))
+ val stop = XmltvTime.parse(p.getAttributeValue(null, "stop"))
+ val keep = ch in wanted && start != null && stop != null && stop > start && stop > windowStart && start < windowEnd
+ val depth = p.depth
+ var title: String? = null
+ var sub: String? = null
+ var desc: String? = null
+ var cat: String? = null
+ while (true) {
+ val ev = p.next()
+ if (ev == XmlPullParser.END_DOCUMENT || (ev == XmlPullParser.END_TAG && p.depth == depth)) break
+ if (keep && ev == XmlPullParser.START_TAG && p.depth == depth + 1) {
+ when (p.name) {
+ "title" -> p.nextText().trim().let { if (title == null && it.isNotEmpty()) title = it }
+ "sub-title" -> p.nextText().trim().let { if (sub == null && it.isNotEmpty()) sub = it }
+ "desc" -> p.nextText().trim().let { if (desc == null && it.isNotEmpty()) desc = it.take(2000) }
+ "category" -> p.nextText().trim().let { if (cat == null && it.isNotEmpty()) cat = it }
+ }
+ }
+ }
+ if (!keep) return null
+ return Programme(ch, start!!, stop!!, title ?: "", sub, desc, cat)
+ }
+
+ companion object {
+ /** Lower case, letters and digits only: "BBC One HD" and "bbc-one-hd" match. */
+ fun normalise(s: String): String = buildString { s.lowercase().forEach { if (it.isLetterOrDigit()) append(it) } }
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/parse/XmltvTime.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/parse/XmltvTime.kt
new file mode 100644
index 000000000..f8fb4a97b
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/parse/XmltvTime.kt
@@ -0,0 +1,51 @@
+package io.github.maxhayim.tvhub.parse
+
+/** XMLTV times: "YYYYMMDDhhmmss +zzzz", where seconds, minutes and the offset may be left out (then UTC). */
+object XmltvTime {
+ fun parse(s: String?): Long? {
+ if (s == null) return null
+ val t = s.trim()
+ var i = 0
+ fun num(len: Int): Int? {
+ if (i + len > t.length) return null
+ var v = 0
+ for (k in 0 until len) {
+ val c = t[i + k]
+ if (c !in '0'..'9') return null
+ v = v * 10 + (c - '0')
+ }
+ i += len
+ return v
+ }
+ val year = num(4) ?: return null
+ val month = num(2) ?: return null
+ val day = num(2) ?: return null
+ val hour = num(2) ?: 0
+ val minute = if (i < t.length && t[i].isDigit()) num(2) ?: 0 else 0
+ val second = if (i < t.length && t[i].isDigit()) num(2) ?: 0 else 0
+ if (month !in 1..12 || day !in 1..31 || hour > 23 || minute > 59 || second > 60) return null
+ while (i < t.length && t[i] == ' ') i++
+ var offsetSec = 0
+ if (i < t.length && (t[i] == '+' || t[i] == '-')) {
+ val sign = if (t[i] == '-') -1 else 1
+ i++
+ val oh = num(2) ?: return null
+ if (i < t.length && t[i] == ':') i++
+ val om = num(2) ?: 0
+ offsetSec = sign * (oh * 3600 + om * 60)
+ }
+ val days = daysFromCivil(year, month, day)
+ return ((days * 86400L) + hour * 3600 + minute * 60 + second - offsetSec) * 1000L
+ }
+
+ /** Days since 1970-01-01 for a proleptic Gregorian date (Howard Hinnant's algorithm). */
+ private fun daysFromCivil(y0: Int, m: Int, d: Int): Long {
+ val y = if (m <= 2) y0 - 1 else y0
+ val era = (if (y >= 0) y else y - 399) / 400
+ val yoe = y - era * 400
+ val mp = (m + 9) % 12
+ val doy = (153 * mp + 2) / 5 + d - 1
+ val doe = yoe * 365 + yoe / 4 - yoe / 100 + doy
+ return era * 146097L + doe - 719468
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/player/PlayerActivity.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/player/PlayerActivity.kt
new file mode 100644
index 000000000..893c390a3
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/player/PlayerActivity.kt
@@ -0,0 +1,383 @@
+package io.github.maxhayim.tvhub.player
+
+import android.app.Activity
+import android.app.AlertDialog
+import android.content.Context
+import android.content.Intent
+import android.os.Bundle
+import android.os.Handler
+import android.os.Looper
+import android.view.Gravity
+import android.view.KeyEvent
+import android.view.View
+import android.view.WindowManager
+import android.widget.FrameLayout
+import android.widget.ProgressBar
+import androidx.annotation.OptIn
+import androidx.media3.common.C
+import androidx.media3.common.MediaItem
+import androidx.media3.common.MimeTypes
+import androidx.media3.common.PlaybackException
+import androidx.media3.common.Player
+import androidx.media3.common.TrackSelectionOverride
+import androidx.media3.common.Tracks
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.datasource.DefaultHttpDataSource
+import androidx.media3.exoplayer.ExoPlayer
+import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
+import androidx.media3.ui.AspectRatioFrameLayout
+import androidx.media3.ui.PlayerView
+import io.github.maxhayim.tvhub.TvHubApp
+import io.github.maxhayim.tvhub.model.Channel
+import io.github.maxhayim.tvhub.model.Programme
+import io.github.maxhayim.tvhub.model.StreamRef
+import io.github.maxhayim.tvhub.ui.Ui
+import io.github.maxhayim.tvhub.ui.Ui.dp
+import io.github.maxhayim.tvhub.util.Log
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.MainScope
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+
+/**
+ * Full-screen live playback with Media3. Keys:
+ * Up/Down and Channel +/- change channel; Left or the Last button goes back to the previous one;
+ * digits tune by number; OK shows what is on; Menu or a long OK opens audio and subtitles;
+ * Back returns to where playback started. The player is released as soon as the screen stops.
+ */
+@OptIn(UnstableApi::class)
+class PlayerActivity : Activity() {
+ private val scope = MainScope()
+ private val repo get() = (application as TvHubApp).repo
+ private val main = Handler(Looper.getMainLooper())
+
+ private var player: ExoPlayer? = null
+ private lateinit var playerView: PlayerView
+ private lateinit var spinner: ProgressBar
+ private lateinit var overlay: InfoOverlay
+ private lateinit var errorBox: android.widget.LinearLayout
+ private lateinit var errorText: android.widget.TextView
+
+ private var list: List<Channel> = emptyList()
+ private var index = 0
+ private var previous = -1
+ private var streamIndex = 0
+ private var retries = 0
+ private var triedHls = false
+ private var digits = ""
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ list = Queue.channels
+ index = Queue.index.coerceIn(0, (list.size - 1).coerceAtLeast(0))
+ if (list.isEmpty()) { finish(); return }
+
+ val root = FrameLayout(this).apply { setBackgroundColor(0xFF000000.toInt()) }
+ playerView = PlayerView(this).apply {
+ useController = false
+ resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT
+ setShutterBackgroundColor(0xFF000000.toInt())
+ isFocusable = false
+ }
+ root.addView(playerView, FrameLayout.LayoutParams(Ui.MATCH, Ui.MATCH))
+ spinner = ProgressBar(this).apply { indeterminateTintList = android.content.res.ColorStateList.valueOf(Ui.TEXT) }
+ root.addView(spinner, FrameLayout.LayoutParams(dp(56), dp(56), Gravity.CENTER))
+ overlay = InfoOverlay(this)
+ root.addView(overlay, FrameLayout.LayoutParams(Ui.MATCH, Ui.WRAP, Gravity.BOTTOM))
+ errorBox = Ui.vertical(this, 10).apply {
+ background = Ui.rounded(this@PlayerActivity, 0xE6161A20.toInt(), 16)
+ setPadding(dp(32), dp(24), dp(32), dp(24)); visibility = View.GONE
+ }
+ errorText = Ui.text(this, "", 18f, lines = 4)
+ errorBox.addView(errorText)
+ errorBox.addView(Ui.text(this, "OK: try again · Up/Down: other channels · Back: guide", 15f, Ui.DIM))
+ root.addView(errorBox, FrameLayout.LayoutParams(dp(640), Ui.WRAP, Gravity.CENTER))
+ setContentView(root)
+ }
+
+ override fun onStart() {
+ super.onStart()
+ if (list.isEmpty()) return
+ createPlayer()
+ tune(index, remember = false)
+ }
+
+ override fun onStop() {
+ releasePlayer()
+ super.onStop()
+ }
+
+ override fun onDestroy() { scope.cancel(); main.removeCallbacksAndMessages(null); super.onDestroy() }
+
+ private fun createPlayer() {
+ if (player != null) return
+ player = ExoPlayer.Builder(this).build().also { p ->
+ playerView.player = p
+ p.playWhenReady = true
+ p.addListener(object : Player.Listener {
+ override fun onPlaybackStateChanged(state: Int) {
+ spinner.visibility = if (state == Player.STATE_BUFFERING || state == Player.STATE_IDLE && errorBox.visibility != View.VISIBLE) View.VISIBLE else View.GONE
+ if (state == Player.STATE_READY) {
+ retries = 0; errorBox.visibility = View.GONE
+ // One line per tune for diagnostics: formats only, never the address.
+ val v = p.videoFormat; val a = p.audioFormat
+ Log.i("Playing: video ${v?.sampleMimeType} ${v?.width}x${v?.height}, audio ${a?.sampleMimeType} ${a?.channelCount}ch")
+ }
+ // A live stream that ends was cut by the server; start it again.
+ if (state == Player.STATE_ENDED) recover("The stream ended")
+ }
+ override fun onPlayerError(error: PlaybackException) { onError(error) }
+ })
+ }
+ }
+
+ private fun releasePlayer() {
+ main.removeCallbacksAndMessages(null)
+ playerView.player = null
+ player?.release()
+ player = null
+ }
+
+ private fun tune(i: Int, remember: Boolean = true) {
+ if (list.isEmpty()) return
+ val target = ((i % list.size) + list.size) % list.size
+ if (remember && target != index) previous = index
+ index = target
+ streamIndex = 0; retries = 0; triedHls = false
+ errorBox.visibility = View.GONE
+ val ch = list[index]
+ repo.addRecent(ch.key)
+ playStream(ch.streams.getOrNull(0))
+ showInfo()
+ }
+
+ private fun playStream(s: StreamRef?, forceHls: Boolean = false) {
+ val p = player ?: return
+ if (s == null) { showError("This channel has no stream address."); return }
+ val headers = HashMap<String, String>()
+ s.referrer?.let { headers["Referer"] = it }
+ val http = DefaultHttpDataSource.Factory()
+ .setUserAgent(s.userAgent ?: "TVHub/1.0 (Android TV; Media3)")
+ .setAllowCrossProtocolRedirects(true)
+ .setConnectTimeoutMs(8_000).setReadTimeoutMs(15_000)
+ .setDefaultRequestProperties(headers)
+ val item = MediaItem.Builder().setUri(s.url).apply {
+ if (forceHls || looksHls(s.url)) setMimeType(MimeTypes.APPLICATION_M3U8)
+ setLiveConfiguration(MediaItem.LiveConfiguration.Builder().setTargetOffsetMs(C.TIME_UNSET).build())
+ }.build()
+ // One retry per load: Media3's default of three, each waiting on a timeout, kept a dead host
+ // on a spinner for over a minute. Recovery below decides what happens next.
+ val factory = DefaultMediaSourceFactory(this).setDataSourceFactory(http)
+ .setLoadErrorHandlingPolicy(androidx.media3.exoplayer.upstream.DefaultLoadErrorHandlingPolicy(1))
+ p.setMediaSource(factory.createMediaSource(item))
+ p.prepare()
+ p.play()
+ }
+
+ private fun looksHls(url: String) = url.substringBefore('?').lowercase().let { it.endsWith(".m3u8") || it.endsWith(".m3u") } || url.contains("m3u8", ignoreCase = true)
+
+ /**
+ * Recovery: fall behind a live window → jump to live; a stream with no extension that is really
+ * HLS → retry as HLS; network trouble → retry twice with a short wait; then the next stream of
+ * a merged channel; then say what went wrong.
+ */
+ private fun onError(e: PlaybackException) {
+ Log.w("Playback error ${e.errorCodeName}")
+ val p = player ?: return
+ val ch = list[index]
+ val s = ch.streams.getOrNull(streamIndex)
+ when {
+ e.errorCode == PlaybackException.ERROR_CODE_BEHIND_LIVE_WINDOW -> { p.seekToDefaultPosition(); p.prepare() }
+ e.errorCode == PlaybackException.ERROR_CODE_PARSING_CONTAINER_UNSUPPORTED && !triedHls && s != null && !looksHls(s.url) -> {
+ triedHls = true; playStream(s, forceHls = true)
+ }
+ isTransient(e) && retries < 2 -> recover(null)
+ streamIndex + 1 < ch.streams.size -> {
+ streamIndex++; retries = 0; triedHls = false
+ playStream(ch.streams[streamIndex])
+ overlay.setSource(ch.streams[streamIndex].sourceName, index, list.size)
+ overlay.flash("Trying ${ch.streams[streamIndex].sourceName}")
+ }
+ else -> showError(message(e))
+ }
+ }
+
+ private fun recover(note: String?) {
+ retries++
+ if (retries > 3) { showError(note ?: "The stream keeps stopping."); return }
+ spinner.visibility = View.VISIBLE
+ main.postDelayed({ player?.let { it.seekToDefaultPosition(); it.prepare(); it.play() } }, 1500L * retries)
+ }
+
+ /** Errors worth starting again from scratch. Connection failures are not: the load already retried. */
+ private fun isTransient(e: PlaybackException) = when (e.errorCode) {
+ PlaybackException.ERROR_CODE_IO_UNSPECIFIED,
+ PlaybackException.ERROR_CODE_TIMEOUT -> true
+ else -> false
+ }
+
+ private fun message(e: PlaybackException): String = when (e.errorCode) {
+ PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS -> when (val code = (e.cause as? androidx.media3.datasource.HttpDataSource.InvalidResponseCodeException)?.responseCode) {
+ 404, 410 -> "The stream is not on its server any more (HTTP $code)."
+ 401, 403 -> "The stream's server refused it (HTTP $code). The link may have expired, or the account may be in use elsewhere."
+ null -> "The stream's server answered with an error."
+ else -> "The stream's server answered HTTP $code."
+ }
+ PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND -> "The stream was not found on its server."
+ PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED, PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_TIMEOUT -> "Can't reach the stream's server."
+ PlaybackException.ERROR_CODE_IO_CLEARTEXT_NOT_PERMITTED -> "This TV blocked an unencrypted (http) stream."
+ PlaybackException.ERROR_CODE_PARSING_CONTAINER_UNSUPPORTED, PlaybackException.ERROR_CODE_PARSING_MANIFEST_MALFORMED -> "This stream's format is not supported."
+ PlaybackException.ERROR_CODE_DECODER_INIT_FAILED, PlaybackException.ERROR_CODE_DECODING_FORMAT_UNSUPPORTED, PlaybackException.ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES ->
+ "This TV can't decode this channel's video or sound (for example MPEG-2 broadcast video or AC-4 audio)."
+ PlaybackException.ERROR_CODE_DRM_UNSPECIFIED, PlaybackException.ERROR_CODE_DRM_SCHEME_UNSUPPORTED -> "This channel is encrypted (DRM) and can't be played here."
+ else -> "Playback failed (${e.errorCodeName})."
+ }
+
+ private fun showError(msg: String) {
+ spinner.visibility = View.GONE
+ errorText.text = "${list[index].name}\n$msg"
+ errorBox.visibility = View.VISIBLE
+ }
+
+ private fun showInfo() {
+ val ch = list[index]
+ overlay.bindChannel(ch, list.size, index)
+ scope.launch {
+ val nn = withContext(Dispatchers.IO) { repo.nowNext(listOf(ch))[ch.key] }
+ if (list.getOrNull(index)?.key == ch.key) overlay.bindProgrammes(nn?.first, nn?.second)
+ }
+ overlay.show()
+ }
+
+ override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
+ when (keyCode) {
+ KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_CHANNEL_UP -> { tune(index + 1); return true }
+ KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_CHANNEL_DOWN -> { tune(index - 1); return true }
+ KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_LAST_CHANNEL -> { if (previous >= 0) tune(previous) else overlay.flash("No previous channel yet"); return true }
+ KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_INFO -> { showInfo(); return true }
+ KeyEvent.KEYCODE_MENU, KeyEvent.KEYCODE_CAPTIONS -> { tracksDialog(); return true }
+ KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER -> { event.startTracking(); return true }
+ }
+ if (keyCode in KeyEvent.KEYCODE_0..KeyEvent.KEYCODE_9) { digit(keyCode - KeyEvent.KEYCODE_0); return true }
+ return super.onKeyDown(keyCode, event)
+ }
+
+ override fun onKeyLongPress(keyCode: Int, event: KeyEvent): Boolean {
+ if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) { tracksDialog(); return true }
+ return super.onKeyLongPress(keyCode, event)
+ }
+
+ override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
+ if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER) {
+ if (event.isTracking && !event.isCanceled) {
+ if (errorBox.visibility == View.VISIBLE) tune(index, remember = false) else showInfo()
+ }
+ return true
+ }
+ return super.onKeyUp(keyCode, event)
+ }
+
+ /** Number entry: digits gather for 1.5 s, then the channel with that number is tuned. */
+ private fun digit(d: Int) {
+ digits = (digits + d).takeLast(5)
+ overlay.flash(digits)
+ main.removeCallbacks(tuneDigits)
+ main.postDelayed(tuneDigits, 1500)
+ }
+
+ private val tuneDigits = Runnable {
+ val i = list.indexOfFirst { it.number == digits }.takeIf { it >= 0 } ?: list.indexOfFirst { it.number?.substringBefore('.') == digits }
+ if (i >= 0) tune(i) else overlay.flash("No channel $digits")
+ digits = ""
+ }
+
+ /** Audio and subtitle tracks the stream offers, as one D-pad list. */
+ private fun tracksDialog() {
+ val p = player ?: return
+ data class Opt(val label: String, val apply: () -> Unit)
+ val opts = ArrayList<Opt>()
+ val groups = p.currentTracks.groups
+ groups.filter { it.type == C.TRACK_TYPE_AUDIO }.forEach { g ->
+ for (t in 0 until g.length) {
+ if (!g.isTrackSupported(t)) continue
+ val f = g.getTrackFormat(t)
+ val mark = if (g.isTrackSelected(t)) "● " else " "
+ opts += Opt(mark + "Audio: " + (f.label ?: f.language ?: "Track ${opts.size + 1}") + (f.channelCount.takeIf { it > 0 }?.let { " · ${it}ch" } ?: "")) {
+ p.trackSelectionParameters = p.trackSelectionParameters.buildUpon().setOverrideForType(TrackSelectionOverride(g.mediaTrackGroup, t)).build()
+ }
+ }
+ }
+ val text = groups.filter { it.type == C.TRACK_TYPE_TEXT }
+ val textOn = text.any { it.isSelected }
+ opts += Opt((if (!textOn) "● " else " ") + "Subtitles: off") {
+ p.trackSelectionParameters = p.trackSelectionParameters.buildUpon().setTrackTypeDisabled(C.TRACK_TYPE_TEXT, true).build()
+ }
+ text.forEach { g: Tracks.Group ->
+ for (t in 0 until g.length) {
+ if (!g.isTrackSupported(t)) continue
+ val f = g.getTrackFormat(t)
+ opts += Opt((if (g.isTrackSelected(t)) "● " else " ") + "Subtitles: " + (f.label ?: f.language ?: "Track ${t + 1}")) {
+ p.trackSelectionParameters = p.trackSelectionParameters.buildUpon()
+ .setTrackTypeDisabled(C.TRACK_TYPE_TEXT, false)
+ .setOverrideForType(TrackSelectionOverride(g.mediaTrackGroup, t)).build()
+ }
+ }
+ }
+ if (text.isEmpty()) opts += Opt(" No subtitles or captions in this stream") {}
+ AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Dialog_Alert)
+ .setTitle("Audio and subtitles")
+ .setItems(opts.map { it.label }.toTypedArray()) { _, i -> opts[i].apply() }
+ .show()
+ }
+
+ /** Hands the channel list to the player without putting thousands of entries through an Intent. */
+ object Queue {
+ var channels: List<Channel> = emptyList()
+ var index = 0
+ }
+
+ companion object {
+ fun start(c: Context, list: List<Channel>, index: Int) {
+ Queue.channels = list
+ Queue.index = index
+ c.startActivity(Intent(c, PlayerActivity::class.java))
+ }
+ }
+
+ /** Channel banner at the bottom: number, name, now and next, hidden after a few seconds. */
+ private inner class InfoOverlay(c: Context) : android.widget.LinearLayout(c) {
+ private val title = Ui.text(c, "", 30f, bold = true)
+ private val position = Ui.text(c, "", 15f, Ui.DIM)
+ private val now = Ui.text(c, "", 19f)
+ private val next = Ui.text(c, "", 16f, Ui.DIM)
+ private val note = Ui.text(c, "", 16f, Ui.ACCENT)
+ private val hide = Runnable { animate().alpha(0f).setDuration(if (Ui.animations(context)) 250 else 0).start() }
+
+ init {
+ orientation = VERTICAL
+ setPadding(dp(64), dp(48), dp(64), dp(40))
+ background = android.graphics.drawable.GradientDrawable(android.graphics.drawable.GradientDrawable.Orientation.BOTTOM_TOP, intArrayOf(0xE6000000.toInt(), 0x00000000))
+ addView(note); addView(title); addView(position); addView(now); addView(next)
+ alpha = 0f
+ }
+
+ fun bindChannel(ch: Channel, total: Int, i: Int) {
+ title.text = listOfNotNull(ch.number, ch.name).joinToString(" ")
+ position.text = "${i + 1} of $total · ${ch.streams.getOrNull(streamIndex)?.sourceName ?: ""}"
+ now.text = if (ch.epgIds.isEmpty()) "No guide information" else ""
+ next.text = ""; note.text = ""
+ }
+
+ fun setSource(name: String, i: Int, total: Int) { position.text = "${i + 1} of $total · $name" }
+
+ fun bindProgrammes(cur: Programme?, nx: Programme?) {
+ if (cur != null) now.text = "Now ${Ui.time(context, cur.start)} – ${Ui.time(context, cur.stop)} ${cur.title}"
+ if (nx != null) next.text = "Next ${Ui.time(context, nx.start)} ${nx.title}"
+ }
+
+ fun show() { alpha = 1f; main.removeCallbacks(hide); main.postDelayed(hide, 5000) }
+ fun flash(msg: String) { note.text = msg; show() }
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/source/Apps.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/source/Apps.kt
new file mode 100644
index 000000000..6090e0dcf
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/source/Apps.kt
@@ -0,0 +1,54 @@
+package io.github.maxhayim.tvhub.source
+
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import io.github.maxhayim.tvhub.model.AppShortcut
+
+/**
+ * Installed live-TV apps, offered as shortcuts that open the app. None of these publishes its
+ * channel list or guide to other apps, so the hub never shows their channels as its own.
+ * Package visibility: the known packages are declared in the manifest's <queries>, and the
+ * "other apps" list uses the LEANBACK_LAUNCHER intent query; no QUERY_ALL_PACKAGES.
+ */
+object Apps {
+ /** Package to display name. Order is the order shown. Keep in sync with <queries> in the manifest. */
+ val KNOWN = linkedMapOf(
+ "tv.pluto.android" to "Pluto TV",
+ "com.tubitv" to "Tubi",
+ "com.plexapp.android" to "Plex",
+ "org.xbmc.kodi" to "Kodi",
+ "com.getchannels.dvr.app" to "Channels",
+ "com.silicondust.view" to "HDHomeRun",
+ "com.google.android.youtube.tvunplugged" to "YouTube TV",
+ "com.sling" to "Sling TV",
+ "com.philo.philo.google" to "Philo",
+ "com.haystack.android" to "Haystack News",
+ "com.google.android.tv" to "Live Channels",
+ "ar.tvplayer.tv" to "TiviMate",
+ )
+
+ fun launchIntent(context: Context, pkg: String): Intent? {
+ val pm = context.packageManager
+ return (pm.getLeanbackLaunchIntentForPackage(pkg) ?: pm.getLaunchIntentForPackage(pkg))?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
+
+ fun isInstalled(context: Context, pkg: String) = launchIntent(context, pkg) != null
+
+ fun label(context: Context, pkg: String): String = KNOWN[pkg] ?: try {
+ val pm = context.packageManager
+ pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString()
+ } catch (_: PackageManager.NameNotFoundException) { pkg }
+
+ /** Known live-TV apps that are installed. */
+ fun detected(context: Context): List<AppShortcut> = KNOWN.keys.filter { isInstalled(context, it) }.map { AppShortcut(it, label(context, it)) }
+
+ /** Every app with a TV launcher entry, for picking an app the known list does not cover. */
+ fun allTvApps(context: Context): List<AppShortcut> {
+ val pm = context.packageManager
+ val i = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LEANBACK_LAUNCHER)
+ return pm.queryIntentActivities(i, 0).map { it.activityInfo.packageName }
+ .filter { it != context.packageName }.distinct()
+ .map { AppShortcut(it, label(context, it)) }.sortedBy { it.label.lowercase() }
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/source/HdHomeRun.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/source/HdHomeRun.kt
new file mode 100644
index 000000000..1434b7a97
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/source/HdHomeRun.kt
@@ -0,0 +1,99 @@
+package io.github.maxhayim.tvhub.source
+
+import io.github.maxhayim.tvhub.data.Http
+import io.github.maxhayim.tvhub.model.RawChannel
+import io.github.maxhayim.tvhub.model.SourceConfig
+import org.json.JSONArray
+import org.json.JSONObject
+import java.io.IOException
+import java.net.DatagramPacket
+import java.net.DatagramSocket
+import java.net.InetAddress
+import java.net.SocketTimeoutException
+import java.util.zip.CRC32
+
+/**
+ * SiliconDust HDHomeRun network tuners, through the device's own local HTTP interface
+ * (discover.json and lineup.json). Nothing goes to SiliconDust's cloud, so the guide is not read
+ * from it: add an XMLTV source for programme data.
+ */
+object HdHomeRun {
+ data class Device(val host: String, val name: String, val model: String, val tuners: Int)
+
+ /** UDP broadcast discovery on port 65001, the tuners' own protocol. Blocking for [timeoutMs]. */
+ fun discover(timeoutMs: Int = 2500): List<Device> {
+ val hosts = LinkedHashSet<String>()
+ DatagramSocket().use { s ->
+ s.broadcast = true
+ s.soTimeout = 300
+ val req = request()
+ val deadline = System.currentTimeMillis() + timeoutMs
+ var nextSend = 0L
+ val buf = ByteArray(2048)
+ while (System.currentTimeMillis() < deadline) {
+ if (System.currentTimeMillis() >= nextSend) {
+ runCatching { s.send(DatagramPacket(req, req.size, InetAddress.getByName("255.255.255.255"), 65001)) }
+ nextSend = System.currentTimeMillis() + 800
+ }
+ val p = DatagramPacket(buf, buf.size)
+ try {
+ s.receive(p)
+ // A discover reply is packet type 0x0003.
+ if (p.length >= 4 && buf[0].toInt() == 0 && buf[1].toInt() == 3) p.address.hostAddress?.let { hosts += it }
+ } catch (_: SocketTimeoutException) {
+ }
+ }
+ }
+ return hosts.mapNotNull { h -> runCatching { info(h) }.getOrNull() }
+ }
+
+ fun info(host: String): Device {
+ val o = JSONObject(Http.text("http://${clean(host)}/discover.json", 64 * 1024))
+ return Device(clean(host), o.optString("FriendlyName", "HDHomeRun"), o.optString("ModelNumber"), o.optInt("TunerCount"))
+ }
+
+ fun load(cfg: SourceConfig): ProviderResult {
+ val host = clean(cfg.url)
+ if (host.isEmpty()) throw IOException("Enter the tuner's address, or scan for it")
+ try {
+ val lineupUrl = runCatching { JSONObject(Http.text("http://$host/discover.json", 64 * 1024)).optString("LineupURL") }
+ .getOrNull()?.takeIf { it.startsWith("http") } ?: "http://$host/lineup.json"
+ val arr = JSONArray(Http.text(lineupUrl, 8L * 1024 * 1024))
+ return parseLineup(arr, cfg)
+ } catch (e: org.json.JSONException) {
+ throw IOException("The tuner's channel list could not be read")
+ } catch (e: Exception) {
+ throw Http.friendly(e)
+ }
+ }
+
+ /** Encrypted cable channels (DRM 1) cannot be played by any app but the tuner maker's, so they are skipped. */
+ internal fun parseLineup(arr: JSONArray, cfg: SourceConfig): ProviderResult {
+ val out = ArrayList<RawChannel>()
+ var skipped = 0
+ for (i in 0 until arr.length()) {
+ val o = arr.optJSONObject(i) ?: continue
+ var url = o.optString("URL")
+ if (!url.startsWith("http") || o.optInt("DRM") == 1) { skipped++; continue }
+ if (cfg.transcode) url += (if ('?' in url) "&" else "?") + "transcode=heavy"
+ out += RawChannel(
+ sourceId = cfg.id, sourceName = cfg.name,
+ name = o.optString("GuideName").ifBlank { o.optString("GuideNumber") },
+ number = o.optString("GuideNumber").takeIf { it.isNotBlank() },
+ url = url,
+ )
+ }
+ return ProviderResult(out, emptyList(), skipped)
+ }
+
+ private fun clean(h: String) = h.trim().removePrefix("http://").removePrefix("https://").substringBefore('/')
+
+ internal fun request(): ByteArray {
+ // Payload: device type = any (tag 1), device id = any (tag 2), each 4 bytes.
+ val payload = byteArrayOf(1, 4, -1, -1, -1, -1, 2, 4, -1, -1, -1, -1)
+ val head = byteArrayOf(0, 2, 0, payload.size.toByte())
+ val body = head + payload
+ val crc = CRC32().apply { update(body) }.value
+ return body + byteArrayOf(crc.toByte(), (crc shr 8).toByte(), (crc shr 16).toByte(), (crc shr 24).toByte())
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/source/Providers.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/source/Providers.kt
new file mode 100644
index 000000000..6e810b312
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/source/Providers.kt
@@ -0,0 +1,64 @@
+package io.github.maxhayim.tvhub.source
+
+import io.github.maxhayim.tvhub.data.Http
+import io.github.maxhayim.tvhub.model.RawChannel
+import io.github.maxhayim.tvhub.model.SourceConfig
+import io.github.maxhayim.tvhub.model.SourceType
+import io.github.maxhayim.tvhub.parse.M3uParser
+import java.io.IOException
+import java.net.URLEncoder
+
+/** What one source gives a refresh: its streams and the guides it names. */
+data class ProviderResult(val channels: List<RawChannel>, val epgUrls: List<String>, val skipped: Int = 0)
+
+/** Blocking; the refresh calls it off the main thread. Throws an IOException with a message for the owner. */
+fun interface Provider {
+ fun load(cfg: SourceConfig): ProviderResult
+}
+
+object Providers {
+ private const val PLAYLIST_MAX = 64L * 1024 * 1024
+
+ fun forType(t: SourceType): Provider = when (t) {
+ SourceType.M3U -> Provider(::m3u)
+ SourceType.XMLTV -> Provider { ProviderResult(emptyList(), listOf(it.url)) }
+ SourceType.DISPATCHARR -> Provider(::dispatcharr)
+ SourceType.HDHOMERUN -> Provider { HdHomeRun.load(it) }
+ SourceType.APPS -> Provider { ProviderResult(emptyList(), emptyList()) }
+ }
+
+ private fun m3u(cfg: SourceConfig): ProviderResult {
+ val r = readPlaylist(cfg.url, cfg)
+ val epg = buildList {
+ if (cfg.epgUrl.isNotBlank()) add(cfg.epgUrl.trim())
+ if (cfg.useHeaderEpg) addAll(r.epgUrls)
+ }.distinct()
+ return ProviderResult(r.channels, epg, r.skipped)
+ }
+
+ /**
+ * Dispatcharr's documented outputs: /output/m3u and /output/epg, optionally followed by an
+ * output profile name. Its "M3U/EPG" network setting decides which addresses may read them,
+ * so a 403 here usually means the TV's network is not allowed yet.
+ */
+ private fun dispatcharr(cfg: SourceConfig): ProviderResult {
+ val (m3u, epg) = dispatcharrUrls(cfg.url, cfg.profile)
+ val r = readPlaylist(m3u, cfg)
+ return ProviderResult(r.channels, listOf(epg), r.skipped)
+ }
+
+ fun dispatcharrUrls(base: String, profile: String): Pair<String, String> {
+ val b = base.trim().trimEnd('/')
+ val p = profile.trim().let { if (it.isEmpty()) "" else "/" + URLEncoder.encode(it, "UTF-8").replace("+", "%20") }
+ return "$b/output/m3u$p" to "$b/output/epg$p"
+ }
+
+ private fun readPlaylist(url: String, cfg: SourceConfig): M3uParser.Result {
+ if (!M3uParser.isHttp(url.trim())) throw IOException("The address must start with http:// or https://")
+ val r = try {
+ Http.open(url.trim(), PLAYLIST_MAX).bufferedReader(Charsets.UTF_8).use { M3uParser.parse(it, cfg.id, cfg.name) }
+ } catch (e: Exception) { throw Http.friendly(e) }
+ if (!r.isPlaylist) throw IOException("That address did not return an M3U playlist")
+ return r
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/ChannelViews.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/ChannelViews.kt
new file mode 100644
index 000000000..cc105cb43
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/ChannelViews.kt
@@ -0,0 +1,128 @@
+package io.github.maxhayim.tvhub.ui
+
+import android.content.Context
+import android.view.Gravity
+import android.view.View
+import android.view.ViewGroup
+import android.widget.FrameLayout
+import android.widget.ImageView
+import android.widget.LinearLayout
+import android.widget.ProgressBar
+import android.widget.TextView
+import androidx.recyclerview.widget.RecyclerView
+import io.github.maxhayim.tvhub.TvHubApp
+import io.github.maxhayim.tvhub.model.Channel
+import io.github.maxhayim.tvhub.model.Programme
+import io.github.maxhayim.tvhub.ui.Ui.dp
+
+typealias NowNext = Map<String, Pair<Programme?, Programme?>>
+
+/** A row of the channel list: number, logo, name, now and next. */
+class ChannelRow(c: Context) : LinearLayout(c) {
+ val number = Ui.text(c, "", 18f, Ui.DIM).apply { gravity = Gravity.END or Gravity.CENTER_VERTICAL }
+ val logo = ImageView(c).apply { scaleType = ImageView.ScaleType.FIT_CENTER }
+ val name = Ui.text(c, "", 20f, bold = true)
+ val now = Ui.text(c, "", 16f, Ui.DIM)
+ val next = Ui.text(c, "", 14f, Ui.DIM)
+ val fav = Ui.text(c, "★", 18f, Ui.ACCENT)
+ val progress = ProgressBar(c, null, android.R.attr.progressBarStyleHorizontal).apply {
+ max = 1000; progressTintList = android.content.res.ColorStateList.valueOf(Ui.ACCENT)
+ }
+
+ init {
+ orientation = HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ isFocusable = true; isClickable = true; isLongClickable = true
+ background = Ui.focusable(c, 0x00000000)
+ setPadding(dp(12), dp(10), dp(16), dp(10))
+ addView(number, Ui.lp(dp(56), Ui.WRAP))
+ addView(logo, Ui.lp(dp(72), dp(44)).apply { marginStart = dp(16); marginEnd = dp(16) })
+ val col = Ui.vertical(c, 4)
+ col.addView(name); col.addView(now); col.addView(progress, Ui.lp(Ui.MATCH, dp(4))); col.addView(next)
+ addView(col, Ui.lp(0, Ui.WRAP, 1f))
+ addView(fav, Ui.lp(Ui.WRAP, Ui.WRAP).apply { marginStart = dp(12) })
+ }
+
+ fun bind(ch: Channel, nn: Pair<Programme?, Programme?>?, isFav: Boolean, nowMs: Long) {
+ number.text = ch.number ?: ""
+ name.text = ch.name
+ fav.visibility = if (isFav) View.VISIBLE else View.INVISIBLE
+ (context.applicationContext as TvHubApp).logos.load(ch.logo, logo, dp(44))
+ val cur = nn?.first
+ val nx = nn?.second
+ if (cur != null) {
+ now.text = "${Ui.time(context, cur.start)} – ${Ui.time(context, cur.stop)} ${cur.title}"
+ progress.visibility = View.VISIBLE
+ progress.progress = (((nowMs - cur.start) * 1000) / (cur.stop - cur.start).coerceAtLeast(1)).toInt()
+ } else {
+ now.text = if (ch.epgIds.isEmpty()) "No guide information" else "No programme listed now"
+ progress.visibility = View.GONE
+ }
+ next.text = nx?.let { "Next ${Ui.time(context, it.start)} ${it.title}" } ?: ""
+ next.visibility = if (nx == null) View.GONE else View.VISIBLE
+ contentDescription = listOfNotNull(ch.number, ch.name, cur?.title?.let { "now $it" }).joinToString(", ")
+ }
+}
+
+class ChannelAdapter(
+ private val onPlay: (List<Channel>, Int) -> Unit,
+ private val onLong: (Channel) -> Unit,
+) : RecyclerView.Adapter<ChannelAdapter.H>() {
+ var items: List<Channel> = emptyList(); private set
+ var nowNext: NowNext = emptyMap()
+ var favorites: Set<String> = emptySet()
+
+ class H(val row: ChannelRow) : RecyclerView.ViewHolder(row)
+
+ fun submit(list: List<Channel>) { items = list; notifyDataSetChanged() }
+
+ override fun getItemCount() = items.size
+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = H(ChannelRow(parent.context).apply {
+ layoutParams = RecyclerView.LayoutParams(Ui.MATCH, Ui.WRAP)
+ })
+ override fun onBindViewHolder(h: H, position: Int) {
+ val ch = items[position]
+ h.row.bind(ch, nowNext[ch.key], ch.key in favorites, System.currentTimeMillis())
+ h.row.setOnClickListener { onPlay(items, h.bindingAdapterPosition.coerceAtLeast(0)) }
+ h.row.setOnLongClickListener { onLong(ch); true }
+ }
+}
+
+/** A tile for the Home rows: logo or name on a card, the programme on air under it. */
+class ChannelCard(c: Context) : LinearLayout(c) {
+ val logo = ImageView(c).apply { scaleType = ImageView.ScaleType.FIT_CENTER }
+ val initial = Ui.text(c, "", 22f, bold = true).apply { gravity = Gravity.CENTER }
+ val name = Ui.text(c, "", 16f, bold = true)
+ val sub = Ui.text(c, "", 14f, Ui.DIM)
+ val tile = FrameLayout(c).apply { background = Ui.focusable(c, Ui.SURFACE); setPadding(dp(16), dp(16), dp(16), dp(16)) }
+
+ init {
+ orientation = VERTICAL
+ tile.addView(initial, FrameLayout.LayoutParams(Ui.MATCH, Ui.MATCH))
+ tile.addView(logo, FrameLayout.LayoutParams(Ui.MATCH, Ui.MATCH))
+ tile.isDuplicateParentStateEnabled = true
+ addView(tile, Ui.lp(dp(208), dp(117)))
+ addView(name, Ui.lp(dp(208), Ui.WRAP).apply { topMargin = dp(8) })
+ addView(sub, Ui.lp(dp(208), Ui.WRAP).apply { topMargin = dp(2) })
+ isFocusable = true; isClickable = true; isLongClickable = true
+ Ui.scaleOnFocus(this, 1.06f)
+ }
+
+ fun bindChannel(ch: Channel, now: Programme?) {
+ name.text = listOfNotNull(ch.number, ch.name).joinToString(" ")
+ sub.text = now?.title ?: if (ch.epgIds.isEmpty()) "Live" else ""
+ initial.text = ch.name
+ // The name stands in for the logo until one arrives, never behind it.
+ (context.applicationContext as TvHubApp).logos.load(ch.logo, logo, dp(85)) { has -> initial.visibility = if (has) View.INVISIBLE else View.VISIBLE }
+ contentDescription = ch.name
+ }
+
+ fun bindApp(label: String, icon: android.graphics.drawable.Drawable?) {
+ name.text = label
+ sub.text = "Opens the app"
+ initial.text = if (icon == null) label else ""
+ initial.visibility = View.VISIBLE
+ logo.setImageDrawable(icon)
+ contentDescription = "$label, opens the app"
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/ChannelsScreen.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/ChannelsScreen.kt
new file mode 100644
index 000000000..00e15f830
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/ChannelsScreen.kt
@@ -0,0 +1,182 @@
+package io.github.maxhayim.tvhub.ui
+
+import android.text.Editable
+import android.text.TextWatcher
+import android.view.KeyEvent
+import android.view.View
+import android.view.ViewGroup
+import android.view.inputmethod.EditorInfo
+import android.widget.EditText
+import android.widget.TextView
+import android.widget.Toast
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import io.github.maxhayim.tvhub.model.Channel
+import io.github.maxhayim.tvhub.parse.XmltvParser
+import io.github.maxhayim.tvhub.ui.Ui.dp
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+
+/**
+ * Live TV: categories on the left, the channels of the chosen one on the right with what is on
+ * now and next, and a search box. Favorites is the same page limited to favourite channels.
+ */
+class ChannelsScreen(host: MainActivity, private val favoritesOnly: Boolean) : Screen(host) {
+
+ /** A category: a label and the channels in it. */
+ private data class Cat(val label: String, val filter: (Channel) -> Boolean)
+
+ private var channels: List<Channel> = emptyList()
+ private var favs: Set<String> = emptySet()
+ private var cats: List<Cat> = emptyList()
+ private var catIndex = 0
+ private var query = ""
+ private var nnJob: Job? = null
+
+ private val title = Ui.text(ctx, if (favoritesOnly) "Favorites" else "Live TV", 30f, bold = true)
+ private val empty = Ui.text(ctx, "", 18f, Ui.DIM, lines = 4)
+ private val adapter = ChannelAdapter({ list, i -> host.play(list, i) }, ::toggleFav)
+ private val list = RecyclerView(ctx).apply {
+ layoutManager = LinearLayoutManager(ctx)
+ this.adapter = [email protected]
+ itemAnimator = null
+ clipToPadding = false
+ setPadding(dp(4), dp(4), dp(4), dp(24))
+ descendantFocusability = ViewGroup.FOCUS_AFTER_DESCENDANTS
+ }
+ private val catAdapter = CatAdapter()
+ private val catList = RecyclerView(ctx).apply {
+ layoutManager = LinearLayoutManager(ctx)
+ adapter = catAdapter
+ itemAnimator = null
+ setPadding(0, dp(4), 0, dp(24)); clipToPadding = false
+ }
+ private val search = EditText(ctx).apply {
+ hint = "Search channels"
+ setHintTextColor(Ui.DIM); setTextColor(Ui.TEXT); textSize = 18f
+ isSingleLine = true
+ imeOptions = EditorInfo.IME_ACTION_SEARCH
+ background = Ui.focusable(ctx, Ui.SURFACE, 24)
+ setPadding(dp(20), dp(10), dp(20), dp(10))
+ addTextChangedListener(object : TextWatcher {
+ override fun beforeTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
+ override fun onTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
+ override fun afterTextChanged(s: Editable?) { query = s?.toString().orEmpty(); apply() }
+ })
+ setOnEditorActionListener { _, _, _ -> list.post { list.getChildAt(0)?.requestFocus() }; true }
+ }
+
+ override val view: View = Ui.vertical(ctx, 16).apply {
+ val head = Ui.horizontal(ctx, 24)
+ head.addView(title, Ui.lp(0, Ui.WRAP, 1f))
+ head.addView(search, Ui.lp(dp(360), Ui.WRAP))
+ addView(head)
+ val bodyRow = Ui.horizontal(ctx, 20)
+ if (!favoritesOnly) bodyRow.addView(catList, Ui.lp(dp(230), Ui.MATCH))
+ val right = android.widget.FrameLayout(ctx)
+ right.addView(list, android.widget.FrameLayout.LayoutParams(Ui.MATCH, Ui.MATCH))
+ right.addView(empty, android.widget.FrameLayout.LayoutParams(Ui.MATCH, Ui.WRAP))
+ bodyRow.addView(right, Ui.lp(0, Ui.MATCH, 1f))
+ addView(bodyRow, Ui.lp(Ui.MATCH, 0, 1f))
+ }
+
+ override fun onShow() {
+ watch(combine(repo.channels, repo.favorites) { c, f -> c to f }) { (c, f) ->
+ channels = c; favs = f; adapter.favorites = f
+ rebuildCats(); apply()
+ }
+ watch(repo.guideVersion) { loadNowNext() }
+ launch { while (true) { delay(60_000); loadNowNext() } }
+ }
+
+ private fun rebuildCats() {
+ val out = ArrayList<Cat>()
+ out += Cat("All channels") { true }
+ if (!favoritesOnly) {
+ out += Cat("Favorites") { it.key in favs }
+ channels.mapNotNull { it.group }.distinct().forEach { g -> out += Cat(g) { it.group == g } }
+ val sources = channels.flatMap { it.sourceNames }.distinct()
+ if (sources.size > 1) sources.forEach { s -> out += Cat("From $s") { s in it.sourceNames } }
+ }
+ cats = out
+ if (catIndex >= cats.size) catIndex = 0
+ catAdapter.notifyDataSetChanged()
+ }
+
+ private fun apply() {
+ val cat = cats.getOrNull(catIndex)
+ val q = XmltvParser.normalise(query)
+ val shown = channels.filter { ch ->
+ (!favoritesOnly || ch.key in favs) && (cat?.filter?.invoke(ch) ?: true) &&
+ (q.isEmpty() || XmltvParser.normalise(ch.name).contains(q) || ch.number?.startsWith(query.trim()) == true)
+ }
+ adapter.submit(shown)
+ empty.text = when {
+ shown.isNotEmpty() -> ""
+ channels.isEmpty() -> "No channels yet. Add a source in Sources."
+ favoritesOnly && favs.isEmpty() -> "No favourites yet. Hold OK on a channel in Live TV or the Guide to add it."
+ query.isNotEmpty() -> "No channel matches \"$query\"."
+ else -> "No channels here."
+ }
+ empty.visibility = if (shown.isEmpty()) View.VISIBLE else View.GONE
+ loadNowNext()
+ }
+
+ private fun loadNowNext() {
+ nnJob?.cancel()
+ val items = adapter.items
+ nnJob = host.scope.launch {
+ val nn = withContext(Dispatchers.IO) { repo.nowNext(items.take(3000)) }
+ adapter.nowNext = nn
+ adapter.notifyItemRangeChanged(0, adapter.itemCount)
+ }
+ }
+
+ private fun toggleFav(ch: Channel) {
+ val on = repo.toggleFavorite(ch.key)
+ Toast.makeText(ctx, if (on) "Added ${ch.name} to Favorites" else "Removed ${ch.name} from Favorites", Toast.LENGTH_SHORT).show()
+ }
+
+ override fun focusFirst(): Boolean {
+ if (adapter.itemCount > 0) {
+ val v = list.layoutManager?.findViewByPosition(0) ?: list.getChildAt(0)
+ if (v != null) return v.requestFocus()
+ }
+ return if (!favoritesOnly && catList.childCount > 0) catList.getChildAt(0).requestFocus() else search.requestFocus()
+ }
+
+ private inner class CatAdapter : RecyclerView.Adapter<CatAdapter.H>() {
+ inner class H(val v: TextView) : RecyclerView.ViewHolder(v)
+ override fun getItemCount() = cats.size
+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = H(Ui.text(ctx, "", 17f, Ui.DIM, bold = true).apply {
+ isFocusable = true; isClickable = true
+ background = Ui.focusable(ctx, 0x00000000, 20, Ui.SURFACE)
+ setPadding(dp(16), dp(10), dp(16), dp(10))
+ layoutParams = RecyclerView.LayoutParams(Ui.MATCH, Ui.WRAP).apply { bottomMargin = dp(4) }
+ })
+ override fun onBindViewHolder(h: H, position: Int) {
+ val c = cats[position]
+ val count = channels.count(c.filter)
+ h.v.text = "${c.label} ${if (count > 0) count else ""}".trim()
+ h.v.isSelected = position == catIndex
+ h.v.setTextColor(if (position == catIndex) Ui.TEXT else Ui.DIM)
+ h.v.setOnFocusChangeListener { _, has ->
+ val pos = h.bindingAdapterPosition
+ if (has && catIndex != pos && pos >= 0) {
+ val old = catIndex
+ catIndex = pos
+ apply()
+ list.post { catAdapter.notifyItemChanged(old); catAdapter.notifyItemChanged(pos) }
+ }
+ }
+ h.v.setOnClickListener { list.getChildAt(0)?.requestFocus() }
+ h.v.setOnKeyListener { _, code, e ->
+ if (code == KeyEvent.KEYCODE_DPAD_RIGHT && e.action == KeyEvent.ACTION_DOWN && adapter.itemCount > 0) { list.getChildAt(0)?.requestFocus(); true } else false
+ }
+ }
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/GuideScreen.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/GuideScreen.kt
new file mode 100644
index 000000000..87cdce491
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/GuideScreen.kt
@@ -0,0 +1,140 @@
+package io.github.maxhayim.tvhub.ui
+
+import android.app.AlertDialog
+import android.view.View
+import android.widget.FrameLayout
+import android.widget.HorizontalScrollView
+import android.widget.ScrollView
+import android.widget.TextView
+import android.widget.Toast
+import io.github.maxhayim.tvhub.model.Channel
+import io.github.maxhayim.tvhub.model.Programme
+import io.github.maxhayim.tvhub.ui.Ui.dp
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+
+/** The programme grid with a row of categories above it. */
+class GuideScreen(host: MainActivity) : Screen(host) {
+ private val grid = GuideView(ctx)
+ private val chips = Ui.horizontal(ctx, 10)
+ private val empty = Ui.text(ctx, "", 18f, Ui.DIM, lines = 4)
+ private var channels: List<Channel> = emptyList()
+ private var favs: Set<String> = emptySet()
+ private var category = "All"
+ private var shown: List<Channel> = emptyList()
+
+ override val view: View = Ui.vertical(ctx, 14).apply {
+ addView(Ui.text(ctx, "Guide", 30f, bold = true))
+ addView(HorizontalScrollView(ctx).apply { isHorizontalScrollBarEnabled = false; clipToPadding = false; setPadding(dp(4), dp(4), dp(4), dp(4)); addView(chips) })
+ val frame = FrameLayout(ctx)
+ frame.addView(grid, FrameLayout.LayoutParams(Ui.MATCH, Ui.MATCH))
+ frame.addView(empty, FrameLayout.LayoutParams(Ui.MATCH, Ui.WRAP))
+ addView(frame, Ui.lp(Ui.MATCH, 0, 1f))
+ }
+
+ init {
+ grid.onNeed = { first, last ->
+ val slice = shown.subList(first, last + 1).toList()
+ val (from, to) = grid.timeRange
+ host.scope.launch {
+ val data = withContext(Dispatchers.IO) { repo.programmes(slice, from, to) }
+ if (slice.firstOrNull()?.key == shown.getOrNull(first)?.key) grid.putProgrammes(first, last, data)
+ }
+ }
+ grid.onSelect = { ch, p ->
+ if (p == null || p.isOn(System.currentTimeMillis())) play(ch) else details(ch, p)
+ }
+ grid.onInfo = { ch, p -> details(ch, p) }
+ grid.onLong = { ch ->
+ val on = repo.toggleFavorite(ch.key)
+ Toast.makeText(ctx, if (on) "Added ${ch.name} to Favorites" else "Removed ${ch.name} from Favorites", Toast.LENGTH_SHORT).show()
+ }
+ }
+
+ override fun onShow() {
+ watch(combine(repo.channels, repo.favorites) { c, f -> c to f }) { (c, f) ->
+ val changed = c !== channels || (category == "Favorites" && f != favs)
+ channels = c; favs = f; grid.favorites = f
+ if (changed) { buildChips(); applyCategory() }
+ }
+ watch(repo.guideVersion) { applyCategory() }
+ // Keeps the now line moving and the grid starting at the current half hour.
+ launch { while (true) { delay(60_000); grid.invalidate() } }
+ }
+
+ private fun buildChips() {
+ chips.removeAllViews()
+ val names = listOf("All", "Favorites") + channels.mapNotNull { it.group }.distinct()
+ if (category !in names) category = "All"
+ names.forEach { n ->
+ chips.addView(Ui.text(ctx, n, 16f, if (n == category) Ui.TEXT else Ui.DIM, bold = true).apply {
+ isFocusable = true; isClickable = true; isSelected = n == category
+ background = Ui.focusable(ctx, Ui.SURFACE, 20, Ui.SURFACE_2)
+ setPadding(dp(18), dp(8), dp(18), dp(8))
+ setOnClickListener { select(n); grid.requestFocus() }
+ setOnFocusChangeListener { _, has -> if (has) select(n) }
+ nextFocusDownId = View.NO_ID
+ })
+ }
+ }
+
+ private fun select(n: String) {
+ if (n == category) return
+ category = n
+ for (i in 0 until chips.childCount) (chips.getChildAt(i) as TextView).let {
+ val on = it.text == n
+ it.isSelected = on; it.setTextColor(if (on) Ui.TEXT else Ui.DIM)
+ }
+ applyCategory()
+ }
+
+ private fun applyCategory() {
+ shown = when (category) {
+ "All" -> channels
+ "Favorites" -> channels.filter { it.key in favs }
+ else -> channels.filter { it.group == category }
+ }
+ grid.setData(shown, repo.prefs.guideDays)
+ empty.text = when {
+ shown.isNotEmpty() -> ""
+ channels.isEmpty() -> "No channels yet. Add a playlist, Dispatcharr or a tuner in Sources, and an XMLTV guide for programme listings."
+ category == "Favorites" -> "No favourites yet. Hold OK on a channel to add it."
+ else -> "No channels in $category."
+ }
+ empty.visibility = if (shown.isEmpty()) View.VISIBLE else View.GONE
+ grid.visibility = if (shown.isEmpty()) View.INVISIBLE else View.VISIBLE
+ }
+
+ private fun play(ch: Channel) {
+ host.play(shown, shown.indexOfFirst { it.key == ch.key }.coerceAtLeast(0))
+ }
+
+ private fun details(ch: Channel, p: Programme?) {
+ host.scope.launch {
+ val desc = p?.let { withContext(Dispatchers.IO) { repo.description(it) } }
+ val body = Ui.vertical(ctx, 10).apply { setPadding(dp(28), dp(12), dp(28), dp(8)) }
+ body.addView(Ui.text(ctx, listOfNotNull(ch.number, ch.name).joinToString(" "), 16f, Ui.DIM))
+ if (p != null) {
+ body.addView(Ui.text(ctx, "${Ui.dayTime(ctx, p.start)} – ${Ui.time(ctx, p.stop)}", 16f, Ui.DIM))
+ p.subtitle?.let { body.addView(Ui.text(ctx, it, 18f, bold = true, lines = 2)) }
+ p.category?.let { body.addView(Ui.text(ctx, it, 14f, Ui.ACCENT)) }
+ body.addView(Ui.text(ctx, desc ?: "No description in the guide.", 17f, lines = 0))
+ } else {
+ body.addView(Ui.text(ctx, if (ch.epgIds.isEmpty()) "This channel has no guide information." else "Nothing is listed for this time.", 17f, lines = 0))
+ }
+ body.addView(Ui.text(ctx, "From " + ch.sourceNames.joinToString(", "), 14f, Ui.DIM))
+ AlertDialog.Builder(ctx, android.R.style.Theme_DeviceDefault_Dialog_Alert)
+ .setTitle(p?.title?.ifEmpty { null } ?: ch.name)
+ .setView(ScrollView(ctx).apply { addView(body) })
+ .setPositiveButton("Watch now") { _, _ -> play(ch) }
+ .setNeutralButton(if (ch.key in favs) "Remove from Favorites" else "Add to Favorites") { _, _ -> repo.toggleFavorite(ch.key) }
+ .setNegativeButton("Close", null)
+ .show()
+ }
+ }
+
+ override fun focusFirst(): Boolean = if (shown.isNotEmpty()) grid.requestFocus() else chips.getChildAt(0)?.requestFocus() ?: false
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/GuideView.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/GuideView.kt
new file mode 100644
index 000000000..93a2aab9b
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/GuideView.kt
@@ -0,0 +1,312 @@
+package io.github.maxhayim.tvhub.ui
+
+import android.animation.ValueAnimator
+import android.content.Context
+import android.graphics.Canvas
+import android.graphics.Paint
+import android.graphics.RectF
+import android.graphics.Typeface
+import android.text.TextPaint
+import android.text.TextUtils
+import android.view.KeyEvent
+import android.view.View
+import android.view.accessibility.AccessibilityManager
+import io.github.maxhayim.tvhub.TvHubApp
+import io.github.maxhayim.tvhub.model.Channel
+import io.github.maxhayim.tvhub.model.Programme
+import io.github.maxhayim.tvhub.ui.Ui.dp
+import kotlin.math.max
+import kotlin.math.min
+
+/**
+ * The programme grid, drawn on one canvas: a few thousand channels cost no more than the rows on
+ * screen. Up and Down move between channels, Left and Right between programmes; Left from the
+ * first programme leaves the grid. The cursor keeps a time, so moving up and down stays at
+ * roughly the same hour, as on a TV's own guide.
+ */
+class GuideView(c: Context) : View(c) {
+ var onNeed: (first: Int, last: Int) -> Unit = { _, _ -> }
+ var onSelect: (Channel, Programme?) -> Unit = { _, _ -> }
+ var onLong: (Channel) -> Unit = {}
+ var onInfo: (Channel, Programme?) -> Unit = { _, _ -> }
+
+ private var channels: List<Channel> = emptyList()
+ private val programmes = HashMap<String, List<Programme>>()
+ private val loaded = HashSet<Int>()
+ var favorites: Set<String> = emptySet()
+ set(v) { field = v; invalidate() }
+
+ private val headerH = dp(40).toFloat()
+ private val rowH = dp(64).toFloat()
+ private val chanW = dp(270).toFloat()
+ private val slotW = dp(240).toFloat()
+ private val slotMs = 30 * 60_000L
+ private val pxPerMs get() = slotW / slotMs
+ private val gap = dp(3).toFloat()
+
+ private var timeMin = floorSlot(System.currentTimeMillis())
+ private var timeMax = timeMin + 2 * 86_400_000L
+ private var viewStart = timeMin
+ private var focusRow = 0
+ private var focusTime = System.currentTimeMillis()
+ private var topRow = 0
+ private var drawTop = 0f
+ private var anim: ValueAnimator? = null
+
+ private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
+ private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = dp(3).toFloat(); color = 0xFFFFFFFF.toInt() }
+ private val titleP = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { textSize = sp(17f); color = Ui.TEXT; typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) }
+ private val smallP = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { textSize = sp(13f); color = Ui.DIM }
+ private val numP = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { textSize = sp(15f); color = Ui.DIM }
+ private val rect = RectF()
+ private val radius = dp(8).toFloat()
+
+ init {
+ isFocusable = true
+ isFocusableInTouchMode = true
+ importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_YES
+ }
+
+ private fun sp(v: Float) = android.util.TypedValue.applyDimension(android.util.TypedValue.COMPLEX_UNIT_SP, v, resources.displayMetrics)
+
+ fun setData(list: List<Channel>, days: Int) {
+ val keepKey = channels.getOrNull(focusRow)?.key
+ channels = list
+ programmes.clear(); loaded.clear()
+ timeMin = floorSlot(System.currentTimeMillis())
+ timeMax = System.currentTimeMillis() + days * 86_400_000L
+ viewStart = max(viewStart, timeMin)
+ focusTime = max(focusTime, System.currentTimeMillis())
+ focusRow = list.indexOfFirst { it.key == keepKey }.takeIf { it >= 0 } ?: 0
+ topRow = min(topRow, max(0, list.size - visibleRows()))
+ if (focusRow !in topRow until topRow + visibleRows()) topRow = max(0, focusRow - 1)
+ drawTop = topRow.toFloat()
+ requestRows(); invalidate()
+ }
+
+ fun channelCount() = channels.size
+ val timeRange get() = timeMin to timeMax
+
+ /** Programmes for rows [first, last], by channel key, as asked for through [onNeed]. */
+ fun putProgrammes(first: Int, last: Int, data: Map<String, List<Programme>>) {
+ for (r in first..min(last, channels.size - 1)) {
+ loaded += r
+ val ch = channels[r]
+ programmes[ch.key] = data[ch.key].orEmpty()
+ }
+ invalidate()
+ }
+
+ private fun visibleRows() = max(1, ((height - headerH) / rowH).toInt())
+
+ private fun requestRows() {
+ if (channels.isEmpty() || height == 0) return
+ val first = max(0, topRow - 10)
+ val last = min(channels.size - 1, topRow + visibleRows() + 20)
+ if ((first..last).any { it !in loaded }) {
+ // Mark now, so a burst of key presses asks once.
+ (first..last).forEach { loaded += it }
+ onNeed(first, last)
+ }
+ }
+
+ override fun onSizeChanged(w: Int, h: Int, ow: Int, oh: Int) { super.onSizeChanged(w, h, ow, oh); requestRows() }
+
+ private fun rowProgrammes(r: Int): List<Programme>? = channels.getOrNull(r)?.let { programmes[it.key] }
+
+ /** The programme under the cursor, or null in a gap or on a row without guide data. */
+ private fun focused(): Programme? = rowProgrammes(focusRow)?.firstOrNull { focusTime >= it.start && focusTime < it.stop }
+
+ private fun hasGuide(r: Int) = channels.getOrNull(r)?.epgIds?.isNotEmpty() == true && rowProgrammes(r)?.isNotEmpty() == true
+
+ override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
+ if (channels.isEmpty()) return super.onKeyDown(keyCode, event)
+ when (keyCode) {
+ KeyEvent.KEYCODE_DPAD_UP -> { if (focusRow == 0) return false; moveRow(focusRow - 1); return true }
+ KeyEvent.KEYCODE_DPAD_DOWN -> { if (focusRow < channels.size - 1) moveRow(focusRow + 1); return true }
+ KeyEvent.KEYCODE_CHANNEL_UP, KeyEvent.KEYCODE_PAGE_UP -> { moveRow(max(0, focusRow - visibleRows())); return true }
+ KeyEvent.KEYCODE_CHANNEL_DOWN, KeyEvent.KEYCODE_PAGE_DOWN -> { moveRow(min(channels.size - 1, focusRow + visibleRows())); return true }
+ KeyEvent.KEYCODE_DPAD_LEFT -> {
+ if (!hasGuide(focusRow)) return false
+ val p = focused()
+ val target = (p?.start ?: floorSlot(focusTime)) - 1
+ if (target < timeMin) return false
+ focusTime = rowProgrammes(focusRow)?.firstOrNull { target >= it.start && target < it.stop }?.let { max(it.start, timeMin) } ?: floorSlot(target)
+ afterMove(); return true
+ }
+ KeyEvent.KEYCODE_DPAD_RIGHT -> {
+ if (!hasGuide(focusRow)) return true
+ val target = focused()?.stop ?: (floorSlot(focusTime) + slotMs)
+ if (target >= timeMax) return true
+ focusTime = target
+ afterMove(); return true
+ }
+ KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER -> { event.startTracking(); return true }
+ KeyEvent.KEYCODE_INFO, KeyEvent.KEYCODE_MENU -> { onInfo(channels[focusRow], focused()); return true }
+ }
+ return super.onKeyDown(keyCode, event)
+ }
+
+ override fun onKeyLongPress(keyCode: Int, event: KeyEvent): Boolean {
+ if (isOk(keyCode) && channels.isNotEmpty()) { onLong(channels[focusRow]); return true }
+ return super.onKeyLongPress(keyCode, event)
+ }
+
+ override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
+ if (isOk(keyCode) && channels.isNotEmpty()) {
+ if (event.isTracking && !event.isCanceled) onSelect(channels[focusRow], focused())
+ return true
+ }
+ return super.onKeyUp(keyCode, event)
+ }
+
+ private fun isOk(k: Int) = k == KeyEvent.KEYCODE_DPAD_CENTER || k == KeyEvent.KEYCODE_ENTER || k == KeyEvent.KEYCODE_NUMPAD_ENTER
+
+ private fun moveRow(r: Int) {
+ focusRow = r
+ val vis = visibleRows()
+ val newTop = when {
+ r < topRow -> r
+ r >= topRow + vis -> r - vis + 1
+ else -> topRow
+ }
+ if (newTop != topRow) {
+ topRow = newTop
+ anim?.cancel()
+ if (Ui.animations(context)) {
+ anim = ValueAnimator.ofFloat(drawTop, newTop.toFloat()).setDuration(110).apply {
+ addUpdateListener { drawTop = it.animatedValue as Float; invalidate() }
+ start()
+ }
+ } else drawTop = newTop.toFloat()
+ requestRows()
+ }
+ afterMove()
+ }
+
+ private fun afterMove() {
+ val p = focused()
+ val start = max(p?.start ?: focusTime, timeMin)
+ val span = ((width - chanW) / pxPerMs).toLong()
+ if (start < viewStart || start > viewStart + span - slotMs) viewStart = max(timeMin, floorSlot(start))
+ invalidate()
+ announce()
+ }
+
+ private fun announce() {
+ val am = context.getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager
+ if (!am.isEnabled) return
+ val ch = channels.getOrNull(focusRow) ?: return
+ val p = focused()
+ val text = listOfNotNull(ch.number, ch.name, p?.let { "${it.title}, ${Ui.time(context, it.start)} to ${Ui.time(context, it.stop)}" } ?: "no guide information").joinToString(", ")
+ contentDescription = text
+ announceForAccessibility(text)
+ }
+
+ override fun onDraw(canvas: Canvas) {
+ val w = width.toFloat()
+ val now = System.currentTimeMillis()
+ val viewEnd = viewStart + ((w - chanW) / pxPerMs).toLong()
+ val focusedView = hasFocus()
+
+ // Time header.
+ val dayLabel = if (android.text.format.DateUtils.isToday(viewStart)) "Today" else android.text.format.DateFormat.format("EEE d MMM", viewStart).toString()
+ canvas.drawText(dayLabel, dp(4).toFloat(), headerH - dp(14), smallP)
+ var t = viewStart
+ while (t < viewEnd) {
+ val x = chanW + (t - viewStart) * pxPerMs
+ canvas.drawText(Ui.time(context, t), x + dp(8), headerH - dp(14), smallP)
+ fill.color = 0x33FFFFFF; canvas.drawRect(x, headerH - dp(8), x + dp(1), headerH, fill)
+ t += slotMs
+ }
+
+ val first = drawTop.toInt()
+ val last = min(channels.size - 1, first + visibleRows() + 1)
+ canvas.save()
+ canvas.clipRect(0f, headerH, w, height.toFloat())
+ for (r in first..last) {
+ if (r < 0) continue
+ val y = headerH + (r - drawTop) * rowH
+ val ch = channels[r]
+ val isFocusRow = focusedView && r == focusRow
+
+ // Channel cell.
+ rect.set(0f, y + gap, chanW - gap * 2, y + rowH - gap)
+ fill.color = if (r == focusRow) Ui.SURFACE_2 else Ui.SURFACE
+ canvas.drawRoundRect(rect, radius, radius, fill)
+ val logo = (context.applicationContext as TvHubApp).logos.bitmap(ch.logo, dp(36)) { invalidate() }
+ var tx = dp(12).toFloat()
+ if (ch.number != null) { canvas.drawText(ch.number, tx, y + rowH / 2 + dp(5), numP); tx += dp(40) }
+ if (logo != null) {
+ val lh = dp(28).toFloat(); val lw = min(dp(44).toFloat(), logo.width * lh / logo.height)
+ rect.set(tx, y + (rowH - lh) / 2, tx + lw, y + (rowH + lh) / 2)
+ canvas.drawBitmap(logo, null, rect, null)
+ tx += lw + dp(10)
+ }
+ val star = if (ch.key in favorites) "★ " else ""
+ canvas.drawText(TextUtils.ellipsize(star + ch.name, titleP, chanW - tx - dp(16), TextUtils.TruncateAt.END).toString(), tx, y + rowH / 2 + dp(6), titleP)
+
+ // Programmes.
+ canvas.save()
+ canvas.clipRect(chanW, y, w, y + rowH)
+ val list = programmes[ch.key]
+ when {
+ ch.epgIds.isEmpty() || (list != null && list.isEmpty()) -> {
+ cell(canvas, chanW, w, y, if (ch.epgIds.isEmpty()) "No guide information" else "No listings in this guide", null, isFocusRow, false)
+ }
+ list == null -> cell(canvas, chanW, w, y, "…", null, false, false)
+ else -> {
+ for (p in list) {
+ if (p.stop <= viewStart || p.start >= viewEnd) continue
+ val x0 = chanW + (max(p.start, viewStart) - viewStart) * pxPerMs
+ val x1 = chanW + (min(p.stop, viewEnd) - viewStart) * pxPerMs
+ val f = isFocusRow && focusTime >= p.start && focusTime < p.stop
+ cell(canvas, x0, x1, y, p.title.ifEmpty { "Untitled" }, "${Ui.time(context, p.start)} – ${Ui.time(context, p.stop)}", f, p.isOn(now))
+ }
+ if (isFocusRow && focused() == null) {
+ val s = floorSlot(focusTime)
+ val x0 = chanW + (s - viewStart) * pxPerMs
+ cell(canvas, x0, x0 + slotW, y, "No listing", null, true, false)
+ }
+ }
+ }
+ canvas.restore()
+ }
+ canvas.restore()
+
+ // Now line.
+ if (now in viewStart until viewEnd) {
+ val x = chanW + (now - viewStart) * pxPerMs
+ fill.color = Ui.LIVE
+ canvas.drawRect(x - dp(1), headerH - dp(6), x + dp(1), height.toFloat(), fill)
+ canvas.drawCircle(x, headerH - dp(6), dp(4).toFloat(), fill)
+ }
+ }
+
+ private fun cell(canvas: Canvas, x0: Float, x1: Float, y: Float, title: String, sub: String?, focused: Boolean, onAir: Boolean) {
+ rect.set(x0 + gap, y + gap, x1 - gap, y + rowH - gap)
+ if (rect.width() <= 0) return
+ fill.color = when { focused -> Ui.SURFACE_2; onAir -> 0xFF1B2633.toInt(); else -> Ui.SURFACE }
+ canvas.drawRoundRect(rect, radius, radius, fill)
+ if (focused) canvas.drawRoundRect(rect, radius, radius, ring)
+ val avail = rect.width() - dp(24)
+ if (avail < dp(12)) return
+ val tx = rect.left + dp(12)
+ if (sub == null) {
+ canvas.drawText(TextUtils.ellipsize(title, titleP, avail, TextUtils.TruncateAt.END).toString(), tx, y + rowH / 2 + dp(6), if (title.startsWith("No ") || title == "…") smallP else titleP)
+ } else {
+ canvas.drawText(TextUtils.ellipsize(title, titleP, avail, TextUtils.TruncateAt.END).toString(), tx, y + rowH / 2 - dp(2), titleP)
+ canvas.drawText(TextUtils.ellipsize(sub, smallP, avail, TextUtils.TruncateAt.END).toString(), tx, y + rowH / 2 + dp(17), smallP)
+ }
+ }
+
+ override fun onFocusChanged(gainFocus: Boolean, direction: Int, previouslyFocusedRect: android.graphics.Rect?) {
+ super.onFocusChanged(gainFocus, direction, previouslyFocusedRect)
+ if (gainFocus) afterMove() else invalidate()
+ }
+
+ private fun floorSlot(t: Long): Long {
+ val off = java.util.TimeZone.getDefault().getOffset(t)
+ return ((t + off) / slotMs) * slotMs - off
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/HomeScreen.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/HomeScreen.kt
new file mode 100644
index 000000000..88ce900ed
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/HomeScreen.kt
@@ -0,0 +1,121 @@
+package io.github.maxhayim.tvhub.ui
+
+import android.content.Intent
+import android.view.View
+import android.widget.HorizontalScrollView
+import android.widget.ScrollView
+import android.widget.Toast
+import io.github.maxhayim.tvhub.model.Channel
+import io.github.maxhayim.tvhub.source.Apps
+import io.github.maxhayim.tvhub.ui.Ui.dp
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.withContext
+
+/** Quick ways in: the guide, recent and favourite channels, and the configured apps. */
+class HomeScreen(host: MainActivity) : Screen(host) {
+ private val clock = Ui.text(ctx, "", 20f, Ui.DIM)
+ private val summary = Ui.text(ctx, "", 16f, Ui.DIM, lines = 2)
+ private val actions = Ui.horizontal(ctx, 16)
+ private val rows = Ui.vertical(ctx, 28)
+ private val body = Ui.vertical(ctx, 24)
+
+ override val view: View = ScrollView(ctx).apply {
+ clipChildren = false; clipToPadding = false
+ isFillViewport = true
+ isVerticalScrollBarEnabled = false
+ val head = Ui.horizontal(ctx).apply {
+ addView(Ui.text(ctx, "Live TV", 34f, bold = true), Ui.lp(0, Ui.WRAP, 1f))
+ addView(clock)
+ }
+ body.addView(head)
+ body.addView(summary)
+ body.addView(HorizontalScrollView(ctx).apply { isHorizontalScrollBarEnabled = false; clipToPadding = false; setPadding(dp(4), dp(6), dp(4), dp(6)); addView(actions) })
+ body.addView(rows)
+ addView(body, Ui.lp())
+ }
+
+ override fun onShow() {
+ watch(combine(repo.channels, repo.favorites, repo.sources, repo.guideVersion) { c, f, s, _ -> Triple(c, f, s) }) { (channels, favs, sources) ->
+ launch { build(channels, favs, sources.isNotEmpty()) }
+ }
+ launch {
+ while (true) { clock.text = Ui.dayTime(ctx, System.currentTimeMillis()); delay(15_000) }
+ }
+ }
+
+ private suspend fun build(channels: List<Channel>, favs: Set<String>, hasSources: Boolean) {
+ val hadFocus = view.findFocus() != null
+ val recents = withContext(Dispatchers.IO) { repo.recents() }
+ val favList = channels.filter { it.key in favs }
+ val apps = repo.appShortcuts()
+ val nn = withContext(Dispatchers.IO) { repo.nowNext((recents + favList).distinctBy { it.key }) }
+
+ summary.text = when {
+ !hasSources -> "No sources yet. Add an M3U playlist, Dispatcharr, an HDHomeRun tuner or your streaming apps."
+ channels.isEmpty() -> "Your sources have no channels yet. Check Sources for errors, or refresh."
+ else -> "${channels.size} channels" + (if (apps.isNotEmpty()) " · ${apps.size} app${if (apps.size == 1) "" else "s"}" else "")
+ }
+
+ actions.removeAllViews()
+ if (channels.isNotEmpty()) {
+ actions.addView(Ui.button(ctx, "Open the guide") { host.go(MainActivity.Page.GUIDE) })
+ actions.addView(Ui.button(ctx, "All channels") { host.go(MainActivity.Page.LIVE) })
+ recents.firstOrNull()?.let { last -> actions.addView(Ui.button(ctx, "Resume ${last.name}") { host.play(channels, channels.indexOfFirst { it.key == last.key }.coerceAtLeast(0)) }) }
+ }
+ if (!hasSources || channels.isEmpty()) {
+ actions.addView(Ui.button(ctx, "Set up sources") { ctx.startActivity(Intent(ctx, OnboardingActivity::class.java)) })
+ }
+ actions.addView(Ui.button(ctx, "Refresh") { repo.refreshAll(); Toast.makeText(ctx, "Refreshing…", Toast.LENGTH_SHORT).show() })
+
+ rows.removeAllViews()
+ if (recents.isNotEmpty()) rows.addView(channelRow("Recently watched", recents, nn))
+ if (favList.isNotEmpty()) rows.addView(channelRow("Favorites", favList, nn))
+ else if (channels.isNotEmpty()) rows.addView(Ui.text(ctx, "Hold OK on a channel to add it to Favorites.", 16f, Ui.DIM))
+ if (apps.isNotEmpty()) rows.addView(appRow(apps))
+ if (hadFocus) focusFirst()
+ }
+
+ private fun channelRow(title: String, list: List<Channel>, nn: NowNext): View {
+ val box = Ui.vertical(ctx, 12)
+ box.addView(Ui.text(ctx, title, 20f, bold = true))
+ val strip = Ui.horizontal(ctx, 20).apply { clipChildren = false; setPadding(dp(6), dp(8), dp(6), dp(8)) }
+ list.take(20).forEachIndexed { i, ch ->
+ strip.addView(ChannelCard(ctx).apply {
+ bindChannel(ch, nn[ch.key]?.first)
+ setOnClickListener { host.play(list, i) }
+ setOnLongClickListener {
+ val on = repo.toggleFavorite(ch.key)
+ Toast.makeText(ctx, if (on) "Added ${ch.name} to Favorites" else "Removed ${ch.name} from Favorites", Toast.LENGTH_SHORT).show()
+ true
+ }
+ })
+ }
+ box.addView(HorizontalScrollView(ctx).apply { isHorizontalScrollBarEnabled = false; clipChildren = false; addView(strip) })
+ return box
+ }
+
+ private fun appRow(apps: List<io.github.maxhayim.tvhub.model.AppShortcut>): View {
+ val box = Ui.vertical(ctx, 12)
+ box.addView(Ui.text(ctx, "Apps", 20f, bold = true))
+ box.addView(Ui.text(ctx, "These open the app itself. Their channels are not part of this guide.", 14f, Ui.DIM))
+ val strip = Ui.horizontal(ctx, 20).apply { clipChildren = false; setPadding(dp(6), dp(8), dp(6), dp(8)) }
+ val pm = ctx.packageManager
+ apps.forEach { a ->
+ val icon = runCatching { pm.getApplicationBanner(a.pkg) ?: pm.getApplicationIcon(a.pkg) }.getOrNull()
+ strip.addView(ChannelCard(ctx).apply {
+ bindApp(a.label, icon)
+ setOnClickListener {
+ val i = Apps.launchIntent(ctx, a.pkg)
+ if (i != null) ctx.startActivity(i) else Toast.makeText(ctx, "${a.label} is not installed any more", Toast.LENGTH_SHORT).show()
+ }
+ })
+ }
+ box.addView(HorizontalScrollView(ctx).apply { isHorizontalScrollBarEnabled = false; clipChildren = false; addView(strip) })
+ return box
+ }
+
+ override fun focusFirst(): Boolean = actions.getChildAt(0)?.requestFocus() ?: false
+}
+
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/LogoLoader.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/LogoLoader.kt
new file mode 100644
index 000000000..996a8d7d6
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/LogoLoader.kt
@@ -0,0 +1,72 @@
+package io.github.maxhayim.tvhub.ui
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.os.Handler
+import android.os.Looper
+import android.util.LruCache
+import android.widget.ImageView
+import io.github.maxhayim.tvhub.data.Http
+import io.github.maxhayim.tvhub.parse.M3uParser
+import java.io.File
+import java.security.MessageDigest
+import java.util.concurrent.Executors
+
+/**
+ * Channel logos named by the playlist, fetched on demand, downscaled, and cached in memory and in
+ * the cache directory (which Android may clear). Three threads, a small memory share: budget TVs
+ * have 1 GB of RAM.
+ */
+class LogoLoader(context: Context) {
+ private val dir = File(context.cacheDir, "logos").apply { mkdirs() }
+ private val mem = object : LruCache<String, Bitmap>((Runtime.getRuntime().maxMemory() / 16).toInt()) {
+ override fun sizeOf(key: String, value: Bitmap) = value.byteCount
+ }
+ private val failed = HashSet<String>()
+ private val pool = Executors.newFixedThreadPool(3)
+ private val main = Handler(Looper.getMainLooper())
+
+ /** [shown] runs on the main thread with true once a logo is on the view, false if there is none. */
+ fun load(url: String?, view: ImageView, heightPx: Int, shown: (Boolean) -> Unit = {}) {
+ view.setImageDrawable(null)
+ view.tag = url
+ if (url == null || !M3uParser.isHttp(url) || synchronized(failed) { url in failed }) { shown(false); return }
+ mem.get(url)?.let { view.setImageBitmap(it); shown(true); return }
+ shown(false)
+ pool.execute {
+ val bmp = runCatching { fetch(url, heightPx) }.getOrNull()
+ if (bmp == null) synchronized(failed) { failed += url } else mem.put(url, bmp)
+ main.post { if (view.tag == url && bmp != null) { view.setImageBitmap(bmp); shown(true) } }
+ }
+ }
+
+ /** For views that draw logos themselves: the bitmap if cached, else null and [ready] once it arrives. */
+ fun bitmap(url: String?, heightPx: Int, ready: () -> Unit): Bitmap? {
+ if (url == null || !M3uParser.isHttp(url) || synchronized(failed) { url in failed }) return null
+ mem.get(url)?.let { return it }
+ synchronized(pending) { if (!pending.add(url)) return null }
+ pool.execute {
+ val bmp = runCatching { fetch(url, heightPx) }.getOrNull()
+ if (bmp == null) synchronized(failed) { failed += url } else mem.put(url, bmp)
+ synchronized(pending) { pending -= url }
+ if (bmp != null) main.post(ready)
+ }
+ return null
+ }
+ private val pending = HashSet<String>()
+
+ private fun fetch(url: String, heightPx: Int): Bitmap? {
+ val f = File(dir, sha(url))
+ val bytes = if (f.exists() && System.currentTimeMillis() - f.lastModified() < 7 * 86_400_000L) f.readBytes()
+ else Http.open(url, 1024 * 1024).use { it.readBytes() }.also { runCatching { f.writeBytes(it) } }
+ val o = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, o)
+ if (o.outHeight <= 0) return null
+ var sample = 1
+ while (o.outHeight / (sample * 2) >= heightPx) sample *= 2
+ return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })
+ }
+
+ private fun sha(s: String) = MessageDigest.getInstance("SHA-256").digest(s.toByteArray()).joinToString("") { "%02x".format(it) }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/MainActivity.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/MainActivity.kt
new file mode 100644
index 000000000..8377830c2
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/MainActivity.kt
@@ -0,0 +1,175 @@
+package io.github.maxhayim.tvhub.ui
+
+import android.app.Activity
+import android.content.Intent
+import android.os.Bundle
+import android.view.Gravity
+import android.view.KeyEvent
+import android.view.View
+import android.widget.FrameLayout
+import android.widget.LinearLayout
+import android.widget.TextView
+import io.github.maxhayim.tvhub.R
+import io.github.maxhayim.tvhub.TvHubApp
+import io.github.maxhayim.tvhub.model.Channel
+import io.github.maxhayim.tvhub.player.PlayerActivity
+import io.github.maxhayim.tvhub.ui.Ui.dp
+import kotlinx.coroutines.MainScope
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.launch
+
+/**
+ * The hub's window: a navigation rail on the left and one page beside it. Moving focus along the
+ * rail switches the page; Right enters it; Back returns to the rail, and Back on the rail leaves.
+ */
+class MainActivity : Activity() {
+ val scope = MainScope()
+ val repo get() = (application as TvHubApp).repo
+
+ enum class Page(val label: String) { HOME("Home"), LIVE("Live TV"), GUIDE("Guide"), FAVORITES("Favorites"), SOURCES("Sources"), SETTINGS("Settings") }
+
+ private lateinit var content: FrameLayout
+ private lateinit var status: TextView
+ private val navItems = LinkedHashMap<Page, TextView>()
+ private val screens = HashMap<Page, Screen>()
+ private var current: Page? = null
+ /**
+ * Between leaving this window and getting it back, Android may hand focus to the first rail
+ * item (when the view that had it was rebuilt meanwhile). That must not switch the page.
+ */
+ private var restoring = false
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ val root = LinearLayout(this).apply { setBackgroundColor(Ui.BG) }
+
+ val rail = Ui.vertical(this, 6).apply {
+ setPadding(dp(20), dp(28), dp(12), dp(20))
+ setBackgroundColor(0xFF0F1216.toInt())
+ }
+ rail.addView(Ui.text(this, getString(R.string.app_name), 24f, bold = true).apply { setPadding(dp(12), 0, 0, dp(18)) })
+ Page.entries.forEach { p ->
+ val item = Ui.text(this, p.label, 19f, Ui.DIM, bold = true).apply {
+ isFocusable = true; isClickable = true
+ background = Ui.focusable(this@MainActivity, 0x00000000, 22, Ui.SURFACE)
+ setPadding(dp(16), dp(10), dp(16), dp(10))
+ setOnFocusChangeListener { _, has -> if (has && !restoring) show(p); refreshNavColors() }
+ setOnClickListener { focusContent() }
+ // Right always enters the page at its first control, not whatever sits nearest.
+ setOnKeyListener { _, code, e -> code == KeyEvent.KEYCODE_DPAD_RIGHT && e.action == KeyEvent.ACTION_DOWN && focusContent() }
+ id = View.generateViewId()
+ }
+ navItems[p] = item
+ rail.addView(item, Ui.lp(Ui.MATCH, Ui.WRAP))
+ }
+ // The rail ends at both ends instead of wandering into the page.
+ navItems.values.first().let { it.nextFocusUpId = it.id }
+ navItems.values.last().let { it.nextFocusDownId = it.id }
+ rail.addView(View(this), Ui.lp(Ui.MATCH, 0, 1f))
+ status = Ui.text(this, "", 13f, Ui.DIM, lines = 3).apply { setPadding(dp(12), 0, dp(4), 0) }
+ rail.addView(status, Ui.lp(Ui.MATCH, Ui.WRAP))
+ root.addView(rail, LinearLayout.LayoutParams(dp(210), Ui.MATCH))
+
+ content = FrameLayout(this).apply { setPadding(dp(24), dp(28), dp(32), dp(20)) }
+ root.addView(content, LinearLayout.LayoutParams(0, Ui.MATCH, 1f))
+ setContentView(root)
+
+ scope.launch {
+ repo.refresh.collect { st ->
+ status.text = st.message
+ status.setTextColor(if (!st.running && st.errors > 0) Ui.ERROR else Ui.DIM)
+ }
+ }
+
+ val start = intent.getStringExtra(EXTRA_PAGE)?.let { runCatching { Page.valueOf(it) }.getOrNull() } ?: Page.HOME
+ navItems.getValue(start).requestFocus()
+ show(start)
+
+ if (!repo.prefs.onboarded) startActivity(Intent(this, OnboardingActivity::class.java))
+ else repo.refreshIfStale()
+ }
+
+ override fun onResume() {
+ super.onResume()
+ current?.let { screens[it]?.onShow() }
+ }
+
+ override fun onWindowFocusChanged(hasFocus: Boolean) {
+ super.onWindowFocusChanged(hasFocus)
+ if (!hasFocus || !restoring) return
+ content.post {
+ restoring = false
+ val f = currentFocus
+ val cur = current ?: return@post
+ if (f == null || (navItems.values.any { it === f } && f !== navItems[cur])) navItems.getValue(cur).requestFocus()
+ }
+ }
+
+ override fun onPause() {
+ restoring = true
+ current?.let { screens[it]?.onHide() }
+ super.onPause()
+ }
+
+ override fun onDestroy() { scope.cancel(); super.onDestroy() }
+
+ fun show(p: Page) {
+ if (current == p) return
+ current?.let { screens[it]?.onHide() }
+ current = p
+ val s = screens.getOrPut(p) {
+ when (p) {
+ Page.HOME -> HomeScreen(this)
+ Page.LIVE -> ChannelsScreen(this, favoritesOnly = false)
+ Page.GUIDE -> GuideScreen(this)
+ Page.FAVORITES -> ChannelsScreen(this, favoritesOnly = true)
+ Page.SOURCES -> SourcesScreen(this)
+ Page.SETTINGS -> SettingsScreen(this)
+ }
+ }
+ content.removeAllViews()
+ // A margin inside the page where focused controls can grow (scaleOnFocus) without being cut.
+ s.view.setPadding(dp(8), s.view.paddingTop, dp(8), s.view.paddingBottom)
+ (s.view as? android.view.ViewGroup)?.clipToPadding = false
+ content.addView(s.view, FrameLayout.LayoutParams(Ui.MATCH, Ui.MATCH))
+ // The rail item to the left of the page is the current one, so Left from the page returns to it.
+ s.view.nextFocusLeftId = navItems.getValue(p).id
+ navItems.values.forEach { it.nextFocusRightId = View.NO_ID }
+ s.onShow()
+ refreshNavColors()
+ }
+
+ private fun refreshNavColors() {
+ navItems.forEach { (p, v) ->
+ v.isSelected = p == current && !v.isFocused
+ v.setTextColor(if (p == current || v.isFocused) Ui.TEXT else Ui.DIM)
+ }
+ }
+
+ fun focusContent(): Boolean = current?.let { screens[it]?.focusFirst() } ?: false
+
+ fun go(p: Page) { navItems.getValue(p).requestFocus(); show(p); content.post { focusContent() } }
+
+ fun play(list: List<Channel>, index: Int) {
+ if (list.isEmpty()) return
+ PlayerActivity.start(this, list, index)
+ }
+
+ override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
+ if (keyCode == KeyEvent.KEYCODE_BACK) {
+ val focus = currentFocus
+ if (focus != null && navItems.values.none { it === focus }) {
+ current?.let { navItems.getValue(it).requestFocus() }
+ return true
+ }
+ }
+ return super.onKeyDown(keyCode, event)
+ }
+
+ companion object {
+ const val EXTRA_PAGE = "page"
+ }
+}
+
+/** Gravity helper for one-off centred text. */
+internal fun TextView.centered(): TextView = apply { gravity = Gravity.CENTER }
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/OnboardingActivity.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/OnboardingActivity.kt
new file mode 100644
index 000000000..b9c604a85
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/OnboardingActivity.kt
@@ -0,0 +1,64 @@
+package io.github.maxhayim.tvhub.ui
+
+import android.app.Activity
+import android.content.Intent
+import android.os.Bundle
+import android.widget.ScrollView
+import android.widget.TextView
+import io.github.maxhayim.tvhub.TvHubApp
+import io.github.maxhayim.tvhub.model.SourceType
+import io.github.maxhayim.tvhub.ui.Ui.dp
+
+/** First launch: pick any sources to add now, or skip. Every step is optional and can be done later in Sources. */
+class OnboardingActivity : Activity() {
+ private val repo get() = (application as TvHubApp).repo
+ private val buttons = LinkedHashMap<SourceType, TextView>()
+ private val labels = linkedMapOf(
+ SourceType.M3U to "Add an M3U playlist",
+ SourceType.XMLTV to "Add an XMLTV guide",
+ SourceType.DISPATCHARR to "Connect Dispatcharr",
+ SourceType.HDHOMERUN to "Find an HDHomeRun tuner",
+ SourceType.APPS to "Choose streaming apps",
+ )
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ val col = Ui.vertical(this, 16).apply { setPadding(dp(96), dp(56), dp(96), dp(40)) }
+ col.addView(Ui.text(this, "Welcome to TV Hub", 34f, bold = true))
+ col.addView(Ui.text(this, "One guide for your live TV. Add the sources you have; each one is optional, and you can add or change them later under Sources. Only use playlists and services you are allowed to watch.", 18f, Ui.DIM, lines = 0))
+ val list = Ui.vertical(this, 10)
+ labels.forEach { (t, l) ->
+ val b = Ui.button(this, l) { startActivityForResult(SourceEditorActivity.intent(this, t, 0), 1) }
+ b.gravity = android.view.Gravity.START or android.view.Gravity.CENTER_VERTICAL
+ buttons[t] = b
+ list.addView(b, Ui.lp(dp(520), Ui.WRAP))
+ }
+ col.addView(list)
+ val done = Ui.button(this, "Skip for now") { finishSetup() }
+ col.addView(done, Ui.lp(Ui.WRAP, Ui.WRAP).apply { topMargin = dp(12) })
+ setContentView(ScrollView(this).apply { setBackgroundColor(Ui.BG); addView(col) })
+ buttons.values.first().requestFocus()
+ doneButton = done
+ }
+
+ private var doneButton: TextView? = null
+
+ @Deprecated("Activity result API needs androidx.activity; the platform call is enough here")
+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ super.onActivityResult(requestCode, resultCode, data)
+ if (resultCode != RESULT_OK) return
+ val t = data?.getStringExtra(SourceEditorActivity.EXTRA_TYPE)?.let { SourceType.valueOf(it) } ?: return
+ buttons[t]?.let { it.text = "✓ " + labels[t]; it.setTextColor(Ui.OK) }
+ doneButton?.text = "Done"
+ doneButton?.requestFocus()
+ }
+
+ @Deprecated("Back is handled here so skipping setup still marks it done")
+ override fun onBackPressed() { finishSetup() }
+
+ private fun finishSetup() {
+ repo.prefs.onboarded = true
+ repo.load()
+ finish()
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/Screen.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/Screen.kt
new file mode 100644
index 000000000..a6777acce
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/Screen.kt
@@ -0,0 +1,22 @@
+package io.github.maxhayim.tvhub.ui
+
+import android.view.View
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.launch
+
+/** One page of the main window. Collections run while the page is shown and stop when it is hidden. */
+abstract class Screen(val host: MainActivity) {
+ val ctx get() = host
+ val repo get() = host.repo
+ abstract val view: View
+ private val jobs = ArrayList<Job>()
+
+ open fun onShow() {}
+ open fun onHide() { jobs.forEach { it.cancel() }; jobs.clear() }
+ /** Moves focus into the page; false if it has nothing focusable. */
+ abstract fun focusFirst(): Boolean
+
+ protected fun <T> watch(flow: Flow<T>, block: (T) -> Unit) { jobs += host.scope.launch { flow.collect { block(it) } } }
+ protected fun launch(block: suspend () -> Unit) { jobs += host.scope.launch { block() } }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/SettingsScreen.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/SettingsScreen.kt
new file mode 100644
index 000000000..535179ca8
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/SettingsScreen.kt
@@ -0,0 +1,78 @@
+package io.github.maxhayim.tvhub.ui
+
+import android.app.AlertDialog
+import android.content.Intent
+import android.view.View
+import android.widget.ScrollView
+import android.widget.TextView
+import android.widget.Toast
+import io.github.maxhayim.tvhub.BuildConfig
+import io.github.maxhayim.tvhub.ui.Ui.dp
+
+class SettingsScreen(host: MainActivity) : Screen(host) {
+ private val list = Ui.vertical(ctx, 8)
+
+ override val view: View = ScrollView(ctx).apply {
+ clipChildren = false; clipToPadding = false
+ isVerticalScrollBarEnabled = false
+ val col = Ui.vertical(ctx, 18)
+ col.addView(Ui.text(ctx, "Settings", 30f, bold = true))
+ col.addView(list)
+ addView(col, Ui.lp())
+ build()
+ }
+
+ private fun build() {
+ val p = repo.prefs
+ list.removeAllViews()
+ row("Merge duplicate channels", if (p.mergeDuplicates) "On: channels with the same tvg-id in several sources show once, and the player falls back between their streams" else "Off: every source keeps its own copy") {
+ repo.setMerge(!p.mergeDuplicates); build()
+ }
+ row("Guide length", "${p.guideDays} day${if (p.guideDays == 1) "" else "s"} of listings. Longer guides use more storage and take longer to read") {
+ p.guideDays = when (p.guideDays) { 1 -> 2; 2 -> 3; 3 -> 7; else -> 1 }; build()
+ Toast.makeText(ctx, "Takes effect at the next refresh", Toast.LENGTH_SHORT).show()
+ }
+ row("Refresh when the app opens", if (p.refreshHours == 0) "Never on its own; use Refresh" else "If the last refresh is older than ${p.refreshHours} hours. Nothing runs in the background") {
+ p.refreshHours = when (p.refreshHours) { 6 -> 12; 12 -> 24; 24 -> 0; else -> 6 }; build()
+ }
+ row("Animations", if (p.animations) "On" else "Off: no zoom on focus and no scrolling motion, for slow TVs") {
+ p.animations = !p.animations; build()
+ }
+ row("Clear recently watched", "Empties the Recently watched row") {
+ repo.clearRecents(); Toast.makeText(ctx, "Cleared", Toast.LENGTH_SHORT).show()
+ }
+ row("Run setup again", "The first-launch steps for adding sources") {
+ ctx.startActivity(Intent(ctx, OnboardingActivity::class.java))
+ }
+ row("About and licences", "TV Hub ${BuildConfig.VERSION_NAME}, MIT licence") { about() }
+ }
+
+ private fun row(title: String, sub: String, onClick: () -> Unit) {
+ val r = Ui.vertical(ctx, 4).apply {
+ isFocusable = true; isClickable = true
+ background = Ui.focusable(ctx)
+ setPadding(dp(20), dp(14), dp(20), dp(14))
+ setOnClickListener {
+ val idx = list.indexOfChild(this)
+ onClick()
+ list.getChildAt(idx)?.requestFocus()
+ }
+ }
+ r.addView(Ui.text(ctx, title, 20f, bold = true))
+ r.addView(Ui.text(ctx, sub, 15f, Ui.DIM, lines = 2))
+ list.addView(r)
+ }
+
+ private fun about() {
+ val text = ctx.assets.open("licenses.txt").bufferedReader().use { it.readText() }
+ AlertDialog.Builder(ctx, android.R.style.Theme_DeviceDefault_Dialog_Alert)
+ .setTitle("TV Hub ${BuildConfig.VERSION_NAME}")
+ .setView(ScrollView(ctx).apply {
+ isFocusable = true
+ addView(TextView(ctx).apply { this.text = text; setTextColor(Ui.TEXT); textSize = 14f; setPadding(dp(28), dp(8), dp(28), dp(8)) })
+ })
+ .setPositiveButton("Close", null).show()
+ }
+
+ override fun focusFirst(): Boolean = list.getChildAt(0)?.requestFocus() ?: false
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/SourceEditorActivity.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/SourceEditorActivity.kt
new file mode 100644
index 000000000..933edec26
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/SourceEditorActivity.kt
@@ -0,0 +1,224 @@
+package io.github.maxhayim.tvhub.ui
+
+import android.app.Activity
+import android.content.Context
+import android.content.Intent
+import android.os.Bundle
+import android.text.InputType
+import android.view.View
+import android.view.inputmethod.EditorInfo
+import android.widget.CheckBox
+import android.widget.EditText
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import io.github.maxhayim.tvhub.TvHubApp
+import io.github.maxhayim.tvhub.model.SourceConfig
+import io.github.maxhayim.tvhub.model.SourceType
+import io.github.maxhayim.tvhub.parse.M3uParser
+import io.github.maxhayim.tvhub.source.Apps
+import io.github.maxhayim.tvhub.source.HdHomeRun
+import io.github.maxhayim.tvhub.source.Providers
+import io.github.maxhayim.tvhub.ui.Ui.dp
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.MainScope
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+
+/** Adds or edits one source. "Check" reads it once without saving, so typos show up before they reach the guide. */
+class SourceEditorActivity : Activity() {
+ private val scope = MainScope()
+ private val repo get() = (application as TvHubApp).repo
+ private lateinit var type: SourceType
+ private var existing: SourceConfig? = null
+
+ private lateinit var form: LinearLayout
+ private lateinit var result: android.widget.TextView
+ private val name by lazy { field("Name", "") }
+ private val url by lazy { field("", "", InputType.TYPE_TEXT_VARIATION_URI) }
+ private val epg by lazy { field("Guide (XMLTV) address, optional", "", InputType.TYPE_TEXT_VARIATION_URI) }
+ private val profile by lazy { field("Output profile, optional (empty for all channels)", "") }
+ private val headerEpg by lazy { check("Also use the guide the playlist names in its header (x-tvg-url)") }
+ private val transcode by lazy { check("Ask the tuner for H.264 (HDHomeRun EXTEND models only). Turn on if channels play sound but no picture") }
+ private val appChecks = LinkedHashMap<String, CheckBox>()
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ type = SourceType.valueOf(intent.getStringExtra(EXTRA_TYPE) ?: SourceType.M3U.name)
+ val id = intent.getLongExtra(EXTRA_ID, 0)
+ existing = repo.sources.value.firstOrNull { it.first.id == id }?.first
+
+ form = Ui.vertical(this, 14).apply { setPadding(dp(64), dp(40), dp(64), dp(40)) }
+ result = Ui.text(this, "", 16f, Ui.DIM, lines = 4)
+ form.addView(Ui.text(this, (if (existing == null) "Add " else "Edit ") + SourcesScreen.typeLabel(type), 28f, bold = true))
+ when (type) {
+ SourceType.M3U -> {
+ hint("The address of an M3U or M3U8 playlist you are allowed to use. Many IPTV services give one; it is stored encrypted on this TV.")
+ labelled("Playlist address", url, "http://192.168.1.10:8000/playlist.m3u")
+ labelled("Name", name, "My playlist"); add(epg); add(headerEpg)
+ }
+ SourceType.XMLTV -> {
+ hint("An XMLTV guide (.xml or .xml.gz). Its programmes are matched to channels by tvg-id, or by name for channels without one.")
+ labelled("Guide address", url, "http://192.168.1.10:8000/guide.xml")
+ labelled("Name", name, "My guide")
+ }
+ SourceType.DISPATCHARR -> {
+ hint("Your Dispatcharr server's address, as you open it in a browser. TV Hub reads its /output/m3u and /output/epg. If you get \"refused access\", allow this TV's network under Dispatcharr's M3U/EPG network settings.")
+ labelled("Server address", url, "http://192.168.1.10:9191")
+ labelled("Name", name, "Dispatcharr"); add(profile)
+ }
+ SourceType.HDHOMERUN -> {
+ hint("HDHomeRun tuners are found on the local network. The guide is not read from SiliconDust's online service; add an XMLTV guide for listings.")
+ val found = Ui.vertical(this, 8)
+ add(Ui.button(this, "Scan the network") { scan(found) })
+ add(found)
+ labelled("Tuner address", url, "192.168.1.50")
+ labelled("Name", name, "Antenna"); add(transcode)
+ }
+ SourceType.APPS -> {
+ hint("Apps you pick appear as shortcuts on Home. They open the app; TV Hub cannot read their channels or guides, so they are never shown as channels.")
+ val picked = existing?.packages?.toSet()
+ Apps.detected(this).forEach { appCheck(it.pkg, it.label, picked?.contains(it.pkg) ?: true) }
+ if (appChecks.isEmpty()) hint("None of the live-TV apps TV Hub knows is installed.")
+ val more = Ui.vertical(this, 8)
+ add(Ui.button(this, "Show every TV app") {
+ Apps.allTvApps(this).filter { it.pkg !in appChecks }.forEach { appCheck(it.pkg, it.label, picked?.contains(it.pkg) == true, more) }
+ })
+ add(more)
+ name.setText("Streaming apps")
+ }
+ }
+ existing?.let { e ->
+ name.setText(e.name); url.setText(e.url); epg.setText(e.epgUrl); profile.setText(e.profile)
+ headerEpg.isChecked = e.useHeaderEpg; transcode.isChecked = e.transcode
+ } ?: run { headerEpg.isChecked = true }
+
+ val buttons = Ui.horizontal(this, 16)
+ buttons.addView(Ui.button(this, "Save") { save() })
+ if (type != SourceType.APPS) buttons.addView(Ui.button(this, "Check") { test() })
+ buttons.addView(Ui.button(this, "Cancel") { finish() })
+ form.addView(buttons, Ui.lp(Ui.WRAP, Ui.WRAP).apply { topMargin = dp(10) })
+ form.addView(result)
+
+ setContentView(ScrollView(this).apply { setBackgroundColor(Ui.BG); addView(form) })
+ (if (type == SourceType.APPS) appChecks.values.firstOrNull() else url)?.requestFocus()
+ }
+
+ override fun onDestroy() { scope.cancel(); super.onDestroy() }
+
+ private fun field(hint: String, value: String, variation: Int = 0) = EditText(this).apply {
+ this.hint = hint; setText(value); setHintTextColor(0xFF6B7380.toInt()); setTextColor(Ui.TEXT); textSize = 18f
+ isSingleLine = true
+ inputType = InputType.TYPE_CLASS_TEXT or variation
+ imeOptions = EditorInfo.IME_ACTION_NEXT or EditorInfo.IME_FLAG_NO_FULLSCREEN
+ background = Ui.focusable(this@SourceEditorActivity, Ui.SURFACE, 10)
+ setPadding(dp(18), dp(12), dp(18), dp(12))
+ // An old "Check" result or error no longer applies once the text changes.
+ addTextChangedListener(object : android.text.TextWatcher {
+ override fun beforeTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
+ override fun onTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
+ override fun afterTextChanged(s: android.text.Editable?) { if (::result.isInitialized) result.text = "" }
+ })
+ }
+
+ private fun check(label: String) = CheckBox(this).apply {
+ text = label; setTextColor(Ui.TEXT); textSize = 17f
+ background = Ui.focusable(this@SourceEditorActivity, 0x00000000, 10)
+ setPadding(dp(12), dp(8), dp(12), dp(8))
+ buttonTintList = android.content.res.ColorStateList.valueOf(Ui.ACCENT)
+ }
+
+ private fun appCheck(pkg: String, label: String, on: Boolean, into: LinearLayout = form) {
+ val c = check(label).apply { isChecked = on }
+ appChecks[pkg] = c
+ into.addView(c, if (into === form) form.childCount else into.childCount)
+ }
+
+ private fun add(v: View) = form.addView(v, Ui.lp(Ui.MATCH, Ui.WRAP))
+ private fun hint(s: String) = form.addView(Ui.text(this, s, 16f, Ui.DIM, lines = 0))
+ private fun labelled(label: String, f: EditText, example: String) {
+ form.addView(Ui.text(this, label, 15f, Ui.DIM))
+ f.hint = example
+ add(f)
+ }
+
+ private fun scan(into: LinearLayout) {
+ into.removeAllViews()
+ into.addView(Ui.text(this, "Scanning…", 16f, Ui.DIM))
+ scope.launch {
+ val devices = withContext(Dispatchers.IO) { runCatching { HdHomeRun.discover() }.getOrDefault(emptyList()) }
+ into.removeAllViews()
+ if (devices.isEmpty()) into.addView(Ui.text(this@SourceEditorActivity, "No tuner answered. Check it is on the same network, or type its address below.", 16f, Ui.ERROR, lines = 3))
+ devices.forEach { d ->
+ into.addView(Ui.button(this@SourceEditorActivity, "${d.name} ${d.model} · ${d.host} · ${d.tuners} tuners") {
+ url.setText(d.host)
+ if (name.text.isBlank()) name.setText(d.name)
+ result.text = "Selected ${d.host}. Save to add it."
+ })
+ }
+ into.getChildAt(0)?.requestFocus()
+ }
+ }
+
+ private fun build(): SourceConfig? {
+ val u = url.text.toString().trim()
+ val n = name.text.toString().trim().ifEmpty { defaultName() }
+ val e = epg.text.toString().trim()
+ when (type) {
+ SourceType.M3U, SourceType.XMLTV, SourceType.DISPATCHARR -> if (!M3uParser.isHttp(u)) return fail("Enter an address starting with http:// or https://")
+ SourceType.HDHOMERUN -> if (u.isEmpty() || u.contains(' ')) return fail("Enter the tuner's address, or scan for it")
+ SourceType.APPS -> Unit
+ }
+ if (type == SourceType.M3U && e.isNotEmpty() && !M3uParser.isHttp(e)) return fail("The guide address must start with http:// or https://")
+ return (existing ?: SourceConfig(type = type, name = n)).copy(
+ name = n, url = u, epgUrl = e, profile = profile.text.toString().trim(),
+ useHeaderEpg = headerEpg.isChecked, transcode = transcode.isChecked,
+ packages = appChecks.filterValues { it.isChecked }.keys.toList(),
+ )
+ }
+
+ private fun defaultName() = when (type) {
+ SourceType.M3U -> "Playlist"; SourceType.XMLTV -> "Guide"; SourceType.DISPATCHARR -> "Dispatcharr"
+ SourceType.HDHOMERUN -> "Antenna"; SourceType.APPS -> "Streaming apps"
+ }
+
+ private fun fail(msg: String): SourceConfig? { result.setTextColor(Ui.ERROR); result.text = msg; return null }
+
+ private fun save() {
+ val s = build() ?: return
+ repo.saveSource(s)
+ setResult(RESULT_OK, Intent().putExtra(EXTRA_TYPE, type.name))
+ finish()
+ }
+
+ private fun test() {
+ val s = build() ?: return
+ result.setTextColor(Ui.DIM); result.text = "Checking…"
+ scope.launch {
+ val msg = withContext(Dispatchers.IO) {
+ try {
+ if (type == SourceType.XMLTV) {
+ io.github.maxhayim.tvhub.data.Http.open(s.url, 256L * 1024 * 1024).use { input ->
+ val head = ByteArray(4096); val n = input.read(head)
+ val t = String(head, 0, maxOf(n, 0))
+ if (t.contains("<tv")) "Found an XMLTV guide. Save to read it." else throw java.io.IOException("That address did not return an XMLTV guide")
+ }
+ } else {
+ val r = Providers.forType(type).load(s)
+ "Found ${SourcesScreen.plural(r.channels.size, "channel")}" + (if (r.skipped > 0) ", ${r.skipped} skipped" else "") +
+ (if (r.epgUrls.isNotEmpty()) " and a guide address" else "") + ". Save to add them."
+ }
+ } catch (e: Exception) { "!" + (io.github.maxhayim.tvhub.data.Http.friendly(e).message ?: "Could not read it") }
+ }
+ result.setTextColor(if (msg.startsWith("!")) Ui.ERROR else Ui.OK)
+ result.text = msg.removePrefix("!")
+ }
+ }
+
+ companion object {
+ const val EXTRA_TYPE = "type"
+ const val EXTRA_ID = "id"
+ fun intent(c: Context, type: SourceType, id: Long) = Intent(c, SourceEditorActivity::class.java).putExtra(EXTRA_TYPE, type.name).putExtra(EXTRA_ID, id)
+ fun start(c: Context, type: SourceType, id: Long) = c.startActivity(intent(c, type, id))
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/SourcesScreen.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/SourcesScreen.kt
new file mode 100644
index 000000000..8fdd68847
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/SourcesScreen.kt
@@ -0,0 +1,105 @@
+package io.github.maxhayim.tvhub.ui
+
+import android.app.AlertDialog
+import android.view.View
+import android.widget.ScrollView
+import io.github.maxhayim.tvhub.model.SourceConfig
+import io.github.maxhayim.tvhub.model.SourceStatus
+import io.github.maxhayim.tvhub.model.SourceType
+import io.github.maxhayim.tvhub.ui.Ui.dp
+
+/** Every configured source with its last result, and the way to add, edit, refresh or remove one. */
+class SourcesScreen(host: MainActivity) : Screen(host) {
+ private val actions = Ui.horizontal(ctx, 16)
+ private val list = Ui.vertical(ctx, 10)
+
+ override val view: View = ScrollView(ctx).apply {
+ clipChildren = false; clipToPadding = false
+ isVerticalScrollBarEnabled = false
+ val col = Ui.vertical(ctx, 18)
+ col.addView(Ui.text(ctx, "Sources", 30f, bold = true))
+ col.addView(Ui.text(ctx, "Every source is optional. Channels from playlists, Dispatcharr and tuners play here; apps open on their own.", 16f, Ui.DIM, lines = 2))
+ actions.addView(Ui.button(ctx, "Add a source") { addDialog() })
+ actions.addView(Ui.button(ctx, "Refresh all") { repo.refreshAll() })
+ col.addView(actions)
+ col.addView(list)
+ addView(col, Ui.lp())
+ }
+
+ override fun onShow() {
+ watch(repo.sources) { build(it) }
+ watch(repo.refresh) { if (!it.running) repo.load() }
+ }
+
+ private fun build(sources: List<Pair<SourceConfig, SourceStatus>>) {
+ val hadFocus = list.findFocus() != null
+ list.removeAllViews()
+ if (sources.isEmpty()) list.addView(Ui.text(ctx, "No sources yet.", 18f, Ui.DIM))
+ sources.forEach { (s, st) ->
+ val row = Ui.vertical(ctx, 4).apply {
+ isFocusable = true; isClickable = true
+ background = Ui.focusable(ctx)
+ setPadding(dp(20), dp(14), dp(20), dp(14))
+ setOnClickListener { actionsFor(s) }
+ }
+ row.addView(Ui.text(ctx, s.name + if (!s.enabled) " (off)" else "", 20f, if (s.enabled) Ui.TEXT else Ui.DIM, bold = true))
+ row.addView(Ui.text(ctx, typeLabel(s.type), 14f, Ui.DIM))
+ val line = when {
+ !s.enabled -> "Turned off"
+ s.type == SourceType.APPS -> "${s.packages.size} app${if (s.packages.size == 1) "" else "s"}, opened as shortcuts"
+ st.error != null -> st.error
+ st.lastRefresh == 0L -> "Not read yet"
+ s.type == SourceType.XMLTV -> "${plural(st.channelCount, "guide channel")} · read ${Ui.dayTime(ctx, st.lastRefresh)}"
+ else -> plural(st.channelCount, "channel") + (if (st.skipped > 0) " · ${plural(st.skipped, "entry", "entries")} skipped (not http/https, or encrypted)" else "") + " · read ${Ui.dayTime(ctx, st.lastRefresh)}"
+ }
+ row.addView(Ui.text(ctx, line, 15f, if (st.error != null && s.enabled) Ui.ERROR else Ui.DIM, lines = 2))
+ list.addView(row)
+ }
+ if (hadFocus) list.getChildAt(0)?.requestFocus()
+ }
+
+ private fun actionsFor(s: SourceConfig) {
+ val items = arrayOf(
+ if (s.type == SourceType.APPS) "Choose apps" else "Edit",
+ if (s.enabled) "Turn off" else "Turn on",
+ "Refresh all sources now",
+ "Remove",
+ )
+ AlertDialog.Builder(ctx, android.R.style.Theme_DeviceDefault_Dialog_Alert)
+ .setTitle(s.name)
+ .setItems(items) { _, which ->
+ when (which) {
+ 0 -> SourceEditorActivity.start(ctx, s.type, s.id)
+ 1 -> repo.saveSource(s.copy(enabled = !s.enabled))
+ 2 -> repo.refreshAll()
+ 3 -> AlertDialog.Builder(ctx, android.R.style.Theme_DeviceDefault_Dialog_Alert)
+ .setTitle("Remove ${s.name}?")
+ .setMessage("Its channels leave the guide. Favourites of channels no other source has are kept in case you add it back.")
+ .setPositiveButton("Remove") { _, _ -> repo.deleteSource(s.id) }
+ .setNegativeButton("Cancel", null).show()
+ }
+ }.show()
+ }
+
+ private fun addDialog() {
+ val types = SourceType.entries
+ AlertDialog.Builder(ctx, android.R.style.Theme_DeviceDefault_Dialog_Alert)
+ .setTitle("Add a source")
+ .setItems(types.map { typeLabel(it) }.toTypedArray()) { _, i -> SourceEditorActivity.start(ctx, types[i], 0) }
+ .show()
+ }
+
+ override fun focusFirst(): Boolean = actions.getChildAt(0)?.requestFocus() ?: false
+
+ companion object {
+ fun plural(n: Int, one: String, many: String = one + "s") = "$n ${if (n == 1) one else many}"
+
+ fun typeLabel(t: SourceType) = when (t) {
+ SourceType.M3U -> "M3U playlist"
+ SourceType.XMLTV -> "XMLTV guide"
+ SourceType.DISPATCHARR -> "Dispatcharr"
+ SourceType.HDHOMERUN -> "HDHomeRun tuner (antenna or cable)"
+ SourceType.APPS -> "Streaming apps (shortcuts)"
+ }
+ }
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/Ui.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/Ui.kt
new file mode 100644
index 000000000..a65213da3
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/ui/Ui.kt
@@ -0,0 +1,98 @@
+package io.github.maxhayim.tvhub.ui
+
+import android.content.Context
+import android.graphics.Color
+import android.graphics.Typeface
+import android.graphics.drawable.Drawable
+import android.graphics.drawable.GradientDrawable
+import android.graphics.drawable.StateListDrawable
+import android.text.TextUtils
+import android.util.TypedValue
+import android.view.Gravity
+import android.view.View
+import android.view.ViewGroup
+import android.widget.LinearLayout
+import android.widget.TextView
+import io.github.maxhayim.tvhub.TvHubApp
+import java.text.DateFormat
+import java.util.Date
+
+/** The small view kit every screen is built from: colours, type sizes and the focus look. */
+object Ui {
+ const val BG = 0xFF0B0D10.toInt()
+ const val SURFACE = 0xFF161A20.toInt()
+ const val SURFACE_2 = 0xFF222832.toInt()
+ const val TEXT = 0xFFF2F4F7.toInt()
+ const val DIM = 0xFF9AA4B2.toInt()
+ const val ACCENT = 0xFF4FA3E0.toInt()
+ const val LIVE = 0xFFE5484D.toInt()
+ const val ERROR = 0xFFFF7B72.toInt()
+ const val OK = 0xFF5BC782.toInt()
+
+ fun Context.dp(v: Number): Int = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, v.toFloat(), resources.displayMetrics).toInt()
+ fun View.dp(v: Number): Int = context.dp(v)
+
+ fun animations(c: Context) = (c.applicationContext as TvHubApp).repo.prefs.animations
+
+ fun rounded(c: Context, color: Int, radiusDp: Int = 12, strokeColor: Int = 0, strokeDp: Int = 0) = GradientDrawable().apply {
+ setColor(color); cornerRadius = c.dp(radiusDp).toFloat()
+ if (strokeDp > 0) setStroke(c.dp(strokeDp), strokeColor)
+ }
+
+ /** Focused: lighter surface with a white ring. Clear focus is the main thing a 10-foot UI needs. */
+ fun focusable(c: Context, normal: Int = SURFACE, radiusDp: Int = 12, selected: Int = SURFACE_2): Drawable = StateListDrawable().apply {
+ addState(intArrayOf(android.R.attr.state_focused), rounded(c, SURFACE_2, radiusDp, Color.WHITE, 3))
+ addState(intArrayOf(android.R.attr.state_selected), rounded(c, selected, radiusDp, ACCENT, 2))
+ addState(intArrayOf(), rounded(c, normal, radiusDp))
+ }
+
+ /** Grows the focused view a little; off with Settings > Animations. */
+ fun scaleOnFocus(v: View, scale: Float = 1.04f) {
+ val prev = v.onFocusChangeListener
+ v.setOnFocusChangeListener { view, has ->
+ prev?.onFocusChange(view, has)
+ if (!animations(view.context)) { view.scaleX = 1f; view.scaleY = 1f; return@setOnFocusChangeListener }
+ val s = if (has) scale else 1f
+ view.animate().scaleX(s).scaleY(s).setDuration(120).start()
+ }
+ }
+
+ fun text(c: Context, s: CharSequence = "", sizeSp: Float = 18f, color: Int = TEXT, bold: Boolean = false, lines: Int = 1) = TextView(c).apply {
+ text = s; setTextColor(color); setTextSize(TypedValue.COMPLEX_UNIT_SP, sizeSp)
+ if (bold) typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
+ if (lines > 0) { maxLines = lines; ellipsize = TextUtils.TruncateAt.END }
+ includeFontPadding = false
+ }
+
+ fun button(c: Context, label: String, onClick: () -> Unit) = text(c, label, 18f, bold = true).apply {
+ isFocusable = true; isClickable = true
+ background = focusable(c, SURFACE_2, 24)
+ gravity = Gravity.CENTER
+ setPadding(c.dp(24), c.dp(12), c.dp(24), c.dp(12))
+ minWidth = c.dp(120)
+ setOnClickListener { onClick() }
+ scaleOnFocus(this, 1.05f)
+ }
+
+ // Children grow on focus (scaleOnFocus), so containers never clip them.
+ fun vertical(c: Context, gapDp: Int = 0) = LinearLayout(c).apply {
+ orientation = LinearLayout.VERTICAL
+ clipChildren = false; clipToPadding = false
+ if (gapDp > 0) { dividerDrawable = spacer(c, gapDp); showDividers = LinearLayout.SHOW_DIVIDER_MIDDLE }
+ }
+ fun horizontal(c: Context, gapDp: Int = 0) = LinearLayout(c).apply {
+ orientation = LinearLayout.HORIZONTAL
+ clipChildren = false; clipToPadding = false
+ if (gapDp > 0) { dividerDrawable = spacer(c, gapDp); showDividers = LinearLayout.SHOW_DIVIDER_MIDDLE }
+ }
+ private fun spacer(c: Context, d: Int) = GradientDrawable().apply { setSize(c.dp(d), c.dp(d)); setColor(Color.TRANSPARENT) }
+
+ fun lp(w: Int = ViewGroup.LayoutParams.MATCH_PARENT, h: Int = ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float = 0f) =
+ LinearLayout.LayoutParams(w, h, weight)
+
+ const val MATCH = ViewGroup.LayoutParams.MATCH_PARENT
+ const val WRAP = ViewGroup.LayoutParams.WRAP_CONTENT
+
+ fun time(c: Context, t: Long): String = android.text.format.DateFormat.getTimeFormat(c).format(Date(t))
+ fun dayTime(c: Context, t: Long): String = DateFormat.getDateInstance(DateFormat.MEDIUM).format(Date(t)) + " " + time(c, t)
+}
diff --git a/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/util/Log.kt b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/util/Log.kt
new file mode 100644
index 000000000..03362ae00
--- /dev/null
+++ b/addons/tv-hub/app/src/main/java/io/github/maxhayim/tvhub/util/Log.kt
@@ -0,0 +1,18 @@
+package io.github.maxhayim.tvhub.util
+
+/**
+ * The only logging in the app. Messages never include a URL, a host's path or a query string:
+ * playlist URLs often carry account names and passwords. Use [redact] for anything that could.
+ */
+object Log {
+ private const val TAG = "TvHub"
+ fun w(msg: String, t: Throwable? = null) { android.util.Log.w(TAG, msg + (t?.let { ": " + it.javaClass.simpleName } ?: "")) }
+ fun i(msg: String) { android.util.Log.i(TAG, msg) }
+
+ /** "https://example.com/get.php?username=a&password=b" becomes "https://example.com/…". */
+ fun redact(url: String): String {
+ val scheme = url.substringBefore("://", "")
+ val host = url.substringAfter("://").substringBefore('/').substringBefore('?').substringAfter('@')
+ return if (scheme.isEmpty()) "…" else "$scheme://$host/…"
+ }
+}
diff --git a/addons/tv-hub/app/src/main/res/drawable-xhdpi/banner.png b/addons/tv-hub/app/src/main/res/drawable-xhdpi/banner.png
new file mode 100644
index 000000000..be8c6217e
Binary files /dev/null and b/addons/tv-hub/app/src/main/res/drawable-xhdpi/banner.png differ
diff --git a/addons/tv-hub/app/src/main/res/mipmap-hdpi/ic_launcher.png b/addons/tv-hub/app/src/main/res/mipmap-hdpi/ic_launcher.png
new file mode 100644
index 000000000..eca554e4b
Binary files /dev/null and b/addons/tv-hub/app/src/main/res/mipmap-hdpi/ic_launcher.png differ
diff --git a/addons/tv-hub/app/src/main/res/mipmap-mdpi/ic_launcher.png b/addons/tv-hub/app/src/main/res/mipmap-mdpi/ic_launcher.png
new file mode 100644
index 000000000..afc36e524
Binary files /dev/null and b/addons/tv-hub/app/src/main/res/mipmap-mdpi/ic_launcher.png differ
diff --git a/addons/tv-hub/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/addons/tv-hub/app/src/main/res/mipmap-xhdpi/ic_launcher.png
new file mode 100644
index 000000000..d3710211d
Binary files /dev/null and b/addons/tv-hub/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ
diff --git a/addons/tv-hub/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/addons/tv-hub/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
new file mode 100644
index 000000000..9c482e3ae
Binary files /dev/null and b/addons/tv-hub/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ
diff --git a/addons/tv-hub/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/addons/tv-hub/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 000000000..ce576bfc1
Binary files /dev/null and b/addons/tv-hub/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ
diff --git a/addons/tv-hub/app/src/main/res/values/colors.xml b/addons/tv-hub/app/src/main/res/values/colors.xml
new file mode 100644
index 000000000..bc46e68e4
--- /dev/null
+++ b/addons/tv-hub/app/src/main/res/values/colors.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <color name="bg">#0B0D10</color>
+ <color name="accent">#4FA3E0</color>
+</resources>
diff --git a/addons/tv-hub/app/src/main/res/values/strings.xml b/addons/tv-hub/app/src/main/res/values/strings.xml
new file mode 100644
index 000000000..231fe3e24
--- /dev/null
+++ b/addons/tv-hub/app/src/main/res/values/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">TV Hub</string>
+</resources>
diff --git a/addons/tv-hub/app/src/main/res/values/themes.xml b/addons/tv-hub/app/src/main/res/values/themes.xml
new file mode 100644
index 000000000..264c647c7
--- /dev/null
+++ b/addons/tv-hub/app/src/main/res/values/themes.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <style name="Theme.TvHub" parent="@android:style/Theme.DeviceDefault.NoActionBar">
+ <item name="android:windowBackground">@color/bg</item>
+ <item name="android:colorAccent">@color/accent</item>
+ <item name="android:windowNoTitle">true</item>
+ <item name="android:windowFullscreen">true</item>
+ </style>
+ <style name="Theme.TvHub.Player">
+ <item name="android:windowBackground">@android:color/black</item>
+ </style>
+</resources>
diff --git a/addons/tv-hub/app/src/main/res/xml/data_extraction_rules.xml b/addons/tv-hub/app/src/main/res/xml/data_extraction_rules.xml
new file mode 100644
index 000000000..fe61eb717
--- /dev/null
+++ b/addons/tv-hub/app/src/main/res/xml/data_extraction_rules.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<data-extraction-rules>
+ <cloud-backup>
+ <exclude domain="root" />
+ <exclude domain="file" />
+ <exclude domain="database" />
+ <exclude domain="sharedpref" />
+ <exclude domain="external" />
+ </cloud-backup>
+ <device-transfer>
+ <exclude domain="root" />
+ <exclude domain="file" />
+ <exclude domain="database" />
+ <exclude domain="sharedpref" />
+ <exclude domain="external" />
+ </device-transfer>
+</data-extraction-rules>
diff --git a/addons/tv-hub/app/src/main/res/xml/module_card.xml b/addons/tv-hub/app/src/main/res/xml/module_card.xml
new file mode 100644
index 000000000..81ad26c4f
--- /dev/null
+++ b/addons/tv-hub/app/src/main/res/xml/module_card.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="utf-8"?>
+<card spec="1" label="TV Hub" caption="Live channels" accent="#4FA3E0" />
diff --git a/addons/tv-hub/app/src/test/java/io/github/maxhayim/tvhub/ChannelMergerTest.kt b/addons/tv-hub/app/src/test/java/io/github/maxhayim/tvhub/ChannelMergerTest.kt
new file mode 100644
index 000000000..07f30dc38
--- /dev/null
+++ b/addons/tv-hub/app/src/test/java/io/github/maxhayim/tvhub/ChannelMergerTest.kt
@@ -0,0 +1,65 @@
+package io.github.maxhayim.tvhub
+
+import io.github.maxhayim.tvhub.model.RawChannel
+import io.github.maxhayim.tvhub.parse.ChannelMerger
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ChannelMergerTest {
+ private fun raw(src: Long, name: String, url: String, tvg: String? = null, num: String? = null, logo: String? = null, tvgName: String? = null) =
+ RawChannel(src, "S$src", name, num, tvg, tvgName, logo, null, url)
+
+ @Test fun mergesSameTvgIdAcrossSourcesKeepingBothStreams() {
+ val out = ChannelMerger.merge(listOf(raw(1, "News", "http://a/1", "news", "2"), raw(2, "News HD", "http://b/1", "NEWS", logo = "http://l")), true)
+ assertEquals(1, out.size)
+ val c = out[0]
+ assertEquals("tvg:news", c.key)
+ assertEquals("News", c.name)
+ assertEquals(listOf("http://a/1", "http://b/1"), c.streams.map { it.url })
+ assertEquals(listOf("S1", "S2"), c.sourceNames)
+ assertEquals("http://l", c.logo)
+ assertEquals(listOf("news", "NEWS"), c.epgIds)
+ }
+
+ @Test fun keepsSourcesSeparateWhenMergingIsOff() {
+ val out = ChannelMerger.merge(listOf(raw(1, "News", "http://a/1", "news"), raw(2, "News", "http://b/1", "news")), false)
+ assertEquals(2, out.size)
+ assertNotEquals(out[0].key, out[1].key)
+ }
+
+ @Test fun neverMergesByNameAlone() {
+ val out = ChannelMerger.merge(listOf(raw(1, "News", "http://a/1"), raw(2, "News", "http://b/1")), true)
+ assertEquals(2, out.size)
+ }
+
+ @Test fun duplicateNamesInOneSourceGetStableDistinctKeys() {
+ val list = listOf(raw(1, "Live", "http://a/1"), raw(1, "Live", "http://a/2"))
+ val a = ChannelMerger.merge(list, true).map { it.key }
+ val b = ChannelMerger.merge(list, true).map { it.key }
+ assertEquals(2, a.toSet().size)
+ assertEquals(a, b)
+ }
+
+ @Test fun sameUrlTwiceIsOneStream() {
+ val out = ChannelMerger.merge(listOf(raw(1, "N", "http://a/1", "n"), raw(2, "N", "http://a/1", "n")), true)
+ assertEquals(1, out.single().streams.size)
+ }
+
+ @Test fun guideIdByDisplayNameForChannelsWithoutTvgId() {
+ val out = ChannelMerger.merge(listOf(raw(1, "Movies Channel", "http://a/1"), raw(1, "Other", "http://a/2")), true, mapOf("movieschannel" to "movies.example"))
+ assertEquals(listOf("movies.example"), out.first { it.name == "Movies Channel" }.epgIds)
+ assertTrue(out.first { it.name == "Other" }.epgIds.isEmpty())
+ }
+
+ @Test fun ordersByNumberThenName() {
+ val out = ChannelMerger.merge(listOf(
+ raw(1, "Zed", "http://a/1"), raw(1, "Twelve", "http://a/2", num = "12"), raw(1, "Four ten", "http://a/3", num = "4.10"),
+ raw(1, "Four one", "http://a/4", num = "4.1"), raw(1, "Alpha", "http://a/5"),
+ ), true)
+ assertEquals(listOf("Four one", "Four ten", "Twelve", "Alpha", "Zed"), out.map { it.name })
+ }
+
+ @Test fun emptyInput() { assertTrue(ChannelMerger.merge(emptyList(), true).isEmpty()) }
+}
diff --git a/addons/tv-hub/app/src/test/java/io/github/maxhayim/tvhub/M3uParserTest.kt b/addons/tv-hub/app/src/test/java/io/github/maxhayim/tvhub/M3uParserTest.kt
new file mode 100644
index 000000000..21a246289
--- /dev/null
+++ b/addons/tv-hub/app/src/test/java/io/github/maxhayim/tvhub/M3uParserTest.kt
@@ -0,0 +1,95 @@
+package io.github.maxhayim.tvhub
+
+import io.github.maxhayim.tvhub.parse.M3uParser
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class M3uParserTest {
+ private fun parse(text: String) = M3uParser.parse(text.reader().buffered(), 7, "Test")
+ private fun fixture() = M3uParser.parse(javaClass.getResourceAsStream("/sample.m3u")!!.bufferedReader(), 7, "Test")
+
+ @Test fun readsAttributesTitleAndGroup() {
+ val r = fixture()
+ val news = r.channels[0]
+ assertEquals("Example News", news.name)
+ assertEquals("news.example", news.tvgId)
+ assertEquals("Example News HD", news.tvgName)
+ assertEquals("2", news.number)
+ assertEquals("News", news.group)
+ assertEquals("http://192.168.1.10:8000/logos/news.png", news.logo)
+ assertEquals(7L, news.sourceId)
+ }
+
+ @Test fun commaInsideQuotedValueDoesNotStartTheTitle() {
+ val sport = fixture().channels[1]
+ assertEquals("Sport, Live", sport.group)
+ assertEquals("Example Sport, Weekend", sport.name)
+ assertEquals("5.1", sport.number)
+ }
+
+ @Test fun vlcOptionsBecomeHeaders() {
+ val sport = fixture().channels[1]
+ assertEquals("ExamplePlayer/2.0", sport.userAgent)
+ assertEquals("http://192.168.1.10/", sport.referrer)
+ assertNull(fixture().channels[0].userAgent)
+ }
+
+ @Test fun extgrpAppliesWhenThereIsNoGroupTitle() {
+ assertEquals("Movies", fixture().channels[2].group)
+ }
+
+ @Test fun skipsNonHttpStreamsAndCountsThem() {
+ val r = fixture()
+ assertEquals(1, r.skipped)
+ assertTrue(r.channels.none { it.url.startsWith("udp") })
+ }
+
+ @Test fun emptyTvgIdAndNonHttpLogoAreDropped() {
+ val kids = fixture().channels.first { it.name == "Kids" }
+ assertNull(kids.tvgId)
+ assertNull(kids.logo)
+ }
+
+ @Test fun bareUrlGetsNameFromPath() {
+ val bare = fixture().channels.last()
+ assertEquals("stream.ts", bare.name)
+ assertNull(bare.group)
+ }
+
+ @Test fun headerGuideUrlsAreCollectedOnce() {
+ assertEquals(listOf("http://192.168.1.10:8000/guide.xml.gz", "http://192.168.1.10:8000/extra.xml"), fixture().epgUrls)
+ }
+
+ @Test fun byteOrderMarkAndCrlfAreTolerated() {
+ val r = parse("\uFEFF#EXTM3U\r\n#EXTINF:-1,One\r\nhttp://h/1\r\n")
+ assertEquals(1, r.channels.size)
+ assertEquals("One", r.channels[0].name)
+ assertEquals("http://h/1", r.channels[0].url)
+ }
+
+ @Test fun emptyAndInvalidInput() {
+ val empty = parse("")
+ assertTrue(empty.channels.isEmpty())
+ assertFalse(empty.isPlaylist)
+ val html = parse("<html><body>Not found</body></html>")
+ assertFalse(html.isPlaylist)
+ val headerOnly = parse("#EXTM3U\n")
+ assertTrue(headerOnly.isPlaylist)
+ assertTrue(headerOnly.channels.isEmpty())
+ }
+
+ @Test fun infoWithoutUrlDoesNotLeakIntoNextEntry() {
+ val r = parse("#EXTM3U\n#EXTINF:-1 tvg-id=\"a\",A\nrtmp://x/a\n#EXTINF:-1,B\nhttp://h/b\n")
+ assertEquals(1, r.channels.size)
+ assertEquals("B", r.channels[0].name)
+ assertNull(r.channels[0].tvgId)
+ }
+
+ @Test fun attributeParsingIsCaseInsensitiveOnKeysAndFirstWins() {
+ val a = parse("#EXTM3U\n#EXTINF:-1 TVG-ID=\"x\" tvg-id=\"y\",N\nhttp://h/n\n").channels[0]
+ assertEquals("x", a.tvgId)
+ }
+}
diff --git a/addons/tv-hub/app/src/test/java/io/github/maxhayim/tvhub/ProvidersTest.kt b/addons/tv-hub/app/src/test/java/io/github/maxhayim/tvhub/ProvidersTest.kt
new file mode 100644
index 000000000..723b09272
--- /dev/null
+++ b/addons/tv-hub/app/src/test/java/io/github/maxhayim/tvhub/ProvidersTest.kt
@@ -0,0 +1,47 @@
+package io.github.maxhayim.tvhub
+
+import io.github.maxhayim.tvhub.model.SourceConfig
+import io.github.maxhayim.tvhub.model.SourceType
+import io.github.maxhayim.tvhub.source.HdHomeRun
+import io.github.maxhayim.tvhub.source.Providers
+import io.github.maxhayim.tvhub.util.Log
+import org.json.JSONArray
+import org.junit.Assert.assertEquals
+import org.junit.Test
+import java.util.zip.CRC32
+
+class ProvidersTest {
+ @Test fun dispatcharrOutputUrls() {
+ assertEquals("http://nas:9191/output/m3u" to "http://nas:9191/output/epg", Providers.dispatcharrUrls("http://nas:9191/", ""))
+ assertEquals("http://nas:9191/output/m3u/Living%20Room" to "http://nas:9191/output/epg/Living%20Room", Providers.dispatcharrUrls(" http://nas:9191 ", "Living Room"))
+ }
+
+ @Test fun hdhomerunLineupSkipsDrmAndAddsTranscode() {
+ val arr = JSONArray("""[
+ {"GuideNumber":"2.1","GuideName":"KABC","URL":"http://192.168.1.50:5004/auto/v2.1"},
+ {"GuideNumber":"7.1","GuideName":"Cable","URL":"http://192.168.1.50:5004/auto/v7.1","DRM":1},
+ {"GuideNumber":"9.1","GuideName":"","URL":"http://192.168.1.50:5004/auto/v9.1"}
+ ]""")
+ val cfg = SourceConfig(id = 3, type = SourceType.HDHOMERUN, name = "Antenna", transcode = true)
+ val r = HdHomeRun.parseLineup(arr, cfg)
+ assertEquals(1, r.skipped)
+ assertEquals(listOf("KABC", "9.1"), r.channels.map { it.name })
+ assertEquals("http://192.168.1.50:5004/auto/v2.1?transcode=heavy", r.channels[0].url)
+ assertEquals("2.1", r.channels[0].number)
+ }
+
+ @Test fun hdhomerunDiscoverPacketHasValidCrc() {
+ val p = HdHomeRun.request()
+ assertEquals(20, p.size)
+ assertEquals(2, p[1].toInt()) // discover request
+ val crc = CRC32().apply { update(p, 0, 16) }.value
+ val le = (p[16].toLong() and 0xff) or ((p[17].toLong() and 0xff) shl 8) or ((p[18].toLong() and 0xff) shl 16) or ((p[19].toLong() and 0xff) shl 24)
+ assertEquals(crc, le)
+ }
+
+ @Test fun redactHidesPathAndQuery() {
+ assertEquals("http://iptv.example:8080/…", Log.redact("http://iptv.example:8080/get.php?username=me&password=secret"))
+ assertEquals("https://host/…", Log.redact("https://user:pw@host/path"))
+ assertEquals("…", Log.redact("garbage"))
+ }
+}
diff --git a/addons/tv-hub/app/src/test/java/io/github/maxhayim/tvhub/XmltvParserTest.kt b/addons/tv-hub/app/src/test/java/io/github/maxhayim/tvhub/XmltvParserTest.kt
new file mode 100644
index 000000000..2fcc1adef
--- /dev/null
+++ b/addons/tv-hub/app/src/test/java/io/github/maxhayim/tvhub/XmltvParserTest.kt
@@ -0,0 +1,81 @@
+package io.github.maxhayim.tvhub
+
+import io.github.maxhayim.tvhub.model.Programme
+import io.github.maxhayim.tvhub.parse.XmltvParser
+import io.github.maxhayim.tvhub.parse.XmltvTime
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.kxml2.io.KXmlParser
+
+class XmltvParserTest {
+ private val t1800 = XmltvTime.parse("20261022180000 +0000")!!
+
+ private fun run(wanted: Set<String>, names: Set<String> = emptySet(), from: Long = t1800 - 86_400_000, to: Long = t1800 + 2 * 86_400_000L): Pair<XmltvParser, List<Programme>> {
+ val p = KXmlParser()
+ p.setInput(javaClass.getResourceAsStream("/sample.xml"), null)
+ val x = XmltvParser(wanted, names, from, to)
+ val out = ArrayList<Programme>()
+ x.parse(p) { out += it }
+ return x to out
+ }
+
+ @Test fun timesWithOffsetsAndWithout() {
+ assertEquals(1792692000000L, t1800) // 2026-10-22 18:00 UTC
+ assertEquals(t1800 - 2 * 3_600_000, XmltvTime.parse("20261022180000 +0200"))
+ assertEquals(t1800 + 5 * 3_600_000 + 30 * 60_000, XmltvTime.parse("20261022180000 -0530"))
+ assertEquals(t1800, XmltvTime.parse("20261022180000"))
+ assertEquals(t1800, XmltvTime.parse("202610221800"))
+ assertEquals(t1800 + 60 * 60_000, XmltvTime.parse("20261022180000 +01:00".replace("+01:00", "-01:00")))
+ assertNull(XmltvTime.parse("garbage"))
+ assertNull(XmltvTime.parse("20261322180000 +0000"))
+ assertNull(XmltvTime.parse(null))
+ }
+
+ @Test fun keepsOnlyWantedChannelsInTheWindow() {
+ val (x, list) = run(setOf("news.example", "sport.example"))
+ assertEquals(listOf("Evening News", "Weather", "Match Day"), list.map { it.title })
+ assertEquals(4, x.channelCount)
+ }
+
+ @Test fun readsSubtitleDescriptionCategoryAndEntities() {
+ val news = run(setOf("news.example")).second.first()
+ assertEquals("Headlines", news.subtitle)
+ assertEquals("The day's news & weather.", news.description)
+ assertEquals("News", news.category)
+ assertEquals(t1800, news.start)
+ assertEquals(t1800 + 3_600_000, news.stop)
+ }
+
+ @Test fun offsetIsAppliedToProgrammeTimes() {
+ val sport = run(setOf("sport.example")).second.single()
+ assertEquals(t1800 - 2 * 3_600_000, sport.start)
+ }
+
+ @Test fun matchesChannelsWithoutIdByDisplayName() {
+ val (x, list) = run(emptySet(), names = setOf(XmltvParser.normalise("Movies Channel")))
+ assertEquals("movies.example", x.nameMatches["movieschannel"])
+ assertEquals(listOf("Feature Film"), list.map { it.title })
+ }
+
+ @Test fun windowExcludesPastAndFarFuture() {
+ val (_, list) = run(setOf("news.example"), from = t1800 + 3_600_000, to = t1800 + 2 * 3_600_000)
+ assertEquals(listOf("Weather"), list.map { it.title })
+ }
+
+ @Test fun badTimesAreSkipped() {
+ val titles = run(setOf("news.example"), to = t1800 + 30 * 86_400_000L).second.map { it.title }
+ assertTrue("Bad time" !in titles)
+ assertTrue("Stop before start" !in titles)
+ assertTrue("Too far ahead" in titles)
+ }
+
+ @Test fun emptyGuide() {
+ val p = KXmlParser(); p.setInput("<tv></tv>".reader())
+ val x = XmltvParser(setOf("a"), emptySet(), 0, Long.MAX_VALUE)
+ var n = 0
+ x.parse(p) { n++ }
+ assertEquals(0, n); assertEquals(0, x.channelCount)
+ }
+}
diff --git a/addons/tv-hub/app/src/test/resources/sample.m3u b/addons/tv-hub/app/src/test/resources/sample.m3u
new file mode 100644
index 000000000..8b3ae8f2f
--- /dev/null
+++ b/addons/tv-hub/app/src/test/resources/sample.m3u
@@ -0,0 +1,16 @@
+#EXTM3U x-tvg-url="http://192.168.1.10:8000/guide.xml.gz,http://192.168.1.10:8000/extra.xml" url-tvg="http://192.168.1.10:8000/guide.xml.gz"
+#EXTINF:-1 tvg-id="news.example" tvg-name="Example News HD" tvg-logo="http://192.168.1.10:8000/logos/news.png" tvg-chno="2" group-title="News",Example News
+http://192.168.1.10:8000/live/news.m3u8
+#EXTINF:-1 tvg-id="sport.example" tvg-chno="5.1" group-title="Sport, Live",Example Sport, Weekend
+#EXTVLCOPT:http-user-agent=ExamplePlayer/2.0
+#EXTVLCOPT:http-referrer=http://192.168.1.10/
+http://192.168.1.10:8000/live/sport.ts
+#EXTINF:-1 tvg-name="Movies Channel",Movies Channel
+#EXTGRP:Movies
+https://streams.example.test/movies/index.m3u8?token=abc
+#EXTINF:-1,Multicast only
+udp://@239.0.0.1:1234
+#EXTINF:-1 tvg-id="" tvg-logo="ftp://bad/logo.png",Kids
+http://192.168.1.10:8000/live/kids.m3u8
+
+http://192.168.1.10:8000/bare/stream.ts
diff --git a/addons/tv-hub/app/src/test/resources/sample.xml b/addons/tv-hub/app/src/test/resources/sample.xml
new file mode 100644
index 000000000..e990b5c6b
--- /dev/null
+++ b/addons/tv-hub/app/src/test/resources/sample.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE tv SYSTEM "xmltv.dtd">
+<tv generator-info-name="tv-hub fixture">
+ <channel id="news.example"><display-name>Example News</display-name><icon src="http://192.168.1.10:8000/logos/news.png"/></channel>
+ <channel id="sport.example"><display-name lang="en">Example Sport</display-name></channel>
+ <channel id="movies.example"><display-name>Movies-Channel</display-name><display-name>Movies</display-name></channel>
+ <channel id="unused.example"><display-name>Nobody Watches</display-name></channel>
+ <programme start="20261022180000 +0000" stop="20261022190000 +0000" channel="news.example">
+ <title lang="en">Evening News</title><sub-title>Headlines</sub-title><desc lang="en">The day's news &amp; weather.</desc><category>News</category>
+ </programme>
+ <programme start="20261022190000 +0000" stop="20261022193000 +0000" channel="news.example"><title>Weather</title></programme>
+ <programme start="20261022180000 +0200" stop="20261022200000 +0200" channel="sport.example"><title>Match Day</title></programme>
+ <programme start="20261022180000" stop="20261022200000" channel="movies.example"><title>Feature Film</title></programme>
+ <programme start="20261022180000 +0000" stop="20261022190000 +0000" channel="unused.example"><title>Ignored</title></programme>
+ <programme start="20261030180000 +0000" stop="20261030190000 +0000" channel="news.example"><title>Too far ahead</title></programme>
+ <programme start="garbage" stop="20261022190000 +0000" channel="news.example"><title>Bad time</title></programme>
+ <programme start="20261022190000 +0000" stop="20261022180000 +0000" channel="news.example"><title>Stop before start</title></programme>
+</tv>
diff --git a/addons/tv-hub/build.gradle.kts b/addons/tv-hub/build.gradle.kts
new file mode 100644
index 000000000..c7ad7549e
--- /dev/null
+++ b/addons/tv-hub/build.gradle.kts
@@ -0,0 +1,4 @@
+plugins {
+ id("com.android.application") version "8.7.3" apply false
+ id("org.jetbrains.kotlin.android") version "2.0.21" apply false
+}
diff --git a/addons/tv-hub/docs/TESTING.md b/addons/tv-hub/docs/TESTING.md
new file mode 100644
index 000000000..d48f699ae
--- /dev/null
+++ b/addons/tv-hub/docs/TESTING.md
@@ -0,0 +1,122 @@
+# Testing TV Hub
+
+## Automated (runs on any computer, and in CI)
+
+```bash
+./gradlew testDebugUnitTest lintDebug assembleDebug assembleRelease
+```
+
+- `M3uParserTest`: attributes, quoted commas, `#EXTGRP`, `#EXTVLCOPT`, skipped schemes, BOM and CRLF, empty and non-playlist input.
+- `XmltvParserTest`: time formats and offsets, wanted-channel filtering, the time window, display-name matching, bad times, entities, an empty guide.
+- `ChannelMergerTest`: merging by `tvg-id` only, merging off, stable keys for duplicates, guide ids by name, ordering by channel number.
+- `ProvidersTest`: Dispatcharr addresses, HDHomeRun lineup (DRM skipped, transcode), the discovery packet's CRC, log redaction.
+
+To check the card made it into the APK: `aapt2 dump xmltree app/build/outputs/apk/debug/app-debug.apk --file res/xml/module_card.xml`
+should print `label="TV Hub"`, `caption="Live channels"`, `spec=1` and `accent=#ff4fa3e0`.
+None of this proves anything on a TV; the rest of this page does.
+
+## Demo sources
+
+```bash
+python3 tools/make_fixtures.py <this computer's LAN IP>
+python3 -m http.server --directory fixtures/out 8000
+```
+
+| Address | Exercises |
+| :- | :- |
+| `http://IP:8000/demo.m3u` | Six entries: one working HLS stream (Big Buck Bunny, CC BY), a 404 stream, a stream that falls back, a channel with no guide, an unreachable host, and a `udp://` entry that is skipped. Its header names `demo.xml` |
+| `http://IP:8000/backup.m3u` | Shares `tvg-id` with channel 3: with merging on, 3 fails on demo and plays from here |
+| `http://IP:8000/demo.xml` | Listings for three channels from an hour ago to two days ahead (regenerate it each day) |
+| `http://IP:8000/empty.m3u` | Empty playlist: the source shows an error, nothing else breaks |
+| `http://IP:8000/invalid.xml` | Broken guide: "The guide is not valid XMLTV", channels stay |
+
+For a stream that does not leave your network, any HLS or MPEG-TS file served over http works, for example
+`ffmpeg -re -f lavfi -i testsrc2=size=1280x720:rate=25 -f lavfi -i sine -c:v libx264 -c:a aac -f hls -hls_time 4 -hls_list_size 6 -hls_flags delete_segments fixtures/out/local.m3u8`.
+
+## On a TV
+
+Install: `adb install -r app/build/outputs/apk/debug/app-debug.apk`. Write down the TV model and Android version for each run.
+
+### 1. Install and first launch
+- [ ] TV Hub appears in the app row (Android TV / Google TV) or Apps > Your Apps (Fire TV) with its banner.
+- [ ] First launch shows the welcome page; **Skip for now** opens Home with "No sources yet".
+- [ ] Settings > Run setup again brings the welcome page back.
+
+### 2. Sources
+- [ ] Add `demo.m3u`; **Check** reports "Found 5 channels, 1 skipped and a guide address".
+- [ ] After saving, Sources shows 5 channels, "1 entries skipped", and a time.
+- [ ] A wrong address (`http://IP:8000/nope.m3u`) shows "Nothing at that address (HTTP 404)" on Check and, if saved, in red on Sources.
+- [ ] `empty.m3u` shows an error; `invalid.xml` as an XMLTV source shows "not valid XMLTV"; the demo channels stay.
+- [ ] Stop the http.server and press Refresh: sources show errors, channels from the last refresh stay.
+- [ ] Turn a source off: its channels leave Live TV and the Guide. Turn it on: they come back.
+
+### 3. Guide and lists
+- [ ] Guide: rows for channels 1 to 5; 1 to 3 have listings, 4 says "No guide information", the now line is at the current time.
+- [ ] Up/Down move between channels, Left/Right between programmes; Left from the first programme returns to the menu.
+- [ ] OK on a programme on air plays it; OK on a later one opens details with Watch and Favorite.
+- [ ] Hold OK: star appears; the Favorites page and the Favorites chip list it.
+- [ ] Live TV: categories (All, Favorites, Demo, Sport, Films), search "spo" finds Demo Sport, number "3" finds it too.
+- [ ] Home: Recently watched fills after playing; Favorites row; Apps row if apps are picked.
+
+### 4. Player
+- [ ] Channel 1 plays within a few seconds with a spinner while loading; the banner shows now/next.
+- [ ] Up/Down and Channel +/- change channel; Left returns to the previous one; typing 4 tunes channel 4.
+- [ ] Channel 2 (404) shows "The stream was not found…" or "refused it"; OK retries; Up moves on.
+- [ ] Channel 5 (unreachable) retries, then shows "Can't reach the stream's server".
+- [ ] With `backup.m3u` added and merging on, channel 3 shows "Trying …backup" and plays.
+- [ ] Menu (or hold OK) lists audio tracks and "Subtitles: off".
+- [ ] Back returns to the page you started from. Home button during playback, then `adb shell dumpsys media.audio_flinger | grep -i tvhub` or `top`: no TV Hub playback continues.
+
+### 5. Providers that need hardware
+- [ ] HDHomeRun: **Scan the network** finds the tuner; channels play (tick H.264 on an EXTEND if there is sound but no picture).
+- [ ] Dispatcharr: server address and an output profile; with the TV's network not allowed, the 403 message appears.
+- [ ] Streaming apps: installed known apps are pre-ticked; "Show every TV app" lists the rest; the Home shortcut opens the app; uninstall the app and it disappears from Home.
+
+### 6. CleanYourTV module card
+On a TV running CleanYourTV (com.gathin.tvhome) or a fork that keeps its card category:
+
+```bash
+adb shell pm dump io.github.maxhayim.tvhub | grep -B2 -A6 DOCK_CARD
+adb shell input keyevent KEYCODE_HOME
+adb logcat -d -s TvHomeCards
+```
+
+- [ ] The prompt names TV Hub, its package and the key's first twelve hex digits. **Keep hidden** leaves the ordinary tile.
+- [ ] Hold OK on Settings > Module cards: set TV Hub to Shown; the card replaces the tile, shows "TV Hub · Live channels" focused, and glows blue in the dock.
+- [ ] OK on the card opens TV Hub; holding OK opens App info.
+- [ ] `adb logcat -d -s TvHomeCards` has no rejection line for io.github.maxhayim.tvhub.
+- [ ] Uninstall: the card is gone; reinstall the same build: no new prompt.
+
+### 7. Platforms
+| Check | Android TV | Google TV | Fire TV |
+| :- | :- | :- | :- |
+| Installs from adb | | | |
+| Banner in the app list | | | |
+| D-pad, Back, Menu work | | | Menu is the ≡ button |
+| Text entry opens the TV keyboard | | | |
+| HLS demo plays | | | |
+| 720p and 4K output: text readable, nothing cut off | | | |
+
+### 8. Constrained hardware
+On a 1 GB TV: add a playlist with a few thousand channels and a full XMLTV guide; time the refresh;
+scroll the guide with Down held: it should keep up without the TV stalling. `adb shell dumpsys meminfo io.github.maxhayim.tvhub`
+after scrolling should stay well under 150 MB total PSS. Settings > Animations off for slow TVs.
+
+## Results so far
+
+### 2026-10-22, MOKA R8G (Realtek, Android 14, 1080p output, 2 GB RAM), debug build (Media3 1.5.1, SDK 35; the add-on builds with 1.4.1 and SDK 34), launcher: a custom home without module-card support
+
+Passed on the TV:
+- Install over adb; first launch shows the welcome page; M3U form with the TV keyboard; Check reports "Found 5 channels, 1 skipped and a guide address".
+- Header guide (`x-tvg-url`) read; Guide grid with logos, now line, listings, "No guide information" rows; Left/Right/Up/Down keep the cursor's time; programme details for a later programme.
+- Playback of HLS (H.264 + AAC, Media3 READY in about 3 s), channel up/down, number entry, previous channel, audio/subtitle menu, Back releases the player (`ExoPlayerImpl: Release`).
+- Errors: 404 stream message; unreachable host gives up after about 20 s (was 62 s before the load-retry limit).
+- Merge and fallback: channel 3's dead stream fails and plays from the second source about 3 s later.
+- Favourites by holding OK in the guide; Favorites page and Home rows; search by name and number.
+- Streaming apps: six installed apps detected through `<queries>` (Pluto TV, Tubi, Plex, YouTube TV, Sling TV, Philo), shown with their own banners as "Opens the app".
+- Database upgrade from schema 1 to 2 on an installed copy.
+- Memory: about 54 MB PSS while browsing.
+
+Fixed during this run: guide wiped when a source failed a refresh; focus switching the page after returning from the editor; card text drawn behind logos; zoomed focus clipped; error text for 404s; playlist status plurals.
+
+Not tested yet: the module card (this TV's launcher does not read cards), HDHomeRun and Dispatcharr (no hardware or server on hand), Fire TV, Google TV, 720p and 4K output modes, a large real playlist and guide.
diff --git a/addons/tv-hub/gradle.properties b/addons/tv-hub/gradle.properties
new file mode 100644
index 000000000..5f4cff371
--- /dev/null
+++ b/addons/tv-hub/gradle.properties
@@ -0,0 +1,4 @@
+org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
+android.useAndroidX=true
+android.nonTransitiveRClass=true
+kotlin.code.style=official
diff --git a/addons/tv-hub/gradle/wrapper/gradle-wrapper.jar b/addons/tv-hub/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 000000000..2c3521197
Binary files /dev/null and b/addons/tv-hub/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/addons/tv-hub/gradle/wrapper/gradle-wrapper.properties b/addons/tv-hub/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000..9715a887c
--- /dev/null
+++ b/addons/tv-hub/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,8 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
+distributionSha256Sum=f397b287023acdba1e9f6fc5ea72d22dd63669d59ed4a289a29b1a76eee151c6
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/addons/tv-hub/gradlew b/addons/tv-hub/gradlew
new file mode 100755
index 000000000..f5feea6d6
--- /dev/null
+++ b/addons/tv-hub/gradlew
@@ -0,0 +1,252 @@
+#!/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
+' "$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=$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
+ 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, 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" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# 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/addons/tv-hub/gradlew.bat b/addons/tv-hub/gradlew.bat
new file mode 100644
index 000000000..9d21a2183
--- /dev/null
+++ b/addons/tv-hub/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=%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% 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/addons/tv-hub/settings.gradle.kts b/addons/tv-hub/settings.gradle.kts
new file mode 100644
index 000000000..e5879a811
--- /dev/null
+++ b/addons/tv-hub/settings.gradle.kts
@@ -0,0 +1,16 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+rootProject.name = "tv-hub"
+include(":app")
diff --git a/addons/tv-hub/tools/make_art.py b/addons/tv-hub/tools/make_art.py
new file mode 100644
index 000000000..7bd8f46ce
--- /dev/null
+++ b/addons/tv-hub/tools/make_art.py
@@ -0,0 +1,47 @@
+"""Draws TV Hub's banner and launcher icon: a rounded screen with two antennas and a live dot.
+Usage: python3 tools/make_art.py <font.ttf> (any sans-serif TTF; the repo's PNGs used Outfit)."""
+import sys
+from pathlib import Path
+from PIL import Image, ImageDraw, ImageFont
+
+RES = Path(__file__).resolve().parent.parent / "app/src/main/res"
+BG, ACCENT, INK, LIVE = (17, 22, 29), (79, 163, 224), (242, 244, 247), (229, 72, 77)
+S = 4 # supersampling
+
+
+def glyph(d, cx, cy, w):
+ h = w * 0.62
+ x0, y0 = cx - w / 2, cy - h / 2 + w * 0.08
+ lw = max(2, int(w * 0.07))
+ d.line([(cx, y0), (cx - w * 0.22, y0 - w * 0.24)], fill=ACCENT, width=lw)
+ d.line([(cx, y0), (cx + w * 0.22, y0 - w * 0.24)], fill=ACCENT, width=lw)
+ d.rounded_rectangle([x0, y0, x0 + w, y0 + h], radius=w * 0.14, outline=ACCENT, width=lw, fill=(24, 34, 46))
+ r = w * 0.07
+ d.ellipse([cx - r, cy + w * 0.08 - r, cx + r, cy + w * 0.08 + r], fill=LIVE)
+
+
+def banner(font):
+ W, H = 320 * S, 180 * S
+ im = Image.new("RGB", (W, H), BG)
+ d = ImageDraw.Draw(im)
+ glyph(d, 78 * S, 92 * S, 92 * S)
+ f = ImageFont.truetype(font, 46 * S)
+ d.text((140 * S, 90 * S), "TV Hub", font=f, fill=INK, anchor="lm")
+ out = RES / "drawable-xhdpi" / "banner.png"
+ out.parent.mkdir(parents=True, exist_ok=True)
+ im.resize((320, 180), Image.LANCZOS).save(out, optimize=True)
+
+
+def icon():
+ for name, px in {"mdpi": 48, "hdpi": 72, "xhdpi": 96, "xxhdpi": 144, "xxxhdpi": 192}.items():
+ im = Image.new("RGBA", (px * S, px * S), (0, 0, 0, 0))
+ d = ImageDraw.Draw(im)
+ d.rounded_rectangle([0, 0, px * S - 1, px * S - 1], radius=px * S * 0.22, fill=BG)
+ glyph(d, px * S / 2, px * S / 2, px * S * 0.62)
+ out = RES / f"mipmap-{name}" / "ic_launcher.png"
+ out.parent.mkdir(parents=True, exist_ok=True)
+ im.resize((px, px), Image.LANCZOS).save(out, optimize=True)
+
+
+banner(sys.argv[1])
+icon()
diff --git a/addons/tv-hub/tools/make_fixtures.py b/addons/tv-hub/tools/make_fixtures.py
new file mode 100644
index 000000000..065d8f2ca
--- /dev/null
+++ b/addons/tv-hub/tools/make_fixtures.py
@@ -0,0 +1,91 @@
+"""Writes a demo playlist and guide for testing TV Hub on a TV, with programmes around the current time.
+
+Usage:
+ python3 tools/make_fixtures.py 192.168.1.20 # this computer's LAN address
+ python3 -m http.server --directory fixtures/out 8000
+
+Then add http://192.168.1.20:8000/demo.m3u as an M3U source (its header names demo.xml as the guide),
+and optionally http://192.168.1.20:8000/backup.m3u to test merging and stream fallback.
+
+Content: the only working stream is Big Buck Bunny (c) Blender Foundation, CC BY 3.0
+(https://peach.blender.org), as published by Mux at test-streams.mux.dev for player testing.
+Every other entry is made up to exercise error handling. Logos are drawn here, not downloaded.
+"""
+import struct
+import sys
+import time
+import zlib
+from pathlib import Path
+
+HOST = sys.argv[1] if len(sys.argv) > 1 else "127.0.0.1"
+PORT = sys.argv[2] if len(sys.argv) > 2 else "8000"
+BASE = f"http://{HOST}:{PORT}"
+OUT = Path(__file__).resolve().parent.parent / "fixtures" / "out"
+OUT.mkdir(parents=True, exist_ok=True)
+BUNNY = "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8"
+
+
+def png(path, rgb):
+ """A 160x90 solid PNG, so logo loading can be tested without third-party logos."""
+ w, h = 160, 90
+ raw = b"".join(b"\x00" + bytes(rgb) * w for _ in range(h))
+ def chunk(t, d): return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
+ data = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
+ path.write_bytes(data)
+
+
+(OUT / "logos").mkdir(exist_ok=True)
+for name, rgb in {"bunny": (79, 163, 224), "news": (229, 72, 77), "sport": (91, 199, 130), "film": (200, 162, 107)}.items():
+ png(OUT / "logos" / f"{name}.png", rgb)
+
+(OUT / "demo.m3u").write_text(f'''#EXTM3U x-tvg-url="{BASE}/demo.xml"
+#EXTINF:-1 tvg-id="bunny.demo" tvg-chno="1" tvg-logo="{BASE}/logos/bunny.png" group-title="Demo",Big Buck Bunny
+{BUNNY}
+#EXTINF:-1 tvg-id="news.demo" tvg-chno="2" tvg-logo="{BASE}/logos/news.png" group-title="Demo",Demo News (dead stream)
+{BASE}/missing/news.m3u8
+#EXTINF:-1 tvg-id="sport.demo" tvg-chno="3" tvg-logo="{BASE}/logos/sport.png" group-title="Sport",Demo Sport (falls back)
+{BASE}/missing/sport.m3u8
+#EXTINF:-1 tvg-chno="4" tvg-logo="{BASE}/logos/film.png" group-title="Films",Film Channel (no guide)
+{BUNNY}
+#EXTINF:-1 tvg-chno="5" group-title="Demo",Unreachable host
+http://192.0.2.1:9/never.m3u8
+#EXTINF:-1,Multicast (skipped, not http)
+udp://@239.0.0.1:1234
+''')
+
+# A second source that shares tvg-id sport.demo, with a working stream: with merging on, channel 3
+# fails on the first source and the player moves to this one.
+(OUT / "backup.m3u").write_text(f'''#EXTM3U
+#EXTINF:-1 tvg-id="sport.demo" tvg-chno="3" group-title="Sport",Demo Sport backup
+{BUNNY}
+''')
+
+def t(ms): return time.strftime("%Y%m%d%H%M%S +0000", time.gmtime(ms / 1000))
+
+now = int(time.time() * 1000)
+slot = now - now % 1_800_000
+progs = []
+for ch, names, length in [
+ ("bunny.demo", ["Big Buck Bunny", "Behind the Bunny", "Meadow Live"], 60),
+ ("news.demo", ["Morning Headlines", "Weather", "World Report", "Local News"], 30),
+ ("sport.demo", ["Match Preview", "Live Match", "Highlights"], 90),
+]:
+ start = slot - 3_600_000
+ i = 0
+ while start < now + 2 * 86_400_000:
+ stop = start + length * 60_000
+ title = names[i % len(names)]
+ progs.append(f' <programme start="{t(start)}" stop="{t(stop)}" channel="{ch}"><title lang="en">{title}</title>'
+ f'<desc lang="en">Made-up listing number {i + 1} for testing the guide.</desc><category>Demo</category></programme>')
+ start = stop
+ i += 1
+
+(OUT / "demo.xml").write_text('<?xml version="1.0" encoding="UTF-8"?>\n<tv generator-info-name="tv-hub make_fixtures.py">\n'
+ ' <channel id="bunny.demo"><display-name>Big Buck Bunny</display-name></channel>\n'
+ ' <channel id="news.demo"><display-name>Demo News</display-name></channel>\n'
+ ' <channel id="sport.demo"><display-name>Demo Sport</display-name></channel>\n'
+ + "\n".join(progs) + "\n</tv>\n")
+(OUT / "empty.m3u").write_text("")
+(OUT / "invalid.xml").write_text("<tv><programme start=")
+print(f"Wrote {OUT}: demo.m3u, backup.m3u, demo.xml ({len(progs)} programmes), empty.m3u, invalid.xml")
+print(f"Serve with: python3 -m http.server --directory {OUT} {PORT}")