diff --git a/samples/56.teams-file-upload/LICENSE b/samples/56.teams-file-upload/LICENSE new file mode 100644 index 000000000..21071075c --- /dev/null +++ b/samples/56.teams-file-upload/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/samples/56.teams-file-upload/README.md b/samples/56.teams-file-upload/README.md new file mode 100644 index 000000000..04d4a14e1 --- /dev/null +++ b/samples/56.teams-file-upload/README.md @@ -0,0 +1,64 @@ + +# 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 + +- Microsoft Teams is installed and you have an account +- [ngrok](https://ngrok.com/) or equivalent tunnelling solution + +## To try this sample + +> 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 8080 + + ```bash + ngrok http -host-header=rewrite 8080 + ``` + +1) 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.*__ + - **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 `<>` (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: + - 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` + + +## Interacting with the bot in Teams + +> 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. + +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. + +## 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. + +## Further reading + +- [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) + diff --git a/samples/56.teams-file-upload/deploymentTemplates/new-rg-parameters.json b/samples/56.teams-file-upload/deploymentTemplates/new-rg-parameters.json new file mode 100644 index 000000000..ead339093 --- /dev/null +++ b/samples/56.teams-file-upload/deploymentTemplates/new-rg-parameters.json @@ -0,0 +1,42 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "groupLocation": { + "value": "" + }, + "groupName": { + "value": "" + }, + "appId": { + "value": "" + }, + "appSecret": { + "value": "" + }, + "botId": { + "value": "" + }, + "botSku": { + "value": "" + }, + "newAppServicePlanName": { + "value": "" + }, + "newAppServicePlanSku": { + "value": { + "name": "S1", + "tier": "Standard", + "size": "S1", + "family": "S", + "capacity": 1 + } + }, + "newAppServicePlanLocation": { + "value": "" + }, + "newWebAppName": { + "value": "" + } + } +} \ No newline at end of file diff --git a/samples/56.teams-file-upload/deploymentTemplates/preexisting-rg-parameters.json b/samples/56.teams-file-upload/deploymentTemplates/preexisting-rg-parameters.json new file mode 100644 index 000000000..b6f5114fc --- /dev/null +++ b/samples/56.teams-file-upload/deploymentTemplates/preexisting-rg-parameters.json @@ -0,0 +1,39 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "appId": { + "value": "" + }, + "appSecret": { + "value": "" + }, + "botId": { + "value": "" + }, + "botSku": { + "value": "" + }, + "newAppServicePlanName": { + "value": "" + }, + "newAppServicePlanSku": { + "value": { + "name": "S1", + "tier": "Standard", + "size": "S1", + "family": "S", + "capacity": 1 + } + }, + "appServicePlanLocation": { + "value": "" + }, + "existingAppServicePlan": { + "value": "" + }, + "newWebAppName": { + "value": "" + } + } +} \ No newline at end of file diff --git a/samples/56.teams-file-upload/deploymentTemplates/template-with-new-rg.json b/samples/56.teams-file-upload/deploymentTemplates/template-with-new-rg.json new file mode 100644 index 000000000..dcd6260a5 --- /dev/null +++ b/samples/56.teams-file-upload/deploymentTemplates/template-with-new-rg.json @@ -0,0 +1,191 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "groupLocation": { + "defaultValue": "", + "type": "string", + "metadata": { + "description": "Specifies the location of the Resource Group." + } + }, + "groupName": { + "type": "string", + "metadata": { + "description": "Specifies the name of the Resource Group." + } + }, + "appId": { + "type": "string", + "metadata": { + "description": "Active Directory App ID, set as MicrosoftAppId in the Web App's Application Settings." + } + }, + "appSecret": { + "type": "string", + "metadata": { + "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings." + } + }, + "botId": { + "type": "string", + "metadata": { + "description": "The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable." + } + }, + "botSku": { + "defaultValue": "F0", + "type": "string", + "metadata": { + "description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1." + } + }, + "newAppServicePlanName": { + "defaultValue": "", + "type": "string", + "metadata": { + "description": "The name of the App Service Plan." + } + }, + "newAppServicePlanSku": { + "type": "object", + "defaultValue": { + "name": "P1v2", + "tier": "PremiumV2", + "size": "P1v2", + "family": "Pv2", + "capacity": 1 + }, + "metadata": { + "description": "The SKU of the App Service Plan. Defaults to Standard values." + } + }, + "newAppServicePlanLocation": { + "defaultValue": "", + "type": "string", + "metadata": { + "description": "The location of the App Service Plan. Defaults to \"westus\"." + } + }, + "newWebAppName": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "The globally unique name of the Web App. Defaults to the value passed in for \"botId\"." + } + } + }, + "variables": { + "resourcesLocation": "[deployment().location]", + "effectiveGroupLocation": "[if(empty(parameters('groupLocation')), variables('resourcesLocation'), parameters('groupLocation'))]", + "effectivePlanLocation": "[if(empty(parameters('newAppServicePlanLocation')), variables('resourcesLocation'), parameters('newAppServicePlanLocation'))]", + "appServicePlanName": "[if(empty(parameters('newAppServicePlanName')), concat(parameters('botId'), 'ServicePlan'), parameters('newAppServicePlanName'))]", + "webAppName": "[if(empty(parameters('newWebAppName')), parameters('botId'), parameters('newWebAppName'))]", + "siteHost": "[concat(variables('webAppName'), '.azurewebsites.net')]", + "botEndpoint": "[concat('https://', variables('siteHost'), '/api/messages')]" + }, + "resources": [ + { + "name": "[parameters('groupName')]", + "type": "Microsoft.Resources/resourceGroups", + "apiVersion": "2018-05-01", + "location": "[variables('effectiveGroupLocation')]", + "properties": { + } + }, + { + "type": "Microsoft.Resources/deployments", + "apiVersion": "2018-05-01", + "name": "storageDeployment", + "resourceGroup": "[parameters('groupName')]", + "dependsOn": [ + "[resourceId('Microsoft.Resources/resourceGroups/', parameters('groupName'))]" + ], + "properties": { + "mode": "Incremental", + "template": { + "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": {}, + "variables": {}, + "resources": [ + { + "comments": "Create a new App Service Plan", + "type": "Microsoft.Web/serverfarms", + "name": "[variables('appServicePlanName')]", + "apiVersion": "2018-02-01", + "location": "[variables('effectivePlanLocation')]", + "sku": "[parameters('newAppServicePlanSku')]", + "kind": "linux", + "properties": { + "name": "[variables('appServicePlanName')]", + "reserved":true + } + }, + { + "comments": "Create a Web App using the new App Service Plan", + "type": "Microsoft.Web/sites", + "apiVersion": "2015-08-01", + "location": "[variables('resourcesLocation')]", + "kind": "app", + "dependsOn": [ + "[resourceId('Microsoft.Web/serverfarms/', variables('appServicePlanName'))]" + ], + "name": "[variables('webAppName')]", + "properties": { + "name": "[variables('webAppName')]", + "serverFarmId": "[variables('appServicePlanName')]", + "siteConfig": { + "appSettings": [ + { + "name": "JAVA_OPTS", + "value": "-Dserver.port=80" + }, + { + "name": "MicrosoftAppId", + "value": "[parameters('appId')]" + }, + { + "name": "MicrosoftAppPassword", + "value": "[parameters('appSecret')]" + } + ], + "cors": { + "allowedOrigins": [ + "https://botservice.hosting.portal.azure.net", + "https://hosting.onecloud.azure-test.net/" + ] + } + } + } + }, + { + "apiVersion": "2017-12-01", + "type": "Microsoft.BotService/botServices", + "name": "[parameters('botId')]", + "location": "global", + "kind": "bot", + "sku": { + "name": "[parameters('botSku')]" + }, + "properties": { + "name": "[parameters('botId')]", + "displayName": "[parameters('botId')]", + "endpoint": "[variables('botEndpoint')]", + "msaAppId": "[parameters('appId')]", + "developerAppInsightsApplicationId": null, + "developerAppInsightKey": null, + "publishingCredentials": null, + "storageResourceId": null + }, + "dependsOn": [ + "[resourceId('Microsoft.Web/sites/', variables('webAppName'))]" + ] + } + ], + "outputs": {} + } + } + } + ] +} \ No newline at end of file diff --git a/samples/56.teams-file-upload/deploymentTemplates/template-with-preexisting-rg.json b/samples/56.teams-file-upload/deploymentTemplates/template-with-preexisting-rg.json new file mode 100644 index 000000000..b790d2bdc --- /dev/null +++ b/samples/56.teams-file-upload/deploymentTemplates/template-with-preexisting-rg.json @@ -0,0 +1,158 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "appId": { + "type": "string", + "metadata": { + "description": "Active Directory App ID, set as MicrosoftAppId in the Web App's Application Settings." + } + }, + "appSecret": { + "type": "string", + "metadata": { + "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. Defaults to \"\"." + } + }, + "botId": { + "type": "string", + "metadata": { + "description": "The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable." + } + }, + "botSku": { + "defaultValue": "S1", + "type": "string", + "metadata": { + "description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1." + } + }, + "newAppServicePlanName": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "The name of the new App Service Plan." + } + }, + "newAppServicePlanSku": { + "type": "object", + "defaultValue": { + "name": "P1v2", + "tier": "PremiumV2", + "size": "P1v2", + "family": "Pv2", + "capacity": 1 + }, + "metadata": { + "description": "The SKU of the App Service Plan. Defaults to Standard values." + } + }, + "appServicePlanLocation": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "The location of the App Service Plan." + } + }, + "existingAppServicePlan": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "Name of the existing App Service Plan used to create the Web App for the bot." + } + }, + "newWebAppName": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "The globally unique name of the Web App. Defaults to the value passed in for \"botId\"." + } + } + }, + "variables": { + "defaultAppServicePlanName": "[if(empty(parameters('existingAppServicePlan')), 'createNewAppServicePlan', parameters('existingAppServicePlan'))]", + "useExistingAppServicePlan": "[not(equals(variables('defaultAppServicePlanName'), 'createNewAppServicePlan'))]", + "servicePlanName": "[if(variables('useExistingAppServicePlan'), parameters('existingAppServicePlan'), if(empty(parameters('newAppServicePlanName')),concat(parameters('botId'), 'ServicePlan'),parameters('newAppServicePlanName')))]", + "resourcesLocation": "[if(empty(parameters('appServicePlanLocation')), resourceGroup().location, parameters('appServicePlanLocation'))]", + "webAppName": "[if(empty(parameters('newWebAppName')), parameters('botId'), parameters('newWebAppName'))]", + "siteHost": "[concat(variables('webAppName'), '.azurewebsites.net')]", + "botEndpoint": "[concat('https://', variables('siteHost'), '/api/messages')]" + }, + "resources": [ + { + "comments": "Create a new App Service Plan if no existing App Service Plan name was passed in.", + "type": "Microsoft.Web/serverfarms", + "condition": "[not(variables('useExistingAppServicePlan'))]", + "name": "[variables('servicePlanName')]", + "apiVersion": "2018-02-01", + "location": "[variables('resourcesLocation')]", + "sku": "[parameters('newAppServicePlanSku')]", + "kind": "linux", + "properties": { + "name": "[variables('servicePlanName')]", + "reserved":true + } + }, + { + "comments": "Create a Web App using an App Service Plan", + "type": "Microsoft.Web/sites", + "apiVersion": "2016-08-01", + "location": "[variables('resourcesLocation')]", + "kind": "app", + "dependsOn": [ + "[resourceId('Microsoft.Web/serverfarms/', variables('servicePlanName'))]" + ], + "name": "[variables('webAppName')]", + "properties": { + "name": "[variables('webAppName')]", + "serverFarmId": "[variables('servicePlanName')]", + "siteConfig": { + "linuxFxVersion": "JAVA|8-jre8", + "appSettings": [ + { + "name": "JAVA_OPTS", + "value": "-Dserver.port=80" + }, + { + "name": "MicrosoftAppId", + "value": "[parameters('appId')]" + }, + { + "name": "MicrosoftAppPassword", + "value": "[parameters('appSecret')]" + } + ], + "cors": { + "allowedOrigins": [ + "https://botservice.hosting.portal.azure.net", + "https://hosting.onecloud.azure-test.net/" + ] + } + } + } + }, + { + "apiVersion": "2017-12-01", + "type": "Microsoft.BotService/botServices", + "name": "[parameters('botId')]", + "location": "global", + "kind": "bot", + "sku": { + "name": "[parameters('botSku')]" + }, + "properties": { + "name": "[parameters('botId')]", + "displayName": "[parameters('botId')]", + "endpoint": "[variables('botEndpoint')]", + "msaAppId": "[parameters('appId')]", + "developerAppInsightsApplicationId": null, + "developerAppInsightKey": null, + "publishingCredentials": null, + "storageResourceId": null + }, + "dependsOn": [ + "[resourceId('Microsoft.Web/sites/', variables('webAppName'))]" + ] + } + ] +} \ No newline at end of file diff --git a/samples/56.teams-file-upload/files/teams-logo.png b/samples/56.teams-file-upload/files/teams-logo.png new file mode 100644 index 000000000..78b0a0c30 Binary files /dev/null and b/samples/56.teams-file-upload/files/teams-logo.png differ diff --git a/samples/56.teams-file-upload/pom.xml b/samples/56.teams-file-upload/pom.xml new file mode 100644 index 000000000..cd8e24ee2 --- /dev/null +++ b/samples/56.teams-file-upload/pom.xml @@ -0,0 +1,315 @@ + + + + 4.0.0 + + com.microsoft.bot.sample + bot-teams-file-upload + sample + jar + + ${project.groupId}:${project.artifactId} + This package contains a Java Teams File Upload sample using Spring Boot. + http://maven.apache.org + + + org.springframework.boot + spring-boot-starter-parent + 2.1.7.RELEASE + + + + + + MIT License + http://www.opensource.org/licenses/mit-license.php + + + + + + Bot Framework Development + + Microsoft + https://dev.botframework.com/ + + + + + UTF-8 + UTF-8 + 1.8 + 1.8 + 1.8 + com.microsoft.bot.sample.teamsfileupload.Application + https://botbuilder.myget.org/F/botbuilder-v4-java-daily/maven/ + + + + + junit + junit + 4.12 + test + + + org.springframework.boot + spring-boot-starter-test + 2.1.8.RELEASE + test + + + + org.slf4j + slf4j-api + + + org.apache.logging.log4j + log4j-api + 2.11.0 + + + org.apache.logging.log4j + log4j-core + 2.11.0 + + + + com.microsoft.bot + bot-integration-spring + 4.0.0-SNAPSHOT + compile + + + + + + MyGet + ${repo.url} + + + + + + ossrh + + https://oss.sonatype.org/ + + + + + + + build + + true + + + + + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + + + + maven-war-plugin + 3.2.3 + + src/main/webapp + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + com.microsoft.bot.sample.teamsfileupload.Application + + + + + + com.microsoft.azure + azure-webapp-maven-plugin + 1.7.0 + + V2 + {groupname} + {botname} + + + JAVA_OPTS + -Dserver.port=80 + + + + linux + jre8 + jre8 + + + + + ${project.basedir}/target + + *.jar + + + + + + + + org.eluder.coveralls + coveralls-maven-plugin + 4.3.0 + + yourcoverallsprojectrepositorytoken + + + + org.codehaus.mojo + cobertura-maven-plugin + 2.7 + + ../../cobertura-report/spring-teamsfileupload-sample + xml + 256m + + true + + + + + + org.apache.maven.plugins + maven-site-plugin + 3.7.1 + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 3.0.0 + + + + + + + + publish + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.8 + true + + true + ossrh + https://oss.sonatype.org/ + true + + + + + org.apache.maven.plugins + maven-gpg-plugin + + + sign-artifacts + verify + + sign + + + + + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + + 8 + false + + + + attach-javadocs + + jar + + + + + + + + + + + + + org.apache.maven.plugins + maven-pmd-plugin + 3.12.0 + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.1.0 + + + + checkstyle + + + + + + + + diff --git a/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/Application.java b/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/Application.java new file mode 100644 index 000000000..0ab16e191 --- /dev/null +++ b/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/Application.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.microsoft.bot.sample.teamsfileupload; + +import com.microsoft.bot.integration.AdapterWithErrorHandler; +import com.microsoft.bot.integration.BotFrameworkHttpAdapter; +import com.microsoft.bot.integration.Configuration; +import com.microsoft.bot.integration.spring.BotController; +import com.microsoft.bot.integration.spring.BotDependencyConfiguration; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Import; + +/** + * This is the starting point of the Sprint Boot Bot application. + *

