Skip to content

Commit

Permalink
[Samples][Java] Fix disparities of 56.teams-file-upload sample (#3278)
Browse files Browse the repository at this point in the history
* Remove autogenerated files

* Update README

* Add package-info file

* Update index.html

* Send configuration of application.properties to Bot

* Add missing scenario to send an inline image download

* Remove unnecesary and empty lines
  • Loading branch information
Batta32 authored May 17, 2021
1 parent c178b60 commit 26716f2
Show file tree
Hide file tree
Showing 9 changed files with 164 additions and 54 deletions.
103 changes: 77 additions & 26 deletions samples/java_springboot/56.teams-file-upload/README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@

# Teams File Upload Bot
# Teams File Upload Bot

Bot Framework v4 file upload bot sample for Teams.

This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to
upload files to Teams from a bot and how to receive a file sent to a bot as an attachment.

## Prerequisites
This sample is a Spring Boot app and uses the Azure CLI and azure-webapp Maven plugin to deploy to Azure.

## Prerequisites
- Java 1.8+
- Install [Maven](https://maven.apache.org/)
- An account on [Azure](https://azure.microsoft.com) if you want to deploy to Azure.
- Microsoft Teams is installed and you have an account
- [ngrok](https://ngrok.com/) or equivalent tunnelling solution

Expand All @@ -16,31 +19,17 @@ upload files to Teams from a bot and how to receive a file sent to a bot as an a
> Note these instructions are for running the sample on your local machine, the tunnelling solution is required because
the Teams service needs to call into the bot.

1) Clone the repository

```bash
git clone https://github.com/Microsoft/botbuilder-java.git
```

1) Run ngrok - point to port 3978

```bash
ngrok http -host-header=rewrite 3978
```

1) Create [Bot Framework registration resource](https://docs.microsoft.com/en-us/azure/bot-service/bot-service-quickstart-registration) in Azure
- Run ngrok - point to port 3978
- Create [Bot Framework registration resource](https://docs.microsoft.com/en-us/azure/bot-service/bot-service-quickstart-registration) in Azure
- Use the current `https` URL you were given by running ngrok. Append with the path `/api/messages` used by this sample
- Ensure that you've [enabled the Teams Channel](https://docs.microsoft.com/en-us/azure/bot-service/channel-connect-teams?view=azure-bot-service-4.0)
- __*If you don't have an Azure account*__ you can use this [Bot Framework registration](https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/create-a-bot-for-teams#register-your-web-service-with-the-bot-framework)

1) Update the `resources/application.properties` configuration for the bot to use the Microsoft App Id and App Password from the Bot Framework registration. (Note the App Password is referred to as the "client secret" in the azure portal and you can always create a new client secret anytime.)

1) __*This step is specific to Teams.*__
- Update the `resources/application.properties` configuration for the bot to use the Microsoft App Id and App Password from the Bot Framework registration. (Note the App Password is referred to as the "client secret" in the azure portal and you can always create a new client secret anytime.)
- __*This step is specific to Teams.*__
- **Edit** the `manifest.json` contained in the `teamsAppManifest` folder to replace your Microsoft App Id (that was created when you registered your bot earlier) *everywhere* you see the place holder string `<<YOUR-MICROSOFT-APP-ID>>` (depending on the scenario the Microsoft App Id may occur multiple times in the `manifest.json`)
- **Zip** up the contents of the `teamsAppManifest` folder to create a `manifest.zip`
- **Upload** the `manifest.zip` to Teams (in the Apps view click "Upload a custom app")
1) From the root of this project folder:
- From the root of this project folder:
- Build the sample using `mvn package`
- Unless done previously, install the packages in the local cache by using `mvn install`
- Run it by using `java -jar .\target\bot-teams-file-upload-sample.jar`
Expand All @@ -50,15 +39,77 @@ the Teams service needs to call into the bot.

> Note this `manifest.json` specified that the bot will be installed in "personal" scope which is why you immediately entered a one on one chat conversation with the bot. Please refer to Teams documentation for more details.
Sending a message to the bot will cause it to respond with a card that will prompt you to upload a file. The file that's being uploaded is the `teams-logo.png` in the `Files` directory in this sample. The `Accept` and `Decline` events illustrated in this sample are specific to Teams. You can message the bot again to receive another prompt.
1. Sending a message to the bot will cause it to respond with a card that will prompt you to upload a file. The file that's being uploaded is the `teams-logo.png` in the `Files` directory in this sample. The `Accept` and `Decline` events illustrated in this sample are specific to Teams. You can message the bot again to receive another prompt.

