Ejemplo n.º 1
0
        public async Task <JToken> Handler(JToken @event, ILambdaContext context)
        {
            if (@event == null)
            {
                throw new Exception("Missing workflow input");
            }

            var resourceManager = AwsEnvironment.GetAwsV4ResourceManager();

            try
            {
                var jobData = new JobBase
                {
                    Status           = "RUNNING",
                    ParallelProgress = { ["speech-text-translate"] = 20 }
                };
                await resourceManager.SendNotificationAsync(jobData, @event["notificationEndpoint"].ToMcmaObject <NotificationEndpoint>());
            }
            catch (Exception error)
            {
                Logger.Error("Failed to send notification: {0}", error);
            }

            var stepFunction = new AmazonStepFunctionsClient();
            var data         = await stepFunction.GetActivityTaskAsync(new GetActivityTaskRequest
            {
                ActivityArn = ACTIVITY_ARN
            });

            var taskToken = data.TaskToken;

            if (taskToken == null)
            {
                throw new Exception("Failed to obtain activity task");
            }

            @event = JToken.Parse(data.Input);

            var jobProfiles = await resourceManager.GetAsync <JobProfile>(("name", JOB_PROFILE_NAME));

            var jobProfileId = jobProfiles?.FirstOrDefault()?.Id;

            if (jobProfileId == null)
            {
                throw new Exception($"JobProfile '{JOB_PROFILE_NAME}' not found");
            }

            var job = new AIJob
            {
                JobProfile = jobProfileId,
                JobInput   = new JobParameterBag
                {
                    ["inputFile"]      = @event["data"]["mediaFileLocator"],
                    ["outputLocation"] = new S3Locator
                    {
                        AwsS3Bucket    = TEMP_BUCKET,
                        AwsS3KeyPrefix = JOB_RESULTS_PREFIX
                    }
                },
                NotificationEndpoint = new NotificationEndpoint
                {
                    HttpEndpoint = ACTIVITY_CALLBACK_URL + "?taskToken=" + Uri.EscapeDataString(taskToken)
                }
            };

            job = await resourceManager.CreateAsync(job);

            return(job.Id);
        }
