public AudioFileService(ICloudBlob blob, ExecutionContext context)
 {
     IncomingBlob      = blob;
     AudioFileName     = new AudioFileName(blob.Name);
     TempFileDirectory = Path.GetTempPath();
     ExecutionContext  = context;
 }
Пример #2
0
        public static async Task BlobListener([BlobTrigger(StaticData.ShiurimContainerName + "/" + StaticData.UploadedFileRootContainerPath + "/{name}", Connection = "AzureWebJobsStorage")] ICloudBlob blob, string name, ILogger log, ExecutionContext context)
        {
            log.LogInformation($"Executing directory: {context.FunctionAppDirectory}");
            log.LogInformation($"Processing Name: {name}, Size: {blob.Properties.Length}b");
            var podcastMetadata  = RabbiYosefBrombergFull;
            var audioFileService = new AudioFileService(blob, context);
            await audioFileService.ProcessFile(podcastMetadata).ConfigureAwait(false);

            var audioFile = new AudioFileName(blob.Name);

            //await new GitHubClientWrapper(
            //        Environment.GetEnvironmentVariable("GitHub.Owner", EnvironmentVariableTarget.Process),
            //        Environment.GetEnvironmentVariable("GitHub.RepositoryName", EnvironmentVariableTarget.Process),
            //        Environment.GetEnvironmentVariable("GitHub.PrivateKey", EnvironmentVariableTarget.Process),
            //        Environment.GetEnvironmentVariable("GitHub.AppId", EnvironmentVariableTarget.Process),
            //        Environment.GetEnvironmentVariable("GitHub.AppName", EnvironmentVariableTarget.Process)
            //    ).CreatePostComment(podcastMetadata.Author, audioFile.RecordedOn, audioFile.Masechta, audioFile.Daf, audioFile.Subtitle, audioFileService.Duration).ConfigureAwait(false);

            log.LogInformation($"Uploaded Name:{Path.GetFileName(audioFileService.OutgoingBlobReference.Name)}, Size: {audioFileService.OutgoingBlobReference.Properties.Length}b");

            await UpdateDataStore(audioFile, audioFileService.Duration).ConfigureAwait(false);

            if (audioFile.Subtitle.Equals("with Rashi", StringComparison.OrdinalIgnoreCase) && bool.Parse(Environment.GetEnvironmentVariable("ShouldSendEmail", EnvironmentVariableTarget.Process) ?? bool.FalseString))
            {
                await EmailerService.SendEmails(blob.Container, audioFile, audioFileService.OutgoingBlobReference).ConfigureAwait(false);
            }
        }
Пример #3
0
        public static async Task SendEmails(CloudBlobContainer cloudBlobContainer, AudioFileName audioFile, CloudBlockBlob distBlockBlob)
        {
            var emailBlobReference = cloudBlobContainer.GetBlockBlobReference("emails");
            var emailList          = (await emailBlobReference.DownloadTextAsync().ConfigureAwait(false)).Split('\n');
            var apiKey             = Environment.GetEnvironmentVariable("SendGrid.ApiKey", EnvironmentVariableTarget.Process);
            var client             = new SendGridClient(apiKey);
            var fromEmail          = emailList.First().Split(',');
            var from              = new EmailAddress(fromEmail[0], fromEmail[1]);
            var subject           = $"{audioFile.Masechta.ToUppercaseWords()} Daf {audioFile.Daf}";
            var plainTextContent  = $"{audioFile.Masechta.ToUppercaseWords()} Daf {audioFile.Daf} is now available. https://torahis.life/#/shiurim(daf-yomi&shabbos)";
            var htmlContent       = $"<a href=\"https://torahis.life/#/shiurim(daf-yomi&shabbos)\">{audioFile.Masechta.ToUppercaseWords()} Daf {audioFile.Daf}</a> is now available.";
            var groupedRecipients = emailList.Skip(1)
                                    .Select(line => line.Split(','))
                                    .Select(lineParts => (bool.Parse(string.IsNullOrWhiteSpace(lineParts[2]) ? bool.FalseString : lineParts[2]), new EmailAddress(lineParts[0], lineParts[1])))
                                    .ToLookup(r => r.Item1);

            if (groupedRecipients.Contains(false))
            {
                var to       = groupedRecipients[false].Select(recipient => recipient.Item2).ToList();
                var msg      = MailHelper.CreateSingleEmailToMultipleRecipients(from, to, subject, plainTextContent, htmlContent);
                var response = await client.SendEmailAsync(msg);
            }

            if (groupedRecipients.Contains(true))
            {
                var to    = groupedRecipients[true].Select(recipient => recipient.Item2).ToList();
                var msg   = MailHelper.CreateSingleEmailToMultipleRecipients(from, to, subject, plainTextContent, htmlContent);
                var bytes = new byte[distBlockBlob.Properties.Length];
                await distBlockBlob.DownloadToByteArrayAsync(bytes, 0).ConfigureAwait(false);

                msg.AddAttachment($"{audioFile.Masechta.ToUppercaseWords()} Daf {audioFile.Daf}", Convert.ToBase64String(bytes));
                var response = await client.SendEmailAsync(msg);
            }
        }
