[message pusher] - standlone gin service

This commit is contained in:
zeaslity
2024-04-23 11:45:32 +08:00
parent 30d83f3c61
commit 16541183ef
41 changed files with 1481 additions and 133 deletions

View File

@@ -0,0 +1,33 @@
package io.wdd.pusher;
import io.wdd.pusher.core.model.ClientType;
import io.wdd.pusher.core.publish.PubClient;
import io.wdd.pusher.core.publish.PubClientImpl;
import io.wdd.pusher.core.publish.PubServiceImpl;
public final class NtfyClient {
private PubClient pubClient;
public NtfyClient(ClientType type) {
switch (type) {
case PUB:
PubServiceImpl pubService = new PubServiceImpl();
this.pubClient = new PubClientImpl(pubService);
break;
case SUB:
break;
default:
throw new IllegalArgumentException("Invalid client type");
}
}
public PubClient getClient() {
return pubClient;
}
}

View File

@@ -0,0 +1,14 @@
package io.wdd.pusher.core.common;
public class NtfyConstants {
public static final String DEFAULT_URL = "https://ntfy.sh/";
public static final String POST = "POST";
public static final String CONTENT_TYPE = "Content-Type";
public static final String DEFAULT_HOST = "ntfy.sh";
public static final String NTFY_CONNECTION_ERROR_MSG = "Unable to connect to ntfy host";
public static final String CONNECTION_ERROR_MSG = "Unable to open connection";
public static final String HTTPS = "https://";
public static final String GET = "GET";
public static final String JSON = "json";
}

View File

@@ -0,0 +1,20 @@
package io.wdd.pusher.core.exception;
public class NtfyConnectionException extends Exception {
public NtfyConnectionException() {
super();
}
public NtfyConnectionException(String message) {
super(message);
}
public NtfyConnectionException(String message, Throwable cause) {
super(message, cause);
}
public NtfyConnectionException(Throwable cause) {
super(cause);
}
}

View File

