internal/android.go
420 lines · 13543 bytes
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}