Пример #4
0
        private static async Task UpdateDataStore(AudioFileName audioFile, TimeSpan duration)
        {
            var data = await GetData().ConfigureAwait(false);

            var tagStrings = new[] { "Daf Yomi", audioFile.Masechta.ToUppercaseWords(), audioFile.Subtitle };

            var unknownTags = tagStrings.Where(ts => data.tags.All(t => t.tag != ts));

            if (unknownTags.Any())
            {
                var currentIdMax = data.tags.Max(t => t.id);
                foreach (var unknownTag in unknownTags)
                {
                    data.tags.Append(new V2Tag
                    {
                        id   = ++currentIdMax,
                        tag  = unknownTag,
                        type = V2TagType.SeriesLevel2
                    });
                }
            }

            var shiur = new V2Shiur
            {
                date     = audioFile.RecordedOn.ToString("s"),
                title    = $"Daf {audioFile.Daf}",
                id       = (data.shiurim.Any() ? data.shiurim.Max(s => s.id) : 0) + 1,
                tags     = tagStrings.Select(str => data.tags.First(t => t.tag == str).id).ToArray(),
                duration = duration > TimeSpan.FromHours(1) ? duration.ToString("hh':'mm':'ss") : duration.ToString("mm':'ss"),
                authorId = data.authors.First(a => a.name.Equals(RabbiYosefBrombergFull.Author, StringComparison.OrdinalIgnoreCase)).id
            };

            var(previousMasechta, previousDaf) = StaticData.CalculateDafForDate(audioFile.RecordedOn.AddDays(-1));
            var previousShiurim = data.shiurim.Where(s => s.title == $"Daf {previousDaf}" && s.tags.Contains(data.tags.First(t => t.tag.Equals(previousMasechta, StringComparison.OrdinalIgnoreCase)).id));

            foreach (var previousShiur in previousShiurim)
            {
                if (previousShiur.tags.All(tag => shiur.tags.Contains(tag)) || previousShiur.nextId == null)
                {
                    previousShiur.nextId = shiur.id;
                }
            }

            shiur.previousId = previousShiurim.Count() == 1 ? previousShiurim.First().id : previousShiurim.FirstOrDefault(ps => ps.tags.All(tag => shiur.tags.Contains(tag)))?.id;

            data.shiurim = data.shiurim.Concat(new[] { shiur }).ToArray();

            var cachedFilePath = Path.Combine(Path.GetTempPath(), "data.json");
            var serializedData = JsonSerializer.Serialize(data);
            await StorageAccount.NewFromConnectionString(Environment.GetEnvironmentVariable("AzureWebJobsStorage", EnvironmentVariableTarget.Process))
            .CreateCloudBlobClient()
            .GetContainerReference(StaticData.ShiurimContainerName)
            .GetBlockBlobReference("data.json")
            .UploadTextAsync(serializedData)
            .ConfigureAwait(false);

            File.WriteAllText(cachedFilePath, serializedData);
        }