99 lines
2.4 KiB
Go
99 lines
2.4 KiB
Go
package db
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
type targetConfig struct {
|
|
Targets []struct {
|
|
Name string `yaml:"name"`
|
|
TargetURL string `yaml:"target_url"`
|
|
Platform string `yaml:"platform"`
|
|
IsActive bool `yaml:"is_active"`
|
|
} `yaml:"targets"`
|
|
}
|
|
|
|
// LoadTargetsFromYAML reads a YAML file and inserts/syncs targets with the database
|
|
func (db *DB) LoadTargetsFromYAML(filepath string) error {
|
|
data, err := os.ReadFile(filepath)
|
|
if err != nil {
|
|
return fmt.Errorf("could not read target config: %w", err)
|
|
}
|
|
|
|
var config targetConfig
|
|
if err := yaml.Unmarshal(data, &config); err != nil {
|
|
return fmt.Errorf("could not parse target config: %w", err)
|
|
}
|
|
|
|
// Get existing targets to prevent duplicates and sync is_active if needed
|
|
existingTargets, err := db.GetAllTargets()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
existingURLs := make(map[string]*SearchTarget)
|
|
for i := range existingTargets {
|
|
existingURLs[existingTargets[i].TargetURL] = &existingTargets[i]
|
|
}
|
|
|
|
for _, t := range config.Targets {
|
|
existing, found := existingURLs[t.TargetURL]
|
|
if !found {
|
|
_, err := db.CreateTarget(t.Name, t.TargetURL, t.Platform, t.IsActive)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to insert target %s: %w", t.Name, err)
|
|
}
|
|
} else {
|
|
// Sync is_active state with targets.yaml on startup
|
|
if existing.IsActive != t.IsActive {
|
|
_ = db.SetTargetActive(existing.ID, t.IsActive)
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// RemoveTargetFromYAML removes a target from the target configuration YAML file if it exists
|
|
func RemoveTargetFromYAML(filepath string, targetURL string) error {
|
|
if filepath == "" {
|
|
return nil
|
|
}
|
|
data, err := os.ReadFile(filepath)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("could not read target config: %w", err)
|
|
}
|
|
|
|
var config targetConfig
|
|
if err := yaml.Unmarshal(data, &config); err != nil {
|
|
return fmt.Errorf("could not parse target config: %w", err)
|
|
}
|
|
|
|
var newTargets []struct {
|
|
Name string `yaml:"name"`
|
|
TargetURL string `yaml:"target_url"`
|
|
Platform string `yaml:"platform"`
|
|
IsActive bool `yaml:"is_active"`
|
|
}
|
|
|
|
for _, t := range config.Targets {
|
|
if t.TargetURL != targetURL {
|
|
newTargets = append(newTargets, t)
|
|
}
|
|
}
|
|
|
|
config.Targets = newTargets
|
|
outData, err := yaml.Marshal(&config)
|
|
if err != nil {
|
|
return fmt.Errorf("could not marshal target config: %w", err)
|
|
}
|
|
|
|
return os.WriteFile(filepath, outData, 0644)
|
|
}
|
|
|