Ejemplo n.º 2
0
        //const aws = require('aws-sdk');
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public string FunctionHandler(ILambdaContext context)
        {
            //try
            //{
            //    var bucketName = System.Environment.GetEnvironmentVariable("mysqlconnection");
            //    var quotenumber = GetQuote(58);
            //    string input = quotenumber.QuoteNumber;
            //    return input?.ToUpper();
            //}
            //catch (Exception e)
            //{ }
            LambdaLogger.Log("1. Lambda start");
            //Starts workflow instance with parameter
            var stste = StartWorkflowInstanceAsync();

            LambdaLogger.Log("2. Workflow started." + stste ?? "".ToString());
            string emailstatus = "Problem occured in email approval.";
            string token       = string.Empty;

            try
            {
                //AmazonStepFunctionsClient stepfunctions = new AmazonStepFunctionsClient(Amazon.RegionEndpoint.USEast1);
                AmazonSimpleEmailServiceClient ses          = new AmazonSimpleEmailServiceClient(Amazon.RegionEndpoint.USEast1);
                Task <GetActivityTaskResponse> responsetask = null;
                GetActivityTaskResponse        response     = null;
                //return "Success";
                LambdaLogger.Log("Task ARN");
                var aws_access_key_id     = Environment.GetEnvironmentVariable("aws_access_key_id");
                var aws_secret_access_key = Environment.GetEnvironmentVariable("aws_secret_access_key");
                using (AmazonStepFunctionsClient stepfunctions = new AmazonStepFunctionsClient(aws_access_key_id, aws_secret_access_key, Amazon.RegionEndpoint.USEast1))
                {
                    GetActivityTaskRequest request = new GetActivityTaskRequest {
                        ActivityArn = "arn:aws:states:us-east-1:494875521123:activity:PMApprovalStep", WorkerName = "PMApprovingTaskActivity"
                    };
                    LambdaLogger.Log("Response Output req sent ");
                    responsetask = stepfunctions.GetActivityTaskAsync(request);
                    responsetask.GetAwaiter();
                    response = responsetask.Result;
                    //if(responsetask.)
                    if (response != null)
                    {
                        LambdaLogger.Log("Response Output = " + response.Input);
                    }
                    else
                    {
                        LambdaLogger.Log("Response Output = null");
                    }
                    token = response.TaskToken;
                    LambdaLogger.Log("Token = " + token);
                }
                if (!string.IsNullOrEmpty(response.Input))
                {
                    List <string> tolst = GetUsersAsPerRole("PM");

                    var input = JObject.Parse(response.Input);
                    //var email = "*****@*****.**"; //get to mail from salesOrg as per approval level
                    var quoteid = (int)input.SelectToken("quoteid");
                    //var tolst = new List<string>();
                    //tolst.Add(email);
                    Body body = new Body
                    {
                        Html = new Content
                        {
                            Charset = "UTF-8",
                            Data    = "<div>Hi!<br /><br /> " +
                                      "Promotion '" + (string)input.SelectToken("promodesc") + "' needs your approval!<br />" +
                                      "Can you please approve:<br /> <h3><a href='https://wyunsq1ccf.execute-api.us-east-1.amazonaws.com/respond/approve?taskToken=" + Uri.EscapeDataString(token) + "&quoteid=" + quoteid + "'>Click To Approve</a></h3><br />" +
                                      //"https://wyunsq1ccf.execute-api.us-east-1.amazonaws.com/respond/approve?taskToken=" + Uri.EscapeDataString(token) + "&quoteid=" + quoteid + "<br />" +
                                      "Or reject:<br />" +
                                      "<h3><a href='https://wyunsq1ccf.execute-api.us-east-1.amazonaws.com/respond/reject?taskToken=" + Uri.EscapeDataString(token) + "&quoteid=" + quoteid + "'>Click To Reject</a></h3></div><br /><br />Thank You,<br />Application Team"
                                      //"https://wyunsq1ccf.execute-api.us-east-1.amazonaws.com/respond/reject?taskToken=" + Uri.EscapeDataString(token) + "&quoteid=" + quoteid + "</div>"
                        }
                    };
                    Content subjectContent = new Content
                    {
                        Charset = "UTF-8",
                        Data    = "Your Approval Needed as Pricing Manager for Promotion Id " + quoteid
                    };

                    LambdaLogger.Log("Starting Mail sending.. ");
                    Message msg = new Message {
                        Body = body, Subject = subjectContent
                    };
                    SendEmailRequest s = new SendEmailRequest
                    {
                        Source      = "*****@*****.**",
                        Destination = new Destination {
                            ToAddresses = tolst
                        },
                        Message = msg,
                        ConfigurationSetName = "sesconfigset",
                        SourceArn            = "arn:aws:ses:us-east-1:494875521123:identity/[email protected]"
                    };
                    var status = ses.SendEmailAsync(s);
                    status.GetAwaiter();

                    emailstatus = status.Result.HttpStatusCode.ToString();


                    LambdaLogger.Log("Going to update Db");
                    if (!string.IsNullOrEmpty(token))
                    {
                        UpdateApprovalStatusWithToken(quoteid, Uri.EscapeDataString(token));   //Moving quote status to 3(PM) and updating token
                    }
                    //string input,
                    //var bucketName = System.Environment.GetEnvironmentVariable("mysqlconnection");
                    //var quotenumber = GetQuote(58);
                    //input = quotenumber.QuoteNumber;
                    //return input?.ToUpper();
                }
            }
            catch (Exception e)
            { LambdaLogger.Log("Response Output = " + e); }
            return(emailstatus);
        }
