示例#1
0
        /// <summary>
        /// Check job batch recordings download results.
        /// Link: https://developer.mypurecloud.com/api/rest/v2/recording/#get-api-v2-recording-batchrequests--jobId-
        /// </summary>
        /// <param name="conversationId">String, conversation id</param>
        /// <returns>BatchDownloadJobStatusResult, object of bach request</returns>
        public async Task <BatchDownloadJobStatusResult> GetJobRecordingDownloadResultByConversation(string jobId)
        {
            BatchDownloadJobStatusResult result = new BatchDownloadJobStatusResult();

            using (HttpClient hc = new HttpClient())
            {
                hc.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Bearer {_token}");
                hc.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

                HttpResponseMessage responseMessage = new HttpResponseMessage();

                Task.Delay(3000).Wait();
                responseMessage = await hc.GetAsync(_uribase + $"/api/v2/recording/batchrequests/{jobId}");

                string jsonMessage = await responseMessage.Content.ReadAsStringAsync();

                if (responseMessage.IsSuccessStatusCode)
                {
                    result = JsonConvert.DeserializeObject <BatchDownloadJobStatusResult>(jsonMessage);
                }
                else if (responseMessage.StatusCode == HttpStatusCode.TooManyRequests)
                {
                    await DelayTime(responseMessage);
                }
                else if ((int)responseMessage.StatusCode >= 300 && (int)responseMessage.StatusCode < 600)
                {
                    throw new Exception(jsonMessage);
                }
            }

            return(result);
        }
        // >> START recordings-downloader-step-5
        public static void downloadAllRecordings(string dates)
        {
            Console.WriteLine("Start batch request process.");
            BatchDownloadJobStatusResult completedBatchStatus = new BatchDownloadJobStatusResult();

            // Process and build the request for downloading the recordings
            // Get the conversations within the date interval and start adding them to batch request
            AnalyticsConversationQueryResponse conversationDetails = conversationsApi.PostAnalyticsConversationsDetailsQuery(new ConversationQuery(Interval: dates));

            foreach (var conversations in conversationDetails.Conversations)
            {
                addConversationRecordingsToBatch(conversations.ConversationId);
            }

            // Send a batch request and start polling for updates
            BatchDownloadJobSubmissionResult result = recordingApi.PostRecordingBatchrequests(batchRequestBody);

            completedBatchStatus = getRecordingStatus(result);

            // Start downloading the recording files individually
            foreach (var recording in completedBatchStatus.Results)
            {
                downloadRecording(recording);
            }
        }
        /// <summary>
        /// Get extension of every recordings
        /// </summary>
        /// <param name="getRecordingBatchRequestData"></param>
        /// <returns></returns>
        private static void getExtension(BatchDownloadJobStatusResult getRecordingBatchRequestData)
        {
            // Store the contentType to a variable that will be used later to determine the extension of recordings.
            string contentType = getRecordingBatchRequestData.Results[0].ContentType;
            // Split the text and gets the extension that will be used for the recording
            string ext = contentType.Split('/').Last();

            createDirectory(ext, getRecordingBatchRequestData);
        }
        /// <summary>
        /// Generate directory for recordings that will be downloaded
        /// </summary>
        /// <param name="ext"></param>
        /// <param name="getRecordingBatchRequestData"></param>
        /// <returns></returns>
        private static void createDirectory(string ext, BatchDownloadJobStatusResult getRecordingBatchRequestData)
        {
            Console.WriteLine("Processing please wait...");

            string conversationId = getRecordingBatchRequestData.Results[0].ConversationId;
            string recordingId    = getRecordingBatchRequestData.Results[0].RecordingId;
            string url            = getRecordingBatchRequestData.Results[0].ResultUrl;

            string path = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            path = path.Substring(0, path.LastIndexOf("bin"));
            System.IO.Directory.CreateDirectory(path + "\\Recordings\\" + conversationId + "_" + recordingId);

            downloadRecording(url, ext, path + "\\Recordings\\" + conversationId + "_" + recordingId);
        }
        /// <summary>
        /// Check status of generating url for downloading, if the result is still unavailble. The function will be called again until the result is available.
        /// </summary>
        /// <param name="recordingBatchRequestId"></param>
        /// <returns></returns>
        private static void recordingStatus(BatchDownloadJobSubmissionResult recordingBatchRequestId)
        {
            BatchDownloadJobStatusResult getRecordingBatchRequestData = new BatchDownloadJobStatusResult();
            RecordingApi recordingApi = new RecordingApi();

            getRecordingBatchRequestData = recordingApi.GetRecordingBatchrequest(recordingBatchRequestId.Id);

            if (getRecordingBatchRequestData.ExpectedResultCount == getRecordingBatchRequestData.ResultCount)
            {
                // Pass the getRecordingBatchRequestData to getExtension function
                getExtension(getRecordingBatchRequestData);
            }
            else
            {
                Thread.Sleep(5000);
                recordingStatus(recordingBatchRequestId);
            }
        }
        // Plot conversationId and recordingId to request for batchdownload Recordings
        private static BatchDownloadJobStatusResult getRecordingStatus(BatchDownloadJobSubmissionResult recordingBatchRequest)
        {
            Console.WriteLine("Processing the recordings...");
            BatchDownloadJobStatusResult result = new BatchDownloadJobStatusResult();

            result = recordingApi.GetRecordingBatchrequest(recordingBatchRequest.Id);

            if (result.ExpectedResultCount != result.ResultCount)
            {
                Console.WriteLine("Batch Result Status:" + result.ResultCount + " / " + result.ExpectedResultCount);

                // Simple polling through recursion
                Thread.Sleep(5000);
                return(getRecordingStatus(recordingBatchRequest));
            }

            // Once result count reach expected.
            return(result);
        }
