collaborator.go

 1package webhook
 2
 3import (
 4	"context"
 5
 6	"github.com/charmbracelet/soft-serve/pkg/access"
 7	"github.com/charmbracelet/soft-serve/pkg/db"
 8	"github.com/charmbracelet/soft-serve/pkg/proto"
 9	"github.com/charmbracelet/soft-serve/pkg/store"
10)
11
12// CollaboratorEvent is a collaborator event.
13type CollaboratorEvent struct {
14	Common
15
16	// Action is the collaborator event action.
17	Action CollaboratorEventAction `json:"action" url:"action"`
18	// AccessLevel is the collaborator access level.
19	AccessLevel access.AccessLevel `json:"access_level" url:"access_level"`
20	// Collaborator is the collaborator.
21	Collaborator User `json:"collaborator" url:"collaborator"`
22}
23
24// CollaboratorEventAction is a collaborator event action.
25type CollaboratorEventAction string
26
27const (
28	// CollaboratorEventAdded is a collaborator added event.
29	CollaboratorEventAdded CollaboratorEventAction = "added"
30	// CollaboratorEventRemoved is a collaborator removed event.
31	CollaboratorEventRemoved CollaboratorEventAction = "removed"
32)
33
34// NewCollaboratorEvent sends a collaborator event.
35func NewCollaboratorEvent(ctx context.Context, user proto.User, repo proto.Repository, collabUsername string, action CollaboratorEventAction) (CollaboratorEvent, error) {
36	event := EventCollaborator
37
38	payload := CollaboratorEvent{
39		Action: action,
40		Common: Common{
41			EventType: event,
42			Repository: Repository{
43				ID:          repo.ID(),
44				Name:        repo.Name(),
45				Description: repo.Description(),
46				ProjectName: repo.ProjectName(),
47				Private:     repo.IsPrivate(),
48				CreatedAt:   repo.CreatedAt(),
49				UpdatedAt:   repo.UpdatedAt(),
50			},
51			Sender: User{
52				ID:       user.ID(),
53				Username: user.Username(),
54			},
55		},
56	}
57
58	// Find repo owner.
59	dbx := db.FromContext(ctx)
60	datastore := store.FromContext(ctx)
61	owner, err := datastore.GetUserByID(ctx, dbx, repo.UserID())
62	if err != nil {
63		return CollaboratorEvent{}, db.WrapError(err) //nolint:wrapcheck
64	}
65
66	payload.Repository.Owner.ID = owner.ID
67	payload.Repository.Owner.Username = owner.Username
68	payload.Repository.DefaultBranch, _ = getDefaultBranch(repo)
69
70	collab, err := datastore.GetCollabByUsernameAndRepo(ctx, dbx, collabUsername, repo.Name())
71	if err != nil {
72		return CollaboratorEvent{}, err //nolint:wrapcheck
73	}
74
75	payload.AccessLevel = collab.AccessLevel
76	payload.Collaborator.ID = collab.UserID
77	payload.Collaborator.Username = collabUsername
78
79	return payload, nil
80}