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

feat: Implement second step for automatic action - Application + event - MEED-2962 - Meeds-io/MIPs#105 #133

Merged
merged 2 commits into from
Dec 7, 2023
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -251,30 +251,6 @@ public Response updateWebHookRepoStatus(@Parameter(description = "GitHub organiz
}
}

@Path("events/status")
@POST
@RolesAllowed("users")
@Operation(summary = "enables/disables event for gitHub organization.", description = "enables/disables event for gitHub organization", method = "POST")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "Request fulfilled"),
@ApiResponse(responseCode = "400", description = "Bad request"),
@ApiResponse(responseCode = "401", description = "Unauthorized operation"),
@ApiResponse(responseCode = "500", description = "Internal server error"), })
public Response updateWebHookEventStatus(@Parameter(description = "Event Id", required = true) @FormParam("eventId") long eventId,
@Parameter(description = "Organization remote Id", required = true) @FormParam("organizationId") long organizationId,
@Parameter(description = "Event status enabled/disabled. possible values: true for enabled, else false", required = true) @FormParam("enabled") boolean enabled) {

String currentUser = getCurrentUser();
try {
webhookService.setEventEnabledForOrganization(eventId, organizationId, enabled, currentUser);
return Response.noContent().build();
} catch (IllegalAccessException e) {
return Response.status(Response.Status.UNAUTHORIZED).entity(e.getMessage()).type(MediaType.TEXT_PLAIN).build();
} catch (ObjectNotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).entity("Event not found").build();
}
}

@Path("watchScope/status")
@POST
@RolesAllowed("users")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,4 @@ public interface GithubTriggerService {
* @param payload payload The raw payload of the webhook request.
*/
void handleTrigger(String trigger, String signature, String payload);

/**
* Gets list of configured github triggers
*
* @return list of configured github triggers
*/
String[] getTriggers();
}
Original file line number Diff line number Diff line change
Expand Up @@ -197,19 +197,4 @@ List<RemoteRepository> retrieveOrganizationRepos(long organizationRemoteId,
int perPage,
String keyword) throws IllegalAccessException, ObjectNotFoundException;

/**
* Enables/disables organization event
*
* @param eventId event Id
* @param organizationId organization remote id
* @param enabled true to enabled, else false
* @param currentUser user name attempting to enables/disables event.
* @throws IllegalAccessException when user is not authorized enables/disables
* organization event
*/
void setEventEnabledForOrganization(long eventId,
long organizationId,
boolean enabled,
String currentUser) throws IllegalAccessException, ObjectNotFoundException;

}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import io.meeds.gamification.model.filter.EventFilter;
import io.meeds.gamification.service.ConnectorService;
import io.meeds.gamification.service.EventService;
import io.meeds.gamification.service.TriggerService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
Expand All @@ -40,7 +41,6 @@
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import static org.exoplatform.gamification.github.utils.Utils.*;

Expand All @@ -54,6 +54,8 @@ public class GithubTriggerServiceImpl implements GithubTriggerService, Startable

private final EventService eventService;

private final TriggerService triggerService;

private WebhookService webhookService;

private final IdentityManager identityManager;
Expand All @@ -65,11 +67,13 @@ public class GithubTriggerServiceImpl implements GithubTriggerService, Startable
public GithubTriggerServiceImpl(ListenerService listenerService,
ConnectorService connectorService,
IdentityManager identityManager,
EventService eventService) {
EventService eventService,
TriggerService triggerService) {
this.listenerService = listenerService;
this.connectorService = connectorService;
this.identityManager = identityManager;
this.eventService = eventService;
this.triggerService = triggerService;
}

@Override
Expand Down Expand Up @@ -118,28 +122,15 @@ public void handleTrigger(String trigger, String signature, String payload) {
if (triggerPlugin != null) {
events = triggerPlugin.getEvents(payloadMap);
}
processEvents(events, trigger, organizationId);
processEvents(events, organizationId);
}

