package internal import ( "context" "encoding/json" "fmt" "os" "path/filepath" "github.com/pkg/errors" ) type ChannelConfig struct { ID int64 `json:"id"` Offset int `json:"offset"` MinID int `json:"min_id"` } func NewChannelConfig(channelID int64) *ChannelConfig { if channelID == 0 { panic("channel id is required") } return &ChannelConfig{ID: channelID} } func (c *ChannelConfig) Asset(assetID int64, ext string) string { assetFile := fmt.Sprintf("outputs/%d/assets/%d.%s", c.ID, assetID, ext) // if file dir not exists then create it if _, err := os.Stat(filepath.Dir(assetFile)); os.IsNotExist(err) { if err := os.MkdirAll(filepath.Dir(assetFile), 0o755); err != nil { panic(err) } } // if file exists then delete it if _, err := os.Stat(assetFile); err == nil { if err := os.Remove(assetFile); err != nil { panic(err) } } return assetFile } func (c *ChannelConfig) file(_ context.Context) (string, error) { channelConfigFile := fmt.Sprintf("outputs/%d/config.json", c.ID) // if file dir not exists then create it if _, err := os.Stat(filepath.Dir(channelConfigFile)); os.IsNotExist(err) { if err := os.MkdirAll(filepath.Dir(channelConfigFile), 0o755); err != nil { return "", errors.Wrap(err, "create channel config dir") } } // if file not exists then create it if _, err := os.Stat(channelConfigFile); os.IsNotExist(err) { // create config file data, _ := json.Marshal(c) if err := os.WriteFile(channelConfigFile, data, 0o644); err != nil { return "", errors.Wrap(err, "write channel config") } } return channelConfigFile, nil } func (c *ChannelConfig) Read(ctx context.Context) error { channelConfigFile, err := c.file(ctx) if err != nil { return err } // read config file data, err := os.ReadFile(channelConfigFile) if err != nil { return errors.Wrap(err, "read channel config") } if err := json.Unmarshal(data, &c); err != nil { return errors.Wrap(err, "unmarshal channel config") } return nil } func (c *ChannelConfig) Update(ctx context.Context, offsetID int) error { channelConfigFile, err := c.file(ctx) if err != nil { return err } c.Offset = offsetID if c.MinID < offsetID { c.MinID = offsetID } b, err := json.Marshal(c) if err != nil { return errors.Wrap(err, "marshal channel config") } if err := os.WriteFile(channelConfigFile, b, 0o644); err != nil { return errors.Wrap(err, "write channel config") } return nil } func (c *ChannelConfig) SaveMessage(msg *ChannelMessage) { // save message saveTo := fmt.Sprintf("outputs/%d/%d.json", c.ID, msg.ID) b, err := json.Marshal(msg) if err != nil { panic(err) } if err := os.WriteFile(saveTo, b, 0o644); err != nil { panic(err) } }