+ * This class also provides overrides for dependency injections. A class that extends the {@link + * com.microsoft.bot.builder.Bot} interface should be annotated with @Component. + * + * @see TeamsFileUploadBot + */ +@SpringBootApplication + +// Use the default BotController to receive incoming Channel messages. A custom controller +// could be used by eliminating this import and creating a new RestController. The default +// controller is created by the Spring Boot container using dependency injection. The +// default route is /api/messages. +@Import({BotController.class}) + +public class Application extends BotDependencyConfiguration { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + /** + * Returns a custom Adapter that provides error handling. + * + * @param configuration The Configuration object to use. + * @return An error handling BotFrameworkHttpAdapter. + */ + @Override + public BotFrameworkHttpAdapter getBotFrameworkHttpAdaptor(Configuration configuration) { + return new AdapterWithErrorHandler(configuration); + } +} diff --git a/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/TeamsFileUploadBot.java b/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/TeamsFileUploadBot.java new file mode 100644 index 000000000..2ec4fb393 --- /dev/null +++ b/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/TeamsFileUploadBot.java @@ -0,0 +1,270 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.microsoft.bot.sample.teamsfileupload; + +import com.microsoft.bot.builder.MessageFactory; +import com.microsoft.bot.builder.TurnContext; +import com.microsoft.bot.builder.teams.TeamsActivityHandler; +import com.microsoft.bot.schema.Activity; +import com.microsoft.bot.schema.Attachment; +import com.microsoft.bot.schema.ResultPair; +import com.microsoft.bot.schema.Serialization; +import com.microsoft.bot.schema.TextFormatTypes; +import com.microsoft.bot.schema.teams.FileConsentCard; +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.lang3.StringUtils; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +/** + * This class implements the functionality of the Bot. + * + *

