Commit e675ea9642

e675ea96422047c4ee46823015201334a75886ed

parent: 3bfcdea64b

Unsigned

Wraient <wraient.911@gmail.com> · 2026-04-05 18:04 UTC

add: explict android support

Layout: unified · split

Build/buildandroid added +3
@@ -0,0 +1,3 @@
1#!/bin/bash
2
3./Build/buildandroid-arm64
Build/buildandroid-arm64 added +4
@@ -0,0 +1,4 @@
1#!/bin/bash
2
3VERSION=$(cat VERSION.txt)
4CGO_ENABLED=0 GOOS=android GOARCH=arm64 go build -o curd-android-arm64 -ldflags="-X main.version=${VERSION} -s -w" -trimpath cmd/curd/main.go
Build/install-termux.sh added +17
@@ -0,0 +1,17 @@
1#!/data/data/com.termux/files/usr/bin/bash
2set -euo pipefail
3
4REPO="${REPO:-wraient/curd}"
5ASSET="${ASSET:-curd-android-arm64}"
6INSTALL_DIR="${PREFIX:-/data/data/com.termux/files/usr}/bin"
7TARGET="${INSTALL_DIR}/curd"
8TMP="$(mktemp)"
9
10echo "Downloading ${ASSET} from ${REPO}..."
11curl -fsSL "https://github.com/${REPO}/releases/latest/download/${ASSET}" -o "${TMP}"
12chmod +x "${TMP}"
13mkdir -p "${INSTALL_DIR}"
14mv "${TMP}" "${TARGET}"
15
16echo "Installed curd to ${TARGET}"
17echo "Run: curd --android-setup"
README.md +20 −1
@@ -1,7 +1,7 @@
11# Curd
22
33A cli application to stream anime with [Anilist](https://anilist.co/) integration and Discord RPC written in golang.
4Works on Windows and Linux
4Works on Windows, Linux, macOS, and Android via Termux
55
66## Join the discord server
77
@@ -35,6 +35,25 @@ https://github.com/user-attachments/assets/cbf799bc-9fdd-4402-ab61-b4e31f1e264d
3535## Installing and Setup
3636> **Note**: `Curd` requires `mpv`, `rofi`, and `ueberzugpp` for Rofi support and image preview. These are included in the installation instructions below for each distribution.
3737
38### Android / Termux
39
40```bash
41pkg install curl termux-api
42curl -fsSL https://raw.githubusercontent.com/Wraient/curd/main/Build/install-termux.sh | bash
43curd --android-setup
44```
45
46Android mode keeps the terminal UI inside Termux, writes config to `~/.config/curd/android.conf`, and supports two playback modes:
47- `ipc`: full automation when the configured Android player exposes MPV-compatible control
48- `intent`: basic fallback launch mode with no reliable progress/control channel
49
50`mpvEx` is built on libmpv and does load its own `mpv.conf`, but `curd` cannot rely on MPV socket IPC with `mpvEx` on stock Android:
51- `VIEW` intent extras do not appear to expose arbitrary MPV CLI options.
52- `mpvEx` copies `mpv.conf` into its own app sandbox, not Termux's `~/.config/mpv/mpv.conf`.
53- Unix socket paths inside Termux are not writable by another app, and shared storage is not a usable place for MPV Unix sockets.
54
55So `curd` currently uses `mpvEx` in `intent` mode unless `mpvEx` adds an exported control bridge that Termux can reach.
56
3857### Linux
3958<details>
4059<summary>Arch Linux / Manjaro (AUR-based systems)</summary>
android-plan.md added +155
@@ -0,0 +1,155 @@
1# Android / Termux Support for Curd
2
3## Summary
4Add a dedicated Android-on-Termux mode that keeps `curd` terminal-first, uses a separate Android config schema, and introduces an Android playback backend instead of assuming desktop `mpv` process control.
5
6Target outcome:
7- Android users run `curd` inside Termux with a mobile-tuned TUI.
8- Playback opens in a user-selected Android mpv app or mpv fork package.
9- Full watch-flow features are supported only when that player path exposes MPV-compatible IPC/control.
10- Desktop config stays clean; Android gets its own config file and only Android-relevant options.
11
12## Implementation Changes
13- Add platform detection in startup:
14 - Detect Termux/Android from `runtime.GOOS == "android"` or Termux env markers.
15 - Default config path on Android to `~/.config/curd/android.conf`.
16 - Keep desktop default as `~/.config/curd/curd.conf`.
17 - Add `--config` so either platform can override explicitly.
18
19- Split config into shared core plus Android-only schema:
20 - Keep shared fields such as `SubOrDub`, `SubsLanguage`, `PercentageToMarkComplete`, `NextEpisodePrompt`, `SkipOp`, `SkipEd`, `SkipFiller`, `SkipRecap`, `ScoreOnCompletion`, `SaveMpvSpeed`, `AnimeNameLanguage`, `MenuOrder`.
21 - Remove desktop-only Android noise from desktop config and vice versa by generating different defaults per platform.
22 - Android config should add:
23 - `AndroidPlayerPackage`
24 - `AndroidPlayerActivity`
25 - `AndroidPlayerMode` with `ipc` or `intent`
26 - `AndroidPlayerIntentAction`
27 - `AndroidUseTermuxAPI`
28 - `AndroidOpenLinksWith`
29 - `AndroidNotifications`
30 - `AndroidWakeLock`
31 - `AndroidExtraIntentArgs`
32 - Android defaults:
33 - `RofiSelection=false`
34 - `ImagePreview=false`
35 - `DiscordPresence=false`
36 - `AlternateScreen=false`
37
38- Introduce a playback backend abstraction:
39 - Replace direct desktop assumptions in `internal/player.go` with a `PlayerBackend` interface.
40 - Desktop backend keeps current MPV IPC behavior.
41 - Android backend supports two modes:
42 - `ipc`: required for full Android feature parity; launches the selected mpv/mpv fork with a known socket path or equivalent control bridge.
43 - `intent`: basic fallback; launches player by Android intent only, with no reliable progress/control.
44 - Do not promise full features in `intent` mode.
45
46- Android player launch design:
47 - Launch via `am start` using user-configured package/activity, not hardcoded `is.xyz.mpv/.MPVActivity`.
48 - Support official mpv-android and mpvEx by config, not by special-casing brand names.
49 - Add a player capability check during `curd --android-setup`:
50 - Validate package/activity exists.
51 - Validate whether IPC/control is available.
52 - Write detected capability into Android config.
53
54- Preserve core watch-flow features in Android `ipc` mode:
55 - Resume from saved position.
56 - Track playback time and duration.
57 - Auto update AniList progress.
58 - Auto continue to next episode on completion.
59 - Skip OP/ED through AniSkip.
60 - Skip filler and recap episodes.
61 - Save playback speed.
62 - Prompt for rating on completion.
63 - Sequel prompt / list updates.
64 - Continue last episode.
65 - Local history.
66
67- Android UI changes:
68 - Keep Bubble Tea terminal UI, but add an Android/mobile presentation mode:
69 - larger list rows
70 - explicit footer shortcuts
71 - back behavior mapped cleanly
72 - no alternate-screen dependency
73 - search-first flow with visible quick actions
74 - Do not use rofi or image preview on Android.
75 - Use Termux API optionally for:
76 - `termux-open-url` for AniList auth and sequel pages
77 - `termux-notification` / `termux-toast` for prompts and status
78 - `termux-wake-lock` during active playback sessions if enabled
79
80- Android auth and update flow:
81 - On Android, prefer `termux-open-url` or Android intent for AniList OAuth instead of generic browser open.
82 - Keep localhost callback flow if reachable; retain manual token fallback.
83 - Extend `-u` / updater logic in `internal/curd.go` to support an Android release artifact plus a Termux install/update wrapper.
84 - First release should support both:
85 - direct GitHub Android binary
86 - Termux bootstrap/update script that downloads the correct Android asset
87
88## Feature Reality
89Features we can support well on Android in `ipc` mode: 12+
90- streaming playback
91- mobile-tuned TUI selection/search
92- continue last
93- local resume/history
94- AniList tracking/progress updates
95- next episode on completion
96- skip OP
97- skip ED
98- skip filler
99- skip recap
100- save speed
101- score-on-completion and sequel prompts
102- configurable player package and Android-specific settings
103- self-update/install flow
104
105Features that are possible but conditional:
106- opening in mpvEx or another fork only if the selected package/activity can be launched reliably and exposes MPV-compatible control
107- notifications and wake-locks only when `termux-api` is installed
108- seamless same-session player reuse only if Android player integration supports IPC commands like `loadfile`
109
110Features that should be treated as unsupported on Android:
111- Discord Rich Presence
112- rofi UI
113- rofi image preview / ueberzug flow
114- full playback control against arbitrary external players that only accept a `VIEW` intent
115- guaranteed progress/completion detection if the user picks a player with no IPC/control channel
116- desktop-style “one live mpv window” semantics if the Android player does not support file replacement over IPC
117
118## Public Interfaces / CLI Changes
119- Add `--config <path>`.
120- Add `--android-setup` to:
121 - detect Termux API tools
122 - probe configured player package/activity
123 - verify IPC capability
124 - create `android.conf`
125- Keep existing flags, but on Android ignore or hide desktop-only ones in generated config and help text.
126- Update config loader in `internal/config.go` to generate platform-specific defaults and missing keys from the active schema, not one global desktop schema.
127
128## Test Plan
129- Config tests:
130 - Android auto-selects `android.conf`.
131 - Desktop still uses `curd.conf`.
132 - Android config generation excludes desktop-only options.
133 - Desktop config generation excludes Android-only options.
134
135- Backend tests:
136 - desktop backend still resolves and controls mpv
137 - Android intent backend builds correct `am start` command from config
138 - Android IPC backend reports unsupported when capability probe fails
139
140- Watch-flow tests:
141 - completed episode advances progress and local history in Android IPC mode
142 - next episode starts automatically after threshold
143 - skip OP/ED seeks are issued through Android IPC backend
144 - fallback intent mode disables completion-dependent automation cleanly instead of silently failing
145
146- UX tests:
147 - Termux TUI works without alternate screen
148 - back/quit/search flows are usable on narrow terminal widths
149 - `--android-setup` produces actionable errors when `termux-api` or player integration is missing
150
151## Assumptions
152- Android target is Termux on ARM64.
153- “All desktop features on Android” is only a valid goal when the chosen Android mpv path exposes MPV-compatible IPC or an equivalent control bridge.
154- mpvEx support should be implemented as configurable package/activity targeting, not as a hardcoded special case.
155- If no reliable IPC/control path exists for a chosen player, `curd` must downgrade explicitly to basic launch mode and tell the user which features are unavailable.
cmd/curd/main.go +56 −20
@@ -7,6 +7,7 @@ import (
77 "path/filepath"
88 "runtime"
99 "strconv"
10 "strings"
1011 "sync"
1112 "time"
1213
@@ -15,23 +16,32 @@ import (
1516
1617var version string // Will be set by ldflags during build
1718
19func resolveConfigPath(args []string, defaultPath string) string {
20 for i := 0; i < len(args); i++ {
21 arg := args[i]
22 if arg == "--config" && i+1 < len(args) {
23 return args[i+1]
24 }
25 if strings.HasPrefix(arg, "--config=") {
26 return strings.TrimPrefix(arg, "--config=")
27 }
28 }
29
30 return defaultPath
31}
32
1833func main() {
1934 var anime internal.Anime
2035 var user internal.User
2136
2237 internal.SetGlobalAnime(&anime)
2338
24 var homeDir string
25 if runtime.GOOS == "windows" {
26 homeDir = os.Getenv("USERPROFILE")
27 } else {
28 homeDir = os.Getenv("HOME")
29 }
30
31 configFilePath := filepath.Join(homeDir, ".config", "curd", "curd.conf")
39 platform := internal.DetectPlatform()
40 configFilePath := resolveConfigPath(os.Args[1:], internal.DefaultConfigPathForPlatform(platform))
41 platform = internal.InferPlatformForConfigPath(configFilePath, platform)
3242
3343 // load curd userCurdConfig
34 userCurdConfig, err := internal.LoadConfig(configFilePath)
44 userCurdConfig, err := internal.LoadConfigForPlatform(configFilePath, platform)
3545 if err != nil {
3646 fmt.Println("Error loading config:", err)
3747 return
@@ -43,10 +53,13 @@ func main() {
4353 internal.ClearLogFile(logFile)
4454
4555 // Flags configured here cause userconfig needs to be changed.
46 flag.StringVar(&userCurdConfig.Player, "player", userCurdConfig.Player, "Player binary for playback (mpv-compatible; falls back to mpv if unavailable)")
56 flag.StringVar(&configFilePath, "config", configFilePath, "Path to the active config file")
4757 flag.StringVar(&userCurdConfig.StoragePath, "storage-path", userCurdConfig.StoragePath, "Path to the storage directory")
4858 flag.StringVar(&userCurdConfig.SubsLanguage, "subs-lang", userCurdConfig.SubsLanguage, "Subtitles language")
4959 flag.IntVar(&userCurdConfig.PercentageToMarkComplete, "percentage-to-mark-complete", userCurdConfig.PercentageToMarkComplete, "Percentage to mark episode as complete")
60 if !userCurdConfig.IsAndroid() {
61 flag.StringVar(&userCurdConfig.Player, "player", userCurdConfig.Player, "Player binary for playback (mpv-compatible; falls back to mpv if unavailable)")
62 }
5063
5164 // Boolean flags that accept true/false
5265 flag.BoolVar(&userCurdConfig.NextEpisodePrompt, "next-episode-prompt", userCurdConfig.NextEpisodePrompt, "Prompt for the next episode (true/false)")
@@ -56,14 +69,12 @@ func main() {
5669 flag.BoolVar(&userCurdConfig.SkipRecap, "skip-recap", userCurdConfig.SkipRecap, "Skip recap (true/false)")
5770 flag.BoolVar(&userCurdConfig.ScoreOnCompletion, "score-on-completion", userCurdConfig.ScoreOnCompletion, "Score on episode completion (true/false)")
5871 flag.BoolVar(&userCurdConfig.SaveMpvSpeed, "save-mpv-speed", userCurdConfig.SaveMpvSpeed, "Save MPV speed setting (true/false)")
59 flag.BoolVar(&userCurdConfig.DiscordPresence, "discord-presence", userCurdConfig.DiscordPresence, "Enable Discord presence (true/false)")
60 flag.StringVar(&userCurdConfig.DiscordClientId, "discord-client-id", userCurdConfig.DiscordClientId, "Discord client ID for Rich Presence")
72 if !userCurdConfig.IsAndroid() {
73 flag.BoolVar(&userCurdConfig.DiscordPresence, "discord-presence", userCurdConfig.DiscordPresence, "Enable Discord presence (true/false)")
74 flag.StringVar(&userCurdConfig.DiscordClientId, "discord-client-id", userCurdConfig.DiscordClientId, "Discord client ID for Rich Presence")
75 }
6176 continueLast := flag.Bool("c", false, "Continue last episode")
6277 addNewAnime := flag.Bool("new", false, "Add new anime")
63 rofiSelection := flag.Bool("rofi", false, "Open selection in rofi")
64 noRofi := flag.Bool("no-rofi", false, "No rofi")
65 imagePreview := flag.Bool("image-preview", false, "Show image preview")
66 noImagePreview := flag.Bool("no-image-preview", false, "No image preview")
6778 changeToken := flag.Bool("change-token", false, "Change token")
6879 currentCategory := flag.Bool("current", false, "Current category")
6980 updateScript := flag.Bool("u", false, "Update the script")
@@ -71,6 +82,17 @@ func main() {
7182 subFlag := flag.Bool("sub", false, "Watch sub version")
7283 dubFlag := flag.Bool("dub", false, "Watch dub version")
7384 versionFlag := flag.Bool("v", false, "Print version information")
85 androidSetup := flag.Bool("android-setup", false, "Detect Termux API/player integration and write android.conf")
86 var rofiSelection *bool
87 var noRofi *bool
88 var imagePreview *bool
89 var noImagePreview *bool
90 if !userCurdConfig.IsAndroid() {
91 rofiSelection = flag.Bool("rofi", false, "Open selection in rofi")
92 noRofi = flag.Bool("no-rofi", false, "No rofi")
93 imagePreview = flag.Bool("image-preview", false, "Show image preview")
94 noImagePreview = flag.Bool("no-image-preview", false, "No image preview")
95 }
7496
7597 // Custom help/usage function
7698 flag.Usage = func() {
@@ -112,6 +134,13 @@ func main() {
112134 return
113135 }
114136
137 if *androidSetup {
138 if err := internal.RunAndroidSetup(configFilePath, &userCurdConfig); err != nil {
139 internal.ExitCurd(err)
140 }
141 return
142 }
143
115144 // Setup screen for interactive mode (only if not changing token)
116145 internal.ClearScreen()
117146 defer internal.RestoreScreen()
@@ -120,22 +149,27 @@ func main() {
120149 userCurdConfig.CurrentCategory = true
121150 }
122151
123 if *rofiSelection {
152 if rofiSelection != nil && *rofiSelection {
124153 userCurdConfig.RofiSelection = true
125154 }
126155
127 if *noRofi || runtime.GOOS == "windows" {
156 if (noRofi != nil && *noRofi) || runtime.GOOS == "windows" || userCurdConfig.IsAndroid() {
128157 userCurdConfig.RofiSelection = false
129158 }
130159
131 if *imagePreview {
160 if imagePreview != nil && *imagePreview {
132161 userCurdConfig.ImagePreview = true
133162 }
134163
135 if *noImagePreview || runtime.GOOS == "windows" {
164 if (noImagePreview != nil && *noImagePreview) || runtime.GOOS == "windows" || userCurdConfig.IsAndroid() {
136165 userCurdConfig.ImagePreview = false
137166 }
138167
168 if userCurdConfig.IsAndroid() {
169 userCurdConfig.DiscordPresence = false
170 userCurdConfig.AlternateScreen = false
171 }
172
139173 if *editConfig {
140174 internal.EditConfig(configFilePath)
141175 return
@@ -291,6 +325,7 @@ func main() {
291325 }
292326
293327 // Now start playback for the non-filler episode
328 internal.AcquireWakeLock(&userCurdConfig)
294329 anime.Ep.Player.SocketPath = internal.StartCurd(&userCurdConfig, &anime)
295330 internal.Log(fmt.Sprint("Playback starting time: ", anime.Ep.Player.PlaybackTime))
296331 internal.Log(anime.Ep.Player.SocketPath)
@@ -298,6 +333,7 @@ func main() {
298333 // Handle Android Intent external player
299334 if anime.Ep.Player.SocketPath == "android-intent" {
300335 internal.CurdOut(fmt.Sprintf("\nOpened external player for Episode %d.", anime.Ep.Number))
336 internal.CurdOut("Intent mode disables automatic progress detection, skip automation, and IPC control.")
301337 internal.CurdOut("Press Enter when you have finished watching...")
302338
303339 // Wait for user input to confirm completion
internal/android.go added +420
@@ -0,0 +1,420 @@
1package internal
2
3import (
4 "fmt"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "strings"
9 "time"
10
11 "github.com/pkg/browser"
12)
13
14func startDetached(name string, args ...string) error {
15 cmd := exec.Command(name, args...)
16 if err := cmd.Start(); err != nil {
17 return err
18 }
19 if cmd.Process != nil {
20 _ = cmd.Process.Release()
21 }
22 return nil
23}
24
25type AndroidPlayerProbeResult struct {
26 PackageFound bool
27 ActivityValidated bool
28 Capability string
29 SocketPath string
30 Warnings []string
31}
32
33func hasCommand(name string) bool {
34 _, err := exec.LookPath(name)
35 return err == nil
36}
37
38func termuxToolAvailable(name string) bool {
39 if !hasCommand(name) {
40 return false
41 }
42
43 cmd := exec.Command(name, "--help")
44 return cmd.Run() == nil
45}
46
47func OpenURL(target string, config *CurdConfig) error {
48 if config != nil && config.IsAndroid() {
49 if config.AndroidUseTermuxAPI && hasCommand("termux-open-url") {
50 return startDetached("termux-open-url", target)
51 }
52
53 if hasCommand("am") {
54 action := "android.intent.action.VIEW"
55 if strings.TrimSpace(config.AndroidOpenLinksWith) != "" && config.AndroidOpenLinksWith != "termux-open-url" {
56 action = config.AndroidOpenLinksWith
57 }
58 return startDetached("am", "start", "-a", action, "-d", target)
59 }
60 }
61
62 return browser.OpenURL(target)
63}
64
65func Notify(message string) {
66 config := GetGlobalConfig()
67 if config == nil || !config.IsAndroid() || !config.AndroidNotifications {
68 return
69 }
70
71 if config.AndroidUseTermuxAPI && hasCommand("termux-toast") {
72 if err := exec.Command("termux-toast", message).Run(); err == nil {
73 return
74 }
75 }
76
77 if config.AndroidUseTermuxAPI && hasCommand("termux-notification") {
78 _ = exec.Command("termux-notification", "--title", "Curd", "--content", message).Run()
79 }
80}
81
82func AcquireWakeLock(config *CurdConfig) {
83 if config == nil || !config.IsAndroid() || !config.AndroidWakeLock || !config.AndroidUseTermuxAPI {
84 return
85 }
86 if hasCommand("termux-wake-lock") {
87 _ = exec.Command("termux-wake-lock").Run()
88 }
89}
90
91func ReleaseWakeLock(config *CurdConfig) {
92 if config == nil || !config.IsAndroid() || !config.AndroidWakeLock || !config.AndroidUseTermuxAPI {
93 return
94 }
95 if hasCommand("termux-wake-unlock") {
96 _ = exec.Command("termux-wake-unlock").Run()
97 }
98}
99
100func buildAndroidSocketPath(config *CurdConfig) string {
101 if config != nil && strings.TrimSpace(config.AndroidPlayerSocketPath) != "" {
102 return config.AndroidPlayerSocketPath
103 }
104
105 return filepath.Join(os.TempDir(), fmt.Sprintf("curd_mpvsocket_%d", time.Now().UnixNano()))
106}
107
108func hasCleanPathPrefix(path string, prefix string) bool {
109 path = filepath.Clean(strings.TrimSpace(path))
110 prefix = filepath.Clean(strings.TrimSpace(prefix))
111 if path == "" || prefix == "" {
112 return false
113 }
114 if path == prefix {
115 return true
116 }
117 return strings.HasPrefix(path, prefix+string(os.PathSeparator))
118}
119
120type androidSocketPathAssessment struct {
121 Supported bool
122 Warnings []string
123}
124
125func assessAndroidSocketPath(socketPath string) androidSocketPathAssessment {
126 socketPath = strings.TrimSpace(socketPath)
127 result := androidSocketPathAssessment{Supported: true}
128 if socketPath == "" {
129 return result
130 }
131
132 cleanPath := filepath.Clean(socketPath)
133 lowerPath := strings.ToLower(cleanPath)
134
135 termuxRoots := []string{
136 "/data/data/com.termux",
137 "/data/user/0/com.termux",
138 }
139 if home := strings.TrimSpace(os.Getenv("HOME")); home != "" {
140 termuxRoots = append(termuxRoots, filepath.Clean(home))
141 }
142 if prefix := strings.TrimSpace(os.Getenv("PREFIX")); prefix != "" {
143 termuxRoots = append(termuxRoots, filepath.Clean(prefix))
144 }
145
146 for _, root := range termuxRoots {
147 if hasCleanPathPrefix(cleanPath, root) {
148 result.Supported = false
149 result.Warnings = append(result.Warnings, fmt.Sprintf("Android player apps cannot create Unix sockets inside Termux private storage: %s", cleanPath))
150 return result
151 }
152 }
153
154 for _, root := range []string{"/sdcard", "/storage", "/mnt/media_rw"} {
155 if hasCleanPathPrefix(cleanPath, root) {
156 result.Supported = false
157 result.Warnings = append(result.Warnings, fmt.Sprintf("shared storage is not a reliable location for Unix socket files on Android: %s", cleanPath))
158 return result
159 }
160 }
161
162 if (strings.HasPrefix(lowerPath, "/data/data/") || strings.HasPrefix(lowerPath, "/data/user/0/")) &&
163 !hasCleanPathPrefix(cleanPath, "/data/data/com.termux") &&
164 !hasCleanPathPrefix(cleanPath, "/data/user/0/com.termux") {
165 result.Supported = false
166 result.Warnings = append(result.Warnings, fmt.Sprintf("socket path points to another app's private storage, which curd in Termux cannot access: %s", cleanPath))
167 }
168
169 return result
170}
171
172func androidIntentUsesSocketPlaceholder(config *CurdConfig) bool {
173 if config == nil {
174 return false
175 }
176
177 return strings.Contains(strings.Join(config.AndroidExtraIntentArgs, " "), "{socket}")
178}
179
180func androidConfiguredSocketPath(config *CurdConfig) string {
181 if config == nil {
182 return ""
183 }
184
185 socketPath := strings.TrimSpace(config.AndroidPlayerSocketPath)
186 if socketPath != "" {
187 return socketPath
188 }
189
190 if androidIntentUsesSocketPlaceholder(config) {
191 return buildAndroidSocketPath(config)
192 }
193
194 return ""
195}
196
197func BuildAndroidIntentCommand(config *CurdConfig, link string, title string, socketPath string) []string {
198 action := "android.intent.action.VIEW"
199 if config != nil && strings.TrimSpace(config.AndroidPlayerIntentAction) != "" {
200 action = strings.TrimSpace(config.AndroidPlayerIntentAction)
201 }
202
203 args := []string{"start", "--user", "0", "-a", action}
204 if strings.TrimSpace(link) != "" {
205 args = append(args, "-d", link)
206 }
207
208 component := strings.TrimSpace(strings.TrimSpace(config.AndroidPlayerPackage) + "/" + strings.TrimSpace(config.AndroidPlayerActivity))
209 if config != nil && strings.TrimSpace(component) != "/" {
210 args = append(args, "-n", component)
211 }
212
213 placeholders := map[string]string{
214 "{url}": link,
215 "{title}": title,
216 "{socket}": socketPath,
217 }
218
219 if config != nil {
220 for _, extra := range config.AndroidExtraIntentArgs {
221 value := extra
222 for placeholder, replacement := range placeholders {
223 value = strings.ReplaceAll(value, placeholder, replacement)
224 }
225 args = append(args, value)
226 }
227 }
228
229 return args
230}
231
232func packageExists(packageName string) bool {
233 packageName = strings.TrimSpace(packageName)
234 if packageName == "" || !hasCommand("pm") {
235 return false
236 }
237
238 return exec.Command("pm", "path", packageName).Run() == nil
239}
240
241func validateAndroidActivity(config *CurdConfig) bool {
242 component := strings.TrimSpace(config.AndroidPlayerPackage) + "/" + strings.TrimSpace(config.AndroidPlayerActivity)
243 if component == "/" {
244 return false
245 }
246
247 if hasCommand("am") {
248 output, err := runAndroidIntentProbe(config, "https://example.com", "")
249 if err == nil && !strings.Contains(string(output), "Error:") {
250 return true
251 }
252 }
253
254 return packageExists(config.AndroidPlayerPackage)
255}
256
257func runAndroidIntentProbe(config *CurdConfig, link string, socketPath string) ([]byte, error) {
258 probeArgs := BuildAndroidIntentCommand(config, link, "Curd Android Setup", socketPath)
259 return exec.Command("am", append([]string{"start", "-W"}, probeArgs[1:]...)...).CombinedOutput()
260}
261
262func waitForAndroidSocket(socketPath string, timeout time.Duration) bool {
263 deadline := time.Now().Add(timeout)
264 for time.Now().Before(deadline) {
265 conn, err := connectToPipe(socketPath)
266 if err == nil {
267 conn.Close()
268 return true
269 }
270 time.Sleep(250 * time.Millisecond)
271 }
272
273 return false
274}
275
276func ProbeAndroidPlayer(config *CurdConfig) AndroidPlayerProbeResult {
277 result := AndroidPlayerProbeResult{
278 Capability: "unsupported",
279 }
280
281 if config == nil {
282 result.Warnings = append(result.Warnings, "missing Android config")
283 return result
284 }
285
286 result.PackageFound = packageExists(config.AndroidPlayerPackage)
287 if !result.PackageFound {
288 result.Warnings = append(result.Warnings, "configured Android player package was not found")
289 return result
290 }
291
292 result.ActivityValidated = validateAndroidActivity(config)
293 if !result.ActivityValidated {
294 result.Warnings = append(result.Warnings, "configured Android player activity could not be resolved")
295 return result
296 }
297
298 result.Capability = "intent"
299 if strings.EqualFold(config.AndroidPlayerMode, "intent") {
300 return result
301 }
302
303 socketPath := androidConfiguredSocketPath(config)
304 result.SocketPath = socketPath
305 if socketPath == "" {
306 result.Warnings = append(result.Warnings, "Android IPC mode needs either AndroidPlayerSocketPath or AndroidExtraIntentArgs with {socket}")
307 return result
308 }
309
310 socketAssessment := assessAndroidSocketPath(socketPath)
311 result.Warnings = append(result.Warnings, socketAssessment.Warnings...)
312 if !socketAssessment.Supported {
313 if strings.Contains(strings.ToLower(config.AndroidPlayerPackage), "mpvex") {
314 result.Warnings = append(result.Warnings, "mpvEx loads mpv.conf into its own app sandbox, but curd in Termux cannot attach to a Unix socket inside another Android app's private storage")
315 result.Warnings = append(result.Warnings, "use mpvEx in intent mode unless it adds an exported control bridge that curd can reach from Termux")
316 }
317 return result
318 }
319
320 cmdArgs := BuildAndroidIntentCommand(config, "https://example.com", "Curd Android Setup", socketPath)
321 cmd := exec.Command("am", cmdArgs...)
322 if err := cmd.Start(); err != nil {
323 result.Warnings = append(result.Warnings, fmt.Sprintf("failed to launch Android player probe: %v", err))
324 return result
325 }
326
327 if waitForAndroidSocket(socketPath, 5*time.Second) {
328 result.Capability = "ipc"
329 _ = ExitMPV(socketPath)
330 return result
331 }
332
333 result.Warnings = append(result.Warnings, fmt.Sprintf("player launched but no IPC socket appeared at %s; falling back to intent mode", socketPath))
334 if strings.Contains(strings.ToLower(config.AndroidPlayerPackage), "mpvex") {
335 result.Warnings = append(result.Warnings, "mpvEx does not appear to accept arbitrary MPV options through VIEW intent extras; configure input-ipc-server in mpvEx's own MPV config and set the same AndroidPlayerSocketPath in curd")
336 }
337 return result
338}
339
340func RunAndroidSetup(configPath string, config *CurdConfig) error {
341 if DetectPlatform() != PlatformAndroid {
342 return fmt.Errorf("--android-setup must be run from Termux/Android")
343 }
344
345 if config == nil {
346 return fmt.Errorf("missing config")
347 }
348
349 config.Platform = string(PlatformAndroid)
350
351 CurdOut("Running Android setup...")
352 if config.AndroidUseTermuxAPI {
353 missing := make([]string, 0)
354 for _, tool := range []string{"termux-open-url", "termux-toast", "termux-wake-lock", "termux-wake-unlock"} {
355 if !hasCommand(tool) {
356 missing = append(missing, tool)
357 }
358 }
359 if len(missing) > 0 {
360 CurdOut(fmt.Sprintf("Termux API tools not found: %s", strings.Join(missing, ", ")))
361 }
362 }
363
364 probe := ProbeAndroidPlayer(config)
365 for _, warning := range probe.Warnings {
366 CurdOut("Android setup: " + warning)
367 }
368
369 if !probe.PackageFound {
370 return fmt.Errorf("Android player package %q was not found", config.AndroidPlayerPackage)
371 }
372 if !probe.ActivityValidated {
373 return fmt.Errorf("Android player activity %q/%q could not be resolved", config.AndroidPlayerPackage, config.AndroidPlayerActivity)
374 }
375
376 config.AndroidDetectedCapability = probe.Capability
377 if probe.Capability != "ipc" {
378 config.AndroidPlayerMode = "intent"
379 }
380
381 configMap := map[string]string{
382 "StoragePath": config.StoragePath,
383 "AnimeNameLanguage": config.AnimeNameLanguage,
384 "SubsLanguage": config.SubsLanguage,
385 "MenuOrder": config.MenuOrder,
386 "SubOrDub": config.SubOrDub,
387 "PercentageToMarkComplete": fmt.Sprintf("%d", config.PercentageToMarkComplete),
388 "NextEpisodePrompt": fmt.Sprintf("%t", config.NextEpisodePrompt),
389 "SkipOp": fmt.Sprintf("%t", config.SkipOp),
390 "SkipEd": fmt.Sprintf("%t", config.SkipEd),
391 "SkipFiller": fmt.Sprintf("%t", config.SkipFiller),
392 "SkipRecap": fmt.Sprintf("%t", config.SkipRecap),
393 "RofiSelection": fmt.Sprintf("%t", config.RofiSelection),
394 "ImagePreview": fmt.Sprintf("%t", config.ImagePreview),
395 "CurrentCategory": fmt.Sprintf("%t", config.CurrentCategory),
396 "ScoreOnCompletion": fmt.Sprintf("%t", config.ScoreOnCompletion),
397 "SaveMpvSpeed": fmt.Sprintf("%t", config.SaveMpvSpeed),
398 "AddMissingOptions": fmt.Sprintf("%t", config.AddMissingOptions),
399 "AlternateScreen": fmt.Sprintf("%t", config.AlternateScreen),
400 "DiscordPresence": fmt.Sprintf("%t", config.DiscordPresence),
401 "AndroidPlayerPackage": config.AndroidPlayerPackage,
402 "AndroidPlayerActivity": config.AndroidPlayerActivity,
403 "AndroidPlayerMode": config.AndroidPlayerMode,
404 "AndroidPlayerIntentAction": config.AndroidPlayerIntentAction,
405 "AndroidUseTermuxAPI": fmt.Sprintf("%t", config.AndroidUseTermuxAPI),
406 "AndroidOpenLinksWith": config.AndroidOpenLinksWith,
407 "AndroidNotifications": fmt.Sprintf("%t", config.AndroidNotifications),
408 "AndroidWakeLock": fmt.Sprintf("%t", config.AndroidWakeLock),
409 "AndroidExtraIntentArgs": fmt.Sprintf("[%s]", strings.Join(config.AndroidExtraIntentArgs, ",")),
410 "AndroidPlayerSocketPath": config.AndroidPlayerSocketPath,
411 "AndroidDetectedCapability": config.AndroidDetectedCapability,
412 }
413
414 if err := SaveConfigToFileWithSchema(configPath, configMap, configSchemaForPlatform(PlatformAndroid)); err != nil {
415 return err
416 }
417
418 CurdOut(fmt.Sprintf("Android setup complete. Player capability: %s", probe.Capability))
419 return nil
420}
internal/android_test.go added +122
@@ -0,0 +1,122 @@
1package internal
2
3import (
4 "os"
5 "path/filepath"
6 "strings"
7 "testing"
8)
9
10func TestBuildAndroidIntentCommandUsesConfiguredComponentAndPlaceholders(t *testing.T) {
11 config := &CurdConfig{
12 Platform: string(PlatformAndroid),
13 AndroidPlayerPackage: "is.xyz.mpv",
14 AndroidPlayerActivity: ".MPVActivity",
15 AndroidPlayerIntentAction: "android.intent.action.VIEW",
16 AndroidExtraIntentArgs: []string{
17 "--es",
18 "title",
19 "{title}",
20 "--es",
21 "socket",
22 "{socket}",
23 },
24 }
25
26 cmd := BuildAndroidIntentCommand(config, "https://example.com/video.mp4", "Episode 3", "/tmp/test.sock")
27 joined := strings.Join(cmd, " ")
28
29 if !strings.Contains(joined, "-n is.xyz.mpv/.MPVActivity") {
30 t.Fatalf("expected component in command: %s", joined)
31 }
32 if !strings.Contains(joined, "https://example.com/video.mp4") {
33 t.Fatalf("expected URL placeholder to be replaced: %s", joined)
34 }
35 if !strings.Contains(joined, "Episode 3") {
36 t.Fatalf("expected title placeholder to be replaced: %s", joined)
37 }
38 if !strings.Contains(joined, "/tmp/test.sock") {
39 t.Fatalf("expected socket placeholder to be replaced: %s", joined)
40 }
41}
42
43func TestProbeAndroidPlayerReturnsUnsupportedWhenPackageMissing(t *testing.T) {
44 config := &CurdConfig{
45 Platform: string(PlatformAndroid),
46 AndroidPlayerPackage: "missing.package",
47 AndroidPlayerActivity: ".MissingActivity",
48 AndroidPlayerMode: "ipc",
49 }
50
51 result := ProbeAndroidPlayer(config)
52
53 if result.Capability != "unsupported" {
54 t.Fatalf("expected unsupported capability, got %q", result.Capability)
55 }
56 if len(result.Warnings) == 0 {
57 t.Fatalf("expected warning when package probe fails")
58 }
59}
60
61func TestAndroidBackendSupportsAutomationOnlyInIPCMode(t *testing.T) {
62 intentBackend := &androidPlayerBackend{config: &CurdConfig{
63 Platform: string(PlatformAndroid),
64 AndroidPlayerMode: "intent",
65 }}
66 if intentBackend.SupportsAutomation() {
67 t.Fatalf("intent backend should not support automation")
68 }
69
70 ipcBackend := &androidPlayerBackend{config: &CurdConfig{
71 Platform: string(PlatformAndroid),
72 AndroidPlayerMode: "ipc",
73 }}
74 if !ipcBackend.SupportsAutomation() {
75 t.Fatalf("ipc backend should support automation")
76 }
77}
78
79func TestAndroidConfiguredSocketPathUsesStaticPathWhenProvided(t *testing.T) {
80 config := &CurdConfig{
81 Platform: string(PlatformAndroid),
82 AndroidPlayerSocketPath: "/data/data/com.termux/files/home/.tmp/mpvex.sock",
83 AndroidExtraIntentArgs: []string{"--es", "ignored", "{socket}"},
84 }
85
86 if got := androidConfiguredSocketPath(config); got != "/data/data/com.termux/files/home/.tmp/mpvex.sock" {
87 t.Fatalf("expected static socket path, got %q", got)
88 }
89}
90
91func TestAndroidConfiguredSocketPathUsesPlaceholderWhenConfigured(t *testing.T) {
92 config := &CurdConfig{
93 Platform: string(PlatformAndroid),
94 AndroidExtraIntentArgs: []string{"--es", "socket", "{socket}"},
95 }
96
97 if got := androidConfiguredSocketPath(config); got == "" {
98 t.Fatalf("expected generated socket path when {socket} placeholder is present")
99 }
100}
101
102func TestAssessAndroidSocketPathRejectsTermuxPrivateStorage(t *testing.T) {
103 t.Setenv("HOME", filepath.Join(string(os.PathSeparator), "data", "data", "com.termux", "files", "home"))
104
105 result := assessAndroidSocketPath("/data/data/com.termux/files/home/.tmp/mpv.sock")
106 if result.Supported {
107 t.Fatalf("expected Termux private storage socket path to be rejected")
108 }
109 if len(result.Warnings) == 0 {
110 t.Fatalf("expected warning for Termux private storage socket path")
111 }
112}
113
114func TestAssessAndroidSocketPathRejectsSharedStorage(t *testing.T) {
115 result := assessAndroidSocketPath("/storage/emulated/0/Download/mpv.sock")
116 if result.Supported {
117 t.Fatalf("expected shared storage socket path to be rejected")
118 }
119 if len(result.Warnings) == 0 {
120 t.Fatalf("expected warning for shared storage socket path")
121 }
122}
internal/config.go +212 −40
@@ -15,8 +15,6 @@ import (
1515 "strconv"
1616 "strings"
1717 "time"
18
19 "github.com/pkg/browser"
2018)
2119
2220const (
@@ -38,33 +36,50 @@ type AnilistToken struct {
3836
3937// CurdConfig struct with field names that match the config keys
4038type CurdConfig struct {
41 Player string `config:"Player"`
42 MpvArgs []string `config:MpvArgs`
43 SubsLanguage string `config:"SubsLanguage"`
44 SubOrDub string `config:"SubOrDub"`
45 StoragePath string `config:"StoragePath"`
46 AnimeNameLanguage string `config:"AnimeNameLanguage"`
47 MenuOrder string `config:"MenuOrder"`
48 PercentageToMarkComplete int `config:"PercentageToMarkComplete"`
49 NextEpisodePrompt bool `config:"NextEpisodePrompt"`
50 SkipOp bool `config:"SkipOp"`
51 SkipEd bool `config:"SkipEd"`
52 SkipFiller bool `config:"SkipFiller"`
53 ImagePreview bool `config:"ImagePreview"`
54 SkipRecap bool `config:"SkipRecap"`
55 RofiSelection bool `config:"RofiSelection"`
56 CurrentCategory bool `config:"CurrentCategory"`
57 ScoreOnCompletion bool `config:"ScoreOnCompletion"`
58 SaveMpvSpeed bool `config:"SaveMpvSpeed"`
59 AddMissingOptions bool `config:"AddMissingOptions"`
60 AlternateScreen bool `config:"AlternateScreen"`
61 DiscordPresence bool `config:"DiscordPresence"`
62 DiscordClientId string `config:"DiscordClientId"`
39 Platform string `config:"-"`
40 Player string `config:"Player"`
41 MpvArgs []string `config:"MpvArgs"`
42 SubsLanguage string `config:"SubsLanguage"`
43 SubOrDub string `config:"SubOrDub"`
44 StoragePath string `config:"StoragePath"`
45 AnimeNameLanguage string `config:"AnimeNameLanguage"`
46 MenuOrder string `config:"MenuOrder"`
47 PercentageToMarkComplete int `config:"PercentageToMarkComplete"`
48 NextEpisodePrompt bool `config:"NextEpisodePrompt"`
49 SkipOp bool `config:"SkipOp"`
50 SkipEd bool `config:"SkipEd"`
51 SkipFiller bool `config:"SkipFiller"`
52 ImagePreview bool `config:"ImagePreview"`
53 SkipRecap bool `config:"SkipRecap"`
54 RofiSelection bool `config:"RofiSelection"`
55 CurrentCategory bool `config:"CurrentCategory"`
56 ScoreOnCompletion bool `config:"ScoreOnCompletion"`
57 SaveMpvSpeed bool `config:"SaveMpvSpeed"`
58 AddMissingOptions bool `config:"AddMissingOptions"`
59 AlternateScreen bool `config:"AlternateScreen"`
60 DiscordPresence bool `config:"DiscordPresence"`
61 DiscordClientId string `config:"DiscordClientId"`
62 AndroidPlayerPackage string `config:"AndroidPlayerPackage"`
63 AndroidPlayerActivity string `config:"AndroidPlayerActivity"`
64 AndroidPlayerMode string `config:"AndroidPlayerMode"`
65 AndroidPlayerIntentAction string `config:"AndroidPlayerIntentAction"`
66 AndroidUseTermuxAPI bool `config:"AndroidUseTermuxAPI"`
67 AndroidOpenLinksWith string `config:"AndroidOpenLinksWith"`
68 AndroidNotifications bool `config:"AndroidNotifications"`
69 AndroidWakeLock bool `config:"AndroidWakeLock"`
70 AndroidExtraIntentArgs []string `config:"AndroidExtraIntentArgs"`
71 AndroidPlayerSocketPath string `config:"AndroidPlayerSocketPath"`
72 AndroidDetectedCapability string `config:"AndroidDetectedCapability"`
73}
74
75type ConfigSchema struct {
76 platform Platform
77 keys []string
78 defaults map[string]string
6379}
6480
65// Default configuration values as a map
66func defaultConfigMap() map[string]string {
67 return map[string]string{
81func desktopConfigSchema() ConfigSchema {
82 defaults := map[string]string{
6883 "Player": "mpv",
6984 "MpvArgs": "[]",
7085 "StoragePath": "$HOME/.local/share/curd",
@@ -80,6 +95,7 @@ func defaultConfigMap() map[string]string {
8095 "SkipRecap": "true",
8196 "RofiSelection": "false",
8297 "ImagePreview": "false",
98 "CurrentCategory": "false",
8399 "ScoreOnCompletion": "true",
84100 "SaveMpvSpeed": "true",
85101 "AddMissingOptions": "true",
@@ -87,6 +103,115 @@ func defaultConfigMap() map[string]string {
87103 "DiscordPresence": "true",
88104 "DiscordClientId": "1287457464148820089",
89105 }
106
107 return ConfigSchema{
108 platform: PlatformDesktop,
109 keys: []string{
110 "Player",
111 "MpvArgs",
112 "StoragePath",
113 "AnimeNameLanguage",
114 "SubsLanguage",
115 "MenuOrder",
116 "SubOrDub",
117 "PercentageToMarkComplete",
118 "NextEpisodePrompt",
119 "SkipOp",
120 "SkipEd",
121 "SkipFiller",
122 "SkipRecap",
123 "RofiSelection",
124 "ImagePreview",
125 "CurrentCategory",
126 "ScoreOnCompletion",
127 "SaveMpvSpeed",
128 "AddMissingOptions",
129 "AlternateScreen",
130 "DiscordPresence",
131 "DiscordClientId",
132 },
133 defaults: defaults,
134 }
135}
136
137func androidConfigSchema() ConfigSchema {
138 defaults := map[string]string{
139 "StoragePath": "$HOME/.local/share/curd",
140 "AnimeNameLanguage": "english",
141 "SubsLanguage": "english",
142 "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST",
143 "SubOrDub": "sub",
144 "PercentageToMarkComplete": "85",
145 "NextEpisodePrompt": "false",
146 "SkipOp": "true",
147 "SkipEd": "true",
148 "SkipFiller": "true",
149 "SkipRecap": "true",
150 "RofiSelection": "false",
151 "ImagePreview": "false",
152 "CurrentCategory": "false",
153 "ScoreOnCompletion": "true",
154 "SaveMpvSpeed": "true",
155 "AddMissingOptions": "true",
156 "AlternateScreen": "false",
157 "DiscordPresence": "false",
158 "AndroidPlayerPackage": "is.xyz.mpv",
159 "AndroidPlayerActivity": ".MPVActivity",
160 "AndroidPlayerMode": "intent",
161 "AndroidPlayerIntentAction": "android.intent.action.VIEW",
162 "AndroidUseTermuxAPI": "true",
163 "AndroidOpenLinksWith": "termux-open-url",
164 "AndroidNotifications": "false",
165 "AndroidWakeLock": "false",
166 "AndroidExtraIntentArgs": "[]",
167 "AndroidPlayerSocketPath": "",
168 "AndroidDetectedCapability": "intent",
169 }
170
171 return ConfigSchema{
172 platform: PlatformAndroid,
173 keys: []string{
174 "StoragePath",
175 "AnimeNameLanguage",
176 "SubsLanguage",
177 "MenuOrder",
178 "SubOrDub",
179 "PercentageToMarkComplete",
180 "NextEpisodePrompt",
181 "SkipOp",
182 "SkipEd",
183 "SkipFiller",
184 "SkipRecap",
185 "RofiSelection",
186 "ImagePreview",
187 "CurrentCategory",
188 "ScoreOnCompletion",
189 "SaveMpvSpeed",
190 "AddMissingOptions",
191 "AlternateScreen",
192 "DiscordPresence",
193 "AndroidPlayerPackage",
194 "AndroidPlayerActivity",
195 "AndroidPlayerMode",
196 "AndroidPlayerIntentAction",
197 "AndroidUseTermuxAPI",
198 "AndroidOpenLinksWith",
199 "AndroidNotifications",
200 "AndroidWakeLock",
201 "AndroidExtraIntentArgs",
202 "AndroidPlayerSocketPath",
203 "AndroidDetectedCapability",
204 },
205 defaults: defaults,
206 }
207}
208
209func configSchemaForPlatform(platform Platform) ConfigSchema {
210 if platform == PlatformAndroid {
211 return androidConfigSchema()
212 }
213
214 return desktopConfigSchema()
90215}
91216
92217var globalConfig *CurdConfig
@@ -99,6 +224,10 @@ func GetGlobalConfig() *CurdConfig {
99224 return globalConfig
100225}
101226
227func (c *CurdConfig) IsAndroid() bool {
228 return c != nil && c.Platform == string(PlatformAndroid)
229}
230
102231// Helper function to parse string array from config
103232func parseStringArray(value string) []string {
104233 // Remove brackets and split by comma
@@ -124,13 +253,24 @@ func parseStringArray(value string) []string {
124253
125254// LoadConfig reads or creates the config file, adds missing fields, and returns the populated CurdConfig struct
126255func LoadConfig(configPath string) (CurdConfig, error) {
256 platform := DetectPlatform()
257 if strings.TrimSpace(configPath) == "" {
258 configPath = DefaultConfigPathForPlatform(platform)
259 }
260 platform = InferPlatformForConfigPath(configPath, platform)
261
262 return LoadConfigForPlatform(configPath, platform)
263}
264
265func LoadConfigForPlatform(configPath string, platform Platform) (CurdConfig, error) {
127266 configPath = os.ExpandEnv(configPath) // Substitute environment variables like $HOME
267 schema := configSchemaForPlatform(platform)
128268
129269 // Check if config file exists
130270 if _, err := os.Stat(configPath); os.IsNotExist(err) {
131271 // Create the config file with default values if it doesn't exist
132272 CurdOut("Config file not found. Creating default config...")
133 if err := createDefaultConfig(configPath); err != nil {
273 if err := createDefaultConfig(configPath, schema); err != nil {
134274 return CurdConfig{}, fmt.Errorf("error creating default config file: %v", err)
135275 }
136276 }
@@ -149,8 +289,7 @@ func LoadConfig(configPath string) (CurdConfig, error) {
149289
150290 // Add missing fields to the config map
151291 updated := false
152 defaultConfigMap := defaultConfigMap()
153 for key, defaultValue := range defaultConfigMap {
292 for key, defaultValue := range schema.defaults {
154293 if _, exists := configMap[key]; !exists {
155294 configMap[key] = defaultValue
156295 updated = true
@@ -159,7 +298,7 @@ func LoadConfig(configPath string) (CurdConfig, error) {
159298
160299 // Write updated config back to file only if AddMissingOptions is true
161300 if addMissing && updated {
162 if err := SaveConfigToFile(configPath, configMap); err != nil {
301 if err := SaveConfigToFileWithSchema(configPath, configMap, schema); err != nil {
163302 return CurdConfig{}, fmt.Errorf("error saving updated config file: %v", err)
164303 }
165304 }
@@ -171,15 +310,14 @@ func LoadConfig(configPath string) (CurdConfig, error) {
171310
172311 // Populate the CurdConfig struct from the config map
173312 config := PopulateConfig(configMap)
313 config.Platform = string(platform)
174314
175315 return config, nil
176316}
177317
178318// Create a config file with default values in key=value format
179319// Ensure the directory exists before creating the file
180func createDefaultConfig(path string) error {
181 defaultConfig := defaultConfigMap()
182
320func createDefaultConfig(path string, schema ConfigSchema) error {
183321 // Ensure the directory exists
184322 dir := filepath.Dir(path)
185323 if err := os.MkdirAll(dir, 0755); err != nil {
@@ -193,7 +331,8 @@ func createDefaultConfig(path string) error {
193331 defer file.Close()
194332
195333 writer := bufio.NewWriter(file)
196 for key, value := range defaultConfig {
334 for _, key := range schema.keys {
335 value := schema.defaults[key]
197336 line := fmt.Sprintf("%s=%s\n", key, value)
198337 if _, err := writer.WriteString(line); err != nil {
199338 return fmt.Errorf("error writing to file: %v", err)
@@ -206,13 +345,21 @@ func createDefaultConfig(path string) error {
206345}
207346
208347// authenticateWithBrowser performs OAuth authentication using browser
209func authenticateWithBrowser(tokenPath string) (string, error) {
348func authenticateWithBrowser(tokenPath string, forceRefresh bool) (string, error) {
210349 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
211350 defer cancel()
212351
213352 // Try to load existing token first
214 if token, err := loadToken(tokenPath); err == nil && isTokenValid(token) {
215 return token.AccessToken, nil
353 if !forceRefresh {
354 if token, err := loadToken(tokenPath); err == nil && isTokenValid(token) {
355 return token.AccessToken, nil
356 }
357 }
358
359 if forceRefresh {
360 if err := os.Remove(tokenPath); err != nil && !os.IsNotExist(err) {
361 Log("Failed to remove existing token before refresh: " + err.Error())
362 }
216363 }
217364
218365 // Start local server to handle OAuth callback
@@ -353,7 +500,7 @@ func authenticateWithBrowser(tokenPath string) (string, error) {
353500 fmt.Println("Opening browser for AniList authentication...")
354501 fmt.Printf("If the browser doesn't open automatically, visit: %s\n", authURL)
355502
356 if err := browser.OpenURL(authURL); err != nil {
503 if err := OpenURL(authURL, GetGlobalConfig()); err != nil {
357504 fmt.Printf("Failed to open browser automatically: %v\n", err)
358505 fmt.Println("Please copy and paste the URL above into your browser")
359506 }
@@ -452,7 +599,7 @@ func ChangeToken(config *CurdConfig, user *User) {
452599
453600 // Try browser-based OAuth first
454601 fmt.Println("Starting browser-based authentication...")
455 user.Token, err = authenticateWithBrowser(tokenPath)
602 user.Token, err = authenticateWithBrowser(tokenPath, true)
456603
457604 if err != nil {
458605 Log("Browser authentication failed: " + err.Error())
@@ -522,6 +669,11 @@ func LoadConfigFromFile(path string) (map[string]string, error) {
522669
523670// SaveConfigToFile saves updated config map to file in key=value format
524671func SaveConfigToFile(path string, configMap map[string]string) error {
672 platform := InferPlatformForConfigPath(path, DetectPlatform())
673 return SaveConfigToFileWithSchema(path, configMap, configSchemaForPlatform(platform))
674}
675
676func SaveConfigToFileWithSchema(path string, configMap map[string]string, schema ConfigSchema) error {
525677 file, err := os.Create(path)
526678 if err != nil {
527679 return err
@@ -529,7 +681,24 @@ func SaveConfigToFile(path string, configMap map[string]string) error {
529681 defer file.Close()
530682
531683 writer := bufio.NewWriter(file)
684 written := make(map[string]bool, len(configMap))
685 for _, key := range schema.keys {
686 value, exists := configMap[key]
687 if !exists {
688 continue
689 }
690
691 line := fmt.Sprintf("%s=%s\n", key, value)
692 if _, err := writer.WriteString(line); err != nil {
693 return err
694 }
695 written[key] = true
696 }
697
532698 for key, value := range configMap {
699 if written[key] {
700 continue
701 }
533702 line := fmt.Sprintf("%s=%s\n", key, value)
534703 if _, err := writer.WriteString(line); err != nil {
535704 return err
@@ -569,6 +738,9 @@ func PopulateConfig(configMap map[string]string) CurdConfig {
569738 if mpvArgs, exists := configMap["MpvArgs"]; exists {
570739 config.MpvArgs = parseStringArray(mpvArgs)
571740 }
741 if androidExtraArgs, exists := configMap["AndroidExtraIntentArgs"]; exists {
742 config.AndroidExtraIntentArgs = parseStringArray(androidExtraArgs)
743 }
572744
573745 return config
574746}
internal/config_test.go added +97
@@ -0,0 +1,97 @@
1package internal
2
3import (
4 "os"
5 "path/filepath"
6 "strings"
7 "testing"
8)
9
10func TestLoadConfigForPlatformCreatesAndroidSchema(t *testing.T) {
11 t.Setenv("HOME", t.TempDir())
12
13 configPath := filepath.Join(os.Getenv("HOME"), ".config", "curd", "android.conf")
14 config, err := LoadConfigForPlatform(configPath, PlatformAndroid)
15 if err != nil {
16 t.Fatalf("LoadConfigForPlatform returned error: %v", err)
17 }
18
19 if !config.IsAndroid() {
20 t.Fatalf("expected android platform config, got %+v", config)
21 }
22 if config.AndroidPlayerPackage == "" {
23 t.Fatalf("expected AndroidPlayerPackage to be populated")
24 }
25 if config.Player != "" {
26 t.Fatalf("expected desktop Player to be excluded from android schema, got %q", config.Player)
27 }
28
29 data, err := os.ReadFile(configPath)
30 if err != nil {
31 t.Fatalf("failed to read config file: %v", err)
32 }
33
34 content := string(data)
35 if !strings.Contains(content, "AndroidPlayerPackage=") {
36 t.Fatalf("expected AndroidPlayerPackage in android config: %s", content)
37 }
38 if strings.Contains(content, "Player=") {
39 t.Fatalf("did not expect desktop Player key in android config: %s", content)
40 }
41}
42
43func TestLoadConfigForPlatformCreatesDesktopSchema(t *testing.T) {
44 t.Setenv("HOME", t.TempDir())
45
46 configPath := filepath.Join(os.Getenv("HOME"), ".config", "curd", "curd.conf")
47 config, err := LoadConfigForPlatform(configPath, PlatformDesktop)
48 if err != nil {
49 t.Fatalf("LoadConfigForPlatform returned error: %v", err)
50 }
51
52 if config.IsAndroid() {
53 t.Fatalf("expected desktop platform config, got %+v", config)
54 }
55 if config.Player == "" {
56 t.Fatalf("expected desktop Player to be populated")
57 }
58 if config.AndroidPlayerPackage != "" {
59 t.Fatalf("expected AndroidPlayerPackage to be excluded from desktop schema, got %q", config.AndroidPlayerPackage)
60 }
61
62 data, err := os.ReadFile(configPath)
63 if err != nil {
64 t.Fatalf("failed to read config file: %v", err)
65 }
66
67 content := string(data)
68 if !strings.Contains(content, "Player=") {
69 t.Fatalf("expected Player in desktop config: %s", content)
70 }
71 if strings.Contains(content, "AndroidPlayerPackage=") {
72 t.Fatalf("did not expect AndroidPlayerPackage in desktop config: %s", content)
73 }
74}
75
76func TestDefaultConfigPathForPlatform(t *testing.T) {
77 t.Setenv("HOME", "/tmp/curd-home")
78
79 androidPath := DefaultConfigPathForPlatform(PlatformAndroid)
80 desktopPath := DefaultConfigPathForPlatform(PlatformDesktop)
81
82 if !strings.HasSuffix(androidPath, filepath.Join(".config", "curd", "android.conf")) {
83 t.Fatalf("unexpected android config path: %s", androidPath)
84 }
85 if !strings.HasSuffix(desktopPath, filepath.Join(".config", "curd", "curd.conf")) {
86 t.Fatalf("unexpected desktop config path: %s", desktopPath)
87 }
88}
89
90func TestInferPlatformForConfigPath(t *testing.T) {
91 if got := InferPlatformForConfigPath("/tmp/android.conf", PlatformDesktop); got != PlatformAndroid {
92 t.Fatalf("expected android platform for android.conf, got %q", got)
93 }
94 if got := InferPlatformForConfigPath("/tmp/curd.conf", PlatformAndroid); got != PlatformDesktop {
95 t.Fatalf("expected desktop platform for curd.conf, got %q", got)
96 }
97}
internal/curd.go +14 −7
@@ -17,7 +17,6 @@ import (
1717 "time"
1818
1919 "github.com/gen2brain/beeep"
20 "github.com/pkg/browser"
2120)
2221
2322func EditConfig(configFilePath string) {
@@ -132,13 +131,15 @@ func ExitCurd(err error) {
132131 RestoreScreen()
133132
134133 anime := GetGlobalAnime()
135 if (anime != nil) && (anime.Ep.Player.SocketPath != "") {
134 if (anime != nil) && (anime.Ep.Player.SocketPath != "") && (anime.Ep.Player.SocketPath != androidIntentSocketPath) {
136135 _, err = MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
137136 if err != nil {
138137 Log("Error closing MPV: " + err.Error())
139138 }
140139 }
141140
141 ReleaseWakeLock(GetGlobalConfig())
142
142143 CurdOut("Have a great day!")
143144 // If the error is not about the connection refused, print the error
144145 if err != nil && !strings.Contains(err.Error(), "dial unix "+anime.Ep.Player.SocketPath+": connect: connection refused") {
@@ -162,6 +163,7 @@ func CurdOut(data interface{}) {
162163 }
163164 if !userCurdConfig.RofiSelection {
164165 fmt.Println(fmt.Sprintf("%v", data))
166 Notify(fmt.Sprintf("%v", data))
165167 } else {
166168 switch runtime.GOOS {
167169 case "windows":
@@ -517,14 +519,19 @@ func UpdateCurd(repo, fileName string) error {
517519
518520 // Determine the correct binary name based on OS and architecture
519521 var binaryName string
520 switch runtime.GOOS {
521 case "windows":
522 switch {
523 case DetectPlatform() == PlatformAndroid:
524 if runtime.GOARCH != "arm64" {
525 return fmt.Errorf("unsupported Android architecture: %s", runtime.GOARCH)
526 }
527 binaryName = "curd-android-arm64"
528 case runtime.GOOS == "windows":
522529 if runtime.GOARCH == "arm64" {
523530 binaryName = "curd-windows-arm64.exe"
524531 } else {
525532 binaryName = "curd-windows-x86_64.exe"
526533 }
527 case "darwin": // macOS
534 case runtime.GOOS == "darwin": // macOS
528535 switch runtime.GOARCH {
529536 case "amd64":
530537 binaryName = "curd-macos-x86_64"
@@ -533,7 +540,7 @@ func UpdateCurd(repo, fileName string) error {
533540 default:
534541 binaryName = "curd-macos-universal"
535542 }
536 case "linux":
543 case runtime.GOOS == "linux":
537544 switch runtime.GOARCH {
538545 case "amd64":
539546 binaryName = "curd-linux-x86_64"
@@ -1836,7 +1843,7 @@ func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken strin
18361843 if selectedOption.Key == "yes" {
18371844 url := fmt.Sprintf("https://anilist.co/anime/%d", anime.AnilistId)
18381845 CurdOut(fmt.Sprintf("Opening %s", url))
1839 if err := browser.OpenURL(url); err != nil {
1846 if err := OpenURL(url, GetGlobalConfig()); err != nil {
18401847 Log(fmt.Sprintf("Error opening browser: %v", err))
18411848 CurdOut("Failed to open browser.")
18421849 }
internal/platform.go added +68
@@ -0,0 +1,68 @@
1package internal
2
3import (
4 "os"
5 "path/filepath"
6 "runtime"
7 "strings"
8)
9
10type Platform string
11
12const (
13 PlatformDesktop Platform = "desktop"
14 PlatformAndroid Platform = "android"
15)
16
17func DetectPlatform() Platform {
18 if runtime.GOOS == "android" {
19 return PlatformAndroid
20 }
21
22 termuxMarkers := []string{
23 os.Getenv("TERMUX_VERSION"),
24 os.Getenv("TERMUX_APP_PID"),
25 }
26 for _, marker := range termuxMarkers {
27 if strings.TrimSpace(marker) != "" {
28 return PlatformAndroid
29 }
30 }
31
32 prefix := os.Getenv("PREFIX")
33 if strings.Contains(prefix, "com.termux") {
34 return PlatformAndroid
35 }
36
37 return PlatformDesktop
38}
39
40func DefaultConfigPathForPlatform(platform Platform) string {
41 homeDir := os.Getenv("HOME")
42 if runtime.GOOS == "windows" && homeDir == "" {
43 homeDir = os.Getenv("USERPROFILE")
44 }
45
46 fileName := "curd.conf"
47 if platform == PlatformAndroid {
48 fileName = "android.conf"
49 }
50
51 return filepath.Join(homeDir, ".config", "curd", fileName)
52}
53
54func DefaultConfigPath() string {
55 return DefaultConfigPathForPlatform(DetectPlatform())
56}
57
58func InferPlatformForConfigPath(configPath string, detected Platform) Platform {
59 base := strings.ToLower(filepath.Base(strings.TrimSpace(configPath)))
60 switch base {
61 case "android.conf":
62 return PlatformAndroid
63 case "curd.conf":
64 return PlatformDesktop
65 default:
66 return detected
67 }
68}
internal/player.go +5 −152
@@ -1,7 +1,6 @@
11package internal
22
33import (
4 "crypto/rand"
54 "encoding/json"
65 "fmt"
76 "os"
@@ -147,157 +146,7 @@ func translateMPVArgsForIINA(mpvArgs []string) []string {
147146}
148147
149148func StartVideo(link string, args []string, title string, anime *Anime) (string, error) {
150 var command *exec.Cmd
151 var mpvSocketPath string
152 var err error
153
154 userConfig := GetGlobalConfig()
155
156 // Add custom MPV arguments from config if they exist
157 if userConfig.MpvArgs != nil {
158 args = append(args, userConfig.MpvArgs...)
159 }
160
161 // Check if we have an existing socket and if MPV is still running
162 if anime.Ep.Player.SocketPath != "" && IsMPVRunning(anime.Ep.Player.SocketPath) {
163 // Reuse existing socket
164 mpvSocketPath = anime.Ep.Player.SocketPath
165
166 // Load the new file in the existing MPV instance
167 command := []interface{}{"loadfile", link}
168 _, err = MPVSendCommand(mpvSocketPath, command)
169 if err != nil {
170 return "", fmt.Errorf("failed to load file in existing MPV instance: %w", err)
171 }
172
173 // Wait a brief moment for the file to load
174 time.Sleep(100 * time.Millisecond)
175
176 // Update the window title
177 titleCommand := []interface{}{"set_property", "force-media-title", title}
178 _, err = MPVSendCommand(mpvSocketPath, titleCommand)
179 if err != nil {
180 Log(fmt.Sprintf("Failed to update title: %v", err))
181 }
182
183 // Also update the window title property
184 windowTitleCommand := []interface{}{"set_property", "title", title}
185 _, err = MPVSendCommand(mpvSocketPath, windowTitleCommand)
186 if err != nil {
187 Log(fmt.Sprintf("Failed to update window title: %v", err))
188 }
189
190 return mpvSocketPath, nil
191 }
192
193 if anime.Ep.Player.SocketPath == "" {
194 // Generate a random number for the socket path
195 randomBytes := make([]byte, 4)
196 _, err = rand.Read(randomBytes)
197 if err != nil {
198 Log("Failed to generate random number")
199 return "", fmt.Errorf("failed to generate random number: %w", err)
200 }
201
202 randomNumber := fmt.Sprintf("%x", randomBytes)
203
204 // Create the mpv socket path with the random number
205 if runtime.GOOS == "windows" {
206 mpvSocketPath = fmt.Sprintf(`\\.\pipe\curd_mpvsocket_%s`, randomNumber)
207 } else {
208 mpvSocketPath = fmt.Sprintf("/tmp/curd_mpvsocket_%s", randomNumber)
209 }
210 } else {
211 mpvSocketPath = anime.Ep.Player.SocketPath
212 }
213
214 // Add the title to MPV arguments
215 titleArgs := []string{fmt.Sprintf("--title=%s", title), fmt.Sprintf("--force-media-title=%s", title)}
216
217 // Keep the window open after episode completes, new episode starts in the same mpv window
218 args = append(args, "--force-window=yes", "--idle=yes")
219 args = append(args, titleArgs...)
220
221 // Prepare arguments for mpv-compatible players.
222 var mpvArgs []string
223 mpvArgs = append(mpvArgs, "--no-terminal", "--really-quiet", fmt.Sprintf("--input-ipc-server=%s", mpvSocketPath))
224 // Add any additional arguments passed
225 if len(args) > 0 {
226 mpvArgs = append(mpvArgs, args...)
227 }
228 mpvArgs = append(mpvArgs, link)
229
230 // Check for Android environment
231 amPath, err := exec.LookPath("am")
232 isAndroid := runtime.GOOS == "android" || (err == nil && amPath != "")
233
234 if isAndroid {
235 // Only use MPV on Android via intent
236 cmdArgs := []string{
237 "start", "--user", "0",
238 "-a", "android.intent.action.VIEW",
239 "-d", link,
240 "-n", "is.xyz.mpv/.MPVActivity",
241 }
242
243 command = exec.Command("am", cmdArgs...)
244 err = command.Start()
245 if err != nil {
246 CurdOut("Error: Failed to start android intent")
247 return "", fmt.Errorf("failed to start android intent: %w", err)
248 }
249 return "android-intent", nil
250 }
251
252 resolvedPlayerBinary, effectivePlayerName, err := resolveConfiguredPlayerBinary(userConfig.Player)
253 if err != nil {
254 CurdOut("Error: Failed to resolve media player")
255 Log(fmt.Sprintf("Player resolution failed for '%s': %v", userConfig.Player, err))
256 return "", err
257 }
258
259 playerArgs := mpvArgs
260 if isIINAPlayer(effectivePlayerName, resolvedPlayerBinary) {
261 playerArgs = translateMPVArgsForIINA(mpvArgs)
262 playerArgs = append(playerArgs, "--no-stdin")
263 }
264
265 command = exec.Command(resolvedPlayerBinary, playerArgs...)
266
267 // Start the selected mpv-compatible player process
268 err = command.Start()
269 if err != nil {
270 CurdOut(fmt.Sprintf("Error: Failed to start %s process", effectivePlayerName))
271 return "", fmt.Errorf("failed to start %s: %w", effectivePlayerName, err)
272 }
273
274 // Wait for the socket to become available with retries
275 socketReady := false
276 maxRetries := 10
277 retryDelay := 300 * time.Millisecond
278
279 Log(fmt.Sprintf("Waiting for MPV socket to be ready at %s", mpvSocketPath))
280 for i := 0; i < maxRetries; i++ {
281 time.Sleep(retryDelay)
282
283 // Try to connect to the socket
284 conn, err := connectToPipe(mpvSocketPath)
285 if err == nil {
286 conn.Close()
287 socketReady = true
288 Log(fmt.Sprintf("MPV socket ready after %d attempts", i+1))
289 break
290 }
291
292 Log(fmt.Sprintf("Attempt %d/%d - Socket not ready yet: %v", i+1, maxRetries, err))
293 }
294
295 if !socketReady {
296 Log(fmt.Sprintf("Failed to connect to MPV socket after %d attempts", maxRetries))
297 // Don't fail here, just warn and continue - the next commands will handle any further issues
298 }
299
300 return mpvSocketPath, nil
149 return activePlayerBackend().Start(link, args, title, anime)
301150}
302151
303152// Helper function to join args with a space
@@ -313,6 +162,10 @@ func joinArgs(args []string) string {
313162}
314163
315164func MPVSendCommand(ipcSocketPath string, command []interface{}) (interface{}, error) {
165 return activePlayerBackend().SendCommand(ipcSocketPath, command)
166}
167
168func sendMPVCommandOverIPC(ipcSocketPath string, command []interface{}) (interface{}, error) {
316169 // Use a retry mechanism for transient errors
317170 var lastErr error
318171 maxRetries := 3
internal/player_backend.go added +235
@@ -0,0 +1,235 @@
1package internal
2
3import (
4 "crypto/rand"
5 "fmt"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "runtime"
10 "strings"
11 "time"
12)
13
14const androidIntentSocketPath = "android-intent"
15
16type PlayerBackend interface {
17 Name() string
18 Mode() string
19 SupportsAutomation() bool
20 Start(link string, args []string, title string, anime *Anime) (string, error)
21 SendCommand(target string, command []interface{}) (interface{}, error)
22}
23
24type desktopPlayerBackend struct{}
25
26type androidPlayerBackend struct {
27 config *CurdConfig
28}
29
30func activePlayerBackend() PlayerBackend {
31 config := GetGlobalConfig()
32 if config != nil && config.IsAndroid() {
33 return &androidPlayerBackend{config: config}
34 }
35
36 return &desktopPlayerBackend{}
37}
38
39func (b *desktopPlayerBackend) Name() string {
40 return "desktop"
41}
42
43func (b *desktopPlayerBackend) Mode() string {
44 return "ipc"
45}
46
47func (b *desktopPlayerBackend) SupportsAutomation() bool {
48 return true
49}
50
51func (b *desktopPlayerBackend) Start(link string, args []string, title string, anime *Anime) (string, error) {
52 return startDesktopVideo(link, args, title, anime)
53}
54
55func (b *desktopPlayerBackend) SendCommand(target string, command []interface{}) (interface{}, error) {
56 return sendMPVCommandOverIPC(target, command)
57}
58
59func (b *androidPlayerBackend) Name() string {
60 return "android"
61}
62
63func (b *androidPlayerBackend) Mode() string {
64 if b.config == nil || strings.TrimSpace(b.config.AndroidPlayerMode) == "" {
65 return "intent"
66 }
67 return strings.ToLower(strings.TrimSpace(b.config.AndroidPlayerMode))
68}
69
70func (b *androidPlayerBackend) SupportsAutomation() bool {
71 return b.Mode() == "ipc"
72}
73
74func (b *androidPlayerBackend) Start(link string, args []string, title string, anime *Anime) (string, error) {
75 if b.Mode() != "ipc" {
76 return b.startIntent(link, title)
77 }
78
79 socketPath := androidConfiguredSocketPath(b.config)
80 if socketPath == "" {
81 CurdOut("Android IPC mode is missing a socket path. Falling back to intent mode.")
82 return b.startIntent(link, title)
83 }
84 socketAssessment := assessAndroidSocketPath(socketPath)
85 if !socketAssessment.Supported {
86 for _, warning := range socketAssessment.Warnings {
87 CurdOut("Android IPC mode unavailable: " + warning)
88 }
89 return b.startIntent(link, title)
90 }
91 cmdArgs := BuildAndroidIntentCommand(b.config, link, title, socketPath)
92 cmd := exec.Command("am", cmdArgs...)
93 if err := cmd.Start(); err != nil {
94 return "", fmt.Errorf("failed to start Android player in IPC mode: %w", err)
95 }
96
97 if !waitForAndroidSocket(socketPath, 5*time.Second) {
98 CurdOut("Android player did not expose IPC control. Falling back to intent mode.")
99 return b.startIntent(link, title)
100 }
101
102 if anime != nil {
103 anime.Ep.Player.SocketPath = socketPath
104 }
105 return socketPath, nil
106}
107
108func (b *androidPlayerBackend) startIntent(link string, title string) (string, error) {
109 cmdArgs := BuildAndroidIntentCommand(b.config, link, title, "")
110 cmd := exec.Command("am", cmdArgs...)
111 if err := cmd.Start(); err != nil {
112 return "", fmt.Errorf("failed to start Android intent player: %w", err)
113 }
114
115 return androidIntentSocketPath, nil
116}
117
118func (b *androidPlayerBackend) SendCommand(target string, command []interface{}) (interface{}, error) {
119 if !b.SupportsAutomation() || target == androidIntentSocketPath {
120 return nil, fmt.Errorf("android intent mode does not support playback automation")
121 }
122
123 return sendMPVCommandOverIPC(target, command)
124}
125
126func startDesktopVideo(link string, args []string, title string, anime *Anime) (string, error) {
127 var command *exec.Cmd
128 var mpvSocketPath string
129 var err error
130
131 userConfig := GetGlobalConfig()
132
133 if userConfig != nil && userConfig.MpvArgs != nil {
134 args = append(args, userConfig.MpvArgs...)
135 }
136
137 if anime.Ep.Player.SocketPath != "" && IsMPVRunning(anime.Ep.Player.SocketPath) {
138 mpvSocketPath = anime.Ep.Player.SocketPath
139
140 command := []interface{}{"loadfile", link}
141 _, err = sendMPVCommandOverIPC(mpvSocketPath, command)
142 if err != nil {
143 return "", fmt.Errorf("failed to load file in existing MPV instance: %w", err)
144 }
145
146 time.Sleep(100 * time.Millisecond)
147
148 titleCommand := []interface{}{"set_property", "force-media-title", title}
149 _, err = sendMPVCommandOverIPC(mpvSocketPath, titleCommand)
150 if err != nil {
151 Log(fmt.Sprintf("Failed to update title: %v", err))
152 }
153
154 windowTitleCommand := []interface{}{"set_property", "title", title}
155 _, err = sendMPVCommandOverIPC(mpvSocketPath, windowTitleCommand)
156 if err != nil {
157 Log(fmt.Sprintf("Failed to update window title: %v", err))
158 }
159
160 return mpvSocketPath, nil
161 }
162
163 if anime.Ep.Player.SocketPath == "" {
164 randomBytes := make([]byte, 4)
165 _, err = rand.Read(randomBytes)
166 if err != nil {
167 Log("Failed to generate random number")
168 return "", fmt.Errorf("failed to generate random number: %w", err)
169 }
170
171 randomNumber := fmt.Sprintf("%x", randomBytes)
172 if runtime.GOOS == "windows" {
173 mpvSocketPath = fmt.Sprintf(`\\.\pipe\curd_mpvsocket_%s`, randomNumber)
174 } else {
175 mpvSocketPath = filepath.Join(os.TempDir(), fmt.Sprintf("curd_mpvsocket_%s", randomNumber))
176 }
177 } else {
178 mpvSocketPath = anime.Ep.Player.SocketPath
179 }
180
181 titleArgs := []string{fmt.Sprintf("--title=%s", title), fmt.Sprintf("--force-media-title=%s", title)}
182 args = append(args, "--force-window=yes", "--idle=yes")
183 args = append(args, titleArgs...)
184
185 var mpvArgs []string
186 mpvArgs = append(mpvArgs, "--no-terminal", "--really-quiet", fmt.Sprintf("--input-ipc-server=%s", mpvSocketPath))
187 if len(args) > 0 {
188 mpvArgs = append(mpvArgs, args...)
189 }
190 mpvArgs = append(mpvArgs, link)
191
192 resolvedPlayerBinary, effectivePlayerName, err := resolveConfiguredPlayerBinary(userConfig.Player)
193 if err != nil {
194 CurdOut("Error: Failed to resolve media player")
195 Log(fmt.Sprintf("Player resolution failed for '%s': %v", userConfig.Player, err))
196 return "", err
197 }
198
199 playerArgs := mpvArgs
200 if isIINAPlayer(effectivePlayerName, resolvedPlayerBinary) {
201 playerArgs = translateMPVArgsForIINA(mpvArgs)
202 playerArgs = append(playerArgs, "--no-stdin")
203 }
204
205 command = exec.Command(resolvedPlayerBinary, playerArgs...)
206 if err = command.Start(); err != nil {
207 CurdOut(fmt.Sprintf("Error: Failed to start %s process", effectivePlayerName))
208 return "", fmt.Errorf("failed to start %s: %w", effectivePlayerName, err)
209 }
210
211 socketReady := false
212 maxRetries := 10
213 retryDelay := 300 * time.Millisecond
214
215 Log(fmt.Sprintf("Waiting for MPV socket to be ready at %s", mpvSocketPath))
216 for i := 0; i < maxRetries; i++ {
217 time.Sleep(retryDelay)
218
219 conn, err := connectToPipe(mpvSocketPath)
220 if err == nil {
221 conn.Close()
222 socketReady = true
223 Log(fmt.Sprintf("MPV socket ready after %d attempts", i+1))
224 break
225 }
226
227 Log(fmt.Sprintf("Attempt %d/%d - Socket not ready yet: %v", i+1, maxRetries, err))
228 }
229
230 if !socketReady {
231 Log(fmt.Sprintf("Failed to connect to MPV socket after %d attempts", maxRetries))
232 }
233
234 return mpvSocketPath, nil
235}
internal/selection_menu.go +41 −9
@@ -30,6 +30,11 @@ type Model struct {
3030 isHomeMenu bool // If true, ESC quits; if false, ESC goes back
3131}
3232
33func isAndroidTerminalMode() bool {
34 config := GetGlobalConfig()
35 return config != nil && config.IsAndroid()
36}
37
3338var (
3439 // Style definitions
3540 titleStyle = lipgloss.NewStyle().
@@ -148,13 +153,22 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
148153// View renders the UI and only shows as many options as fit in the terminal
149154func (m Model) View() string {
150155 var b strings.Builder
156 androidMode := isAndroidTerminalMode()
151157
152 // Display the search prompt and filter with colors
153 b.WriteString(titleStyle.Render("Search") + " (Press " +
154 quitHintStyle.Render("Ctrl+C") + " to quit):\n")
158 title := "Search"
159 if androidMode {
160 title = "Search Anime"
161 }
162 b.WriteString(titleStyle.Render(title) + "\n")
155163
156 b.WriteString(filterLabelStyle.Render("Filter: ") +
157 filterTextStyle.Render(m.filter) + "\n\n") // Added extra newline for spacing
164 if androidMode {
165 b.WriteString(filterLabelStyle.Render("Query: ") +
166 filterTextStyle.Render(m.filter) + "\n")
167 } else {
168 b.WriteString(filterLabelStyle.Render("Filter: ") +
169 filterTextStyle.Render(m.filter) + "\n")
170 }
171 b.WriteString("\n")
158172
159173 if len(m.filteredKeys) == 0 {
160174 b.WriteString(noMatchesStyle.Render("No matches found.") + "\n")
@@ -168,12 +182,28 @@ func (m Model) View() string {
168182
169183 // Render the options within the visible range
170184 for i := start; i < end; i++ {
185 label := m.filteredKeys[i].Label
186 if androidMode {
187 label = " " + label
188 }
171189 if i == m.selected {
172 b.WriteString(selectedItemStyle.Render(m.filteredKeys[i].Label) + "\n")
190 b.WriteString(selectedItemStyle.Render(label) + "\n")
173191 } else {
174 b.WriteString(regularItemStyle.Render(m.filteredKeys[i].Label) + "\n")
192 b.WriteString(regularItemStyle.Render(label) + "\n")
175193 }
194
195 if androidMode {
196 b.WriteString("\n")
197 }
198 }
199 }
200
201 if androidMode {
202 footer := "Enter select Esc back Ctrl+C quit Type to search"
203 if m.isHomeMenu {
204 footer = "Enter select Esc quit Ctrl+C quit Type to search"
176205 }
206 b.WriteString("\n" + quitHintStyle.Render(footer))
177207 }
178208
179209 return b.String()
@@ -182,7 +212,10 @@ func (m Model) View() string {
182212// visibleItemsCount calculates how many options fit in the terminal
183213func (m Model) visibleItemsCount() int {
184214 // Leave space for the filter and other UI elements
185 return m.terminalHeight - 4 // Adjust this number based on your terminal layout
215 if isAndroidTerminalMode() {
216 return max(1, (m.terminalHeight-6)/2)
217 }
218 return max(1, m.terminalHeight-4)
186219}
187220
188221// filterOptions filters and sorts options based on the search term
@@ -526,4 +559,3 @@ func DynamicSelect(options []SelectionOption) (SelectionOption, error) {
526559 }
527560 return SelectionOption{}, nil
528561}
529
internal/selection_menu_test.go added +31
@@ -0,0 +1,31 @@
1package internal
2
3import (
4 "strings"
5 "testing"
6)
7
8func TestAndroidSelectionViewShowsMobileFooter(t *testing.T) {
9 SetGlobalConfig(&CurdConfig{Platform: string(PlatformAndroid)})
10
11 model := Model{
12 allOptions: []SelectionOption{
13 {Key: "1", Label: "One Piece"},
14 {Key: "2", Label: "Frieren"},
15 },
16 filteredKeys: []SelectionOption{
17 {Key: "1", Label: "One Piece"},
18 {Key: "2", Label: "Frieren"},
19 },
20 terminalHeight: 20,
21 isHomeMenu: false,
22 }
23
24 view := model.View()
25 if !strings.Contains(view, "Enter select Esc back Ctrl+C quit Type to search") {
26 t.Fatalf("expected android footer in view: %s", view)
27 }
28 if !strings.Contains(view, "Search Anime") {
29 t.Fatalf("expected android title in view: %s", view)
30 }
31}