示例#7
0
        public static async Task RunAsync(
            [ServiceBusTrigger("jobqueue", Connection = "ServiceBusConnectionString")] string jobId,
            [ServiceBus("jobqueue", Connection = "ServiceBusConnectionString", EntityType = EntityType.Queue)] IAsyncCollector <string> jobQueue,
            [Blob("conversation", Connection = "StorageConnectionString")] CloudBlobContainer container,
            ILogger log)
        {
            try
            {
                //await container.CreateIfNotExistsAsync(); // create before execution, to avoid overhead proccess

                // TODO: read from "jobQueue"
                PureCloudClient purecloudClient = new PureCloudClient();
                await purecloudClient.GetAccessToken();

                BatchDownloadJobStatusResult batch = await purecloudClient.GetJobRecordingDownloadResultByConversation(jobId);

                log.LogInformation($"Result forjob: ExpectedResultCound({batch.ExpectedResultCount}) and ResultCount({batch.ResultCount})");

                // TODO: end when resultcount == resultaudios
                if (!batch.ExpectedResultCount.Equals(0) && batch.ExpectedResultCount.Equals(batch.ResultCount))
                {
                    if (batch.Results != null)
                    {
                        //List<Task> taskList = new List<Task>(); // to mutch performatic kkkk :P
                        foreach (var item in batch.Results)
                        {
                            if (!string.IsNullOrEmpty(item.ResultUrl))
                            {
                                if (string.IsNullOrEmpty(item.ErrorMsg))
                                {
                                    var extension = string.Empty;
                                    switch (item.ContentType)
                                    {
                                    case "audio/ogg":
                                        extension = "ogg";
                                        break;

                                    case "application/zip":
                                        extension = "zip";
                                        break;

                                    default:
                                        extension = "none";
                                        break;
                                    }

                                    CloudBlockBlob convesrationBlob = container.GetBlockBlobReference($"{item.ConversationId}-{item.RecordingId}.{extension}");
                                    await convesrationBlob.StartCopyAsync(new Uri(item.ResultUrl));
                                }
                                else
                                {
                                    CloudBlockBlob convesrationBlob = container.GetBlockBlobReference($"{item.ConversationId}.error");
                                    await convesrationBlob.UploadTextAsync(JsonConvert.SerializeObject(item));
                                }
                            }
                        }
                        //await Task.WhenAll(taskList.ToArray()); // to mutch performatic kkkk :P
                    }
                }
                else
                {
                    // TODO: else, return item to jobQueue for next tentative
                    await jobQueue.AddAsync(jobId);

                    log.LogInformation($"JobId: {jobId} re added to jobQueue");
                }
            }
            catch (Exception ex)
            {
                TelemetryClient telemetry = new TelemetryClient();
                telemetry.InstrumentationKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");
                telemetry.TrackException(ex);

                log.LogInformation($"Exception during execution: {ex.Message}");

                do
                {
                    try
                    {
                        await Task.Delay(Convert.ToInt32(Environment.GetEnvironmentVariable("deplaytime")));

                        await jobQueue.AddAsync(jobId);

                        log.LogInformation($"Readded jobId: {jobId} to jobQueue");

                        break;
                    }
                    catch (Exception exEx) {
                        telemetry.InstrumentationKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");
                        telemetry.TrackException(exEx);

                        log.LogInformation($"Exception during execution: {exEx.Message}");
                    }
                } while (true);
            }
        }