Skip to content

Commit

Permalink
feat: add the posibility to send attachments.
Browse files Browse the repository at this point in the history
Rocket.chat Rest API allow to send attributes, emoji and avatar with a message. This update allow this.
  • Loading branch information
Benjamin Raimondi committed Feb 9, 2017
1 parent caa0ff8 commit c56748e
Show file tree
Hide file tree
Showing 17 changed files with 638 additions and 52 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ buildNumber.properties
/.settings
.idea/*

rocket-chat-notifier.iml
*.iml
*.iws
*.ipr
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package jenkins.plugins.rocketchatnotifier;


import sun.security.validator.ValidatorException;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
* Created by mreinhardt on 08.09.16.
Expand All @@ -12,5 +13,9 @@ public interface RocketClient {

boolean publish(String message);

boolean publish(String message, String emoji, String avatar);

boolean publish(String message, String emoji, String avatar, List<Map<String, Object>> attachments);

void validate() throws ValidatorException, IOException;
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package jenkins.plugins.rocketchatnotifier;


import jenkins.plugins.rocketchatnotifier.rocket.LegacyRocketChatClient;
import jenkins.plugins.rocketchatnotifier.rocket.RocketChatClient;
import jenkins.plugins.rocketchatnotifier.rocket.RocketChatClientImpl;
import sun.security.validator.ValidatorException;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

Expand All @@ -25,7 +26,6 @@ public class RocketClientImpl implements RocketClient {

private String channel;


public RocketClientImpl(String serverUrl, String user, String password, String channel) {
this.client = new RocketChatClientImpl(serverUrl, user, password);
try {
Expand All @@ -52,11 +52,42 @@ public boolean publish(String message) {
}
}

@Override
public boolean publish(final String message, final String emoji, final String avatar) {
try {
LOGGER.fine("Starting sending message to channel " + this.channel);
this.client.send(this.channel, message, emoji, avatar);
return true;
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "I/O error error during publishing message", e);
return false;
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Unknown error error during publishing message", e);
return false;
}
}

@Override
public boolean publish(final String message, final String emoji, final String avatar, final List<Map<String, Object>> attachments) {
try {
LOGGER.fine("Starting sending message to channel " + this.channel);
this.client.send(this.channel, message, emoji, avatar, attachments);
return true;
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "I/O error error during publishing message", e);
return false;
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Unknown error error during publishing message", e);
return false;
}
}

@Override
public void validate() throws ValidatorException, IOException {
LOGGER.fine("Starting validating");
this.client.getChannels();
}

}


18 changes: 18 additions & 0 deletions src/main/java/jenkins/plugins/rocketchatnotifier/model/Info.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package jenkins.plugins.rocketchatnotifier.model;

/**
* Created by ben on 09/02/2017.
*/
public class Info {

private String version;

public String getVersion() {
return version;
}

public void setVersion(final String version) {
this.version = version;
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package jenkins.plugins.rocketchatnotifier.model;


public class Response {
private boolean success;
private Message[] messages;
Expand All @@ -9,6 +8,7 @@ public class Response {
private User user;
private Room[] channels;
private Room channel;
private Info info;

public void setSuccess(boolean result) {
this.success = result;
Expand Down Expand Up @@ -69,4 +69,12 @@ public User getUser() {
public boolean isUser() {
return this.user != null;
}

public Info getInfo() {
return info;
}

public void setInfo(final Info info) {
this.info = info;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import jenkins.plugins.rocketchatnotifier.model.Info;
import jenkins.plugins.rocketchatnotifier.model.Message;
import jenkins.plugins.rocketchatnotifier.model.Room;
import jenkins.plugins.rocketchatnotifier.model.Rooms;
Expand All @@ -14,7 +15,11 @@
import sun.security.validator.ValidatorException;

import java.io.IOException;
import java.util.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
* Created by mreinhardt on 26.12.16.
Expand Down Expand Up @@ -56,7 +61,8 @@ public Set<Room> getPublicRooms() throws IOException {

private <T> T authenticatedGet(String method, Class<T> reponseClass) throws IOException {
try {
HttpResponse e = Unirest.get(this.serverUrl + method).header("X-Auth-Token", this.xAuthToken).header("X-User-Id", this.xUserId).asString();
HttpResponse e = Unirest.get(this.serverUrl + method).header("X-Auth-Token", this.xAuthToken).header("X-User-Id",
this.xUserId).asString();
if (e.getStatus() == 401) {
this.login();
return this.authenticatedGet(method, reponseClass);
Expand All @@ -72,9 +78,12 @@ private void authenticatedPost(String method, Object request) throws ValidatorEx
this.authenticatedPost(method, request, (Class) null);
}

private <T> T authenticatedPost(String method, Object request, Class<T> reponseClass) throws ValidatorException, IOException {
private <T> T authenticatedPost(String method, Object request, Class<T> reponseClass)
throws ValidatorException, IOException {
try {
HttpResponse e = Unirest.post(this.serverUrl + method).header("X-Auth-Token", this.xAuthToken).header("X-User-Id", this.xUserId).header("Content-Type", "application/json").body(this.jacksonObjectMapper.writeValueAsString(request)).asString();
HttpResponse e = Unirest.post(this.serverUrl + method).header("X-Auth-Token", this.xAuthToken).header("X-User-Id",
this.xUserId).header(
"Content-Type", "application/json").body(this.jacksonObjectMapper.writeValueAsString(request)).asString();
if (e.getStatus() == 401) {
this.login();
return this.authenticatedPost(method, request, reponseClass);
Expand All @@ -87,7 +96,8 @@ private <T> T authenticatedPost(String method, Object request, Class<T> reponseC
}

void login() throws UnirestException {
HttpResponse asJson = Unirest.post(this.serverUrl + "login").field("user", this.user).field("password", this.password).asJson();
HttpResponse asJson = Unirest.post(this.serverUrl + "login").field("user", this.user).field("password",
this.password).asJson();
if (asJson.getStatus() == 401) {
throw new UnirestException("401 - Unauthorized");
} else {
Expand All @@ -99,7 +109,8 @@ void login() throws UnirestException {

public void logout() throws IOException {
try {
Unirest.post(this.serverUrl + "logout").header("X-Auth-Token", this.xAuthToken).header("X-User-Id", this.xUserId).asJson();
Unirest.post(this.serverUrl + "logout").header("X-Auth-Token", this.xAuthToken).header("X-User-Id",
this.xUserId).asJson();
} catch (UnirestException var2) {
throw new IOException(var2);
}
Expand All @@ -116,7 +127,8 @@ public String getRocketChatVersion() throws IOException {
private JSONObject getVersions() throws IOException {
if (this.lazyVersions == null) {
try {
this.lazyVersions = ((JsonNode) Unirest.get(this.serverUrl + "version").asJson().getBody()).getObject().getJSONObject("versions");
this.lazyVersions = ((JsonNode) Unirest.get(
this.serverUrl + "version").asJson().getBody()).getObject().getJSONObject("versions");
} catch (UnirestException var2) {
throw new IOException(var2);
}
Expand All @@ -128,7 +140,7 @@ private JSONObject getVersions() throws IOException {
public void send(String roomName, String message) throws ValidatorException, IOException {
Room room = this.getRoom(roomName);
if (room == null) {
throw new IOException(String.format("unknown room : %s", new Object[]{roomName}));
throw new IOException(String.format("unknown room : %s", new Object[] { roomName }));
} else {
this.send(room, message);
}
Expand Down Expand Up @@ -160,6 +172,25 @@ public User getUser(String userId) throws IOException {

@Override
public Room[] getChannels() throws IOException {
return this.getPublicRooms().toArray(new Room[0]);
return this.getPublicRooms().toArray(new Room[0]);
}

@Override
public void send(final String channelName, final String message, final String emoji, final String avatar)
throws ValidatorException, IOException {
this.send(channelName, message);
}

@Override
public void send(final String channelName, final String message, final String emoji, final String avatar, final List<Map<String, Object>> attachments)
throws ValidatorException, IOException {
this.send(channelName, message);
}

@Override
public Info getInfo() throws IOException {
Info info = new Info();
info.setVersion(this.getRocketChatVersion());
return info;
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package jenkins.plugins.rocketchatnotifier.rocket;

import jenkins.plugins.rocketchatnotifier.model.Info;
import jenkins.plugins.rocketchatnotifier.model.Room;
import jenkins.plugins.rocketchatnotifier.model.User;
import sun.security.validator.ValidatorException;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
* API used by this Jenkins plugin to communicate to RocketChat server backend
Expand Down Expand Up @@ -58,4 +61,37 @@ public interface RocketChatClient {
*/
void send(String channelName, String message) throws ValidatorException, IOException;

/**
* sends a message to a channel.
* If emoji and avatar are difined, only emoji will be displayed
*
* @param channelName to use
* @param message to send
* @param emoji to display
* @param avatar to display
* @throws ValidatorException in case of SSL errors
* @throws IOException in case of communication errors with the RocketChat server backend
*/
void send(String channelName, String message, String emoji, String avatar) throws ValidatorException, IOException;

/**
* sends a message to a channel.
* If emoji and avatar are difined, only emoji will be displayed
*
* @param channelName to use
* @param message to send
* @param emoji to display
* @param avatar to display
* @param attachments to send
* @throws ValidatorException in case of SSL errors
* @throws IOException in case of communication errors with the RocketChat server backend
*/
void send(String channelName, String message, String emoji, String avatar, List<Map<String, Object>> attachments)
throws ValidatorException, IOException;

/**
* Retrieves server information
*/
Info getInfo() throws IOException;

}
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package jenkins.plugins.rocketchatnotifier.rocket;

import jenkins.plugins.rocketchatnotifier.RocketClientImpl;
import jenkins.plugins.rocketchatnotifier.model.Info;
import jenkins.plugins.rocketchatnotifier.model.Response;
import jenkins.plugins.rocketchatnotifier.model.Room;
import jenkins.plugins.rocketchatnotifier.model.User;
import sun.security.validator.ValidatorException;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

Expand Down Expand Up @@ -36,7 +38,6 @@ public RocketChatClientImpl(String serverUrl, String user, String password) {
this.callBuilder = new RocketChatClientCallBuilder(serverUrl, user, password);
}


@Override
public User[] getUsers() throws IOException {
Response res = this.callBuilder.buildCall(RocketChatRestApiV1.UsersList);
Expand All @@ -54,7 +55,8 @@ public User[] getUsers() throws IOException {

@Override
public User getUser(String userId) throws IOException {
Response res = this.callBuilder.buildCall(RocketChatRestApiV1.UsersInfo, new RocketChatQueryParams("userId", userId));
Response res = this.callBuilder.buildCall(RocketChatRestApiV1.UsersInfo,
new RocketChatQueryParams("userId", userId));

if (!res.isSuccessful()) {
LOG.severe("Could not read user information: " + res.getMessage().getMsg());
Expand All @@ -78,21 +80,53 @@ public Room[] getChannels() throws IOException {
return res.getChannels();
}

@Override
public Info getInfo() throws IOException {
Response res = this.callBuilder.buildCall(RocketChatRestApiV1.Info);

if (!res.isSuccessful()) {
LOG.severe("Could not read information: " + res.getMessage().getMsg());
throw new IOException("The call to get informations was unsuccessful.");
}
return res.getInfo();
}

@Override
public void send(Room room, String message) throws ValidatorException, IOException {
this.send(room.getName(), message);
}

@Override
public void send(String channelName, String message) throws ValidatorException, IOException {
this.send(channelName, message, null, null);
}

@Override
public void send(final String channelName, final String message, final String emoji, final String avatar)
throws ValidatorException, IOException {
this.send(channelName, message, emoji, avatar, null);
}

@Override
public void send(final String channelName, final String message, final String emoji, final String avatar, final List<Map<String, Object>> attachments)
throws ValidatorException, IOException {
Map body = new HashMap<String, String>();
body.put("channel", "#" + channelName);
body.put("text", message);
Response res = this.callBuilder.buildCall(RocketChatRestApiV1.PostMessage,
null, body);
if (this.getInfo().getVersion().compareTo("0.50.1") >= 0) {
if (emoji != null)
body.put("emoji", emoji);
else if (avatar != null)
body.put("avatar", avatar);
if (attachments != null && attachments.size() > 0)
body.put("attachments", attachments);
}
Response res = this.callBuilder.buildCall(RocketChatRestApiV1.PostMessage, null, body);

if (!res.isSuccessful()) {
LOG.severe("Could not send message: " + res.getMessage() != null ? res.getMessage().getMsg() : "");
throw new IOException("The send of the message was unsuccessful.");
}
}

}
Loading

0 comments on commit c56748e

Please sign in to comment.