github.com/vchain-us/vcn@v0.9.11-0.20210921212052-a2484d23c0b3/pkg/store/alerts.go (about) 1 /* 2 * Copyright (c) 2018-2020 vChain, Inc. All Rights Reserved. 3 * This software is released under GPL3. 4 * The full license information can be found under: 5 * https://www.gnu.org/licenses/gpl-3.0.en.html 6 * 7 */ 8 9 package store 10 11 import ( 12 "fmt" 13 "os" 14 "path/filepath" 15 16 "gopkg.in/yaml.v2" 17 ) 18 19 type Alert struct { 20 Name string 21 Arg string 22 Config interface{} 23 } 24 25 func (a Alert) ExportConfig(out interface{}) error { 26 tmp, err := yaml.Marshal(a.Config) 27 if err != nil { 28 return fmt.Errorf("invalid alert config: %s", err) 29 } 30 if err := yaml.Unmarshal(tmp, out); err != nil { 31 return fmt.Errorf("invalid alert config: %s", err) 32 } 33 return nil 34 } 35 36 type Alerts map[string]Alert 37 38 func loadAlerts(filepath string) (Alerts, error) { 39 a := make(Alerts) 40 err := ReadYAML(&a, filepath) 41 if os.IsNotExist(err) { 42 return a, nil 43 } 44 return a, err 45 } 46 47 func saveAlerts(alerts Alerts, filepath string) error { 48 return WriteYAML(alerts, filepath) 49 } 50 51 func AlertFilepath(email string) (string, error) { 52 path := filepath.Join(dir, defaultAlertsDir) 53 if err := ensureDir(path); err != nil { 54 return "", err 55 } 56 return filepath.Join(path, email+".yaml"), nil 57 } 58 59 func SaveAlert(userEmail string, alertID string, alert Alert) error { 60 path, err := AlertFilepath(userEmail) 61 if err != nil { 62 return err 63 } 64 65 alerts, err := loadAlerts(path) 66 if err != nil { 67 return err 68 } 69 70 alerts[alertID] = alert 71 72 return saveAlerts(alerts, path) 73 } 74 75 func DeleteAlert(userEmail string, id string) error { 76 path, err := AlertFilepath(userEmail) 77 if err != nil { 78 return err 79 } 80 81 alerts, err := loadAlerts(path) 82 if err != nil { 83 return err 84 } 85 86 delete(alerts, id) 87 88 return saveAlerts(alerts, path) 89 } 90 91 func ReadAlerts(userEmail string) (Alerts, error) { 92 path, err := AlertFilepath(userEmail) 93 if err != nil { 94 return make(Alerts), err 95 } 96 return loadAlerts(path) 97 }