diff --git a/http.go b/http.go index 914a039..f7b5546 100644 --- a/http.go +++ b/http.go @@ -5,6 +5,7 @@ import ( "net/http" "net/url" "strconv" + "strings" "github.com/ChimeraCoder/anaconda" log "github.com/sirupsen/logrus" @@ -110,6 +111,15 @@ func handleTweetRefresh(w http.ResponseWriter, r *http.Request) { tweet, err := twitter.GetTweet(req.ID, url.Values{}) if err != nil { + if strings.Contains(err.Error(), "No status found with that ID.") { + log.WithField("id", req.ID).Info("Removing no longer existing tweet") + if err = tweetStore.DeleteTweetByID(uint64(req.ID)); err != nil { + log.WithError(err).Error("Unable to delete tweet") + http.Error(w, "Something went wrong", http.StatusInternalServerError) + } + return + } + log.WithError(err).Error("Unable to fetch tweet") http.Error(w, "Something went wrong", http.StatusInternalServerError) return diff --git a/storage.go b/storage.go index c573f14..3ed1bb5 100644 --- a/storage.go +++ b/storage.go @@ -31,32 +31,29 @@ func newStore(location string) (*store, error) { return s, s.load() } -func (s *store) StoreTweets(tweets []tweet) error { +func (s *store) DeleteTweetByID(id uint64) error { s.lock.Lock() defer s.lock.Unlock() - tmp := s.s + var ( + tmp = []tweet{} + needsSave bool + ) - for _, t := range tweets { - var stored bool - - for i := 0; i < len(tmp); i++ { - if tmp[i].ID == t.ID { - tmp[i] = t - stored = true - break - } + for _, t := range s.s { + if t.ID == id { + needsSave = true + continue } - if !stored { - tmp = append(tmp, t) - } + tmp = append(tmp, t) } - sort.Slice(tmp, func(j, i int) bool { return tmp[i].ID < tmp[j].ID }) + if !needsSave { + return nil + } s.s = tmp - return s.save() } @@ -106,6 +103,35 @@ func (s *store) GetTweetsSince(since uint64) ([]tweet, error) { return s.s[:i], nil } +func (s *store) StoreTweets(tweets []tweet) error { + s.lock.Lock() + defer s.lock.Unlock() + + tmp := s.s + + for _, t := range tweets { + var stored bool + + for i := 0; i < len(tmp); i++ { + if tmp[i].ID == t.ID { + tmp[i] = t + stored = true + break + } + } + + if !stored { + tmp = append(tmp, t) + } + } + + sort.Slice(tmp, func(j, i int) bool { return tmp[i].ID < tmp[j].ID }) + + s.s = tmp + + return s.save() +} + func (s *store) load() error { s.lock.Lock() defer s.lock.Unlock()