Ejemplo n.º 3
0
        public async Task Handler(JToken @event, ILambdaContext context)
        {
            var resourceManager = AwsEnvironment.GetAwsV4ResourceManager();

            try
            {
                var jobData = new JobBase
                {
                    Status   = "RUNNING",
                    Progress = 54
                };
                await resourceManager.SendNotificationAsync(jobData, @event["notificationEndpoint"].ToMcmaObject <NotificationEndpoint>());
            }
            catch (Exception error)
            {
                Logger.Error("Failed to send notification: {0}", error);
            }

            var stepFunction = new AmazonStepFunctionsClient();
            var data         = await stepFunction.GetActivityTaskAsync(new GetActivityTaskRequest
            {
                ActivityArn = ACTIVITY_ARN
            });

            var taskToken = data.TaskToken;

            if (taskToken == null)
            {
                throw new Exception("Failed to obtain activity task");
            }

            @event = JToken.Parse(data.Input);

            var jobProfiles = await resourceManager.GetAsync <JobProfile>(("name", JOB_PROFILE_NAME));

            var jobProfileId = jobProfiles?.FirstOrDefault()?.Id;

            if (jobProfileId == null)
            {
                throw new Exception($"JobProfile '{JOB_PROFILE_NAME}' not found");
            }

            var createProxyJob = new TransformJob
            {
                JobProfile = jobProfileId,
                JobInput   = new JobParameterBag
                {
                    ["inputFile"]      = @event["data"]["repositoryFile"],
                    ["outputLocation"] = new S3Locator
                    {
                        AwsS3Bucket    = REPOSITORY_BUCKET,
                        AwsS3KeyPrefix = "TransformJobResults/"
                    }
                },
                NotificationEndpoint = new NotificationEndpoint
                {
                    HttpEndpoint = ACTIVITY_CALLBACK_URL + "?taskToken=" + Uri.EscapeDataString(taskToken)
                }
            };

            createProxyJob = await resourceManager.CreateAsync(createProxyJob);
        }
