-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanager.go
More file actions
502 lines (428 loc) 路 12 KB
/
Copy pathmanager.go
File metadata and controls
502 lines (428 loc) 路 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
package plugin
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/halpworld/halpradio/pkg/util"
)
type pluginEntry struct {
manifest Manifest
state PluginState
dir string
wasmPath string
storage *Storage
sandbox *Sandbox
lastErr string
}
// Manager orchestrates plugin discovery, lifecycle, sandboxing, and event dispatching.
type Manager struct {
mu sync.RWMutex
pluginsDir string
dataDir string
stateFile string
entries map[string]*pluginEntry
registry *RegistryClient
onNotify func(title, msg string)
onFlash func(msg string)
logHandler func(level int, msg string)
isClosing bool
}
// NewManager initializes the plugin manager with configured paths.
func NewManager(registryURL string) *Manager {
pluginsDir := util.GetPluginsDir()
dataDir := util.GetPluginsDataDir()
stateFile := util.GetPluginsConfigFile()
return &Manager{
pluginsDir: pluginsDir,
dataDir: dataDir,
stateFile: stateFile,
entries: make(map[string]*pluginEntry),
registry: NewRegistryClient(registryURL),
}
}
// SetNotifyHandler sets the callback for UI/desktop notifications emitted by plugins.
func (m *Manager) SetNotifyHandler(fn func(title, msg string)) {
m.mu.Lock()
defer m.mu.Unlock()
m.onNotify = fn
}
// SetFlashHandler sets the callback for status bar flash messages emitted by plugins.
func (m *Manager) SetFlashHandler(fn func(msg string)) {
m.mu.Lock()
defer m.mu.Unlock()
m.onFlash = fn
}
// SetLogHandler sets the callback for plugin debug/info/error logs.
func (m *Manager) SetLogHandler(fn func(level int, msg string)) {
m.mu.Lock()
defer m.mu.Unlock()
m.logHandler = fn
}
func (m *Manager) log(level int, msg string) {
m.mu.RLock()
fn := m.logHandler
m.mu.RUnlock()
if fn != nil {
fn(level, msg)
}
}
// Init loads states and initializes installed plugins.
func (m *Manager) Init() error {
m.mu.Lock()
defer m.mu.Unlock()
_ = os.MkdirAll(m.pluginsDir, 0700)
_ = os.MkdirAll(m.dataDir, 0700)
savedStates := m.loadSavedStates()
// Scan plugins directory
entries, err := os.ReadDir(m.pluginsDir)
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to read plugins dir: %w", err)
}
for _, d := range entries {
if !d.IsDir() {
continue
}
pluginID := d.Name()
pluginDirPath := filepath.Join(m.pluginsDir, pluginID)
// Check manifest
manifestPath := filepath.Join(pluginDirPath, "manifest.yaml")
if _, err := os.Stat(manifestPath); os.IsNotExist(err) {
manifestPath = filepath.Join(pluginDirPath, "manifest.json")
}
manifest, err := LoadManifest(manifestPath)
if err != nil {
m.log(3, fmt.Sprintf("Failed loading manifest for plugin %s: %v", pluginID, err))
continue
}
if err := manifest.Validate(); err != nil {
m.log(3, fmt.Sprintf("Plugin manifest validation failed for %s: %v", pluginID, err))
continue
}
wasmPath := filepath.Join(pluginDirPath, manifest.WasmFile)
rel, err := filepath.Rel(pluginDirPath, wasmPath)
if err != nil || strings.HasPrefix(rel, "..") {
m.log(3, fmt.Sprintf("Plugin %s has invalid wasm path: %s", pluginID, wasmPath))
continue
}
_, wasmErr := os.Stat(wasmPath)
state, hasState := savedStates[manifest.ID]
if !hasState {
state = PluginState{
Enabled: true,
PermissionsApproved: false, // Default: requires user approval
InstalledAt: time.Now().Format(time.RFC3339),
}
}
entry := &pluginEntry{
manifest: *manifest,
state: state,
dir: pluginDirPath,
wasmPath: wasmPath,
}
if wasmErr == nil && state.Enabled {
m.startPluginLocked(entry)
}
m.entries[manifest.ID] = entry
}
return m.saveStatesLocked()
}
func (m *Manager) startPluginLocked(entry *pluginEntry) {
storage, err := NewStorage(m.dataDir, entry.manifest.ID)
if err != nil {
entry.lastErr = fmt.Sprintf("Storage init error: %v", err)
return
}
entry.storage = storage
wasmBytes, err := os.ReadFile(entry.wasmPath)
if err != nil {
entry.lastErr = fmt.Sprintf("Wasm read error: %v", err)
return
}
sb, err := NewSandbox(
context.Background(),
entry.manifest,
entry.state,
wasmBytes,
storage,
m.onNotify,
m.onFlash,
m.logHandler,
)
if err != nil {
entry.lastErr = fmt.Sprintf("Sandbox compilation error: %v", err)
return
}
if err := sb.Start(entry.state.Config); err != nil {
entry.lastErr = fmt.Sprintf("Startup error: %v", err)
_ = sb.Close()
return
}
entry.sandbox = sb
entry.lastErr = ""
}
func (m *Manager) stopPluginLocked(entry *pluginEntry) {
if entry.sandbox != nil {
_ = entry.sandbox.Close()
entry.sandbox = nil
}
}
// loadSavedStates reads plugins.json.
func (m *Manager) loadSavedStates() map[string]PluginState {
data, err := os.ReadFile(m.stateFile)
if err != nil {
return make(map[string]PluginState)
}
var cfg PluginsConfigFile
if err := json.Unmarshal(data, &cfg); err != nil {
return make(map[string]PluginState)
}
if cfg.Plugins == nil {
cfg.Plugins = make(map[string]PluginState)
}
return cfg.Plugins
}
// saveStatesLocked writes plugins.json.
func (m *Manager) saveStatesLocked() error {
states := make(map[string]PluginState, len(m.entries))
for id, entry := range m.entries {
states[id] = entry.state
}
cfg := PluginsConfigFile{Plugins: states}
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return err
}
return os.WriteFile(m.stateFile, data, 0644)
}
// GetPlugins returns a snapshot list of all installed plugins.
func (m *Manager) GetPlugins() []PluginInfo {
m.mu.RLock()
defer m.mu.RUnlock()
res := make([]PluginInfo, 0, len(m.entries))
for _, e := range m.entries {
_, wasmErr := os.Stat(e.wasmPath)
res = append(res, PluginInfo{
Manifest: e.manifest,
State: e.state,
Dir: e.dir,
WasmPath: e.wasmPath,
HasValidBinary: wasmErr == nil,
IsLoaded: e.sandbox != nil,
LastError: e.lastErr,
})
}
return res
}
// GetPlugin returns a single installed plugin's info.
func (m *Manager) GetPlugin(id string) (PluginInfo, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
e, found := m.entries[id]
if !found {
return PluginInfo{}, false
}
_, wasmErr := os.Stat(e.wasmPath)
return PluginInfo{
Manifest: e.manifest,
State: e.state,
Dir: e.dir,
WasmPath: e.wasmPath,
HasValidBinary: wasmErr == nil,
IsLoaded: e.sandbox != nil,
LastError: e.lastErr,
}, true
}
// EnablePlugin enables and starts a plugin.
func (m *Manager) EnablePlugin(id string) error {
m.mu.Lock()
defer m.mu.Unlock()
entry, found := m.entries[id]
if !found {
return fmt.Errorf("plugin %s not found", id)
}
entry.state.Enabled = true
if entry.sandbox == nil {
m.startPluginLocked(entry)
}
return m.saveStatesLocked()
}
// DisablePlugin stops and disables a plugin.
func (m *Manager) DisablePlugin(id string) error {
m.mu.Lock()
defer m.mu.Unlock()
entry, found := m.entries[id]
if !found {
return fmt.Errorf("plugin %s not found", id)
}
entry.state.Enabled = false
m.stopPluginLocked(entry)
return m.saveStatesLocked()
}
// ApprovePermissions updates permission approval state for a plugin.
func (m *Manager) ApprovePermissions(id string, approve bool) error {
m.mu.Lock()
defer m.mu.Unlock()
entry, found := m.entries[id]
if !found {
return fmt.Errorf("plugin %s not found", id)
}
entry.state.PermissionsApproved = approve
if entry.sandbox != nil {
entry.sandbox.UpdateState(entry.state)
} else if entry.state.Enabled && approve {
m.startPluginLocked(entry)
}
return m.saveStatesLocked()
}
// RegistryClient returns the active registry client.
func (m *Manager) RegistryClient() *RegistryClient {
return m.registry
}
// InstallFromRegistry downloads and installs a plugin from registry metadata.
func (m *Manager) InstallFromRegistry(ctx context.Context, reg PluginOrRegistry) error {
m.mu.Lock()
defer m.mu.Unlock()
regPlugin := reg.ToRegistryPlugin()
if err := m.registry.DownloadAndInstall(ctx, regPlugin, m.pluginsDir); err != nil {
return err
}
// Reload the plugin into manager
pluginDirPath := filepath.Join(m.pluginsDir, regPlugin.ID)
manifestPath := filepath.Join(pluginDirPath, "manifest.yaml")
manifest, err := LoadManifest(manifestPath)
if err != nil {
return fmt.Errorf("failed loading installed manifest: %w", err)
}
if err := manifest.Validate(); err != nil {
return fmt.Errorf("installed plugin manifest validation failed: %w", err)
}
wasmPath := filepath.Join(pluginDirPath, manifest.WasmFile)
rel, err := filepath.Rel(pluginDirPath, wasmPath)
if err != nil || strings.HasPrefix(rel, "..") {
return fmt.Errorf("invalid wasm path in plugin %s", regPlugin.ID)
}
entry := &pluginEntry{
manifest: *manifest,
state: PluginState{
Enabled: true,
PermissionsApproved: false, // Prompt required after install
InstalledAt: time.Now().Format(time.RFC3339),
UpdatedAt: time.Now().Format(time.RFC3339),
},
dir: pluginDirPath,
wasmPath: wasmPath,
}
// If old sandbox existed, close it
if old, exists := m.entries[regPlugin.ID]; exists {
m.stopPluginLocked(old)
entry.state.PermissionsApproved = old.state.PermissionsApproved
}
m.entries[regPlugin.ID] = entry
if entry.state.Enabled && entry.state.PermissionsApproved {
m.startPluginLocked(entry)
}
return m.saveStatesLocked()
}
// UninstallPlugin stops, deletes, and removes a plugin.
func (m *Manager) UninstallPlugin(id string) error {
m.mu.Lock()
defer m.mu.Unlock()
entry, found := m.entries[id]
if !found {
return fmt.Errorf("plugin %s not found", id)
}
m.stopPluginLocked(entry)
_ = os.RemoveAll(entry.dir)
delete(m.entries, id)
return m.saveStatesLocked()
}
// Close shuts down all running sandboxes and plugins.
func (m *Manager) Close() error {
m.mu.Lock()
defer m.mu.Unlock()
m.isClosing = true
for _, entry := range m.entries {
m.stopPluginLocked(entry)
}
return nil
}
// Asynchronous Event Dispatching
// DispatchTrackChange sends track change payload to all approved enabled plugins.
func (m *Manager) DispatchTrackChange(payload TrackChangePayload) {
m.mu.RLock()
if m.isClosing || len(m.entries) == 0 {
m.mu.RUnlock()
return
}
data, err := json.Marshal(payload)
if err != nil {
m.mu.RUnlock()
return
}
// Dispatch to each plugin in parallel goroutines so Bubble Tea TUI rendering is never blocked
for _, entry := range m.entries {
if entry.state.Enabled && entry.state.PermissionsApproved && entry.sandbox != nil && entry.manifest.Permissions.HasEvent("on_track_change") {
sb := entry.sandbox
go func(s *Sandbox, d []byte) {
_ = s.InvokeHook("on_track_change", d)
}(sb, data)
}
}
m.mu.RUnlock()
}
// DispatchPlaybackChange sends playback state changes to all approved enabled plugins.
func (m *Manager) DispatchPlaybackChange(payload PlaybackChangePayload) {
m.mu.RLock()
if m.isClosing || len(m.entries) == 0 {
m.mu.RUnlock()
return
}
data, err := json.Marshal(payload)
if err != nil {
m.mu.RUnlock()
return
}
for _, entry := range m.entries {
if entry.state.Enabled && entry.state.PermissionsApproved && entry.sandbox != nil && entry.manifest.Permissions.HasEvent("on_playback_change") {
sb := entry.sandbox
go func(s *Sandbox, d []byte) {
_ = s.InvokeHook("on_playback_change", d)
}(sb, data)
}
}
m.mu.RUnlock()
}
// DispatchTimerTick sends periodic timer ticks to plugins.
func (m *Manager) DispatchTimerTick(payload TimerTickPayload) {
m.mu.RLock()
if m.isClosing || len(m.entries) == 0 {
m.mu.RUnlock()
return
}
data, err := json.Marshal(payload)
if err != nil {
m.mu.RUnlock()
return
}
for _, entry := range m.entries {
if entry.state.Enabled && entry.state.PermissionsApproved && entry.sandbox != nil && entry.manifest.Permissions.HasEvent("on_timer_tick") {
sb := entry.sandbox
go func(s *Sandbox, d []byte) {
_ = s.InvokeHook("on_timer_tick", d)
}(sb, data)
}
}
m.mu.RUnlock()
}
// PluginOrRegistry interface for versatile installer
type PluginOrRegistry interface {
ToRegistryPlugin() RegistryPlugin
}
func (r RegistryPlugin) ToRegistryPlugin() RegistryPlugin {
return r
}