@@ -0,0 +1,24 @@
package io.wdd.pusher.core.exception;
public class NtfyException extends Exception {
public NtfyException() {
super();
}
public NtfyException(String message) {
super(message);
}
public NtfyException(String message, Throwable cause) {
super(message, cause);
}
public NtfyException(Throwable cause) {
super(cause);
}
protected NtfyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@@ -0,0 +1,24 @@
package io.wdd.pusher.core.exception;
public class NtfyStreamingException extends Exception {
public NtfyStreamingException() {
super();
}
public NtfyStreamingException(String message) {
super(message);
}
public NtfyStreamingException(String message, Throwable cause) {
super(message, cause);
}
public NtfyStreamingException(Throwable cause) {
super(cause);
}
protected NtfyStreamingException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@@ -0,0 +1,19 @@
package io.wdd.pusher.core.model;
public enum ACTIONS {
VIEW("view"),
BROADCAST("broadcast"),
HTTP("http");
private final String name;
ACTIONS(String name) {
this.name = name;
}
public String getName() {
return name;
}
}

View File

@@ -0,0 +1,49 @@
package io.wdd.pusher.core.model;
public class Action {
private ACTIONS action;
private String label;
private String url;
private boolean clear;
private String body;
public ACTIONS getAction() {
return action;
}
public void setAction(ACTIONS action) {
this.action = action;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean isClear() {
return clear;
}
public void setClear(boolean clear) {
this.clear = clear;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}

View File

@@ -0,0 +1,6 @@
package io.wdd.pusher.core.model;
public enum ClientType {
PUB, SUB, STREAM;
}

View File

@@ -0,0 +1,381 @@
package io.wdd.pusher.core.model;
import java.util.Base64;
import java.util.List;
/**
* This class represents a message object for publishing/ sending notification message.
* It contains various properties related to the structure of the notification.
*/
public class NtfyRequest {
/**
* The topic to which you are publishing the message.
*/
private String topic;
/**
* The actual message content to be published. It can contain markdown as well.
*/
private String message;
/**
* The host or source to which you are publishing.
*/
private String host;
/**
* The title or subject of the message.
*/
private String title;
/**
* The priority level of the message.
*/
private PRIORITY priority;
/**
* A list of tags associated with the message.
*/
private List<String> tags;
/**
* The URL associated with the message.
*/
private String url;
/**
* Indicates whether the message content is in Markdown format.
*/
private boolean isMarkdown;
/**
* A list of actions related to the message.
*/
private List<Action> actions;
/**
* An attachment associated with the message. This will be the url linked of the attachment file.
*/
private String attach;
/**
* This local file that needs to be attached with the message,
*/
private String fileName;
/**
* The icon image url that needs to be used in the notification
*/
private String icon;
/**
* The email address to which the notification is to be sent.
*/
private String email;
/**
* The phone number to which the notification will be read to via call.
*/
private String phone;
/**
* Access token, generated in ntfy CLI
*/
private String accessToken;
/**
* Basic auth in format username:password
*/
private String authToken;
/**
* Get the auth token to authenticate to Server
*
* @return auth token as String
*/
public String getAuthToken() {
return this.authToken;
}
/**
* Sets the auth token (Base64 of username:password)
*
* @param userCombo username/password combo for generation of access token
*/
public void setAuthToken(String userCombo) {
this.authToken = Base64.getEncoder().encodeToString(userCombo.getBytes());
}
/**
* Get the accessToken for Authentication
*
* @return access token
*/
public String getAccessToken() {
return this.accessToken;
}
/**
* @param accessToken The authToken from CLI
*/
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
/**
* Get the phone number to which the notification will be read via a call.
*
* @return The phone number as a String.
*/
public String getPhone() {
return phone;
}
/**
* Set the phone number to which the notification will be read via a call.
*
* @param phone The phone number to set as a String.
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* Get the email address to which the notification is to be sent.
*
* @return The email address as a String.
*/
public String getEmail() {
return email;
}
/**
* Set the email address to which the notification is to be sent.
*
* @param email The email address to set as a String.
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Get the icon image URL that needs to be used in the notification.
*
* @return The icon image URL as a String.
*/
public String getIcon() {
return icon;
}
/**
* Set the icon image URL that needs to be used in the notification.
*
* @param icon The icon image URL to set as a String.
*/
public void setIcon(String icon) {
this.icon = icon;
}
/**
* Get the name of the local file that needs to be attached with the message.
*
* @return The file name as a String.
*/
public String getFileName() {
return fileName;
}
/**
* Set the name of the local file that needs to be attached with the message.
*
* @param fileName The file name to set as a String.
*/
public void setFileName(String fileName) {
this.fileName = fileName;
}
/**
* Get the attachment url associated with the message.
*
* @return The attachment url as a String.
*/
public String getAttach() {
return attach;
}
/**
* Set the attachment url for the message.
*
* @param attach The attachment url to set as a String.
*/
public void setAttach(String attach) {
this.attach = attach;
}
/**
* Get the list of actions related to the message.
*
* @return A list of Action objects.
*/
public List<Action> getActions() {
return actions;
}
/**
* Set the list of actions for the message.
*
* @param actions A list of Action objects to set.
*/
public void setActions(List<Action> actions) {
this.actions = actions;
}
/**
* Check if the message content is in Markdown format.
*
* @return True if the message content is in Markdown, false otherwise.
*/
public boolean isMarkdown() {
return isMarkdown;
}
/**
* Set whether the message content is in Markdown format.
*
* @param markdown True to set the message content as Markdown, false otherwise.
*/
public void setMarkdown(boolean markdown) {
isMarkdown = markdown;
}
/**
* Get the URL associated with the message.
*
* @return The URL as a String.
*/
public String getUrl() {
return url;
}
/**
* Set the URL for the message.
*
* @param url The URL to set as a String.
*/
public void setUrl(String url) {
this.url = url;
}
/**
* Get the actual message content.
*
* @return The message content as a String.
*/
public String getMessage() {
return message;
}
/**
* Set the message content.
*
* @param message The message content to set as a String.
*/
public void setMessage(String message) {
this.message = message;
}
/**
* Get the host or source of the message.
*
* @return The host as a String.
*/
public String getHost() {
return host;
}
/**
* Set the host or source of the message.
*
* @param host The host to set as a String.
*/
public void setHost(String host) {
this.host = host;
}
/**
* Get the title or subject of the message.
*
* @return The title as a String.
*/
public String getTitle() {
return title;
}
/**
* Set the title or subject of the message.
*
* @param title The title to set as a String.
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Get the priority level of the message.
*
* @return The priority level as a PRIORITY enum value.
*/
public PRIORITY getPriority() {
return priority;
}
/**
* Set the priority level of the message.
*
* @param priority The priority level to set as a PRIORITY enum value.
*/
public void setPriority(PRIORITY priority) {
this.priority = priority;
}
/**
* Get the list of tags associated with the message.
*
* @return A list of tags as Strings.
*/
public List<String> getTags() {
return tags;
}
/**
* Set the list of tags associated with the message.
*
* @param tags A list of tags to set as Strings.
*/
public void setTags(List<String> tags) {
this.tags = tags;
}
/**
* Get the topic to which the message is published.
*
* @return The topic as a String.
*/
public String getTopic() {
return topic;
}
/**
* Set the topic to which the message is published.
*
* @param topic The topic to set as a String.
*/
public void setTopic(String topic) {
this.topic = topic;
}
}

View File

@@ -0,0 +1,27 @@
package io.wdd.pusher.core.model;
public enum PRIORITY {
MAX("Max", 5),
HIGH("High", 4),
DEFAULT("Default", 3),
LOW("Low", 2),
MIN("Min", 1);
private final String name;
private final int level;
PRIORITY(String name, int level) {
this.name = name;
this.level = level;
}
public String getName() {
return name;
}
public int getLevel() {
return level;
}
}

View File

@@ -0,0 +1,5 @@
package io.wdd.pusher.core.model;
public class PublishResponse {
}

View File

@@ -0,0 +1,117 @@
package io.wdd.pusher.core.model;
import java.util.List;
public class RequestModel {
private String topic;
private String message;
private String title;
private List<String> tags;
private int priority;
private boolean markdown;
private List<Action> actions;
private String attach;
private String fileName;
private String icon;
private String email;
private String call;
public String getCall() {
return call;
}
public void setCall(String call) {
this.call = call;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getAttach() {
return attach;
}
public void setAttach(String attach) {
this.attach = attach;
}
public List<Action> getActions() {
return actions;
}
public void setActions(List<Action> actions) {
this.actions = actions;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public boolean isMarkdown() {
return markdown;
}
public void setMarkdown(boolean markdown) {
this.markdown = markdown;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

View File

@@ -0,0 +1,25 @@
package io.wdd.pusher.core.model;
public class StreamRequest {
private String host;
private String topic;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
}

View File

@@ -0,0 +1,9 @@
package io.wdd.pusher.core.publish;
import io.wdd.pusher.core.exception.NtfyException;
import io.wdd.pusher.core.model.NtfyRequest;
public interface PubClient {
String sendNotification(NtfyRequest ntfyRequest) throws NtfyException;
}

View File

@@ -0,0 +1,26 @@
package io.wdd.pusher.core.publish;
import io.wdd.pusher.core.exception.NtfyException;
import io.wdd.pusher.core.model.NtfyRequest;
import java.util.logging.Logger;
public class PubClientImpl implements PubClient {
private static final Logger logger = Logger.getLogger(PubClientImpl.class.getName());
private final PubService pubService;
public PubClientImpl(PubService pubService) {
this.pubService = pubService;
}
@Override
public String sendNotification(NtfyRequest ntfyRequest) throws NtfyException {
String response = pubService.publish(ntfyRequest);
if (null != response) {
logger.info("Response from server : " + response);
}
return response;
}
}

View File

@@ -0,0 +1,9 @@
package io.wdd.pusher.core.publish;
import io.wdd.pusher.core.exception.NtfyException;
import io.wdd.pusher.core.model.NtfyRequest;
public interface PubService {
String publish(NtfyRequest ntfyRequest) throws NtfyException;
}

View File

@@ -0,0 +1,117 @@
package io.wdd.pusher.core.publish;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.wdd.pusher.core.common.NtfyConstants;
import io.wdd.pusher.core.exception.NtfyConnectionException;
import io.wdd.pusher.core.exception.NtfyException;
import io.wdd.pusher.core.model.NtfyRequest;
import io.wdd.pusher.core.model.PRIORITY;
import io.wdd.pusher.core.model.RequestModel;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Logger;
public class PubServiceImpl implements PubService {
private static final Logger logger = Logger.getLogger(PubServiceImpl.class.getName());
@Override
public String publish(NtfyRequest request) throws NtfyException {
return publishMessage(request);
}
private String publishMessage(NtfyRequest request) throws NtfyException {
String response = null;
try {
if (null == request.getHost()) {
request.setUrl(NtfyConstants.DEFAULT_URL);
request.setHost(NtfyConstants.DEFAULT_HOST);
} else {
request.setUrl(NtfyConstants.HTTPS + request.getHost() + "/");
}
if (null == request.getPriority()) {
request.setPriority(PRIORITY.DEFAULT);
}
response = sendPublishRequest(request);
} catch (IOException e) {
logger.severe(NtfyConstants.CONNECTION_ERROR_MSG);
throw new NtfyException(e);
} catch (NtfyConnectionException e) {
logger.severe(NtfyConstants.NTFY_CONNECTION_ERROR_MSG);
throw new NtfyException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
private String sendPublishRequest(NtfyRequest request) throws Exception {
try {
URL obj = new URL(request.getUrl());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod(NtfyConstants.POST);
con.setConnectTimeout(10000);
con.setRequestProperty(NtfyConstants.CONTENT_TYPE, "application/json");
//handle authentication (if supplied)
if (request.getAccessToken() != null) {
con.setRequestProperty("Authorization", "Bearer " + request.getAccessToken());
} else if (request.getAuthToken() != null) {
con.setRequestProperty("Authorization", "Basic " + request.getAuthToken());
}
// Enable input/output streams
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.writeBytes(new ObjectMapper().writeValueAsString(createPublishRequest(request)));
wr.flush();
}
// Get the response from the server
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
StringBuilder response = new StringBuilder();
try (java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(con.getInputStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
return response.toString();
} else {
throw new NtfyConnectionException(NtfyConstants.NTFY_CONNECTION_ERROR_MSG + " : " + responseCode + " " + con.getResponseMessage());
}
} catch (IOException e) {
throw new NtfyConnectionException(NtfyConstants.CONNECTION_ERROR_MSG, e);
}
}
private RequestModel createPublishRequest(NtfyRequest request) {
RequestModel model = new RequestModel();
model.setTopic(request.getTopic());
model.setMessage(request.getMessage());
model.setTitle(request.getTitle());
model.setTags(request.getTags());
model.setMarkdown(request.isMarkdown());
model.setPriority(request.getPriority().getLevel());
model.setActions(request.getActions());
model.setAttach(request.getAttach());
model.setFileName(request.getFileName());
model.setIcon(request.getIcon());
model.setEmail(request.getEmail());
model.setCall(request.getPhone());
return model;
}
}

View File

@@ -0,0 +1,5 @@
package io.wdd.pusher.core.stream;
public interface StreamingDataListener {
void onDataReceived(String data);
}

View File

@@ -0,0 +1,63 @@
package io.wdd.pusher.core.stream;
import io.wdd.pusher.core.common.NtfyConstants;
import io.wdd.pusher.core.exception.NtfyStreamingException;
import io.wdd.pusher.core.model.StreamRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class StreamingService {
private final String streamingUrl;
private boolean running;
private StreamingDataListener dataListener;
public StreamingService(StreamRequest request) {
this.streamingUrl = NtfyConstants.HTTPS + request.getHost() + "/" +
request.getTopic() + "/" + NtfyConstants.JSON;
}
public void start() throws NtfyStreamingException {
try {
running = true;
Thread streamThread = new Thread(() -> {
try {
URL url = new URL(streamingUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(NtfyConstants.GET);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while (running) {
String line = reader.readLine();
if (line != null) {
if (dataListener != null) {
dataListener.onDataReceived(line);
}
}
}
reader.close();
connection.disconnect();
} catch (IOException e) {
System.err.println(e.getMessage());
}
});
streamThread.start();
} catch (Exception e) {
throw new NtfyStreamingException(NtfyConstants.CONNECTION_ERROR_MSG, e);
}
}
public void stop() {
running = false;
}
public void setDataListener(StreamingDataListener listener) {
this.dataListener = listener;
}
}

View File

@@ -0,0 +1,40 @@
package io.wdd.pusher.example;
import io.wdd.pusher.NtfyClient;
import io.wdd.pusher.core.exception.NtfyException;
import io.wdd.pusher.core.model.*;
import io.wdd.pusher.core.publish.PubClient;
import java.util.ArrayList;
import java.util.List;
public class PublishExample {
public static void main(String[] args) throws NtfyException {
PubClient client = new NtfyClient(ClientType.PUB).getClient();
NtfyRequest request = new NtfyRequest();
request.setTopic("test_ntfy2");
request.setMessage("Look ma, **bold text**, *italics*, ...");
request.setTitle("This is the obj msg");
request.setPriority(PRIORITY.MAX);
request.setAttach("https://media.licdn.com/dms/image/D4E03AQEZTNXuX3kG7g/profile-displayphoto-shrink_400_400/0/1669618932666?e=1699488000&v=beta&t=q2z_UDFvwTZa02SligKZqgwk66BjuXQZxWtQF_K1Jqw");
request.setFileName("Screenshot.png");
request.setIcon("https://styles.redditmedia.com/t5_32uhe/styles/communityIcon_xnt6chtnr2j21.png");
request.setEmail("mahesh.b.pec@gmail.com");
request.setPhone("");
Action action = new Action();
action.setAction(ACTIONS.VIEW);
action.setLabel("Open github");
action.setUrl("https://github.com/MaheshBabu11/ntfy-java");
action.setClear(true);
List<Action> actions = new ArrayList<>(List.of(action));
List<String> tags = new ArrayList<>(List.of("+1", "warning"));
request.setTags(tags);
request.setMarkdown(true);
request.setActions(actions);
client.sendNotification(request);
}
}

View File

@@ -0,0 +1,27 @@
package io.wdd.pusher.example;
import io.wdd.pusher.core.exception.NtfyStreamingException;
import io.wdd.pusher.core.model.StreamRequest;
import io.wdd.pusher.core.stream.StreamingService;
public class StreamingExample {
public static void main(String[] args) throws NtfyStreamingException {
StreamRequest request = new StreamRequest();
request.setHost("ntfy.sh");
request.setTopic("test_ntfy2");
StreamingService streamingConnection = new StreamingService(request);
streamingConnection.setDataListener(data -> {
// Process the incoming data here
System.out.println("Received data: " + data);
});
// Start the streaming connection
streamingConnection.start();
// Keep the connection open and receive data indefinitely
// To stop the connection, call streamingConnection.stop()
}
}

View File

@@ -0,0 +1,34 @@
package io.wdd.pusher;
import io.wdd.pusher.core.exception.NtfyException;
import io.wdd.pusher.core.model.ClientType;
import io.wdd.pusher.core.model.NtfyRequest;
import io.wdd.pusher.core.model.PRIORITY;
import io.wdd.pusher.core.publish.PubClient;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class PusherTest {
@Test
public void test() {
PubClient client = new NtfyClient(ClientType.PUB).getClient();
NtfyRequest ntfyRequest = new NtfyRequest();
ntfyRequest.setHost("push.107421.xyz");
ntfyRequest.setTopic("octopus");
ntfyRequest.setTitle("来自Java的测试推送");
ntfyRequest.setPriority(PRIORITY.HIGH);
ntfyRequest.setAccessToken("tk_zvdb67fwj1hrjivkq3ga9z7u63av5");
ntfyRequest.setMessage("这是一条来自Java的测试推送");
ntfyRequest.setAuthToken("tk_zvdb67fwj1hrjivkq3ga9z7u63av5");
try {
client.sendNotification(ntfyRequest);
} catch (NtfyException e) {
throw new RuntimeException(e);
}
}
}

View File

@@ -44,7 +44,7 @@ public class TestImageSyncScheduler {
ArrayList<String> ImageFullNameList = new ArrayList<>(List.of(
// "harbor.cdcyy.com.cn/cmii/cmii-live-operator:5.2.0",
// "harbor.cdcyy.com.cn/cmii/cmii/srs:v5.0.195"
"harbor.cdcyy.com.cn/cmii/cmii-uav-platform:5.3.0-cqly-042202"
"harbor.cdcyy.com.cn/cmii/cmii-uav-industrial-portfolio:54.0-cqly-042301"
));
Boolean downloadAndCompressOnly = false;