Ejemplo n.º 4
0
        public async Task <JToken> Handler(JToken @event, ILambdaContext context)
        {
            if (@event == null)
            {
                throw new Exception("Missing workflow input");
            }

            var resourceManager = AwsEnvironment.GetAwsV4ResourceManager();

            try
            {
                var jobData = new JobBase
                {
                    Status           = "RUNNING",
                    ParallelProgress = { ["speech-text-translate"] = 60 }
                };
                await resourceManager.SendNotificationAsync(jobData, @event["notificationEndpoint"].ToMcmaObject <NotificationEndpoint>());
            }
            catch (Exception error)
            {
                Logger.Error("Failed to send notification: {0}", error);
            }

            var stepFunction = new AmazonStepFunctionsClient();
            var data         = await stepFunction.GetActivityTaskAsync(new GetActivityTaskRequest
            {
                ActivityArn = ACTIVITY_ARN
            });

            var taskToken = data.TaskToken;

            if (taskToken == null)
            {
                throw new Exception("Failed to obtain activity task");
            }

            @event = JToken.Parse(data.Input);

            var jobProfiles = await resourceManager.GetAsync <JobProfile>(("name", JOB_PROFILE_NAME));

            var jobProfileId = jobProfiles?.FirstOrDefault()?.Id;

            if (jobProfileId == null)
            {
                throw new Exception($"JobProfile '{JOB_PROFILE_NAME}' not found");
            }

            // writing speech transcription to a textfile in temp bucket
            var bmContent = await resourceManager.ResolveAsync <BMContent>(@event["input"]["bmContent"].Value <string>());

            // get the transcript from the BMContent
            var transcript =
                bmContent.Get <McmaExpandoObject>("awsAiMetadata")
                ?.Get <McmaExpandoObject>("transcription")
                ?.Get <string>("original");

            if (transcript == null)
            {
                throw new Exception("Missing transcription on BMContent");
            }

            var s3Params = new PutObjectRequest
            {
                BucketName  = TEMP_BUCKET,
                Key         = "AiInput/" + Guid.NewGuid() + ".txt",
                ContentBody = transcript
            };

            var s3Client = new AmazonS3Client();
            await s3Client.PutObjectAsync(s3Params);

            var job = new AIJob
            {
                JobProfile = jobProfileId,
                JobInput   = new JobParameterBag
                {
                    ["inputFile"] = new S3Locator
                    {
                        AwsS3Bucket = s3Params.BucketName,
                        AwsS3Key    = s3Params.Key
                    },
                    ["targetLanguageCode"] = "ja",
                    ["outputLocation"]     = new S3Locator
                    {
                        AwsS3Bucket = TEMP_BUCKET,
                        AwsS3Key    = JOB_RESULTS_PREFIX
                    }
                },
                NotificationEndpoint = new NotificationEndpoint
                {
                    HttpEndpoint = ACTIVITY_CALLBACK_URL + "?taskToken=" + Uri.EscapeDataString(taskToken)
                }
            };

            job = await resourceManager.CreateAsync(job);

            return(job.Id);
        }
        private async Task <string> InsufficientCreditHandler(string insufficientCreditActivityARN, ILambdaContext context)
        {
            string result = "";
            GetActivityTaskResponse response = await stepFunctionsClient.GetActivityTaskAsync(
                new GetActivityTaskRequest()
            {
                ActivityArn = insufficientCreditActivityARN
            });

            if (HttpStatusCode.OK.Equals(response.HttpStatusCode) && !string.IsNullOrEmpty(response.TaskToken))
            {
                // Task is found
                context.Logger.LogLine($"InsufficientCreditHandler: Found a task. Input is: {response.Input}");
                NumberPlateTrigger input = JsonConvert.DeserializeObject <NumberPlateTrigger>(response.Input);

                if (!input.numberPlate.detected)
                {
                    context.Logger.LogLine("TESTING::input.numberPlate.detected is false which means this must be a test");
                    context.Logger.LogLine("Forcing number plate to test value");
                    input.numberPlate.detected          = true;
                    input.numberPlate.numberPlateString = "TESTPLATE";
                }
                //Sign Image URL
                string imageLink = s3client.GetPreSignedURL(new GetPreSignedUrlRequest()
                {
                    BucketName = input.bucket, Key = input.key, Expires = DateTime.Now.AddDays(1)
                });
                //
                // Query DynamoDB to get the owner email
                //
                Table    table    = Table.LoadTable(dbClient, Environment.GetEnvironmentVariable("DDBTableName"));
                Document document = await table.GetItemAsync(input.numberPlate.numberPlateString);

                if (document == null)
                {
                    context.Logger.LogLine($"Could not find plate {input.numberPlate.numberPlateString} in our records");
                }
                var sendRequest = new SendEmailRequest
                {
                    Source           = Environment.GetEnvironmentVariable("TargetEmailAddress"),
                    ReplyToAddresses = new List <string> {
                        Environment.GetEnvironmentVariable("TargetEmailAddress")
                    },
                    Destination = new Destination
                    {
                        ToAddresses =
                            new List <string> {
                            document["ownerEmail"]
                        }
                    },
                    Message = new Message
                    {
                        Subject = new Content("[ACTION] - Your account credit is exhausted"),
                        Body    = new Body
                        {
                            Html = new Content
                            {
                                Charset = "UTF-8",
                                Data    = $"Hello {document["ownerFirstName"]} {document["ownerLastName"]},<br/><br/>Your vehicle with number plate <b>{document["numberPlate"]}</b> was recently detected on a toll road, but your account has insufficient credit to pay the toll.<br/><br/>" +
                                          $"<img src='{imageLink}'/><br/><a href='{imageLink}'>Click here to see the original image</a><br/><br/>" +
                                          "Please update your account balance immediately to avoid a fine. <br/>" +
                                          $"<a href='{Environment.GetEnvironmentVariable("APIGWEndpoint")}topup/{document["numberPlate"]}?taskToken={HttpUtility.UrlEncode(response.TaskToken)}><b>Click this link to top up your account now.</b></a><br/>" +
                                          "<br/><br/> Thanks<br/><b>Toll Road Administrator.</b><br/><br/>"
                            },
                            Text = new Content
                            {
                                Charset = "UTF-8",
                                Data    = $"Hello {document["ownerFirstName"]} {document["ownerLastName"]}, Your vehicle with number plate: {document["numberPlate"]} was recently detected on a toll road, but your account has insufficient credit to pay the toll." +
                                          "Please update your account balance immediately to avoid a fine." +
                                          $"Please access this link to top up: {Environment.GetEnvironmentVariable("APIGWEndpoint")}topup/{document["numberPlate"]}?taskToken={HttpUtility.UrlEncode(response.TaskToken)}" +
                                          ".. Thanks. Toll Road Administrator."
                            }
                        }
                    },
                    // If you are not using a configuration set, comment
                    // or remove the following line
                    //ConfigurationSetName = configSet
                };

                context.Logger.LogLine($"Sending email to ({Environment.GetEnvironmentVariable("TargetEmailAddress")})");
                SendEmailResponse sendEmailResponse = await emailServiceClient.SendEmailAsync(sendRequest);

                if (sendEmailResponse.HttpStatusCode.Equals(HttpStatusCode.OK))
                {
                    context.Logger.LogLine("The email was successfully sent.");
                    result = "success";
                }
                else
                {
                    context.Logger.LogLine("Internal Error: The email could not be sent.");
                    result = "error";
                }
            }
            return(result);
        }
        public async Task <string> Handler(JToken @event, ILambdaContext context)
        {
            var resourceManager = AwsEnvironment.GetAwsV4ResourceManager();

            try
            {
                var jobData = new JobBase
                {
                    Status   = "RUNNING",
                    Progress = 27
                };
                await resourceManager.SendNotificationAsync(jobData, @event["notificationEndpoint"].ToMcmaObject <NotificationEndpoint>());
            }
            catch (Exception error)
            {
                Logger.Error("Failed to send notification: {0}", error);
            }

            var stepFunction = new AmazonStepFunctionsClient();

            Logger.Debug($"Getting Activity Task with ARN {ACTIVITY_ARN}...");
            var data = await stepFunction.GetActivityTaskAsync(new GetActivityTaskRequest
            {
                ActivityArn = ACTIVITY_ARN
            });

            var taskToken = data.TaskToken;

            if (taskToken == null)
            {
                throw new Exception("Failed to obtain activity task");
            }

            Logger.Debug($"Activity Task token is {taskToken}");

            @event = JToken.Parse(data.Input);

            Logger.Debug($"Getting job profile 'ExtractTechnicalMetadata'...");

            var jobProfiles = await resourceManager.GetAsync <JobProfile>(("name", "ExtractTechnicalMetadata"));

            var jobProfileId = jobProfiles?.FirstOrDefault()?.Id;

            if (jobProfileId == null)
            {
                throw new Exception("JobProfile 'ExtractTechnicalMetadata' not found");
            }

            var ameJob = new AmeJob
            {
                JobProfile = jobProfileId,
                JobInput   = new JobParameterBag
                {
                    ["inputFile"]      = @event["data"]["repositoryFile"],
                    ["outputLocation"] = new S3Locator
                    {
                        AwsS3Bucket    = TEMP_BUCKET,
                        AwsS3KeyPrefix = "AmeJobResults/"
                    }
                },
                NotificationEndpoint = new NotificationEndpoint
                {
                    HttpEndpoint = ACTIVITY_CALLBACK_URL + "?taskToken=" + Uri.EscapeDataString(taskToken)
                }
            };

            Logger.Debug($"Submitting AME job...");

            ameJob = await resourceManager.CreateAsync(ameJob);

            Logger.Debug($"Successfully created AME job {ameJob.Id}.");

            return(ameJob.Id);
        }