mid day commit
This commit is contained in:
80
relay/storage/storage.go
Normal file
80
relay/storage/storage.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
|
||||
"github.com/disgoorg/snowflake/v2"
|
||||
)
|
||||
|
||||
func NewChannelStorage(filename string) (*ChannelStorage, error) {
|
||||
storage := &ChannelStorage{
|
||||
filename: filename,
|
||||
Channels: make(map[snowflake.ID]bool),
|
||||
}
|
||||
|
||||
if err := storage.Load(); err != nil && !os.IsNotExist(err) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return storage, nil
|
||||
}
|
||||
|
||||
func (s *ChannelStorage) Load() error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
data, err := os.ReadFile(s.filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return json.Unmarshal(data, s)
|
||||
}
|
||||
|
||||
func (s *ChannelStorage) Save() error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
data, err := json.MarshalIndent(s, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.WriteFile(s.filename, data, 0644)
|
||||
}
|
||||
|
||||
func (s *ChannelStorage) AddChannel(channelID snowflake.ID) error {
|
||||
s.mutex.Lock()
|
||||
s.Channels[channelID] = true
|
||||
s.mutex.Unlock()
|
||||
|
||||
return s.Save()
|
||||
}
|
||||
|
||||
func (s *ChannelStorage) RemoveChannel(channelID snowflake.ID) error {
|
||||
s.mutex.Lock()
|
||||
delete(s.Channels, channelID)
|
||||
s.mutex.Unlock()
|
||||
|
||||
return s.Save()
|
||||
}
|
||||
|
||||
func (s *ChannelStorage) IsRegistered(channelID snowflake.ID) bool {
|
||||
s.mutex.RLock()
|
||||
defer s.mutex.RUnlock()
|
||||
|
||||
return s.Channels[channelID]
|
||||
}
|
||||
|
||||
func (s *ChannelStorage) GetAll() []snowflake.ID {
|
||||
s.mutex.RLock()
|
||||
defer s.mutex.RUnlock()
|
||||
|
||||
channels := make([]snowflake.ID, 0, len(s.Channels))
|
||||
for channelID := range s.Channels {
|
||||
channels = append(channels, channelID)
|
||||
}
|
||||
|
||||
return channels
|
||||
}
|
||||
13
relay/storage/structs.go
Normal file
13
relay/storage/structs.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/disgoorg/snowflake/v2"
|
||||
)
|
||||
|
||||
type ChannelStorage struct {
|
||||
mutex sync.RWMutex
|
||||
filename string
|
||||
Channels map[snowflake.ID]bool `json:"channels"`
|
||||
}
|
||||
Reference in New Issue
Block a user