├── .gitignore ├── LICENSE ├── README.md ├── cloudformation └── template.yaml ├── deploy.sh ├── fn └── index.js ├── iam ├── cognito.json └── fn.json ├── iot └── rules.txt ├── sync_static.sh ├── undeploy.sh └── www ├── custom.css ├── index.html └── index.js /.gitignore: -------------------------------------------------------------------------------- 1 | tmp 2 | cloudformation/* 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Serverless Chat 2 | 3 | A serverless web chat built using AWS Lambda, AWS IoT (for WebSockets) and Amazon DynamoDB. 4 | 5 | The architecture of this application is described in this article: 6 | 7 | - [Serverless beyond Functions](https://medium.com/danilop/serverless-beyond-functions-cd81ee4c6b8d) 8 | 9 | ## Deploying to AWS 10 | 11 | A script is provided, `deploy.sh` which uses AWS CloudFormation to provision all the resources needed for this demo. To use it: 12 | 13 | - Create an AWS account. 14 | - Visit the [IoT management page](https://console.aws.amazon.com/iot/home) in the AWS web console and ensure that an IoT endpoint has been provisioned for your account. 15 | - Install the [AWS command line tools](https://aws.amazon.com/cli/) and set up your credentials. 16 | - Run the `deploy.sh` script, specifying a name for your new CloudFormation stack, an AWS region and the name of an S3 bucket where the CloudFormation config files will be stored. The S3 bucket will be created if it does not exist. 17 | 18 | ./deploy.sh LambdaChatStack us-west-1 my.s3.bucket.name 19 | 20 | Once the AWS resources have been provisioned, the script will print a URL to visit in your browser to see the demo. 21 | 22 | NB: The Kinesis functionality has been disabled because it is billed per shard-hour. To enable it, edit `cloudformation/template.yaml` and uncomment the relevant lines before running `deploy.sh`. 23 | -------------------------------------------------------------------------------- /cloudformation/template.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Parameters: 3 | AwsIoTEndpoint: 4 | Type: String 5 | Outputs: 6 | IdentityPoolId: 7 | Value: !Ref ChatIdentityPool 8 | Resources: 9 | ChatFunction: 10 | Type: AWS::Lambda::Function 11 | Properties: 12 | Handler: index.handler 13 | Code: ../fn 14 | Runtime: nodejs6.10 15 | Role: !GetAtt ChatFunctionRole.Arn 16 | Environment: 17 | Variables: 18 | AWS_IOT_ENDPOINT: !Ref AwsIoTEndpoint 19 | ChatIdentityPool: 20 | Type: AWS::Cognito::IdentityPool 21 | Properties: 22 | IdentityPoolName: chatPool 23 | AllowUnauthenticatedIdentities: true 24 | ChatIdentityPoolRoleAttachment: 25 | Type: AWS::Cognito::IdentityPoolRoleAttachment 26 | Properties: 27 | IdentityPoolId: !Ref ChatIdentityPool 28 | Roles: 29 | unauthenticated: !GetAtt CognitoUnauthenticatedRole.Arn 30 | ChatTable: 31 | Type: AWS::DynamoDB::Table 32 | Properties: 33 | AttributeDefinitions: 34 | - 35 | AttributeName: room 36 | AttributeType: S 37 | - 38 | AttributeName: timestamp 39 | AttributeType: N 40 | KeySchema: 41 | - 42 | AttributeName: room 43 | KeyType: HASH 44 | - 45 | AttributeName: timestamp 46 | KeyType: RANGE 47 | ProvisionedThroughput: 48 | ReadCapacityUnits: 2 49 | WriteCapacityUnits: 2 50 | TableName: chat 51 | TimeToLiveSpecification: 52 | AttributeName: ttl 53 | Enabled: true 54 | ChatRule: 55 | Type: AWS::IoT::TopicRule 56 | Properties: 57 | RuleName: chatRule 58 | TopicRulePayload: 59 | AwsIotSqlVersion: '2016-03-23' 60 | RuleDisabled: false 61 | Sql: "SELECT *, clientId() AS clientId, timestamp() AS timestamp FROM 'chat/out'" 62 | Actions: 63 | - Lambda: 64 | FunctionArn: !GetAtt ChatFunction.Arn 65 | ChatPresenceRule: 66 | Type: AWS::IoT::TopicRule 67 | Properties: 68 | RuleName: chatPresenceRule 69 | TopicRulePayload: 70 | AwsIotSqlVersion: '2016-03-23' 71 | RuleDisabled: false 72 | Sql: "SELECT * FROM '$aws/events/presence/#'" 73 | Actions: 74 | - Lambda: 75 | FunctionArn: !GetAtt ChatFunction.Arn 76 | ChatStoreRule: 77 | Type: AWS::IoT::TopicRule 78 | Properties: 79 | RuleName: chatStore 80 | TopicRulePayload: 81 | AwsIotSqlVersion: '2016-03-23' 82 | RuleDisabled: false 83 | Sql: "SELECT *, timestamp() AS timestamp, round(timestamp() / 1000) + 86400 AS ttl FROM 'chat/pub/#'" 84 | Actions: 85 | - DynamoDBv2: 86 | PutItem: 87 | TableName: chat 88 | RoleArn: !GetAtt ChatStoreRole.Arn 89 | ChatStoreRole: 90 | Type: AWS::IAM::Role 91 | Properties: 92 | AssumeRolePolicyDocument: 93 | Version: '2012-10-17' 94 | Statement: 95 | - 96 | Action: sts:AssumeRole 97 | Effect: Allow 98 | Principal: 99 | Service: ['iot.amazonaws.com'] 100 | Policies: 101 | - 102 | PolicyName: ChatStorePolicy 103 | PolicyDocument: 104 | Version: '2012-10-17' 105 | Statement: 106 | - 107 | Action: dynamodb:PutItem 108 | Effect: Allow 109 | Resource: 110 | - !GetAtt ChatTable.Arn 111 | ChatPublishRule: 112 | Type: AWS::IoT::TopicRule 113 | Properties: 114 | RuleName: chatPubRule 115 | TopicRulePayload: 116 | AwsIotSqlVersion: '2016-03-23' 117 | RuleDisabled: false 118 | Sql: "SELECT *, clientId() AS clientId, timestamp() AS timestamp FROM 'chat/out' WHERE NOT isUndefined(message) AND NOT isUndefined(room)" 119 | Actions: 120 | - Republish: 121 | Topic: 'chat/pub${room}' 122 | RoleArn: !GetAtt ChatPublishRole.Arn 123 | ChatPublishRole: 124 | Type: AWS::IAM::Role 125 | Properties: 126 | AssumeRolePolicyDocument: 127 | Version: 2012-10-17 128 | Statement: 129 | - Effect: Allow 130 | Action: sts:AssumeRole 131 | Principal: 132 | Service: 133 | - iot.amazonaws.com 134 | Policies: 135 | - PolicyName: ChatPublishPolicy 136 | PolicyDocument: 137 | Version: 2012-10-17 138 | Statement: 139 | - Effect: Allow 140 | Action: iot:Publish 141 | Resource: !Sub 'arn:aws:iot:${AWS::Region}:${AWS::AccountId}:topic/chat/pub/*' 142 | ChatRulePermission: 143 | Type: AWS::Lambda::Permission 144 | Properties: 145 | SourceArn: !Sub 'arn:aws:iot:${AWS::Region}:${AWS::AccountId}:rule/${ChatRule}' 146 | Action: lambda:InvokeFunction 147 | Principal: iot.amazonaws.com 148 | FunctionName: !GetAtt ChatFunction.Arn 149 | SourceAccount: !Ref AWS::AccountId 150 | ChatPresenceRulePermission: 151 | Type: AWS::Lambda::Permission 152 | Properties: 153 | SourceArn: !Sub 'arn:aws:iot:${AWS::Region}:${AWS::AccountId}:rule/${ChatPresenceRule}' 154 | Action: lambda:InvokeFunction 155 | Principal: iot.amazonaws.com 156 | FunctionName: !GetAtt ChatFunction.Arn 157 | SourceAccount: !Ref AWS::AccountId 158 | ChatFunctionRole: 159 | Type: AWS::IAM::Role 160 | Properties: 161 | ManagedPolicyArns: ['arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'] 162 | AssumeRolePolicyDocument: 163 | Version: '2012-10-17' 164 | Statement: 165 | - 166 | Action: sts:AssumeRole 167 | Effect: Allow 168 | Principal: 169 | Service: ['lambda.amazonaws.com'] 170 | Policies: 171 | - 172 | PolicyName: ChatFunctionRolePolicy 173 | PolicyDocument: 174 | Version: '2012-10-17' 175 | Statement: 176 | - 177 | Action: iot:Connect 178 | Effect: Allow 179 | Resource: ['*'] 180 | - 181 | Action: dynamodb:Query 182 | Effect: Allow 183 | Resource: 184 | - !GetAtt ChatTable.Arn 185 | - 186 | Action: iot:Publish 187 | Effect: Allow 188 | Resource: 189 | - !Sub 'arn:aws:iot:${AWS::Region}:${AWS::AccountId}:topic/chat/in/*' 190 | - !Sub 'arn:aws:iot:${AWS::Region}:${AWS::AccountId}:topic/chat/pub/*' 191 | # Uncomment to enable Kinesis 192 | # - 193 | # Action: 194 | # - 'kinesis:DescribeStream' 195 | # - 'kinesis:GetShardIterator' 196 | # - 'kinesis:GetRecords' 197 | # - 'kinesis:ListStreams' 198 | # Effect: Allow 199 | # Resource: 200 | # - !GetAtt ChatStream.Arn 201 | CognitoUnauthenticatedRole: 202 | Type: AWS::IAM::Role 203 | Properties: 204 | AssumeRolePolicyDocument: 205 | Version: "2012-10-17" 206 | Statement: 207 | - Effect: Allow 208 | Principal: 209 | Federated: cognito-identity.amazonaws.com 210 | Action: sts:AssumeRoleWithWebIdentity 211 | Condition: 212 | StringEquals: 213 | "cognito-identity.amazonaws.com:aud": !Ref ChatIdentityPool 214 | Policies: 215 | - 216 | PolicyName: CognitoUnauthenticatedPolicy 217 | PolicyDocument: 218 | Version: '2012-10-17' 219 | Statement: 220 | - 221 | Action: iot:Connect 222 | Effect: Allow 223 | Resource: ['*'] 224 | - 225 | Action: iot:Publish 226 | Effect: Allow 227 | Resource: 228 | - !Sub 'arn:aws:iot:${AWS::Region}:${AWS::AccountId}:topic/chat/out' 229 | - !Sub 'arn:aws:iot:${AWS::Region}:${AWS::AccountId}:topic/chat/stream' 230 | - 231 | Action: iot:Subscribe 232 | Effect: Allow 233 | Resource: 234 | - !Sub 'arn:aws:iot:${AWS::Region}:${AWS::AccountId}:topicfilter/chat/in/*' 235 | - !Sub 'arn:aws:iot:${AWS::Region}:${AWS::AccountId}:topicfilter/chat/pub/*' 236 | - 237 | Action: iot:Receive 238 | Effect: Allow 239 | Resource: 240 | - !Sub 'arn:aws:iot:${AWS::Region}:${AWS::AccountId}:topic/chat/in/*' 241 | - !Sub 'arn:aws:iot:${AWS::Region}:${AWS::AccountId}:topic/chat/pub/*' 242 | - 243 | Action: 244 | - translate:TranslateText 245 | - comprehend:DetectDominantLanguage 246 | Effect: Allow 247 | Resource: ['*'] 248 | # Uncomment to enable Kinesis 249 | # ChatStream: 250 | # Type: AWS::Kinesis::Stream 251 | # Properties: 252 | # Name: chat 253 | # ShardCount: 1 254 | # ChatStreamRule: 255 | # Type: AWS::IoT::TopicRule 256 | # Properties: 257 | # RuleName: chatStreamRule 258 | # TopicRulePayload: 259 | # AwsIotSqlVersion: '2016-03-23' 260 | # RuleDisabled: false 261 | # Sql: "SELECT *, clientId() AS clientId, timestamp() AS timestamp FROM 'chat/stream'" 262 | # Actions: 263 | # - Kinesis: 264 | # StreamName: chat 265 | # PartitionKey: '${topic()}' 266 | # RoleArn: !GetAtt ChatStreamRole.Arn 267 | # ChatStreamRole: 268 | # Type: AWS::IAM::Role 269 | # Properties: 270 | # AssumeRolePolicyDocument: 271 | # Version: 2012-10-17 272 | # Statement: 273 | # - Effect: Allow 274 | # Action: 275 | # - sts:AssumeRole 276 | # Principal: 277 | # Service: 278 | # - iot.amazonaws.com 279 | # Policies: 280 | # - PolicyName: ChatStreamPolicy 281 | # PolicyDocument: 282 | # Version: 2012-10-17 283 | # Statement: 284 | # - Effect: Allow 285 | # Action: kinesis:PutRecord 286 | # Resource: !GetAtt ChatStream.Arn 287 | -------------------------------------------------------------------------------- /deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | # Before runing this script, open the IoT console to create an endpoint for your account. 5 | 6 | STACK_NAME=${1:?Usage: deploy.sh } 7 | AWS_REGION=${2:?Usage: deploy.sh } 8 | S3_BUCKET=${3:?Usage: deploy.sh } 9 | 10 | mkdir -p tmp 11 | 12 | echo Fetching IoT endpoint URL 13 | AWS_IOT_ENDPOINT=`aws iot describe-endpoint --endpoint-type iot:Data-ATS --region eu-west-1 | perl -lne 'print $1 if /"endpointAddress": "([^"]+)"/'` 14 | 15 | echo Checking S3 bucket 16 | if ! aws s3 ls s3://${S3_BUCKET} >/dev/null; then 17 | echo Creating S3 bucket to host CloudFormation config files 18 | aws s3 mb s3://${S3_BUCKET} --region ${AWS_REGION} 19 | fi 20 | 21 | # Zips up the current directory, writes the zip file to S3, adds a 22 | # CodeUri property for any lambdas with the S3 path to the zip file 23 | # (the template file on S3 does not contain the CodeUri) 24 | echo Packaging CloudFormation template 25 | aws cloudformation package \ 26 | --template-file cloudformation/template.yaml \ 27 | --output-template-file tmp/app.yaml \ 28 | --s3-bucket ${S3_BUCKET} >/dev/null 29 | 30 | echo Creating CloudFormation stack 31 | aws cloudformation deploy \ 32 | --region ${AWS_REGION} \ 33 | --template-file tmp/app.yaml \ 34 | --stack-name ${STACK_NAME} \ 35 | --capabilities CAPABILITY_IAM \ 36 | --parameter-overrides AwsIoTEndpoint=${AWS_IOT_ENDPOINT} 37 | 38 | echo Fetching identity pool id 39 | AWS_IDENTITY_POOL_ID=`aws cloudformation describe-stacks --region ${AWS_REGION} --stack-name ${STACK_NAME} | grep -A 1 '"OutputKey": "IdentityPoolId"' | perl -lne 'print $1 if /"OutputValue": "([^"]+)"/'` 40 | 41 | echo Patching AWS settings into index.js 42 | sed -e "s//${AWS_REGION}/g" \ 43 | -e "s//${AWS_IDENTITY_POOL_ID}/g" \ 44 | -e "s//${AWS_IOT_ENDPOINT}/g" \ 45 | < www/index.js > tmp/index.js 46 | 47 | echo Uploading static website files 48 | aws s3 cp tmp/index.js s3://${S3_BUCKET} --region ${AWS_REGION} --acl public-read-write 49 | aws s3 cp www/index.html s3://${S3_BUCKET} --region ${AWS_REGION} --acl public-read-write 50 | aws s3 cp www/custom.css s3://${S3_BUCKET} --region ${AWS_REGION} --acl public-read-write 51 | # Setting the error document to index.html is a hack to make /myroom load the chat application. 52 | aws s3 website s3://${S3_BUCKET} --region ${AWS_REGION} --index-document index.html --error-document index.html 53 | 54 | echo Visit http://${S3_BUCKET}.s3-website-${AWS_REGION}.amazonaws.com 55 | 56 | rm tmp/* 57 | -------------------------------------------------------------------------------- /fn/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | console.log('Loading function'); 4 | 5 | const APP_NAME = 'chat'; 6 | const DB_TABLE = 'chat'; 7 | const WINDOW_TITLE = 'Chat'; 8 | const AWS_IOT_ENDPOINT = process.env.AWS_IOT_ENDPOINT; 9 | 10 | const AWS = require('aws-sdk'); 11 | const iotdata = new AWS.IotData({endpoint: AWS_IOT_ENDPOINT}); 12 | const dynamodb = new AWS.DynamoDB.DocumentClient(); 13 | 14 | const htmlPage = ` 15 | 16 | 17 | 18 | Babel Chat 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |
%CONTENT%
31 | 32 | 33 | 34 | `; 35 | 36 | const htmlContent = ` 37 |
38 |
39 |
40 |
41 |
42 | Translate to: 43 | 55 |
56 |
57 |
58 |
59 | 60 |
61 |
62 | 63 |
64 |
65 | 66 |
67 |
68 |
69 | 70 | 71 | `; 72 | 73 | exports.handler = (event, context, callback) => { 74 | console.log(event); 75 | 76 | if ('Records' in event) { 77 | event.Records.forEach((record) => { 78 | // Kinesis data is base64 encoded so decode here 79 | const payload = new Buffer(record.kinesis.data, 'base64').toString('ascii'); 80 | console.log('Decoded payload:', payload); 81 | routeData(JSON.parse(payload)); 82 | }); 83 | callback(null, `Successfully processed ${event.Records.length} records.`); 84 | } else if ('httpMethod' in event) { 85 | processHttpRequest(event, callback); 86 | } else { 87 | routeData(event); 88 | } 89 | }; 90 | 91 | function routeData(data) { 92 | if ('eventType' in data) { 93 | console.log(data.eventType + ': ' + data.clientId); 94 | } else if ('connected' in data && data.connected === true) { 95 | clientConnected(data); 96 | } else if ('sendroom' in data) { 97 | sendAllMessages(data); 98 | } else { 99 | console.log('ignored: ' + data); 100 | } 101 | } 102 | 103 | function sendAllMessages(inputData) { 104 | var params = { 105 | TableName: DB_TABLE, 106 | KeyConditionExpression: 'room = :hkey', 107 | ExpressionAttributeValues: { 108 | ':hkey': inputData.sendroom 109 | } 110 | } 111 | 112 | dynamodb.query(params, function(err, data) { 113 | if (err) console.log(err); 114 | else { 115 | console.log(data); 116 | var clientTopic = APP_NAME + "/in/" + inputData.clientId; 117 | 118 | var messages = []; 119 | data.Items.forEach((item) => { 120 | messages.push(item.message); 121 | }); 122 | 123 | function run(message) { 124 | store.messages = store.messages.concat(message.messages); 125 | store.renderMessages(); 126 | } 127 | 128 | var message = { 129 | run: run.toString(), 130 | room: inputData.sendroom, 131 | messages: messages 132 | }; 133 | 134 | sendMessage(clientTopic, message); 135 | } 136 | }); 137 | } 138 | 139 | function clientConnected(data) { 140 | 141 | var clientTopic = APP_NAME + "/in/" + data.clientId; 142 | 143 | function run(message) { 144 | store.messages = message.messages; 145 | store.room = message.room; 146 | store.windowTitle = message.windowTitle; 147 | var pubTopic = APP_NAME + "/pub" + store.room; 148 | console.log('subscribe: ' + pubTopic); 149 | client.subscribe(pubTopic); 150 | 151 | document.getElementById('container').innerHTML = message.htmlContent; 152 | 153 | store.replaceURLWithHTMLLinks = function(text) { 154 | var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; 155 | return text.replace(exp,"$1"); 156 | } 157 | store.htmlEntities = function(str) { 158 | return String(str).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); 159 | } 160 | store.renderMessages = function() { 161 | var html = ''; 162 | store.messages.forEach((m) => { 163 | console.log(m); 164 | var displayText = store.replaceURLWithHTMLLinks(store.htmlEntities(m.text)); 165 | if ('user' in m) { 166 | html += '

' + m.user + ': ' + displayText + '

'; 167 | } else { 168 | html += ''; 169 | } 170 | }); 171 | document.getElementById('messages').innerHTML = html; 172 | }; 173 | store.sendMessage = function(msg) { 174 | var mqttMsg = new Paho.MQTT.Message(JSON.stringify(msg)); 175 | mqttMsg.destinationName = APP_NAME + "/out"; 176 | client.send(mqttMsg); 177 | }; 178 | store.onMessageArrived = function(topic, msg) { 179 | if ('message' in msg) { 180 | store.messages.push(msg.message); 181 | store.renderMessages(); 182 | } 183 | }; 184 | 185 | if (localStorage.getItem(store.room) != null) { 186 | document.getElementById('user').value = JSON.parse(localStorage.getItem(store.room)).user; 187 | } 188 | 189 | var form = document.getElementById('lineForm'); 190 | form.addEventListener('submit', function(evt) { 191 | evt.preventDefault(); 192 | var user = document.getElementById('user'); 193 | var line = document.getElementById('line'); 194 | //var source_language = document.getElementById('source_lang'); 195 | var target_language = document.getElementById('target_lang'); 196 | var timestamp_date = Date.now(); 197 | if (user.value !== '' && line.value !== '') { 198 | localStorage.setItem(store.room, JSON.stringify({ user: user.value })); 199 | store.sendMessage({ room: store.room, message: { user: user.value, text: line.value, source_lang: 'en', timestamp: timestamp_date}}); 200 | line.value = ''; 201 | } 202 | }); 203 | 204 | document.title = store.windowTitle + ' ' + store.room; 205 | 206 | store.renderMessages(); 207 | store.sendMessage({ sendroom: message.room }); 208 | 209 | } 210 | 211 | var message = { 212 | run: run.toString(), 213 | htmlContent: htmlContent, 214 | windowTitle: WINDOW_TITLE, 215 | room: data.path, 216 | messages: [ { text: 'Welcome to chat room ' + data.path } ] 217 | }; 218 | 219 | sendMessage(clientTopic, message); 220 | } 221 | 222 | function sendMessage(topic, message) { 223 | 224 | var params = { 225 | topic: topic, 226 | payload: JSON.stringify(message), 227 | qos: 1 228 | }; 229 | 230 | console.log('publishing to topic: ' + topic); 231 | 232 | iotdata.publish(params, function(err, data) { 233 | if (err) console.log(err, err.stack); // an error occurred 234 | else console.log(data); // successful response 235 | }); 236 | } 237 | 238 | function processHttpRequest(req, callback) { 239 | var response = { 240 | statusCode: 200, 241 | headers: { 242 | "Content-Type": "text/html" 243 | }, 244 | body: htmlPage.replace("%CONTENT%", 245 | '
' 247 | ) 248 | }; 249 | console.log("response: " + JSON.stringify(response)); 250 | callback(null, response); 251 | } 252 | -------------------------------------------------------------------------------- /iam/cognito.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "iot:Connect" 8 | ], 9 | "Resource": [ 10 | "arn:aws:iot:::client/*" 11 | ] 12 | }, 13 | { 14 | "Effect": "Allow", 15 | "Action": [ 16 | "iot:Publish" 17 | ], 18 | "Resource": [ 19 | "arn:aws:iot:::topic/chat/out", 20 | "arn:aws:iot:::topic/chat/stream" 21 | ] 22 | }, 23 | { 24 | "Effect": "Allow", 25 | "Action": [ 26 | "iot:Subscribe" 27 | ], 28 | "Resource": [ 29 | "arn:aws:iot:::topicfilter/chat/in/${iot:ClientId}", 30 | "arn:aws:iot:::topicfilter/chat/pub/*" 31 | ] 32 | }, 33 | { 34 | "Effect": "Allow", 35 | "Action": [ 36 | "iot:Receive" 37 | ], 38 | "Resource": [ 39 | "arn:aws:iot:::topic/chat/in/${iot:ClientId}", 40 | "arn:aws:iot:::topic/chat/pub/*" 41 | ] 42 | } 43 | ] 44 | } 45 | -------------------------------------------------------------------------------- /iam/fn.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "iot:Connect" 8 | ], 9 | "Resource": [ 10 | "*" 11 | ] 12 | }, 13 | { 14 | "Effect": "Allow", 15 | "Action": [ 16 | "iot:Publish" 17 | ], 18 | "Resource": [ 19 | "arn:aws:iot:::topic/chat/in/*", 20 | "arn:aws:iot:::topic/chat/pub/*" 21 | ] 22 | }, 23 | { 24 | "Sid": "Stmt1500489818000", 25 | "Effect": "Allow", 26 | "Action": [ 27 | "dynamodb:Query" 28 | ], 29 | "Resource": [ 30 | "arn:aws:dynamodb:::table/chat" 31 | ] 32 | }, 33 | { 34 | "Effect": "Allow", 35 | "Action": [ 36 | "kinesis:DescribeStream", 37 | "kinesis:GetShardIterator", 38 | "kinesis:GetRecords", 39 | "kinesis:ListStreams" 40 | ], 41 | "Resource": [ 42 | "arn:aws:kinesis:::stream/chat" 43 | ] 44 | } 45 | ] 46 | } 47 | -------------------------------------------------------------------------------- /iot/rules.txt: -------------------------------------------------------------------------------- 1 | for r in $(aws iot list-topic-rules |grep -i chat|grep ruleName|cut -c 26-|sed 's/.$//'); do aws iot get-topic-rule --rule-name $r; done > rules.txt 2 | 3 | { 4 | "ruleArn": "arn:aws:iot:::rule/chatStreamRule", 5 | "rule": { 6 | "awsIotSqlVersion": "2016-03-23", 7 | "sql": "SELECT *, clientId() AS clientId, timestamp() AS timestamp FROM 'chat/stream'", 8 | "ruleDisabled": false, 9 | "actions": [ 10 | { 11 | "kinesis": { 12 | "roleArn": "arn:aws:iam:::role/service-role/chatStreamRole", 13 | "streamName": "chat", 14 | "partitionKey": "${topic()}" 15 | } 16 | } 17 | ], 18 | "ruleName": "chatStreamRule" 19 | } 20 | } 21 | { 22 | "ruleArn": "arn:aws:iot:::rule/chatRule", 23 | "rule": { 24 | "awsIotSqlVersion": "2016-03-23", 25 | "sql": "SELECT *, clientId() AS clientId, timestamp() AS timestamp FROM 'chat/out'", 26 | "ruleDisabled": false, 27 | "actions": [ 28 | { 29 | "lambda": { 30 | "functionArn": "arn:aws:lambda:::function:chat" 31 | } 32 | } 33 | ], 34 | "ruleName": "chatRule" 35 | } 36 | } 37 | { 38 | "ruleArn": "arn:aws:iot:::rule/chatPubRule", 39 | "rule": { 40 | "awsIotSqlVersion": "2016-03-23", 41 | "sql": "SELECT *, clientId() AS clientId, timestamp() AS timestamp FROM 'chat/out' WHERE NOT isUndefined(message) AND NOT isUndefined(room)", 42 | "ruleDisabled": false, 43 | "actions": [ 44 | { 45 | "republish": { 46 | "topic": "chat/pub${room}", 47 | "roleArn": "arn:aws:iam:::role/service-role/aws_iot_republish" 48 | } 49 | } 50 | ], 51 | "ruleName": "chatPubRule" 52 | } 53 | } 54 | { 55 | "ruleArn": "arn:aws:iot:::rule/chatPresenceRule", 56 | "rule": { 57 | "awsIotSqlVersion": "2016-03-23", 58 | "sql": "SELECT * FROM '$aws/events/presence/#'", 59 | "ruleDisabled": false, 60 | "actions": [ 61 | { 62 | "lambda": { 63 | "functionArn": "arn:aws:lambda:::function:chat" 64 | } 65 | } 66 | ], 67 | "ruleName": "chatPresenceRule" 68 | } 69 | } 70 | { 71 | "ruleArn": "arn:aws:iot:::rule/chatStore", 72 | "rule": { 73 | "awsIotSqlVersion": "2016-03-23", 74 | "sql": "SELECT *, concat(timestamp, clientId) AS timestamp_clientId, round(timestamp / 1000) + 86400 AS ttl FROM 'chat/pub/#'", 75 | "ruleDisabled": false, 76 | "actions": [ 77 | { 78 | "dynamoDBv2": { 79 | "putItem": { 80 | "tableName": "chat" 81 | }, 82 | "roleArn": "arn:aws:iam:::role/aws_iot_dynamoDB" 83 | } 84 | } 85 | ], 86 | "ruleName": "chatStore" 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /sync_static.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | # Before runing this script, open the IoT console to create an endpoint for your account. 5 | 6 | STACK_NAME=${1:?Usage: deploy.sh } 7 | AWS_REGION=${2:?Usage: deploy.sh } 8 | S3_BUCKET=${3:?Usage: deploy.sh } 9 | 10 | mkdir -p tmp 11 | 12 | echo Checking S3 bucket 13 | if ! aws s3 ls s3://${S3_BUCKET} >/dev/null; then 14 | echo Error - bucket ${S3_BUCKET} does not exist 15 | exit 16 | fi 17 | 18 | echo Fetching identity pool id 19 | AWS_IDENTITY_POOL_ID=`aws cloudformation describe-stacks --region ${AWS_REGION} --stack-name ${STACK_NAME} | grep -A 1 '"OutputKey": "IdentityPoolId"' | perl -lne 'print $1 if /"OutputValue": "([^"]+)"/'` 20 | 21 | echo Fetching IoT endpoint URL 22 | AWS_IOT_ENDPOINT=`aws iot describe-endpoint --region eu-west-1 | perl -lne 'print $1 if /"endpointAddress": "([^"]+)"/'` 23 | 24 | echo Patching AWS settings into index.js 25 | sed -e "s//${AWS_REGION}/g" \ 26 | -e "s//${AWS_IDENTITY_POOL_ID}/g" \ 27 | -e "s//${AWS_IOT_ENDPOINT}/g" \ 28 | < www/index.js > tmp/index.js 29 | 30 | echo Uploading static website files 31 | aws s3 cp tmp/index.js s3://${S3_BUCKET} --region ${AWS_REGION} --acl public-read-write 32 | aws s3 cp www/index.html s3://${S3_BUCKET} --region ${AWS_REGION} --acl public-read-write 33 | aws s3 cp www/custom.css s3://${S3_BUCKET} --region ${AWS_REGION} --acl public-read-write 34 | # Setting the error document to index.html is a hack to make /myroom load the chat application. 35 | aws s3 website s3://${S3_BUCKET} --region ${AWS_REGION} --index-document index.html --error-document index.html 36 | 37 | echo Visit http://${S3_BUCKET}.s3-website-${AWS_REGION}.amazonaws.com 38 | 39 | rm tmp/* 40 | -------------------------------------------------------------------------------- /undeploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | STACK_NAME=${1:?Usage: undeploy.sh } 5 | AWS_REGION=${2:?Usage: undeploy.sh } 6 | 7 | echo Deleting stack 8 | aws cloudformation delete-stack --region ${AWS_REGION} --stack-name ${STACK_NAME} 9 | 10 | echo Waiting for stack to be deleted 11 | while aws cloudformation describe-stacks --region ${AWS_REGION} --stack-name ${STACK_NAME} >/dev/null 2>&1; 12 | do sleep 3; 13 | done 14 | -------------------------------------------------------------------------------- /www/custom.css: -------------------------------------------------------------------------------- 1 | html, 2 | body { 3 | height: 100%; 4 | width: 100%; 5 | font-family: 'Open Sans','Helvetica Neue',Arial,sans-serif; 6 | } 7 | 8 | body { 9 | display: -ms-flexbox; 10 | display: flex; 11 | -ms-flex-align: center; 12 | padding-top: 40px; 13 | padding-bottom: 40px; 14 | background-color: #f5f5f5; 15 | } 16 | 17 | .form-chat { 18 | padding: 15px; 19 | margin: auto; 20 | } 21 | 22 | .form-chat .form-control { 23 | position: relative; 24 | box-sizing: border-box; 25 | height: auto; 26 | padding: 10px; 27 | font-size: 16px; 28 | } 29 | .form-chat .form-control:focus { 30 | z-index: 2; 31 | } 32 | .form-chat input[type="email"] { 33 | margin-bottom: -1px; 34 | border-bottom-right-radius: 0; 35 | border-bottom-left-radius: 0; 36 | } 37 | .form-signin input[type="password"] { 38 | margin-bottom: 10px; 39 | border-top-left-radius: 0; 40 | border-top-right-radius: 0; 41 | } 42 | 43 | .custom-select { 44 | width: auto; 45 | } 46 | 47 | #translateBox { 48 | padding: 10px 0px 10px 15px; 49 | } 50 | 51 | .light { 52 | color: #bbb; 53 | } 54 | 55 | .f-100 { 56 | font-size: 100%; 57 | } 58 | -------------------------------------------------------------------------------- /www/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Babel Chat 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 |
20 | 23 |
24 |
25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /www/index.js: -------------------------------------------------------------------------------- 1 | const AWS_REGION = ''; 2 | const AWS_IDENTITY_POOL_ID = ''; 3 | const AWS_IOT_ENDPOINT = ''; 4 | const APP_NAME = 'chat'; 5 | 6 | var store = {}; // To be used for "global" variables 7 | 8 | /** 9 | * utilities to do sigv4 10 | * @class SigV4Utils 11 | */ 12 | function SigV4Utils() {} 13 | 14 | SigV4Utils.getSignatureKey = function(key, date, region, service) { 15 | var kDate = AWS.util.crypto.hmac('AWS4' + key, date, 'buffer'); 16 | var kRegion = AWS.util.crypto.hmac(kDate, region, 'buffer'); 17 | var kService = AWS.util.crypto.hmac(kRegion, service, 'buffer'); 18 | var kCredentials = AWS.util.crypto.hmac(kService, 'aws4_request', 'buffer'); 19 | return kCredentials; 20 | }; 21 | 22 | SigV4Utils.getSignedUrl = function(host, region, credentials) { 23 | var datetime = AWS.util.date.iso8601(new Date()).replace(/[:\-]|\.\d{3}/g, ''); 24 | var date = datetime.substr(0, 8); 25 | 26 | var method = 'GET'; 27 | var protocol = 'wss'; 28 | var uri = '/mqtt'; 29 | var service = 'iotdevicegateway'; 30 | var algorithm = 'AWS4-HMAC-SHA256'; 31 | 32 | var credentialScope = date + '/' + region + '/' + service + '/' + 'aws4_request'; 33 | var canonicalQuerystring = 'X-Amz-Algorithm=' + algorithm; 34 | canonicalQuerystring += '&X-Amz-Credential=' + encodeURIComponent(credentials.accessKeyId + '/' + credentialScope); 35 | canonicalQuerystring += '&X-Amz-Date=' + datetime; 36 | canonicalQuerystring += '&X-Amz-SignedHeaders=host'; 37 | 38 | var canonicalHeaders = 'host:' + host + '\n'; 39 | var payloadHash = AWS.util.crypto.sha256('', 'hex') 40 | var canonicalRequest = method + '\n' + uri + '\n' + canonicalQuerystring + '\n' + canonicalHeaders + '\nhost\n' + payloadHash; 41 | 42 | var stringToSign = algorithm + '\n' + datetime + '\n' + credentialScope + '\n' + AWS.util.crypto.sha256(canonicalRequest, 'hex'); 43 | var signingKey = SigV4Utils.getSignatureKey(credentials.secretAccessKey, date, region, service); 44 | var signature = AWS.util.crypto.hmac(signingKey, stringToSign, 'hex'); 45 | 46 | canonicalQuerystring += '&X-Amz-Signature=' + signature; 47 | if (credentials.sessionToken) { 48 | canonicalQuerystring += '&X-Amz-Security-Token=' + encodeURIComponent(credentials.sessionToken); 49 | } 50 | 51 | var requestUrl = protocol + '://' + host + uri + '?' + canonicalQuerystring; 52 | return requestUrl; 53 | }; 54 | 55 | function initClient(requestUrl, clientId) { 56 | 57 | var client = new Paho.MQTT.Client(requestUrl, clientId); 58 | var connectOptions = { 59 | onSuccess: onConnect, 60 | useSSL: true, 61 | timeout: 3, 62 | mqttVersion: 4, 63 | onFailure: onFailure 64 | }; 65 | // set callback handlers 66 | client.onConnectionLost = onConnectionLost; 67 | client.onMessageArrived = onMessageArrived; 68 | client.connect(connectOptions); 69 | 70 | // called when the client connects 71 | function onConnect() { 72 | // Once a connection has been made, make a subscription and send a message. 73 | console.log("onConnect"); 74 | client.subscribe(APP_NAME + "/in/" + clientId); 75 | var message; 76 | message = new Paho.MQTT.Message(JSON.stringify({ 77 | connected: true, 78 | host: window.location.hostname, 79 | path: window.location.pathname 80 | })); 81 | message.destinationName = APP_NAME + "/out"; 82 | client.send(message); 83 | } 84 | 85 | function onFailure() { 86 | console.log("onFailure"); 87 | } 88 | 89 | // called when the client loses its connection 90 | function onConnectionLost(responseObject) { 91 | if (responseObject.errorCode !== 0) { 92 | console.log("onConnectionLost:" + responseObject.errorMessage); 93 | } else { 94 | console.log("onConnectionLost"); 95 | } 96 | connectClient(); // try to reconnect 97 | } 98 | 99 | // called when a message arrives 100 | function onMessageArrived(message) { 101 | console.log("onMessageArrived:" + message.destinationName + " -> " + message.payloadString); 102 | var payload = JSON.parse(message.payloadString); 103 | if (message.destinationName == APP_NAME + '/in/' + clientId && 'run' in payload) { 104 | // Only eval messages coming from the "in" topic 105 | eval(payload.run); 106 | run(payload); 107 | } 108 | else if ('onMessageArrived' in store) { 109 | translation = translateInput(payload.message.text, payload.message.timestamp); 110 | store.onMessageArrived(message.destinationName, payload); 111 | } else { 112 | console.log('ignored: ' + message.destinationName + " -> " + message.payloadString); 113 | } 114 | } 115 | 116 | } 117 | 118 | function connectClient() { 119 | AWS.config.credentials.get(function(err) { 120 | if (err) { 121 | console.log(err); 122 | return; 123 | } 124 | // var clientId = AWS.config.credentials.identityId; 125 | var clientId = String(Math.random()).replace('.', ''); 126 | console.log('clientId: ' + clientId); 127 | var requestUrl = SigV4Utils.getSignedUrl( 128 | AWS_IOT_ENDPOINT, AWS.config.region, AWS.config.credentials); 129 | initClient(requestUrl, clientId); 130 | }); 131 | } 132 | 133 | function translateInput(text, id) { 134 | //var source_language = document.getElementById('source_lang'); 135 | var source_language = 'auto' 136 | var target_language = document.getElementById('target_lang'); 137 | var target_language = target_language.options[target_language.selectedIndex].value 138 | var translate = new AWS.Translate(); 139 | var params = { 140 | SourceLanguageCode: source_language, 141 | TargetLanguageCode: target_language, 142 | Text: text 143 | }; 144 | translate.translateText(params, function (err, data) { 145 | if (err) { 146 | console.log(err, err.stack); 147 | textBox = document.getElementById(id); 148 | textBox.classList.add('badge'); 149 | textBox.classList.add('badge-warning'); 150 | textBox.classList.add('f-100'); 151 | textBox.innerText = textBox.innerText + ' (Translate Error)' 152 | } 153 | else { 154 | console.log(data); 155 | var storeText = {sourceLanguage: data.SourceLanguageCode, sourceText: text, targetLanguage: target_language, translatedText: data.TranslatedText} 156 | localStorage.setItem('translatesCache.' + id, JSON.stringify(storeText)); 157 | $.each(localStorage, function(key, value){ 158 | if (key.substring(0,15) == 'translatesCache') { 159 | values = JSON.parse(value); 160 | strId = key.substring(16); 161 | textBox = document.getElementById(strId); 162 | if (values['sourceLanguage'] != values['targetLanguage']) textBox.innerHTML = values['translatedText'] + ' (' + textBox.innerText + ')'; 163 | } 164 | }); 165 | } 166 | callScroll(); 167 | }); 168 | } 169 | 170 | function callScroll() { 171 | $('#messages').scrollTop($('#messages')[0].scrollHeight - $('#messages')[0].clientHeight); 172 | } 173 | 174 | function init() { 175 | 176 | // Initialize the Amazon Cognito credentials provider 177 | 178 | AWS.config.region = AWS_REGION; // Region 179 | AWS.config.credentials = new AWS.CognitoIdentityCredentials({ 180 | IdentityPoolId: AWS_IDENTITY_POOL_ID, 181 | }); 182 | var userName = localStorage[window.location.pathname]; 183 | localStorage.clear(); 184 | if (userName) localStorage[window.location.pathname] = userName; 185 | connectClient(); 186 | 187 | } 188 | 189 | init(); 190 | --------------------------------------------------------------------------------