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

Cps consumption #124

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
25 changes: 20 additions & 5 deletions backend/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -170,11 +170,26 @@
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-pubsub</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.sendgrid</groupId>
<artifactId>java-http-client</artifactId>
<version>4.3.6</version>
</dependency>
<dependency>
<groupId>com.sendgrid</groupId>
<artifactId>sendgrid-java</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>8.13.0</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
Expand Down
2 changes: 2 additions & 0 deletions backend/src/main/java/com/google/rolecall/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ public static class Permissions {
public static class Notifications {
public static final String PROJECT_ID = "absolute-water-286821";
public static final String TOPIC_ID = "rolecall";
public static final String SUBSCRIPTION_ID = "rolecall_notif";
public static final String PERF_PUB_PREFIX = "Performance Published: ";
}

// Prevents object creation
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.google.rolecall.jsonobjects;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.auto.value.AutoValue;
import javax.annotation.Nullable;

/* Json representation of User class for serializing and deserializing. */
@AutoValue
@JsonDeserialize(builder = AutoValue_GenericMessage.Builder.class)
public abstract class GenericMessage {
@Nullable
@JsonProperty("message")
public abstract String message();


/* Every UserInfo should be unique unless it's being comapred to itself */
@Override
public boolean equals(Object object) {
return this == object;
}

public static Builder newBuilder() {
return new AutoValue_GenericMessage.Builder();
}

@AutoValue.Builder
public abstract static class Builder {
@JsonProperty("message")
public abstract Builder setMessage(String message);

public abstract GenericMessage build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.google.rolecall.restcontrollers;
import com.google.rolecall.jsonobjects.ResponseSchema;
import com.google.rolecall.jsonobjects.GenericMessage;
import com.google.rolecall.restcontrollers.Annotations.Endpoint;
import com.google.rolecall.restcontrollers.Annotations.Post;
import com.google.rolecall.services.NotificationServices;
import java.util.concurrent.CompletableFuture;

/** Endpoints for manipulating User objects. */
@Endpoint("/api/notification")
public class Notification extends AsyncRestEndpoint {

private final NotificationServices service;

@Post
public CompletableFuture<ResponseSchema<GenericMessage>> processNotification() {
try {
service.process();
} catch(Exception e) {
return CompletableFuture.failedFuture(e);
}

ResponseSchema<GenericMessage> response = new ResponseSchema<>(GenericMessage.newBuilder().setMessage("OK").build());
return CompletableFuture.completedFuture(response);
}

public Notification(NotificationServices service) {
this.service = service;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package com.google.rolecall.services;

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

import com.google.rolecall.Constants;
import com.google.rolecall.util.CPSNotification;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sendgrid.*;

import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;

@Service("noticiationServices")
public class NotificationServices {
@Autowired
private org.springframework.core.env.Environment environment;
String topicId;

public void process() throws Exception {
List<CPSNotification> notifications = this.getNotifications();
for (CPSNotification notif : notifications) {
if (!notif.email.equals("")) {
this.sendEmail(notif.email, notif.message);
}
if (!notif.phone.equals("")) {
this.sendSMS(notif.phone, notif.message);
}
}
}

private void sendSMS(String phoneNo, String content) {
String accountSid = this.environment.getProperty("twilio.account.sid");
String authToken = this.environment.getProperty("twilio.auth.token");
Twilio.init(accountSid, authToken);
Message.creator(new com.twilio.type.PhoneNumber(phoneNo),
new com.twilio.type.PhoneNumber(this.environment.getProperty("twilio.from.number")), content).create();
}

private void sendEmail(String email, String messsage) throws IOException {
Email from = new Email("[email protected]"); // for test accout. Jon will provide actual billable account before
// releasing
String subject = messsage;
Email to = new Email(email);
Content content = new Content("text/plain", messsage);
Mail mail = new Mail(from, subject, to, content);
SendGrid sg = new SendGrid(this.environment.getProperty("sendgrid.api.key"));
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
sg.api(request);
} catch (IOException ex) {
throw ex;
}
}

private List<CPSNotification> getNotifications() throws Exception {
String subId = Constants.Notifications.SUBSCRIPTION_ID + "_" + this.environment.getActiveProfiles()[0];
List<CPSNotification> notifs = CPSNotification.readMessages(subId);
return notifs;
}

public NotificationServices() {
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.google.rolecall.services;

import com.google.rolecall.Constants;
import com.google.rolecall.jsonobjects.PerformanceCastInfo;
import com.google.rolecall.jsonobjects.PerformanceCastMemberInfo;
import com.google.rolecall.jsonobjects.PerformanceInfo;
Expand Down Expand Up @@ -75,7 +76,7 @@ public ServiceResult<Performance> editPerformance(PerformanceInfo newPerformance
if (performance.getStatus().equals(Performance.Status.PUBLISHED)) {
String[] profiles = this.environment.getActiveProfiles();
String profile = profiles[0];
String message = performance.getDescription();
String message = Constants.Notifications.PERF_PUB_PREFIX + performance.getDescription();

// get all performers
List<PerformanceSectionInfo> sections = newPerformance.performanceSections();
Expand Down
77 changes: 67 additions & 10 deletions backend/src/main/java/com/google/rolecall/util/CPSNotification.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,32 @@

import com.google.rolecall.Constants;
import com.google.rolecall.models.User;
import com.google.pubsub.v1.AcknowledgeRequest;
import com.google.pubsub.v1.ProjectSubscriptionName;
import com.google.pubsub.v1.PubsubMessage;
import com.google.pubsub.v1.PullRequest;
import com.google.pubsub.v1.PullResponse;
import com.google.pubsub.v1.ReceivedMessage;
import com.google.pubsub.v1.TopicName;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.google.cloud.pubsub.v1.Publisher;
import com.google.cloud.pubsub.v1.stub.GrpcSubscriberStub;
import com.google.cloud.pubsub.v1.stub.SubscriberStub;
import com.google.cloud.pubsub.v1.stub.SubscriberStubSettings;
import com.google.gson.Gson;
import com.google.protobuf.ByteString;

public class CPSNotification {
String email;
String phone;
String message;
String profile;
public String email;
public String phone;
public String message;
public String profile;

public CPSNotification(User user, String message, String profile) {
this.profile = profile;

this.profile = profile;
this.email = user.getEmail();
this.phone = user.getPhoneNumber();
this.message = message;
Expand All @@ -27,14 +37,16 @@ public void send() {
Publisher publisher = null;
try {
Gson gson = new Gson();
TopicName topicName = TopicName.of(Constants.Notifications.PROJECT_ID, Constants.Notifications.TOPIC_ID + "_" +this.profile);
TopicName topicName = TopicName.of(Constants.Notifications.PROJECT_ID,
Constants.Notifications.TOPIC_ID + "_" + this.profile);
publisher = Publisher.newBuilder(topicName).build();
PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8(gson.toJson(this))).build();
publisher.publish(pubsubMessage);
PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8(gson.toJson(this)))
.build();
publisher.publish(pubsubMessage);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (publisher != null) {
if (publisher != null) {
publisher.shutdown();
try {
publisher.awaitTermination(1, TimeUnit.MINUTES);
Expand All @@ -46,4 +58,49 @@ public void send() {

}

public static List<CPSNotification> readMessages(String subscriptionId) throws Exception {
List<CPSNotification> notifications = new ArrayList<CPSNotification>();
SubscriberStub subscriber = null;
try {

SubscriberStubSettings subscriberStubSettings = SubscriberStubSettings.newBuilder()
.setTransportChannelProvider(SubscriberStubSettings.defaultGrpcTransportProviderBuilder()
.setMaxInboundMessageSize(20 * 1024 * 1024) // 20MB (maximum message size).
.build())
.build();
subscriber = GrpcSubscriberStub.create(subscriberStubSettings);

String subscriptionName = ProjectSubscriptionName.format(Constants.Notifications.PROJECT_ID,
subscriptionId);
PullRequest pullRequest = PullRequest.newBuilder().setMaxMessages(100).setSubscription(subscriptionName)
.build();

PullResponse pullResponse = subscriber.pullCallable().call(pullRequest);
List<String> ackIds = new ArrayList<>();
for (ReceivedMessage message : pullResponse.getReceivedMessagesList()) {
Gson gson = new Gson();
CPSNotification notif = gson.fromJson(message.getMessage().getData().toStringUtf8(),
CPSNotification.class);
notifications.add(notif);
ackIds.add(message.getAckId());
}
// Acknowledge received messages.
if(!ackIds.isEmpty()) {
AcknowledgeRequest acknowledgeRequest = AcknowledgeRequest.newBuilder().setSubscription(subscriptionName)
.addAllAckIds(ackIds).build();
subscriber.acknowledgeCallable().call(acknowledgeRequest);
}

} catch (Exception e) {
throw e;
} finally {
if (subscriber != null) {
// When finished with the publisher, shutdown to free up resources.
subscriber.shutdown();
subscriber.awaitTermination(1, TimeUnit.MINUTES);
}

}
return notifications;
}
}
4 changes: 4 additions & 0 deletions backend/src/main/resources/application-dev.properties
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,7 @@ spring.jpa.hibernate.ddl-auto = update
admin.first.name=System
admin.last.name=Admin
[email protected]
sendgrid.api.key=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
twilio.account.sid=ACce909d86c5a052cb475816d8ccb47a1b
twilio.auth.token=ab61c661e150c249c60130a4664dfb0b
twilio.from.number=+17752411428