This is where application specific logic for interacting with the users would be + * added. For this sample, the {@link #onMessageActivity(TurnContext)} echos the text back to the + * user. The {@link #onMembersAdded(List, TurnContext)} will send a greeting to new conversation + * participants.

+ */ +@Component +public class TeamsFileUploadBot extends TeamsActivityHandler { + + @Override + protected CompletableFuture onMessageActivity(TurnContext turnContext) { + if (messageWithDownload(turnContext.getActivity())) { + Attachment attachment = turnContext.getActivity().getAttachments().get(0); + return downloadAttachment(attachment) + .thenCompose(result -> !result.result() + ? fileDownloadFailed(turnContext, result.value()) + : fileDownloadCompleted(turnContext, attachment) + ); + } else { + File filePath = new File("files", "teams-logo.png"); + return sendFileCard(turnContext, filePath.getName(), filePath.length()); + } + } + + @Override + protected CompletableFuture onTeamsFileConsentAccept( + TurnContext turnContext, + FileConsentCardResponse fileConsentCardResponse + ) { + return upload(fileConsentCardResponse) + .thenCompose(result -> !result.result() + ? fileUploadFailed(turnContext, result.value()) + : fileUploadCompleted(turnContext, fileConsentCardResponse) + ); + } + + @Override + protected CompletableFuture onTeamsFileConsentDecline( + TurnContext turnContext, + FileConsentCardResponse fileConsentCardResponse + ) { + Map context = (Map) fileConsentCardResponse.getContext(); + + Activity reply = MessageFactory.text(String.format( + "Declined. We won't upload file {context[%s]}.", context.get("filename")) + ); + reply.setTextFormat(TextFormatTypes.XML); + + return turnContext.sendActivityBlind(reply); + } + + private CompletableFuture sendFileCard( + TurnContext turnContext, String filename, long filesize + ) { + Map consentContext = new HashMap<>(); + consentContext.put("filename", filename); + + FileConsentCard fileCard = new FileConsentCard() {{ + setDescription("This is the file I want to send you"); + setSizeInBytes(filesize); + setAcceptContext(consentContext); + setDeclineContext(consentContext); + }}; + + Attachment asAttachment = new Attachment() {{ + setContent(fileCard); + setContentType(FileConsentCard.CONTENT_TYPE); + setName(filename); + }}; + + Activity reply = turnContext.getActivity().createReply(); + reply.setAttachments(Collections.singletonList(asAttachment)); + + return turnContext.sendActivityBlind(reply); + } + + private CompletableFuture fileUploadCompleted( + TurnContext turnContext, FileConsentCardResponse fileConsentCardResponse + ) { + FileInfoCard downloadCard = new FileInfoCard() {{ + setUniqueId(fileConsentCardResponse.getUploadInfo().getUniqueId()); + setFileType(fileConsentCardResponse.getUploadInfo().getFileType()); + }}; + + Attachment asAttachment = new Attachment() {{ + setContent(downloadCard); + setContentType(FileInfoCard.CONTENT_TYPE); + setName(fileConsentCardResponse.getUploadInfo().getName()); + setContentUrl(fileConsentCardResponse.getUploadInfo().getContentUrl()); + }}; + + Activity reply = MessageFactory.text( + String.format( + "File uploaded. Your file %s is ready to download", + fileConsentCardResponse.getUploadInfo().getName() + ) + ); + reply.setTextFormat(TextFormatTypes.XML); + reply.setAttachment(asAttachment); + + return turnContext.sendActivityBlind(reply); + } + + private CompletableFuture fileUploadFailed(TurnContext turnContext, String error) { + Activity reply = MessageFactory + .text("File upload failed. Error:
" + error + "
"); + reply.setTextFormat(TextFormatTypes.XML); + return turnContext.sendActivityBlind(reply); + } + + private CompletableFuture fileDownloadCompleted( + TurnContext turnContext, Attachment attachment + ) { + Activity reply = MessageFactory.text(String.format( + "%s received and saved.", + attachment.getName() + )); + reply.setTextFormat(TextFormatTypes.XML); + + return turnContext.sendActivityBlind(reply); + } + + private CompletableFuture fileDownloadFailed(TurnContext turnContext, String error) { + Activity reply = MessageFactory + .text("File download failed. Error:
" + error + "
"); + reply.setTextFormat(TextFormatTypes.XML); + return turnContext.sendActivityBlind(reply); + } + + private boolean messageWithDownload(Activity activity) { + boolean messageWithFileDownloadInfo = false; + if (activity.getAttachments() != null + && activity.getAttachments().size() > 0 + ) { + messageWithFileDownloadInfo = StringUtils.equalsIgnoreCase( + activity.getAttachments().get(0).getContentType(), + FileDownloadInfo.CONTENT_TYPE + ); + } + return messageWithFileDownloadInfo; + } + + private CompletableFuture> upload( + FileConsentCardResponse fileConsentCardResponse + ) { + AtomicReference> result = new AtomicReference<>(); + + return CompletableFuture.runAsync(() -> { + Map context = (Map) fileConsentCardResponse + .getContext(); + File filePath = new File("files", context.get("filename")); + HttpURLConnection connection = null; + FileInputStream fileStream = null; + + try { + URL url = new URL(fileConsentCardResponse.getUploadInfo().getUploadUrl()); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("PUT"); + connection.setDoOutput(true); + connection.setRequestProperty("Content-Length", Long.toString(filePath.length())); + connection.setRequestProperty( + "Content-Range", + String.format("bytes 0-%d/%d", filePath.length() - 1, filePath.length()) + ); + + fileStream = new FileInputStream(filePath); + OutputStream uploadStream = connection.getOutputStream(); + byte[] buffer = new byte[4096]; + int bytes_read; + while ((bytes_read = fileStream.read(buffer)) != -1) { + uploadStream.write(buffer, 0, bytes_read); + } + + result.set(new ResultPair(true, null)); + } catch (Throwable t) { + result.set(new ResultPair(false, t.getLocalizedMessage())); + } finally { + if (connection != null) { + connection.disconnect(); + } + if (fileStream != null) { + try { + fileStream.close(); + } catch (Throwable ignored) { + } + } + } + }) + .thenApply(aVoid -> result.get()); + } + + private CompletableFuture> downloadAttachment(Attachment attachment) { + AtomicReference> result = new AtomicReference<>(); + + return CompletableFuture.runAsync(() -> { + FileDownloadInfo fileDownload = Serialization + .getAs(attachment.getContent(), FileDownloadInfo.class); + String filePath = "files/" + attachment.getName(); + + FileOutputStream fileStream = null; + HttpURLConnection connection = null; + + try { + URL url = new URL(fileDownload.getDownloadUrl()); + connection = (HttpURLConnection) url.openConnection(); + connection.setDoInput(true); + + fileStream = new FileOutputStream(filePath); + InputStream downloadStream = connection.getInputStream(); + byte[] buffer = new byte[4096]; + int bytes_read; + while ((bytes_read = downloadStream.read(buffer)) != -1) { + fileStream.write(buffer, 0, bytes_read); + } + + result.set(new ResultPair<>(true, null)); + } catch (Throwable t) { + result.set(new ResultPair<>(false, t.getLocalizedMessage())); + } finally { + if (connection != null) { + connection.disconnect(); + } + if (fileStream != null) { + try { + fileStream.close(); + } catch (Throwable ignored) { + } + } + } + }) + .thenApply(aVoid -> result.get()); + } +} diff --git a/samples/56.teams-file-upload/src/main/resources/application.properties b/samples/56.teams-file-upload/src/main/resources/application.properties new file mode 100644 index 000000000..a695b3bf0 --- /dev/null +++ b/samples/56.teams-file-upload/src/main/resources/application.properties @@ -0,0 +1,2 @@ +MicrosoftAppId= +MicrosoftAppPassword= diff --git a/samples/56.teams-file-upload/src/main/resources/log4j2.json b/samples/56.teams-file-upload/src/main/resources/log4j2.json new file mode 100644 index 000000000..67c0ad530 --- /dev/null +++ b/samples/56.teams-file-upload/src/main/resources/log4j2.json @@ -0,0 +1,18 @@ +{ + "configuration": { + "name": "Default", + "appenders": { + "Console": { + "name": "Console-Appender", + "target": "SYSTEM_OUT", + "PatternLayout": {"pattern": "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"} + } + }, + "loggers": { + "root": { + "level": "debug", + "appender-ref": {"ref": "Console-Appender","level": "debug"} + } + } + } +} diff --git a/samples/56.teams-file-upload/src/main/webapp/META-INF/MANIFEST.MF b/samples/56.teams-file-upload/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 000000000..254272e1c --- /dev/null +++ b/samples/56.teams-file-upload/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/samples/56.teams-file-upload/src/main/webapp/WEB-INF/web.xml b/samples/56.teams-file-upload/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 000000000..383c19004 --- /dev/null +++ b/samples/56.teams-file-upload/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,12 @@ + + + dispatcher + + org.springframework.web.servlet.DispatcherServlet + + + contextConfigLocation + /WEB-INF/spring/dispatcher-config.xml + + 1 + \ No newline at end of file diff --git a/samples/56.teams-file-upload/src/main/webapp/index.html b/samples/56.teams-file-upload/src/main/webapp/index.html new file mode 100644 index 000000000..40b74c007 --- /dev/null +++ b/samples/56.teams-file-upload/src/main/webapp/index.html @@ -0,0 +1,418 @@ + + + + + + + EchoBot + + + + + +
+
+
+
Spring Boot Bot
+
+
+
+
+
Your bot is ready!
+
You can test your bot in the Bot Framework Emulator
+ by connecting to http://localhost:8080/api/messages.
+ +
Visit Azure + Bot Service to register your bot and add it to
+ various channels. The bot's endpoint URL typically looks + like this:
+
https://your_bots_hostname/api/messages
+
+
+
+
+ +
+ + + diff --git a/samples/56.teams-file-upload/src/test/java/com/microsoft/bot/sample/teamsfileupload/ApplicationTests.java b/samples/56.teams-file-upload/src/test/java/com/microsoft/bot/sample/teamsfileupload/ApplicationTests.java new file mode 100644 index 000000000..cdd838d56 --- /dev/null +++ b/samples/56.teams-file-upload/src/test/java/com/microsoft/bot/sample/teamsfileupload/ApplicationTests.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.microsoft.bot.sample.teamsfileupload; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/samples/56.teams-file-upload/teamsAppManifest/icon-color.png b/samples/56.teams-file-upload/teamsAppManifest/icon-color.png new file mode 100644 index 000000000..48a2de133 Binary files /dev/null and b/samples/56.teams-file-upload/teamsAppManifest/icon-color.png differ diff --git a/samples/56.teams-file-upload/teamsAppManifest/icon-outline.png b/samples/56.teams-file-upload/teamsAppManifest/icon-outline.png new file mode 100644 index 000000000..dbfa92772 Binary files /dev/null and b/samples/56.teams-file-upload/teamsAppManifest/icon-outline.png differ diff --git a/samples/56.teams-file-upload/teamsAppManifest/manifest.json b/samples/56.teams-file-upload/teamsAppManifest/manifest.json new file mode 100644 index 000000000..cd1708561 --- /dev/null +++ b/samples/56.teams-file-upload/teamsAppManifest/manifest.json @@ -0,0 +1,38 @@ +{ + "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json", + "manifestVersion": "1.5", + "version": "1.0", + "id": "<>", + "packageName": "com.microsoft.teams.fileupload", + "developer": { + "name": "Microsoft Corp", + "websiteUrl": "https://example.azurewebsites.net", + "privacyUrl": "https://example.azurewebsites.net/privacy", + "termsOfUseUrl": "https://example.azurewebsites.net/termsofuse" + }, + "name": { + "short": "FileUpload", + "full": "FileUpload" + }, + "description": { + "short": "Sample bot using V4 SDK to demo bot file features", + "full": "Sample bot using V4 Bot Builder SDK and V4 Microsoft Teams Extension SDK to demo bot file features" + }, + "icons": { + "outline": "icon-outline.png", + "color": "icon-color.png" + }, + "accentColor": "#abcdef", + "bots": [ + { + "botId": "<>", + "scopes": [ + "personal" + ], + "supportsFiles": true + } + ], + "validDomains": [ + "*.azurewebsites.net" + ] +}