Refactor post handling and add command setup for Telegram bot

This commit is contained in:
dela
2026-02-05 00:52:29 +08:00
parent d82badc6e3
commit 8a6859269c
9 changed files with 612 additions and 21 deletions

View File

@@ -15,6 +15,7 @@ var (
bucketAppConfig = []byte("AppConfig")
bucketCategories = []byte("Categories")
bucketEntries = []byte("Entries")
bucketAdmins = []byte("Admins")
keyTocMsgID = []byte("toc_msg_id")
)
@@ -59,7 +60,7 @@ func New(path string) (*Storage, error) {
func (s *Storage) initBuckets() error {
return s.db.Update(func(tx *bolt.Tx) error {
buckets := [][]byte{bucketAppConfig, bucketCategories, bucketEntries}
buckets := [][]byte{bucketAppConfig, bucketCategories, bucketEntries, bucketAdmins}
for _, b := range buckets {
if _, err := tx.CreateBucketIfNotExists(b); err != nil {
return fmt.Errorf("failed to create bucket %s: %w", b, err)
@@ -102,3 +103,50 @@ func encodeJSON(v any) ([]byte, error) {
func decodeJSON(data []byte, v any) error {
return json.Unmarshal(data, v)
}
// Admin management
func (s *Storage) AddAdmin(userID int64) error {
return s.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket(bucketAdmins)
key := make([]byte, 8)
binary.BigEndian.PutUint64(key, uint64(userID))
return b.Put(key, []byte("1"))
})
}
func (s *Storage) RemoveAdmin(userID int64) error {
return s.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket(bucketAdmins)
key := make([]byte, 8)
binary.BigEndian.PutUint64(key, uint64(userID))
return b.Delete(key)
})
}
func (s *Storage) IsAdmin(userID int64) bool {
var exists bool
s.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket(bucketAdmins)
key := make([]byte, 8)
binary.BigEndian.PutUint64(key, uint64(userID))
exists = b.Get(key) != nil
return nil
})
return exists
}
func (s *Storage) ListAdmins() ([]int64, error) {
var admins []int64
err := s.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket(bucketAdmins)
return b.ForEach(func(k, v []byte) error {
if len(k) == 8 {
userID := int64(binary.BigEndian.Uint64(k))
admins = append(admins, userID)
}
return nil
})
})
return admins, err
}