private void processEvents(List<Event> events, String trigger, String organizationId) {
events.stream().filter(event -> isEventEnabled(event.getName(), trigger, organizationId)).forEach(this::processEvent);
private void processEvents(List<Event> events, String organizationId) {
events.stream().filter(event -> isTriggerEnabled(event.getName(), organizationId)).forEach(this::processEvent);
}

private boolean isEventEnabled(String eventName, String trigger, String organizationId) {
EventDTO eventDTO = eventService.getEventByTitleAndTrigger(eventName, trigger);
if (eventDTO != null) {
return isOrganizationEventEnabled(eventDTO, organizationId);
}
return true;
}

private boolean isOrganizationEventEnabled(EventDTO eventDTO, String organizationId) {
String organizationPropertyKey = organizationId + ".enabled";
Map<String, String> properties = eventDTO.getProperties();
if (properties != null && !properties.isEmpty()) {
return Boolean.parseBoolean(properties.get(organizationPropertyKey));
}
return true;
private boolean isTriggerEnabled(String trigger, String organizationId) {
return triggerService.isTriggerEnabledForAccount(trigger, Long.parseLong(organizationId));
}

private void processEvent(Event event) {
Expand All @@ -158,10 +149,6 @@ private void processEvent(Event event) {
}
}

public String[] getTriggers() {
return triggerPlugins.values().stream().map(GithubTriggerPlugin::getName).toArray(String[]::new);
}

private void broadcastGithubEvent(String ruleTitle, String senderId, String receiverId, String objectId, String objectType) {
try {
Map<String, String> gam = new HashMap<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
import org.exoplatform.gamification.github.model.WebHook;
import org.exoplatform.gamification.github.model.RemoteOrganization;
import org.exoplatform.gamification.github.services.GithubConsumerService;
import org.exoplatform.gamification.github.services.GithubTriggerService;
import org.exoplatform.gamification.github.services.WebhookService;
import org.exoplatform.gamification.github.storage.WebHookStorage;
import org.json.JSONObject;
Expand All @@ -51,28 +50,21 @@ public class WebhookServiceImpl implements WebhookService {

private static final Scope DISABLED_REPOS_SCOPE = Scope.APPLICATION.id("disabledRepos");

public static final String ENABLED = ".enabled";
private static final String[] GITHUB_TRIGGERS = new String[] { "pull_request", "issue_comment",
"pull_request_review_comment", "pull_request_review", "issues", "push" };

private final SettingService settingService;

private final WebHookStorage webHookStorage;

private final GithubTriggerService githubTriggerService;

private final GithubConsumerService githubServiceConsumer;

private final EventService eventService;

public WebhookServiceImpl(SettingService settingService,
GithubTriggerService githubTriggerService,
WebHookStorage webHookStorage,
GithubConsumerService githubServiceConsumer,
EventService eventService) {
GithubConsumerService githubServiceConsumer) {
this.settingService = settingService;
this.githubTriggerService = githubTriggerService;
this.webHookStorage = webHookStorage;
this.githubServiceConsumer = githubServiceConsumer;
this.eventService = eventService;
}

public List<WebHook> getWebhooks(String currentUser, int offset, int limit, boolean forceUpdate) throws IllegalAccessException {
Expand Down Expand Up @@ -142,7 +134,7 @@ public void createWebhook(String organizationName, String accessToken, String cu
if (existsWebHook != null) {
throw new ObjectAlreadyExistsException(existsWebHook);
}
WebHook webHook = githubServiceConsumer.createWebhook(organizationName, githubTriggerService.getTriggers(), accessToken);
WebHook webHook = githubServiceConsumer.createWebhook(organizationName, GITHUB_TRIGGERS, accessToken);

if (webHook != null) {
webHook.setOrganizationId(remoteOrganization.getId());
Expand Down Expand Up @@ -293,34 +285,6 @@ public List<RemoteRepository> retrieveOrganizationRepos(long organizationRemoteI
return remoteRepositories;
}

@Override
public void setEventEnabledForOrganization(long eventId,
long organizationId,
boolean enabled,
String currentUser) throws IllegalAccessException, ObjectNotFoundException {
if (!Utils.isRewardingManager(currentUser)) {
throw new IllegalAccessException("The user is not authorized to enable/disable event for organization");
}
EventDTO eventDTO = eventService.getEvent(eventId);
if (eventDTO == null) {
throw new ObjectNotFoundException("event not found");
}
Map<String, String> eventProperties = eventDTO.getProperties();
if (eventProperties != null && !eventProperties.isEmpty()) {
String eventProjectStatus = eventProperties.get(organizationId + ENABLED);
if (StringUtils.isNotBlank(eventProjectStatus)) {
eventProperties.remove(organizationId + ENABLED);
eventProperties.put(organizationId + ENABLED, String.valueOf(enabled));
eventDTO.setProperties(eventProperties);
}
} else {
Map<String, String> properties = new HashMap<>();
properties.put(organizationId + ENABLED, String.valueOf(enabled));
eventDTO.setProperties(properties);
}
eventService.updateEvent(eventDTO);
}

@SuppressWarnings("unchecked")
private void forceUpdateWebhook(WebHook webHook) {
TokenStatus tokenStatus = githubServiceConsumer.checkGitHubTokenStatus(webHook.getToken());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
<string>github</string>
</field>
<field name="trigger">
<string>push</string>
<string>pushCode</string>
</field>
</object>
</object-param>
Expand All @@ -58,7 +58,7 @@
<string>github</string>
</field>
<field name="trigger">
<string>pull_request</string>
<string>creatPullRequest</string>
</field>
<field name="cancellerEvents">
<collection type="java.util.ArrayList" item-type="java.lang.String">
Expand Down Expand Up @@ -86,7 +86,7 @@
<string>github</string>
</field>
<field name="trigger">
<string>pull_request</string>
<string>requestReviewForPullRequest</string>
</field>
<field name="cancellerEvents">
<collection type="java.util.ArrayList" item-type="java.lang.String">
Expand Down Expand Up @@ -114,7 +114,7 @@
<string>github</string>
</field>
<field name="trigger">
<string>pull_request_review</string>
<string>reviewPullRequest</string>
</field>
</object>
</object-param>
Expand All @@ -135,7 +135,7 @@
<string>github</string>
</field>
<field name="trigger">
<string>pull_request_review</string>
<string>pullRequestValidated</string>
</field>
</object>
</object-param>
Expand All @@ -156,7 +156,7 @@
<string>github</string>
</field>
<field name="trigger">
<string>issue_comment</string>
<string>commentPullRequest</string>
</field>
<field name="cancellerEvents">
<collection type="java.util.ArrayList" item-type="java.lang.String">
Expand Down Expand Up @@ -184,7 +184,7 @@
<string>github</string>
</field>
<field name="trigger">
<string>issues</string>
<string>addIssueLabel</string>
</field>
<field name="cancellerEvents">
<collection type="java.util.ArrayList" item-type="java.lang.String">
Expand Down Expand Up @@ -212,7 +212,7 @@
<string>github</string>
</field>
<field name="trigger">
<string>pull_request_review</string>
<string>validatePullRequest</string>
</field>
</object>
</object-param>
Expand All @@ -233,7 +233,7 @@
<string>github</string>
</field>
<field name="trigger">
<string>issue_comment</string>
<string>commentIssue</string>
</field>
<field name="cancellerEvents">
<collection type="java.util.ArrayList" item-type="java.lang.String">
Expand Down Expand Up @@ -261,7 +261,7 @@
<string>github</string>
</field>
<field name="trigger">
<string>issues</string>
<string>createIssue</string>
</field>
<field name="cancellerEvents">
<collection type="java.util.ArrayList" item-type="java.lang.String">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,5 +80,25 @@
</depends>
</module>

<module>
<name>engagementCenterConnectorsGitHubExtensions</name>
<load-group>engagement-center-connector-extensions</load-group>
<script>
<path>/js/connectorExtensions.bundle.js</path>
</script>
<depends>
<module>vue</module>
</depends>
<depends>
<module>vuetify</module>
</depends>
<depends>
<module>eXoVueI18n</module>
</depends>
<depends>
<module>extensionRegistry</module>
</depends>
</module>

</gatein-resources>

Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* This file is part of the Meeds project (https://meeds.io/).
*
* Copyright (C) 2020 - 2023 Meeds Association [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
export function init() {
extensionRegistry.registerExtension('engagementCenterConnectors', 'connector-extensions', {
id: 'github',
name: 'github',
icon: 'fab fa-github',
iconColorClass: 'text-color',
title: 'Github',
description: 'githubConnector.admin.label.description',
rank: 20,
init: () => {
const lang = window.eXo?.env?.portal?.language || 'en';
const url = `${eXo.env.portal.context}/${eXo.env.portal.rest}/i18n/bundle/locale.portlet.GitHubWebHookManagement-${lang}.json`;
return exoi18n.loadLanguageAsync(lang, url);
}
});
}
Loading
Loading