Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[MI-2029] Add feature to create subscription from modal #25

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions server/constants/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,15 @@ const (
PluginID = "mattermost-plugin-azure-devops"
ChannelID = "channel_id"
HeaderMattermostUserID = "Mattermost-User-ID"
// TODO: Change later according to the needs.
HeaderMattermostUserIDAPI = "User-ID"

// Command configs
CommandTriggerName = "azuredevops"
HelpText = "###### Mattermost Azure Devops Plugin - Slash Command Help\n" +
"* `/azuredevops connect` - Connect your Mattermost account to your Azure Devops account.\n" +
"* `/azuredevops disconnect` - Disconnect your Mattermost account from your Azure Devops account.\n" +
"* `/azuredevops boards create` - Create a new task for your project.\n" +
"* `/azuredevops link [projectURL]` - Link your project to a current channel.\n"
"* `/azuredevops link [projectURL]` - Link your project to the current channel.\n" +
"* `/azuredevops subscribe` - Create a subscription to the current channel.\n"
InvalidCommand = "Invalid command parameters. Please use `/azuredevops help` for more information."

// Get task link preview constants
Expand All @@ -37,6 +36,9 @@ const (
Update = "update"
Delete = "delete"

// Path params
PathParamTeamID = "team_id"

// Authorization constants
Bearer = "Bearer"
Authorization = "Authorization"
Expand Down
1 change: 0 additions & 1 deletion server/constants/messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ const (
TaskTypeRequired = "task type is required"
TaskTitleRequired = "task title is required"
EventTypeRequired = "event type is required"
ChannelNameRequired = "channel name is required"
ChannelIDRequired = "channel ID is required"
SubscriptionIDRequired = "subscription ID is required"
)
Expand Down
1 change: 1 addition & 0 deletions server/constants/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const (
PathLinkProject = "/link"
PathSubscriptions = "/subscriptions"
PathSubscriptionNotifications = "/notification"
PathGetUserChannelsForTeam = "/channels/{team_id:[A-Za-z0-9]+}"

// Azure API paths
CreateTask = "/%s/%s/_apis/wit/workitems/$%s?api-version=7.1-preview.3"
Expand Down
75 changes: 54 additions & 21 deletions server/plugin/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,13 @@ func (p *Plugin) InitRoutes() {
s.HandleFunc(constants.PathSubscriptions, p.handleAuthRequired(p.checkOAuth(p.handleCreateSubscriptions))).Methods(http.MethodPost)
s.HandleFunc(constants.PathSubscriptionNotifications, p.handleSubscriptionNotifications).Methods(http.MethodPost)
s.HandleFunc(constants.PathSubscriptions, p.handleAuthRequired(p.checkOAuth(p.handleDeleteSubscriptions))).Methods(http.MethodDelete)
s.HandleFunc(constants.PathGetUserChannelsForTeam, p.handleAuthRequired(p.getUserChannelsForTeam)).Methods(http.MethodGet)
}

// handleAuthRequired verifies if the provided request is performed by an authorized source.
func (p *Plugin) handleAuthRequired(handleFunc http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserIDAPI)
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserID)
if mattermostUserID == "" {
error := serializers.Error{Code: http.StatusUnauthorized, Message: constants.NotAuthorized}
p.handleError(w, r, &error)
Expand All @@ -61,7 +62,7 @@ func (p *Plugin) handleAuthRequired(handleFunc http.HandlerFunc) http.HandlerFun

func (p *Plugin) checkOAuth(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserIDAPI)
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserID)
user, err := p.Store.LoadUser(mattermostUserID)
if err != nil || user.AccessToken == "" {
if errors.Is(err, ErrNotFound) || user.AccessToken == "" {
Expand Down Expand Up @@ -92,7 +93,7 @@ func (p *Plugin) handleError(w http.ResponseWriter, r *http.Request, error *seri

// API to link a project and an organization to a user.
func (p *Plugin) handleLink(w http.ResponseWriter, r *http.Request) {
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserIDAPI)
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserID)
var body *serializers.LinkRequestPayload
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&body); err != nil {
Expand Down Expand Up @@ -143,7 +144,7 @@ func (p *Plugin) handleLink(w http.ResponseWriter, r *http.Request) {

// handleGetAllLinkedProjects returns all linked projects list
func (p *Plugin) handleGetAllLinkedProjects(w http.ResponseWriter, r *http.Request) {
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserIDAPI)
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserID)
projectList, err := p.Store.GetAllProjects(mattermostUserID)
if err != nil {
p.API.LogError(constants.ErrorFetchProjectList, "Error", err.Error())
Expand Down Expand Up @@ -172,7 +173,7 @@ func (p *Plugin) handleGetAllLinkedProjects(w http.ResponseWriter, r *http.Reque

// handleUnlinkProject unlinks a project
func (p *Plugin) handleUnlinkProject(w http.ResponseWriter, r *http.Request) {
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserIDAPI)
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserID)

var project *serializers.ProjectDetails
decoder := json.NewDecoder(r.Body)
Expand Down Expand Up @@ -220,7 +221,7 @@ func (p *Plugin) handleUnlinkProject(w http.ResponseWriter, r *http.Request) {

// handleUnlinkProject unlinks a project
func (p *Plugin) handleGetUserAccountDetails(w http.ResponseWriter, r *http.Request) {
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserIDAPI)
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserID)

userDetails, err := p.Store.LoadUser(mattermostUserID)
if err != nil {
Expand Down Expand Up @@ -251,7 +252,7 @@ func (p *Plugin) handleGetUserAccountDetails(w http.ResponseWriter, r *http.Requ

// API to create task of a project in an organization.
func (p *Plugin) handleCreateTask(w http.ResponseWriter, r *http.Request) {
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserIDAPI)
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserID)
var body *serializers.TaskCreateRequestPayload
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&body); err != nil {
Expand Down Expand Up @@ -290,7 +291,7 @@ func (p *Plugin) handleCreateTask(w http.ResponseWriter, r *http.Request) {
}

func (p *Plugin) handleCreateSubscriptions(w http.ResponseWriter, r *http.Request) {
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserIDAPI)
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserID)
body, err := serializers.CreateSubscriptionRequestPayloadFromJSON(r.Body)
if err != nil {
p.API.LogError("Error in decoding the body for creating subscriptions", "Error", err.Error())
Expand All @@ -317,30 +318,22 @@ func (p *Plugin) handleCreateSubscriptions(w http.ResponseWriter, r *http.Reques
return
}

// TODO: remove later
teamID := "qteks46as3befxj4ec1mip5ume"
channel, channelErr := p.API.GetChannelByName(teamID, body.ChannelName, false)
if channelErr != nil {
p.handleError(w, r, &serializers.Error{Code: http.StatusBadRequest, Message: channelErr.DetailedError})
return
}

subscriptionList, err := p.Store.GetAllSubscriptions(mattermostUserID)
if err != nil {
p.API.LogError(constants.ErrorFetchSubscriptionList, "Error", err.Error())
p.handleError(w, r, &serializers.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}

_, isSubscriptionPresent := p.IsSubscriptionPresent(subscriptionList, serializers.SubscriptionDetails{OrganizationName: body.Organization, ProjectName: body.Project, ChannelID: channel.Id, EventType: body.EventType})
_, isSubscriptionPresent := p.IsSubscriptionPresent(subscriptionList, serializers.SubscriptionDetails{OrganizationName: body.Organization, ProjectName: body.Project, ChannelID: body.ChannelID, EventType: body.EventType})
if isSubscriptionPresent {
p.API.LogError(constants.SubscriptionAlreadyPresent, "Error")
p.handleError(w, r, &serializers.Error{Code: http.StatusBadRequest, Message: constants.SubscriptionAlreadyPresent})
return
}

pluginURL := p.GetPluginURL()
subscription, statusCode, err := p.Client.CreateSubscription(body, project, channel.Id, pluginURL, mattermostUserID)
subscription, statusCode, err := p.Client.CreateSubscription(body, project, body.ChannelID, pluginURL, mattermostUserID)
if err != nil {
p.API.LogError(constants.ErrorCreateSubscription, "Error", err.Error())
p.handleError(w, r, &serializers.Error{Code: statusCode, Message: err.Error()})
Expand All @@ -353,7 +346,7 @@ func (p *Plugin) handleCreateSubscriptions(w http.ResponseWriter, r *http.Reques
ProjectID: subscription.PublisherInputs.ProjectID,
OrganizationName: body.Organization,
EventType: body.EventType,
ChannelID: channel.Id,
ChannelID: body.ChannelID,
SubscriptionID: subscription.ID,
})
response, err := json.Marshal(subscription)
Expand All @@ -369,7 +362,7 @@ func (p *Plugin) handleCreateSubscriptions(w http.ResponseWriter, r *http.Reques
}

func (p *Plugin) handleGetSubscriptions(w http.ResponseWriter, r *http.Request) {
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserIDAPI)
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserID)
subscriptionList, err := p.Store.GetAllSubscriptions(mattermostUserID)
if err != nil {
p.API.LogError(constants.ErrorFetchSubscriptionList, "Error", err.Error())
Expand Down Expand Up @@ -423,7 +416,7 @@ func (p *Plugin) handleSubscriptionNotifications(w http.ResponseWriter, r *http.
}

func (p *Plugin) handleDeleteSubscriptions(w http.ResponseWriter, r *http.Request) {
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserIDAPI)
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserID)
body, err := serializers.DeleteSubscriptionRequestPayloadFromJSON(r.Body)
if err != nil {
p.API.LogError("Error in decoding the body for deleting subscriptions", "Error", err.Error())
Expand Down Expand Up @@ -467,6 +460,46 @@ func (p *Plugin) handleDeleteSubscriptions(w http.ResponseWriter, r *http.Reques
w.WriteHeader(http.StatusNoContent)
}

func (p *Plugin) getUserChannelsForTeam(w http.ResponseWriter, r *http.Request) {
mattermostUserID := r.Header.Get(constants.HeaderMattermostUserID)
pathParams := mux.Vars(r)
teamID := pathParams[constants.PathParamTeamID]
if !model.IsValidId(teamID) {
p.API.LogError("Invalid team id")
http.Error(w, "Invalid team id", http.StatusBadRequest)
return
}

channels, channelErr := p.API.GetChannelsForTeamForUser(teamID, mattermostUserID, false)
if channelErr != nil {
p.API.LogError("Error in getting channels for team and user", "Error", channelErr.Error())
http.Error(w, fmt.Sprintf("Error in getting channels for team and user. Error: %s", channelErr.Error()), channelErr.StatusCode)
return
}

w.Header().Set("Content-Type", "application/json")
if channels == nil {
_, _ = w.Write([]byte("[]"))
return
}

var requiredChannels []*model.Channel
for _, channel := range channels {
if channel.Type == model.CHANNEL_PRIVATE || channel.Type == model.CHANNEL_OPEN {
requiredChannels = append(requiredChannels, channel)
}
}
if requiredChannels == nil {
_, _ = w.Write([]byte("[]"))
return
}

if err := json.NewEncoder(w).Encode(requiredChannels); err != nil {
p.API.LogError("Error while writing response", "Error", err.Error())
w.WriteHeader(http.StatusInternalServerError)
}
}

func (p *Plugin) WithRecovery(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
Expand Down
15 changes: 14 additions & 1 deletion server/plugin/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ var azureDevopsCommandHandler = Handler{
"disconnect": azureDevopsDisconnectCommand,
"boards": azureDevopsBoardsCommand,
"link": azureDevopsProjectLinkCommand,
"subscribe": azureDevopsSubscribeCommand,
},
defaultHandler: executeDefault,
}
Expand All @@ -43,7 +44,7 @@ func (ch *Handler) Handle(p *Plugin, c *plugin.Context, commandArgs *model.Comma
}

func (p *Plugin) getAutoCompleteData() *model.AutocompleteData {
azureDevops := model.NewAutocompleteData(constants.CommandTriggerName, "[command]", "Available commands: help, connect, disconnect, link")
azureDevops := model.NewAutocompleteData(constants.CommandTriggerName, "[command]", "Available commands: help, connect, disconnect, link, subscribe")

help := model.NewAutocompleteData("help", "", fmt.Sprintf("Show %s slash command help", constants.CommandTriggerName))
azureDevops.AddCommand(help)
Expand All @@ -60,6 +61,9 @@ func (p *Plugin) getAutoCompleteData() *model.AutocompleteData {
link := model.NewAutocompleteData("link", "[link]", "Link a project")
azureDevops.AddCommand(link)

subscribe := model.NewAutocompleteData("subscribe", "", "Add a subscription")
azureDevops.AddCommand(subscribe)

return azureDevops
}

Expand Down Expand Up @@ -133,6 +137,15 @@ func azureDevopsProjectLinkCommand(p *Plugin, c *plugin.Context, commandArgs *mo
return &model.CommandResponse{}, nil
}

func azureDevopsSubscribeCommand(p *Plugin, c *plugin.Context, commandArgs *model.CommandArgs, args ...string) (*model.CommandResponse, *model.AppError) {
message := constants.ConnectAccountFirst
if isConnected := p.UserAlreadyConnected(commandArgs.UserId); !isConnected {
return p.sendEphemeralPostForCommand(commandArgs, message)
}

return &model.CommandResponse{}, nil
}

func executeDefault(p *Plugin, c *plugin.Context, commandArgs *model.CommandArgs, args ...string) (*model.CommandResponse, *model.AppError) {
return p.sendEphemeralPostForCommand(commandArgs, constants.InvalidCommand)
}
Expand Down
8 changes: 4 additions & 4 deletions server/serializers/subscriptions.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ type CreateSubscriptionRequestPayload struct {
Organization string `json:"organization"`
Project string `json:"project"`
EventType string `json:"eventType"`
ChannelName string `json:"channelName"`
ChannelID string `json:"channelID"`
}

type DeleteSubscriptionRequestPayload struct {
Expand Down Expand Up @@ -133,8 +133,8 @@ func (t *CreateSubscriptionRequestPayload) IsSubscriptionRequestPayloadValid() e
if t.EventType == "" {
return errors.New(constants.EventTypeRequired)
}
if t.ChannelName == "" {
return errors.New(constants.ChannelNameRequired)
if t.ChannelID == "" {
return errors.New(constants.ChannelIDRequired)
}
return nil
}
Expand All @@ -150,7 +150,7 @@ func (t *DeleteSubscriptionRequestPayload) IsSubscriptionRequestPayloadValid() e
return errors.New(constants.EventTypeRequired)
}
if t.ChannelID == "" {
return errors.New(constants.ChannelNameRequired)
return errors.New(constants.ChannelIDRequired)
}
return nil
}
2 changes: 1 addition & 1 deletion webapp/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import plugin_constants from 'plugin_constants';
import usePluginApi from 'hooks/usePluginApi';

import {toggleConnectionTriggered, toggleIsDisconnected} from 'reducers/userAcountDetails';
import {getLinkModalState, getTaskModalState, getRhsState, getUserConnectionState} from 'selectors';
import {getLinkModalState, getTaskModalState, getRhsState, getUserConnectionState, getSubscribeModalState} from 'selectors';

// Global styles
import 'styles/main.scss';
Expand Down
Loading