2023-09-17 03:52:37 -04:00
|
|
|
package database
|
|
|
|
|
|
|
|
import (
|
2024-04-24 00:51:37 -04:00
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
2023-09-20 21:08:02 -04:00
|
|
|
"path/filepath"
|
2024-04-24 00:51:37 -04:00
|
|
|
|
2024-09-17 01:10:13 -04:00
|
|
|
"github.com/nitezs/sub2clash/model"
|
2023-11-02 14:35:30 -04:00
|
|
|
|
2024-04-24 00:51:37 -04:00
|
|
|
"go.etcd.io/bbolt"
|
2023-09-17 03:52:37 -04:00
|
|
|
)
|
|
|
|
|
2024-04-24 00:51:37 -04:00
|
|
|
var DB *bbolt.DB
|
2023-09-17 03:52:37 -04:00
|
|
|
|
|
|
|
func ConnectDB() error {
|
2024-04-24 00:51:37 -04:00
|
|
|
path := filepath.Join("data", "sub2clash.db")
|
2024-08-11 11:55:47 -04:00
|
|
|
|
2024-04-24 00:51:37 -04:00
|
|
|
db, err := bbolt.Open(path, 0600, nil)
|
2023-09-20 21:08:02 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2023-09-17 04:14:31 -04:00
|
|
|
}
|
2023-09-17 03:52:37 -04:00
|
|
|
DB = db
|
2023-09-20 21:08:02 -04:00
|
|
|
|
2024-04-24 00:51:37 -04:00
|
|
|
return db.Update(func(tx *bbolt.Tx) error {
|
|
|
|
_, err := tx.CreateBucketIfNotExists([]byte("ShortLinks"))
|
|
|
|
return err
|
|
|
|
})
|
2023-09-20 21:08:02 -04:00
|
|
|
}
|
|
|
|
|
2024-04-24 00:51:37 -04:00
|
|
|
func FindShortLinkByHash(hash string) (*model.ShortLink, error) {
|
|
|
|
var shortLink model.ShortLink
|
|
|
|
err := DB.View(func(tx *bbolt.Tx) error {
|
|
|
|
b := tx.Bucket([]byte("ShortLinks"))
|
|
|
|
v := b.Get([]byte(hash))
|
|
|
|
if v == nil {
|
|
|
|
return errors.New("ShortLink not found")
|
|
|
|
}
|
|
|
|
return json.Unmarshal(v, &shortLink)
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &shortLink, nil
|
2023-09-20 21:08:02 -04:00
|
|
|
}
|
|
|
|
|
2024-04-24 00:51:37 -04:00
|
|
|
func SaveShortLink(shortLink *model.ShortLink) error {
|
|
|
|
return DB.Update(func(tx *bbolt.Tx) error {
|
|
|
|
b := tx.Bucket([]byte("ShortLinks"))
|
|
|
|
encoded, err := json.Marshal(shortLink)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return b.Put([]byte(shortLink.Hash), encoded)
|
|
|
|
})
|
2023-09-20 21:08:02 -04:00
|
|
|
}
|
|
|
|
|
2024-04-24 00:51:37 -04:00
|
|
|
func CheckShortLinkHashExists(hash string) (bool, error) {
|
|
|
|
exists := false
|
|
|
|
err := DB.View(func(tx *bbolt.Tx) error {
|
|
|
|
b := tx.Bucket([]byte("ShortLinks"))
|
|
|
|
v := b.Get([]byte(hash))
|
|
|
|
exists = v != nil
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
return exists, nil
|
2023-09-20 21:08:02 -04:00
|
|
|
}
|