From 4ca3c30ee72121130cc2573a70d671c53e928abc Mon Sep 17 00:00:00 2001 From: nbsp Date: Tue, 7 Jan 2025 14:13:03 +0200 Subject: [PATCH] implement subscription saving --- ttbp/ttbp.go | 42 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/ttbp/ttbp.go b/ttbp/ttbp.go index 8853cbc..0e701a7 100644 --- a/ttbp/ttbp.go +++ b/ttbp/ttbp.go @@ -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() +}