1package state
2
3import (
4 "log"
5 "net/http"
6 "time"
7
8 comatproto "github.com/bluesky-social/indigo/api/atproto"
9 lexutil "github.com/bluesky-social/indigo/lex/util"
10 "tangled.sh/tangled.sh/core/api/tangled"
11 "tangled.sh/tangled.sh/core/appview"
12 "tangled.sh/tangled.sh/core/appview/db"
13 "tangled.sh/tangled.sh/core/appview/pages"
14)
15
16func (s *State) Follow(w http.ResponseWriter, r *http.Request) {
17 currentUser := s.oauth.GetUser(r)
18
19 subject := r.URL.Query().Get("subject")
20 if subject == "" {
21 log.Println("invalid form")
22 return
23 }
24
25 subjectIdent, err := s.resolver.ResolveIdent(r.Context(), subject)
26 if err != nil {
27 log.Println("failed to follow, invalid did")
28 }
29
30 if currentUser.Did == subjectIdent.DID.String() {
31 log.Println("cant follow or unfollow yourself")
32 return
33 }
34
35 client, err := s.oauth.AuthorizedClient(r)
36 if err != nil {
37 log.Println("failed to authorize client")
38 return
39 }
40
41 switch r.Method {
42 case http.MethodPost:
43 createdAt := time.Now().Format(time.RFC3339)
44 rkey := appview.TID()
45 resp, err := client.RepoPutRecord(r.Context(), &comatproto.RepoPutRecord_Input{
46 Collection: tangled.GraphFollowNSID,
47 Repo: currentUser.Did,
48 Rkey: rkey,
49 Record: &lexutil.LexiconTypeDecoder{
50 Val: &tangled.GraphFollow{
51 Subject: subjectIdent.DID.String(),
52 CreatedAt: createdAt,
53 }},
54 })
55 if err != nil {
56 log.Println("failed to create atproto record", err)
57 return
58 }
59
60 err = db.AddFollow(s.db, currentUser.Did, subjectIdent.DID.String(), rkey)
61 if err != nil {
62 log.Println("failed to follow", err)
63 return
64 }
65
66 log.Println("created atproto record: ", resp.Uri)
67
68 s.pages.FollowFragment(w, pages.FollowFragmentParams{
69 UserDid: subjectIdent.DID.String(),
70 FollowStatus: db.IsFollowing,
71 })
72
73 return
74 case http.MethodDelete:
75 // find the record in the db
76 follow, err := db.GetFollow(s.db, currentUser.Did, subjectIdent.DID.String())
77 if err != nil {
78 log.Println("failed to get follow relationship")
79 return
80 }
81
82 _, err = client.RepoDeleteRecord(r.Context(), &comatproto.RepoDeleteRecord_Input{
83 Collection: tangled.GraphFollowNSID,
84 Repo: currentUser.Did,
85 Rkey: follow.Rkey,
86 })
87
88 if err != nil {
89 log.Println("failed to unfollow")
90 return
91 }
92
93 err = db.DeleteFollowByRkey(s.db, currentUser.Did, follow.Rkey)
94 if err != nil {
95 log.Println("failed to delete follow from DB")
96 // this is not an issue, the firehose event might have already done this
97 }
98
99 s.pages.FollowFragment(w, pages.FollowFragmentParams{
100 UserDid: subjectIdent.DID.String(),
101 FollowStatus: db.IsNotFollowing,
102 })
103
104 return
105 }
106
107}