| 1 | package conversation |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "errors" |
| 7 | "net/url" |
| 8 | |
| 9 | "gorm.io/gorm" |
| 10 | ) |
| 11 | |
| 12 | type PreferenceView struct { |
| 13 | Preference |
| 14 | StatusKey, SourceURL, RequestID, DeleteRequestID string |
| 15 | } |
| 16 | type PreferencePage struct { |
| 17 | Topic string |
| 18 | Items []PreferenceView |
| 19 | Source *Message |
| 20 | RequestID string |
| 21 | } |
| 22 | |
| 23 | func (s *Application) PreferencePage(ctx context.Context, actor Actor, sourceID string) (out PreferencePage, err error) { |
| 24 | actor.Address = s.Normalize(actor.Address) |
| 25 | out.RequestID = rand.Text() |
| 26 | err = s.Write(ctx, func(tx *gorm.DB) error { |
| 27 | cs := s.Conversation(tx) |
| 28 | main, err := cs.main(actor) |
| 29 | if err != nil { |
| 30 | return err |
| 31 | } |
| 32 | out.Topic = PersonalTopic(main.TeamID, actor.Address) |
| 33 | if sourceID != "" { |
| 34 | msg, err := cs.preferenceSource(main, sourceID) |
| 35 | if err != nil { |
| 36 | return err |
| 37 | } |
| 38 | out.Source = &msg |
| 39 | return nil |
| 40 | } |
| 41 | prefs, err := cs.Preferences(actor) |
| 42 | if err != nil { |
| 43 | return err |
| 44 | } |
| 45 | for _, p := range prefs { |
| 46 | v := PreferenceView{Preference: p, StatusKey: "preferences." + p.Status, RequestID: rand.Text(), DeleteRequestID: rand.Text()} |
| 47 | if p.SourceMessageID != "" { |
| 48 | if _, err = cs.preferenceSource(main, p.SourceMessageID); err == nil { |
| 49 | v.SourceURL = "/preferences/sources/" + url.PathEscape(p.SourceMessageID) |
| 50 | } else if !errors.Is(err, cs.deps.NotFound) { |
| 51 | return err |
| 52 | } |
| 53 | } |
| 54 | out.Items = append(out.Items, v) |
| 55 | } |
| 56 | return nil |
| 57 | }) |
| 58 | if err != nil { |
| 59 | out = PreferencePage{} |
| 60 | } |
| 61 | return |
| 62 | } |
| 63 | |