[go: nahoru, domu]

Skip to content

Commit

Permalink
Requesting photo.
Browse files Browse the repository at this point in the history
  • Loading branch information
Eugene Freiman committed Nov 30, 2020
1 parent cd1a0db commit 488822c
Show file tree
Hide file tree
Showing 7 changed files with 86 additions and 28 deletions.
2 changes: 1 addition & 1 deletion PhotoFunction/src/main/java/service/GuiceModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public GooglePhotoProxy googlePhotoProxy() {

@Provides
public TelegramProxy telegramProxy() {
return new TelegramProxy(secretRetriever.telegramSecret());
return new TelegramProxy(secretRetriever.telegramSecret(), gson);
}

@Provides
Expand Down
20 changes: 14 additions & 6 deletions PhotoFunction/src/main/java/service/Handler.java
Original file line number Diff line number Diff line change
@@ -1,32 +1,40 @@
package service;

import java.io.IOException;
import java.util.Collections;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.ScheduledEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.inject.Guice;
import com.google.inject.Injector;

/**
* Handler for requests to Lambda function.
*/
public class Handler implements RequestHandler<ScheduledEvent, String> {
public class Handler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {

private Injector injector = Guice.createInjector(new GuiceModule());
private Service service = injector.getInstance(Service.class);

@Override
public String handleRequest(ScheduledEvent event, Context context) {
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) {

final LambdaLogger logger = context.getLogger();
logger.log(String.format("Input event: %s", event.toString()));
try {
service.serve(context, logger);
service.serve(event, context, logger);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
return "200 OK";

return new APIGatewayProxyResponseEvent()
.withStatusCode(200)
.withHeaders(Collections.emptyMap())
.withBody("{\"message\":\"success\"}");
}
}
48 changes: 34 additions & 14 deletions PhotoFunction/src/main/java/service/Service.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.$Gson$Preconditions;
import com.google.photos.types.proto.Album;
import com.google.photos.types.proto.MediaItem;
import service.database.Chat;
Expand All @@ -13,6 +17,7 @@
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.Set;

Expand All @@ -24,25 +29,34 @@ public class Service {
private final TelegramProxy telegramProxy;
private final DBProxy DBProxy;
private final Random random = new Random();
private final Gson gson;

@Inject
public Service(final GooglePhotoProxy googlePhotoProxy,
final TelegramProxy telegramProxy,
final DBProxy DBProxy) {
final DBProxy DBProxy,
final Gson gson) {
this.googlePhotoProxy = googlePhotoProxy;
this.telegramProxy = telegramProxy;
this.DBProxy = DBProxy;
this.gson = gson;
}

public void serve(final Context context, final LambdaLogger logger) throws IOException {
// Read recent messages.
Set<Long> recentChats = telegramProxy.getChats(logger);
public void serve(APIGatewayProxyRequestEvent event, final Context context, final LambdaLogger logger) throws IOException {

Gson gson = new GsonBuilder().setPrettyPrinting().create();
logger.log(String.format("Event: %s", gson.toJson(event)));

// Update the database.
recentChats.stream().forEach(chatId -> {
DBProxy.put(new Chat(chatId));
logger.log(String.format("Chat %d added to database", chatId));
});
// Read recent messages.
Optional<Long> chatId = telegramProxy.getChat(logger, event.getBody());

if (chatId.isPresent()) {
// Update the database.
DBProxy.put(new Chat(chatId.get()));
logger.log(String.format("Chat %d added to database", chatId.get()));
} else {
logger.log(String.format("ChatId isn't found in the request"));
}

// Retrieve a photo.
List<Album> albums = googlePhotoProxy.getAlbums(ALBUM_PREFIX);
Expand Down Expand Up @@ -77,10 +91,16 @@ public void serve(final Context context, final LambdaLogger logger) throws IOExc
// Retrieve a list of all the chats.
List<Chat> chats = DBProxy.scan();

// Send photo to all the chats.
for (Chat chat : chats) {
telegramProxy.sendPhoto(logger, chat.getChatId(), albumTitle, item.getBaseUrl());
logger.log(String.format("Photo sent to %d chat", chat.getChatId()));
};
if (chatId.isPresent()) {
// Send photo to the requester.
telegramProxy.sendPhoto(logger, chatId.get(), albumTitle, item.getBaseUrl());
logger.log(String.format("Photo sent to %d chat", chatId.get()));
} else {
// Send photo to all the chats.
for (Chat chat : chats) {
telegramProxy.sendPhoto(logger, chat.getChatId(), albumTitle, item.getBaseUrl());
logger.log(String.format("Photo sent to %d chat", chat.getChatId()));
}
}
}
}
18 changes: 14 additions & 4 deletions PhotoFunction/src/main/java/service/telegram/TelegramProxy.java
Original file line number Diff line number Diff line change
@@ -1,27 +1,33 @@
package service.telegram;

import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.google.gson.Gson;
import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.request.GetUpdates;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.request.SendPhoto;
import com.pengrad.telegrambot.response.GetUpdatesResponse;
import com.pengrad.telegrambot.response.SendResponse;

import javax.inject.Inject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

public class TelegramProxy {

private final TelegramSecret secret;
private TelegramBot botCache = null;
private Gson gson;

public TelegramProxy(final TelegramSecret secret) {
public TelegramProxy(final TelegramSecret secret, final Gson gson) {
this.secret = secret;
this.gson = gson;
}

private TelegramBot getBot() {
Expand All @@ -31,9 +37,13 @@ private TelegramBot getBot() {
return botCache;
}

public Set<Long> getChats(final LambdaLogger logger) {
GetUpdatesResponse response = getBot().execute(new GetUpdates());
return response.updates().stream().map(update -> update.message().chat().id()).collect(Collectors.toSet());
public Optional<Long> getChat(final LambdaLogger logger, String eventBody) {
if (eventBody == null) {
return Optional.empty();
}

Update update = gson.fromJson(eventBody, Update.class);
return Optional.of(update.message().chat().id());
}

public void sendMessage(final LambdaLogger logger, final Long chatId, final String text) {
Expand Down
10 changes: 7 additions & 3 deletions PhotoFunction/src/test/java/service/ServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.photos.types.proto.Album;
Expand All @@ -22,6 +23,7 @@
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.Set;

Expand All @@ -46,11 +48,13 @@ public class ServiceTest {
@Mock
private DBProxy dbProxy;

private Gson gson = new GsonBuilder().setPrettyPrinting().create();

private Service service;

@Before
public void setUp() throws IOException {
service = new Service(googlePhotoProxy, telegramProxy, dbProxy);
service = new Service(googlePhotoProxy, telegramProxy, dbProxy, gson);
}

@Test
Expand All @@ -62,12 +66,12 @@ public void happyCase() throws IOException {
.setMimeType(MIME_TYPE)
.setBaseUrl(IMAGE_BASE_URL).build();

when(telegramProxy.getChats(any())).thenReturn(Collections.singleton(CHAT_ID));
when(telegramProxy.getChat(any(), any())).thenReturn(Optional.of(CHAT_ID));
when(googlePhotoProxy.getAlbums(any())).thenReturn(Collections.singletonList(album));
when(googlePhotoProxy.getMediaItems(album)).thenReturn(Collections.singletonList(mediaItem));
when(dbProxy.scan()).thenReturn(Collections.singletonList(new Chat(CHAT_ID)));

service.serve(mock(Context.class), mock(LambdaLogger.class));
service.serve(new APIGatewayProxyRequestEvent(), mock(Context.class), mock(LambdaLogger.class));

verify(dbProxy).put(new Chat(CHAT_ID));
verify(telegramProxy).sendPhoto(any(), eq(CHAT_ID), eq(ALBUM_TITLE.substring(1)), eq(IMAGE_BASE_URL));
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
After deployment need to setWebhook for the bot to call api:
```
POST https://api.telegram.org/<token>/setWebhook?url=https://<api id>.execute-api.ca-central-1.amazonaws.com/Prod/more/
```

# LazyPhotoShare

This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders.
Expand Down
11 changes: 11 additions & 0 deletions template.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ Resources:
Type: Schedule
Properties:
Schedule: rate(12 hours)
Input: "{\"resource\":\"/more\",\"path\":\"/more\",\"httpMethod\":\"POST\",\"requestContext\":{\"accountId\":\"641246385999\",\"stage\":\"test-invoke-stage\",\"resourceId\":\"1pc3cp\",\"requestId\":\"8a290575-6638-40f1-82a1-15b255d757ce\",\"identity\":{\"accountId\":\"641246385999\",\"caller\":\"641246385999\",\"apiKey\":\"test-invoke-api-key\",\"sourceIp\":\"test-invoke-source-ip\",\"userArn\":\"arn:aws:iam::641246385999:root\",\"userAgent\":\"aws-internal/3 aws-sdk-java/1.11.864 Linux/4.9.217-0.3.ac.206.84.332.metal1.x86_64 OpenJDK_64-Bit_Server_VM/25.262-b10 java/1.8.0_262 vendor/Oracle_Corporation\",\"user\":\"641246385999\",\"accessKey\":\"ASIAZKTKDK5H7SO6M77F\"},\"resourcePath\":\"/more\",\"httpMethod\":\"POST\",\"apiId\":\"sc6iz53gbk\",\"path\":\"/more\"},\"isBase64Encoded\":false}"
HttpPost:
Type: Api
Properties:
Path: /more
Method: POST
Policies:
- Statement:
Effect: Allow
Expand Down Expand Up @@ -68,3 +74,8 @@ Resources:
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1

Outputs:
ApiUrl:
Description: "API Gateway endpoint URL for Prod stage for Photo function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/more/"

0 comments on commit 488822c

Please sign in to comment.