You can also send a file to the bot as an attachment in the message compose section in Teams. This will be delivered to the bot as a Message Activity and the code in this sample fetches and saves the file.
1. You can send a file to the bot as an attachment in the message compose section in Teams. This will be delivered to the bot as a Message Activity and the code in this sample fetches and saves the file.

1. You can also send an inline image in the message compose section. This will be present in the attachments of the Activity and requires the Bot's access token to fetch the image.

## Deploy the bot to Azure

To learn more about deploying a bot to Azure, see [Deploy your bot to Azure](https://aka.ms/azuredeployment) for a complete list of deployment instructions.
As described on [Deploy your bot](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-deploy-az-cli), you will perform the first 4 steps to setup the Azure app, then deploy the code using the azure-webapp Maven plugin.

## Further reading
### 1. Login to Azure

From a command (or PowerShell) prompt in the root of the bot folder, execute:
`az login`

### 2. Set the subscription

```
az account set --subscription "<azure-subscription>"
```

If you aren't sure which subscription to use for deploying the bot, you can view the list of subscriptions for your account by using `az account list` command.

### 3. Create an App registration

```
az ad app create --display-name "<botname>" --password "<appsecret>" --available-to-other-tenants
```

Replace `<botname>` and `<appsecret>` with your own values.

`<botname>` is the unique name of your bot.
`<appsecret>` is a minimum 16 character password for your bot.

Record the `appid` from the returned JSON

### 4. Create the Azure resources

Replace the values for `<appid>`, `<appsecret>`, `<botname>`, and `<groupname>` in the following commands:

#### To a new Resource Group

```
az deployment sub create --name "teamsFileUploadDeploy" --location "westus" --template-file ".\deploymentTemplates\template-with-new-rg.json" --parameters appId="<appid>" appSecret="<appsecret>" botId="<botname>" botSku=S1 newAppServicePlanName="teamsFileUploadPlan" newWebAppName="teamsFileUpload" groupLocation="westus" newAppServicePlanLocation="westus"
```

#### To an existing Resource Group

```
az deployment group create --resource-group "<groupname>" --template-file ".\deploymentTemplates\template-with-preexisting-rg.json" --parameters appId="<appid>" appSecret="<appsecret>" botId="<botname>" newWebAppName="teamsFileUpload" newAppServicePlanName="teamsFileUploadPlan" appServicePlanLocation="westus" --name "teamsFileUpload"
```

### 5. Update app id and password

In src/main/resources/application.properties update

- `MicrosoftAppPassword` with the botsecret value
- `MicrosoftAppId` with the appid from the first step

### 6. Deploy the code

- Execute `mvn clean package`
- Execute `mvn azure-webapp:deploy -Dgroupname="<groupname>" -Dbotname="<bot-app-service-name>"`

If the deployment is successful, you will be able to test it via "Test in Web Chat" from the Azure Portal using the "Bot Channel Registration" for the bot.

After the bot is deployed, you only need to execute #6 if you make changes to the bot.

## Further reading
- [Spring Boot](https://spring.io/projects/spring-boot)
- [Maven Plugin for Azure App Service](https://github.com/microsoft/azure-maven-plugins/tree/develop/azure-webapp-maven-plugin)
- [How Microsoft Teams bots work](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-basics-teams?view=azure-bot-service-4.0&tabs=javascript)
- [Azure for Java cloud developers](https://docs.microsoft.com/en-us/azure/java/?view=azure-java-stable)

Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ public static void main(String[] args) {
* @return The Bot implementation for this application.
*/
@Bean
public Bot getBot() {
return new TeamsFileUploadBot();
public Bot getBot(Configuration configuration) {
return new TeamsFileUploadBot(configuration);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import com.microsoft.bot.builder.MessageFactory;
import com.microsoft.bot.builder.TurnContext;
import com.microsoft.bot.builder.teams.TeamsActivityHandler;
import com.microsoft.bot.connector.authentication.MicrosoftAppCredentials;
import com.microsoft.bot.integration.Configuration;
import com.microsoft.bot.schema.Activity;
import com.microsoft.bot.schema.Attachment;
import com.microsoft.bot.schema.ResultPair;
Expand All @@ -15,15 +17,19 @@
import com.microsoft.bot.schema.teams.FileConsentCardResponse;
import com.microsoft.bot.schema.teams.FileDownloadInfo;
import com.microsoft.bot.schema.teams.FileInfoCard;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
Expand All @@ -40,6 +46,16 @@
* participants.</p>
*/
public class TeamsFileUploadBot extends TeamsActivityHandler {
// You can install this bot at any scope. You can @mention the bot and it will present you with the file prompt. You can accept and
// the file will be uploaded, or you can decline and it won't.

private static String microsoftAppId;
private static String microsoftAppPassword;

public TeamsFileUploadBot(Configuration configuration) {
microsoftAppId = configuration.getProperty("MicrosoftAppId");
microsoftAppPassword = configuration.getProperty("MicrosoftAppPassword");
}

@Override
protected CompletableFuture<Void> onMessageActivity(TurnContext turnContext) {
Expand All @@ -50,6 +66,10 @@ protected CompletableFuture<Void> onMessageActivity(TurnContext turnContext) {
? fileDownloadFailed(turnContext, result.value())
: fileDownloadCompleted(turnContext, attachment)
);
} else if (turnContext.getActivity().getAttachments() != null
&& turnContext.getActivity().getAttachments().get(0).getContentType().contains("image/*")) {
// Inline image se.
return processInlineImage(turnContext);
} else {
File filePath = new File("files", "teams-logo.png");
return sendFileCard(turnContext, filePath.getName(), filePath.length());
Expand Down Expand Up @@ -215,6 +235,62 @@ private CompletableFuture<ResultPair<String>> upload(
.thenApply(aVoid -> result.get());
}

private CompletableFuture<Void> processInlineImage(TurnContext turnContext) {
Attachment attachment = turnContext.getActivity().getAttachments().get(0);
final HttpURLConnection[] connection = {null};
// Get Bot's access token to fetch inline image.
return new MicrosoftAppCredentials(microsoftAppId, microsoftAppPassword).getToken().thenApply(token -> {
try {
// Save the inline image to Files directory.
String filePath = "files/imageFromUser.png";
URL url = new URL(attachment.getContentUrl());
connection[0] = (HttpURLConnection) url.openConnection();
connection[0].setRequestProperty("Authorization", "Bearer " + token);
try (
FileOutputStream fileStream = new FileOutputStream(filePath);
InputStream downloadStream = connection[0].getInputStream()
) {
byte[] buffer = new byte[4096];
int bytes_read;
while ((bytes_read = downloadStream.read(buffer)) != -1) {
fileStream.write(buffer, 0, bytes_read);
}
// Create reply with image.
byte[] fileSize = FileUtils.readFileToByteArray(new File(filePath));
Activity reply = MessageFactory.text(
String.format(
"Attachment of %s type and size of %d bytes received",
attachment.getContentType(),
fileSize.length));
List<Attachment> attachments = new ArrayList<>();
attachments.add(getInlineAttachment());
reply.setAttachments(attachments);
return turnContext.sendActivity(reply);
}
} catch (Throwable t) {
} finally {
if (connection[0] != null) {
connection[0].disconnect();
}
}
return null;
}).thenApply(aVoid -> null);
}

private static Attachment getInlineAttachment() {
String imagePath = "files/imageFromUser.png";
Attachment attachment = new Attachment();
File file = new File(imagePath);
try {
String imageData = Base64.encodeBase64String(FileUtils.readFileToByteArray(file));
attachment.setName("imageFromUser.png");
attachment.setContentType("image/png");
attachment.setContentUrl("data:image/png;base64," + imageData);
} catch (IOException e) {
}
return attachment;
}

private CompletableFuture<ResultPair<String>> downloadAttachment(Attachment attachment) {
AtomicReference<ResultPair<String>> result = new AtomicReference<>();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.

/**
* This package contains the classes for the teams file upload sample.
*/
package com.microsoft.bot.sample.teamsfileupload;
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>EchoBot</title>
<title>Teams File Upload Bot</title>
<style>
body {
margin: 0px;
Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

0 comments on commit 26716f2

Please sign in to comment.