public async Task <ActionResult <SermonSeries> > CreateNewSermonSeries([FromBody] CreateSermonSeriesRequest request)
        {
            var response = await _sermonsService.CreateNewSermonSeries(request);

            if (response == null)
            {
                return(StatusCode(400));
            }

            if (response.SuccessMessage == "202")
            {
                // Return a 202 here because this is valid, however there is something else active and nothing was done
                // "The request has been received but not yet acted upon" is what I would expect to be a correct response
                // More on that here https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202
                return(StatusCode(202, response.Result));
            }

            return(response.Result);
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            if (args != null && args.Length > 0)
            {
                ParseArguments(args);

                if (string.IsNullOrEmpty(_options.Date))
                {
                    throw new ArgumentException($"Required argument: {nameof(Options.Date)}");
                }

                if (string.IsNullOrEmpty(_options.Title))
                {
                    throw new ArgumentException($"Required argument: {nameof(Options.Title)}");
                }

                if (string.IsNullOrEmpty(_options.Speaker))
                {
                    throw new ArgumentException($"Required argument: {nameof(Options.Speaker)}");
                }
            }
            else
            {
                throw new ArgumentException($"Required arguments: "
                                            + $"[{nameof(Options.Date)}, {nameof(Options.Title)}, "
                                            + $"{nameof(Options.Speaker)}]");
            }

            // Validations
            if (!string.IsNullOrEmpty(_options.VideoUrl) && !ValidURL(_options.VideoUrl))
            {
                throw new ArgumentException($"Argument {nameof(Options.VideoUrl)} is not a properly formatted URL.");
            }

            if (!string.IsNullOrEmpty(_options.AudioUrl) && !ValidURL(_options.AudioUrl))
            {
                throw new ArgumentException($"Argument {nameof(Options.AudioUrl)} is not a properly formatted URL.");
            }

            ReadAppSettings();

            // testing access to the file path
            if (!string.IsNullOrEmpty(_options.AudioFilePath))
            {
                if (!string.IsNullOrEmpty(_options.AudioFileSize) || !string.IsNullOrEmpty(_options.AudioDuration))
                {
                    throw new ArgumentException("Argument AudioFilePath (z) cannot be used in conjunction with " +
                                                "AudioFileSize (f) or AudioDuration (u).");
                }

                try
                {
                    string path = _options.AudioFilePath;

                    FileStream fileStream = File.OpenRead(path);
                    AudioFileSize = (fileStream.Length / Math.Pow(1024.0, 2.0));

                    // We need to get the duration of the reader in seconds
                    Mp3FileReader reader = new Mp3FileReader(path);
                    AudioDuration = reader.TotalTime.TotalSeconds;
                }
                catch
                {
                    throw;
                }
            }

            string seriesId       = _options.SeriesId;
            bool   isNew          = false;
            bool   isSingleSeries = false;

            bool newIsValid = bool.TryParse(_options.IsNew, out bool isNewSeries);

            if (newIsValid)
            {
                isNew = isNewSeries;
            }

            bool validSingle = bool.TryParse(_options.SingleMessageSeries, out bool singleMessageSeries);

            if (validSingle)
            {
                isSingleSeries = singleMessageSeries;
            }

            #region Add new

            if (isNew)
            {
                if (!string.IsNullOrEmpty(seriesId))
                {
                    throw new ArgumentException($"Argument {nameof(Options.SeriesId)} cannot be used when creating a new sermon series.");
                }

                // validations
                if (string.IsNullOrEmpty(_options.ImageURL))
                {
                    throw new ArgumentNullException($"Argument {nameof(Options.ImageURL)} is required when creating a new sermon series.");
                }

                if (string.IsNullOrEmpty(_options.ThumbnailURL))
                {
                    throw new ArgumentNullException($"Argument {nameof(Options.ThumbnailURL)} is required when creating a new sermon series.");
                }

                if (!ValidURL(_options.ImageURL))
                {
                    throw new ArgumentException($"Argument {nameof(Options.ImageURL)} is not a properly formatted URL.");
                }

                if (!ValidURL(_options.ThumbnailURL))
                {
                    throw new ArgumentException($"Argument {nameof(Options.ThumbnailURL)} is not a properly formatted URL.");
                }

                CreateSermonSeriesRequest createRequest = GenerateCreateRequest(isSingleSeries);
                if (createRequest == null)
                {
                    Console.WriteLine("No series create object to send. One or more arguments might be invalid.");
                    return;
                }

                if (DebugMode)
                {
                    Console.ForegroundColor = ConsoleColor.Blue;

                    Console.WriteLine($"Requests will be sent to {APIUrl}", Console.ForegroundColor);

                    Console.ResetColor();
                    Console.WriteLine($"Here is your request: \n{JsonConvert.SerializeObject(createRequest, Formatting.Indented)}");
                    Console.WriteLine("\n\nDebug mode is enabled, stopping execution.");
                    return;
                }

                HttpResponseMessage createResponse = CreateSeries(createRequest).Result;

                if (createResponse.StatusCode == HttpStatusCode.OK)
                {
                    Console.WriteLine("Successfully completed operations. You can now close this window.");
                    Console.ReadLine();
                }
                else
                {
                    Console.WriteLine($"Error sending request: Code - {createResponse.StatusCode}, ReasonPhrase - {createResponse.ReasonPhrase}");
                    Console.ReadLine();
                }

                return;
            }

            #endregion

            #region Update

            if (!isNew)
            {
                if (string.IsNullOrEmpty(_options.SeriesId))
                {
                    GetAllSermons();

                    Console.WriteLine("Which series would you like to modify? Please enter the ID.");

                    seriesId = Console.ReadLine();
                    if (string.IsNullOrEmpty(seriesId))
                    {
                        Console.WriteLine("Unkown series ID. Please start again..");
                        return;
                    }
                }

                bool     endingSeries = false;
                DateTime?endingDate   = null;

                if (!string.IsNullOrEmpty(_options.CloseSeries))
                {
                    bool.TryParse(_options.CloseSeries, out bool closeSeries);

                    if (closeSeries)
                    {
                        if (string.IsNullOrEmpty(_options.EndDate))
                        {
                            Console.WriteLine("In order to close a series, you must supply an ending date. " +
                                              "Please specify a value for 'EndDate' or '-y' and try again.");
                            return;
                        }

                        DateTime.TryParse(_options.EndDate, out DateTime endDate);

                        endingSeries = closeSeries;
                        endingDate   = endDate.Date;
                    }
                }

                // Update this series with the requested ID, we'll just need to ask for each property one at a time
                AddMessageToSeriesRequest updateRequest = GenerateSeriesAddMessageRequest();
                if (updateRequest == null)
                {
                    Console.WriteLine("No series update object to send. One or more arguments might be invalid.");
                    return;
                }

                if (DebugMode)
                {
                    Console.ForegroundColor = ConsoleColor.Blue;

                    Console.WriteLine($"Requests will be sent to {APIUrl}", Console.ForegroundColor);

                    Console.ResetColor();
                    Console.WriteLine($"Here is your request: \n{JsonConvert.SerializeObject(updateRequest, Formatting.Indented)}");
                    Console.WriteLine("\n\nDebug mode is enabled, stopping execution.");
                    return;
                }

                HttpResponseMessage addMessageResponse = AddMessageToSeries(updateRequest, seriesId).Result;

                // The user wants to end the series in this request, so let's make another request just for that
                if (endingSeries)
                {
                    HttpResponseMessage updateResponse = EndSeries(endingDate.Value, seriesId).Result;

                    if (updateResponse.StatusCode != HttpStatusCode.OK)
                    {
                        Console.WriteLine($"Error sending request: Code - {updateResponse.StatusCode}, " +
                                          $"ReasonPhrase - {updateResponse.ReasonPhrase}");
                        Console.ReadLine();
                    }
                }

                if (addMessageResponse.StatusCode == HttpStatusCode.OK)
                {
                    Console.WriteLine("Successfully completed operations. You can now close this window.");
                    Console.ReadLine();
                }
                else
                {
                    Console.WriteLine($"Error sending request: Code - {addMessageResponse.StatusCode}, " +
                                      $"ReasonPhrase - {addMessageResponse.ReasonPhrase}");
                    Console.ReadLine();
                }

                return;
            }

            #endregion
        }
