implement subscription saving

trunk
nbsp 2025-01-07 14:13:03 +02:00
parent a5257bb705
commit 4ca3c30ee7
No known key found for this signature in database
GPG Key ID: 7184AC1C9835CE48
1 changed files with 37 additions and 5 deletions

View File

@ -139,18 +139,30 @@ func SortPostsByRecent(posts []Post) []Post {
}
type Subscriptions struct {
users []User
users []string
}
func GetSubscriptions() *Subscriptions {
file, err := os.OpenFile(path.Join(os.Getenv("HOME"), ".ttbp/config/subs"), os.O_RDONLY|os.O_CREATE, 0644)
if err != nil {
return &Subscriptions{}
}
defer file.Close()
var users []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
users = append(users, scanner.Text())
}
return &Subscriptions{
users: []User{},
users: users,
}
}
func (subscriptions *Subscriptions) IsSubscribed(user User) bool {
for _, sub := range subscriptions.users {
if sub.Name == user.Name {
if sub == user.Name {
return true
}
}
@ -158,14 +170,34 @@ func (subscriptions *Subscriptions) IsSubscribed(user User) bool {
}
func (subscriptions *Subscriptions) Subscribe(user User) {
subscriptions.users = append(subscriptions.users, user)
subscriptions.users = append(subscriptions.users, user.Name)
subscriptions.write()
}
func (subscriptions *Subscriptions) Unsubscribe(user User) {
for i, sub := range subscriptions.users {
if sub.Name == user.Name {
if sub == user.Name {
subscriptions.users = append(subscriptions.users[:i], subscriptions.users[i+1:]...)
subscriptions.write()
return
}
}
}
func (subscriptions *Subscriptions) write() {
file, err := os.Create(path.Join(os.Getenv("HOME"), ".ttbp/config/subs"))
if err != nil {
return
}
defer file.Close()
writer := bufio.NewWriter(file)
for _, line := range subscriptions.users {
_, err := writer.WriteString(line + "\n")
if err != nil {
return
}
}
writer.Flush()
}