use of org.jenkinsci.plugin.gitea.servers.GiteaServer in project gitea-plugin by jenkinsci.
the class GiteaWebhookListener method register.
public static void register(SCMSourceOwner owner, GiteaSCMSource source, WebhookRegistration mode, String credentialsId) {
StandardCredentials credentials;
String serverUrl = source.getServerUrl();
switch(mode) {
case DISABLE:
return;
case SYSTEM:
GiteaServer server = GiteaServers.get().findServer(serverUrl);
if (server == null || !server.isManageHooks()) {
return;
}
credentials = server.credentials();
break;
case ITEM:
credentials = source.credentials();
break;
default:
return;
}
if (credentials == null) {
return;
}
JenkinsLocationConfiguration locationConfiguration = JenkinsLocationConfiguration.get();
if (locationConfiguration == null) {
return;
}
String rootUrl = locationConfiguration.getUrl();
if (StringUtils.isBlank(rootUrl) || rootUrl.startsWith("http://localhost:")) {
return;
}
String hookUrl = UriTemplate.buildFromTemplate(rootUrl).literal("gitea-webhook").literal("/post").build().expand();
try (GiteaConnection c = connect(serverUrl, credentials)) {
GiteaRepository repo = c.fetchRepository(source.getRepoOwner(), source.getRepository());
if (repo == null) {
return;
}
List<GiteaHook> hooks = c.fetchHooks(repo);
GiteaHook hook = null;
for (GiteaHook h : hooks) {
if (hookUrl.equals(h.getConfig().getUrl())) {
if (hook == null && h.getType() == GiteaHookType.GITEA && h.getConfig().getContentType() == GiteaPayloadType.JSON && h.isActive() && EnumSet.allOf(GiteaEventType.class).equals(h.getEvents())) {
hook = h;
} else {
c.deleteHook(repo, h);
}
}
}
if (hook == null) {
hook = new GiteaHook();
GiteaHook.Configuration configuration = new GiteaHook.Configuration();
configuration.setContentType(GiteaPayloadType.JSON);
configuration.setUrl(hookUrl);
hook.setType(GiteaHookType.GITEA);
hook.setConfig(configuration);
hook.setEvents(EnumSet.allOf(GiteaEventType.class));
hook.setActive(true);
c.createHook(repo, hook);
}
} catch (IOException | InterruptedException e) {
LOGGER.log(Level.WARNING, "Could not manage repository hooks for " + source.getRepoOwner() + "/" + source.getRepository() + " on " + serverUrl, e);
}
}
Aggregations