Exemplo n.º 3
0
        /// <summary>
        /// returns a list of all SermonSeries Objets
        /// </summary>
        public async Task <SystemResponse <SermonSeries> > CreateNewSermonSeries(CreateSermonSeriesRequest request)
        {
            var validRequest = CreateSermonSeriesRequest.ValidateRequest(request);

            if (validRequest.HasErrors)
            {
                return(new SystemResponse <SermonSeries>(true, validRequest.ErrorMessage));
            }

            // the Slug on the series should be unique, so if we already have one with this slug
            // return an error - because we want to avoid having bad data in our database
            var allSermonSries = await _sermonsRepository.GetAllSermons();

            if (allSermonSries == null || allSermonSries == default(AllSermonsResponse))
            {
                return(null);
            }

            var seriesWithSameSlug = allSermonSries.Sermons.Where(i => string.Equals(i.Slug, request.Slug, StringComparison.InvariantCultureIgnoreCase));

            if (seriesWithSameSlug.Any())
            {
                var foundSeries = seriesWithSameSlug.FirstOrDefault();

                // there is already a sermon series with this slug, respond with one of those
                return(new SystemResponse <SermonSeries>(foundSeries, "202"));
            }

            // if any of the sermon series' are currently active
            if (request.EndDate == null)
            {
                var currentlyActiveSeries = allSermonSries.Sermons.Where(i => i.EndDate == null);
                if (currentlyActiveSeries.Any())
                {
                    // one of the series' is already active
                    var currentlyActive = currentlyActiveSeries.FirstOrDefault();
                    return(new SystemResponse <SermonSeries>(currentlyActive, "202"));
                }
            }
            else
            {
                request.EndDate = request.EndDate.Value.ToUniversalTime().Date;
            }

            // sanitise the start dates
            request.StartDate = request.StartDate.Value.ToUniversalTime().Date;

            var messageList = new List <SermonMessage>();

            foreach (var message in request.Messages)
            {
                messageList.Add(new SermonMessage
                {
                    AudioFileSize = message.AudioFileSize,
                    AudioDuration = message.AudioDuration,
                    // sanitise the message dates and get rid of the times
                    Date       = message.Date.Value.Date.ToUniversalTime().Date,
                    MessageId  = Guid.NewGuid().ToString(),
                    AudioUrl   = message.AudioUrl,
                    PassageRef = message.PassageRef,
                    Speaker    = message.Speaker,
                    Title      = message.Title,
                    VideoUrl   = message.VideoUrl
                });
            }

            var sermonSeries = new SermonSeries
            {
                ArtUrl    = request.ArtUrl,
                EndDate   = request.EndDate,
                Messages  = messageList,
                Name      = request.Name,
                Slug      = request.Slug,
                StartDate = request.StartDate,
                Thumbnail = request.Thumbnail,
                Year      = request.Year
            };

            var creationResponse = await _sermonsRepository.CreateNewSermonSeries(sermonSeries);

            if (creationResponse.HasErrors)
            {
                return(new SystemResponse <SermonSeries>(true, creationResponse.ErrorMessage));
            }

            // Save data in cache.
            _cache.Set(string.Format(CacheKeys.GetSermonSeries, creationResponse.Result.Id), creationResponse.Result, PersistentCacheEntryOptions);

            return(new SystemResponse <SermonSeries>(creationResponse.Result, "Success!"));
        }