コード例 #1
0
ファイル: Scraper.cs プロジェクト: larrybohn/tvscraper
        private async Task ProcessPage(ShowIndexDto showIndexPage, CancellationToken cancellationToken)
        {
            foreach (var showId in showIndexPage.ShowIds)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }
                ShowDto show = await SafeExecute(() => dataProvider.GetShowCastAsync(showId));

                if (show != null)
                {
                    try
                    {
                        await AddShow(show);
                    }
                    catch (Exception e)
                    {
                        logger.LogError(e.ToString());
                    }
                }
                else
                {
                    logger.LogWarning($"could not load show {showId}");
                }
            }
        }
コード例 #2
0
        public async Task Post(ShowDto model)
        {
            var mapped = _mapper.Map <Show>(model);

            _repository.Show.Create(mapped);
            await _repository.SaveAsync();
        }
コード例 #3
0
        public async Task <ShowDto> GetShowDataById(int showId,
                                                    CancellationToken cancellationToken = default(CancellationToken))
        {
            var jshow = await _jsonApiDataReader.GetJsonData <dynamic>(
                new Uri($"/shows/{showId}?embed=cast", UriKind.Relative), cancellationToken);

            var show = new ShowDto
            {
                Id   = jshow.id,
                Name = jshow.name
            };
            var embedded = jshow._embedded;

            if (embedded is null)
            {
                _logger.LogError($"No embedded data returned for show {showId}.");
            }
            else
            {
                var jcast = embedded.cast;
                if (jcast is null)
                {
                    _logger.LogError($"No cast data found embedded for show {showId}.");
                }
                else
                {
                    show.Cast.AddRange(GetCasts(jcast));
                }
            }

            return(show);
        }
コード例 #4
0
        // PUT api/Shows/5
        public ShowDto Put([FromBody] ShowDto show)
        {
            var updatedShow = show.ConvertFromDto();

            ShowService.Update(updatedShow);
            return(updatedShow.ConvertToDto());
        }
コード例 #5
0
        // POST api/Shows
        public ShowDto Post([FromBody] ShowDto show)
        {
            var newShow = show.ConvertFromDto();

            ShowService.Add(newShow);
            return(newShow.ConvertToDto());
        }
コード例 #6
0
        private IEnumerable <ShowDto> GetExpectedShows()
        {
            var show1 = new ShowDto {
                Id = 1, Name = "Matrix"
            };
            var show2 = new ShowDto {
                Id = 2, Name = "Kill Bill"
            };
            var actor1 = new ActorDto {
                Id = 1, Name = "Bill", Birthday = "1980-07-01"
            };
            var actor2 = new ActorDto {
                Id = 3, Name = "Nick", Birthday = "1981-07-01"
            };
            var actor3 = new ActorDto {
                Id = 2, Name = "Tom", Birthday = "1979-07-01"
            };

            show1.Cast = new List <ActorDto>();
            //show1.Cast = new List<ActorDto> { actor1 };
            //show2.Cast = new List<ActorDto> { actor2, actor3 };
            return(new List <ShowDto> {
                show1
            });
        }
コード例 #7
0
ファイル: Scraper.cs プロジェクト: larrybohn/tvscraper
 private async Task AddShow(ShowDto show)
 {
     var addShowCommand = new AddShowCommand
     {
         Show = show
     };
     await showCommandRepository.AddShowAsync(addShowCommand);
 }
コード例 #8
0
        public static Show ConvertFromDto(this ShowDto showDto)
        {
            var show = new Show(showDto.Id, showDto.Name, showDto.Description);

            //foreach (var contestDto in showDto.Contests)
            //show.Contests.Add(ConvertFromDto(contestDto));

            return(show);
        }
コード例 #9
0
ファイル: FavouritesService.cs プロジェクト: RzuF/showTracker
        public FavouritiesAction AddOrDelete(ShowDto show)
        {
            if (AddShow(show))
            {
                return(FavouritiesAction.Add);
            }

            DeleteShow(show);
            return(FavouritiesAction.Delete);
        }
コード例 #10
0
ファイル: NewShowViewModel.cs プロジェクト: BenJoey/felev6
        public NewShowViewModel(ICinemaService model)
        {
            _model = model ?? throw new ArgumentNullException(nameof(model));

            NewShow = new ShowDto();
            LoadData();

            SendCommand   = new DelegateCommand(param => AddNewShow());
            CancelCommand = new DelegateCommand(param => OnCancel());
        }
コード例 #11
0
ファイル: FavouritesService.cs プロジェクト: RzuF/showTracker
        public bool AddShow(ShowDto show)
        {
            if (FavouritiesShowCollection.Any(x => x.Id == show.Id))
            {
                return(false);
            }

            FavouritiesShowCollection.Add(show);
            SaveShowCollectionToSettings();
            return(true);
        }
コード例 #12
0
ファイル: ShowsController.cs プロジェクト: shtik/Shows
        public async Task <IActionResult> LatestByPresenter(string handle, CancellationToken ct)
        {
            var show = await _context.Shows
                       .Where(s => s.Presenter == handle)
                       .OrderByDescending(s => s.Time)
                       .Take(1)
                       .FirstOrDefaultAsync(ct)
                       .ConfigureAwait(false);

            return(show == null?NotFound() : Ok(ShowDto.FromShow(show)));
        }
コード例 #13
0
 public static Show MapToShow(ShowDto showDto, IList <CastDto> castDtos)
 {
     return(new Show
     {
         Id = showDto.Id,
         Name = showDto.Name,
         Cast = castDtos.Select(MapToCast)
                .OrderByDescending(x => x.Birthday.HasValue)
                .ThenByDescending(x => x.Birthday)
                .ToList()
     });
 }
コード例 #14
0
        private async Task <IEnumerable <CastMember> > GetCastMembersAsync(ShowDto showDto)
        {
            _logger.LogInformation("Collecting casts for show " + showDto.Id);
            var cast = await _castCollector.GetCastAsync(showDto.Id);

            var castMembers = cast.Select(c => new CastMember
            {
                Id = c.Person.Id, BirthDay = c.Person.Birthday, Name = c.Person.Name
            });

            return(castMembers);
        }
コード例 #15
0
        private ShowDto ConvertShow(Show localshow)
        {
            // TODO use mapper
            var coreshow = new ShowDto {
                Id = localshow.Id, Name = localshow.Name
            };

            coreshow.CastMembers.AddRange(localshow.ShowCastMembers
                                          .Select(scm => scm.CastMember)
                                          .Select(cm => new CastMemberDto {
                Id = cm.Id, Name = cm.Name, Birthdate = cm.Birthdate
            }));
            return(coreshow);
        }
コード例 #16
0
        public async Task <ActionResult> Put(int id, [FromBody] ShowDto show)
        {
            var showToUpdate = await _repository.Show.GetShowAsync(id, false);

            if (showToUpdate == null)
            {
                return(NotFound());
            }
            var mappedShow = _mapper.Map <Show>(show);

            _repository.Show.Update(mappedShow);

            await _repository.SaveAsync();

            return(NoContent());
        }
        private async Task <int> AddOrUpdateWithoutSaveAsync(Show show)
        {
            int result  = UpdatedStatus;
            var showDto = await _context.Shows.Include(c => c.Cast).FirstOrDefaultAsync(o => o.Id == show.Id);

            if (showDto == null)
            {
                result  = CreatedStatus;
                showDto = new ShowDto();
                await _context.Shows.AddAsync(showDto);
            }
            _mapper.Map(show, showDto);

            var toDelete = new List <CastDto>();

            //remove deleted cast
            foreach (var deleted in showDto.Cast ?? Enumerable.Empty <CastDto>())
            {
                if (!show.Cast?.Any(c => c.Id == deleted.Id) ?? true)
                {
                    toDelete.Add(deleted);
                }
            }
            if (toDelete.Any())
            {
                _context.Cast.RemoveRange(toDelete);
            }

            //update or add details
            show.Cast?.ToList().ForEach(cast =>
            {
                if (showDto.Cast == null)
                {
                    showDto.Cast = new List <CastDto>();
                }

                var castDto = showDto.Cast.FirstOrDefault(d => d.Id == cast.Id);
                if (castDto == null)
                {
                    castDto = new CastDto();
                    showDto.Cast.Add(castDto);
                }
                _mapper.Map(cast, castDto);
            });

            return(result);
        }
コード例 #18
0
ファイル: CinemaTest.cs プロジェクト: BenJoey/felev6
        public void AddNewShowTest()
        {
            var newShow = new ShowDto
            {
                movieId   = _context.Movies.Single(o => o.Title == "TEST_MOVIE_2").Id,
                roomId    = _context.Rooms.Single(o => o.RoomName == "TEST_ROOM").Id,
                StartTime = "2019-12-20 10:00:00"
            };

            var controller = new ShowController(_context);
            var result     = controller.NewShow(newShow);

            var objectResult = Assert.IsType <OkResult>(result);

            Assert.Equal(_showDTOs.Count + 1, _context.Shows.Count());
            Assert.Equal(200, objectResult.StatusCode);
        }
コード例 #19
0
        private Show ConvertShow(ShowDto coreshow)
        {
            var modelshow = new Show {
                Id = coreshow.Id, Name = coreshow.Name
            };

            modelshow.ShowCastMembers.AddRange(coreshow.CastMembers
                                               .Select(cm => new ShowCastMember
            {
                Show       = modelshow,
                CastMember = new CastMember
                {
                    Id        = cm.Id,
                    Name      = cm.Name,
                    Birthdate = cm.Birthdate
                }
            }));
            return(modelshow);
        }
コード例 #20
0
ファイル: TvMazeService.cs プロジェクト: debabrata-das/tvmaze
        public async Task <ShowDto> GetShowDataById(int showId,
                                                    CancellationToken cancellationToken = default(CancellationToken))
        {
            var jshow = await _jsonApiDataReader.GetJsonData <dynamic>(
                new Uri($"/shows/{showId}?embed=cast", UriKind.Relative), cancellationToken);

            var show = new ShowDto
            {
                Id   = jshow.id,
                Name = jshow.name
            };
            var embedded = jshow._embedded;

            if (embedded is null)
            {
                _logger.LogError($"No embedded data returned for show {showId}.");
            }
            else
            {
                var jcast = embedded.cast;
                if (jcast is null)
                {
                    _logger.LogError($"No cast data found embedded for show {showId}.");
                }
                else
                {
                    foreach (var container in jcast)
                    {
                        var person    = container.person;
                        var personDto = new PersonDto
                        {
                            Id        = person.id,
                            Name      = person.name,
                            Birthdate = person.birthday,
                        };

                        show.Cast.Add(personDto);
                    }
                }
            }

            return(show);
        }
コード例 #21
0
        public async Task <List <ShowDto> > GetShowsByPage(int pageNumber,
                                                           CancellationToken cancellationToken = default(CancellationToken))
        {
            var result = new List <ShowDto>();
            var shows  = await _jsonApiDataReader.GetJsonData <JArray>(
                new Uri($"/shows?page={pageNumber}", UriKind.Relative), cancellationToken);

            foreach (dynamic jshow in shows)
            {
                var show = new ShowDto
                {
                    Id   = jshow.id,
                    Name = jshow.name
                };
                result.Add(show);
            }

            _logger.LogInformation($"Getting {result.Count} Shows for pageNumber {pageNumber}");
            return(result);
        }
コード例 #22
0
        /// <summary>
        /// Scrapes the shows by their initial.
        /// </summary>
        /// <param name="searchWord">The search word.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>
        /// A list of shows.
        /// </returns>
        public async Task <List <ShowDto> > ScrapeShowsBySearch(string searchWord, CancellationToken cancellationToken = default)
        {
            // note: not documented, but apparently returns just the first 10 results
            var(status, json) = await this.apiRepository.RequestJsonForTvMaze(
                new Uri($"/search/shows?q={searchWord}", UriKind.Relative),
                cancellationToken)
                                .ConfigureAwait(false);

            if (status != HttpStatusCode.OK)
            {
                // some error or 429
                this.logger.LogWarning("Scraping shows for '{searchWord}' returned status {status}.", searchWord, status);
                return(null);
            }

            var result = new List <ShowDto>();

            /* NOTE to reviewer: I could have created a tree of objects to deserialize this JSON into,
             * but that would be a tree per API call with no benefit to speed of execution, speed of development
             * or maintainability. A change in the API would in both cases force a rewrite.
             */

            // read json
            var shows = JArray.Parse(json);

            foreach (dynamic showcontainer in shows)
            {
                var jshow = showcontainer.show;
                var show  = new ShowDto
                {
                    Id   = jshow.id,
                    Name = jshow.name,
                };

                result.Add(show);
            }

            this.logger.LogInformation("Scraping for '{searchWord}' returned {resultCount} shows.", searchWord, result.Count);
            return(result);
        }
コード例 #23
0
        private async Task HandleShowDto(
            ShowDto showDto,
            bool reset,
            CancellationToken cancellationToken,
            Action <Show> showAddedAction)
        {
            var addShow = reset || await _dbContext.Show.AllAsync(x => x.Id != showDto.Id, cancellationToken);

            if (!addShow)
            {
                return;
            }
            var castDtos = await _client.ListCast(showDto.Id, cancellationToken);

            var show      = ClientDtoMapper.MapToShow(showDto, castDtos);
            var showDbDto = DbDtoMapper.MapToShowDto(show);

            _dbContext.Show.Add(showDbDto);
            await _dbContext.SaveChangesAsync(cancellationToken);

            _dbContext.Entry(showDbDto).State = EntityState.Detached;
            showAddedAction?.Invoke(show);
        }
コード例 #24
0
ファイル: FavouritesService.cs プロジェクト: RzuF/showTracker
 public bool DeleteShow(ShowDto show)
 {
     return(DeleteShow(show.Id));
 }
コード例 #25
0
        public IActionResult NewShow([FromBody] ShowDto item)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var selectedMovie = (_context.Movies.Where(o => o.Id == item.movieId)).FirstOrDefault();
                    var selectedRoom  = (_context.Rooms.Where(o => o.Id == item.roomId)).FirstOrDefault();
                    if (selectedMovie == null || selectedRoom == null)
                    {
                        return(NotFound());
                    }

                    var newShowStart = DateTime.Parse(item.StartTime);
                    var newShowEnd   = newShowStart + selectedMovie.Length + TimeSpan.FromMinutes(15);
                    var showsToCheck = (_context.Shows.Where(o => o.RoomRefId == selectedRoom.Id)).ToList();
                    foreach (var show in showsToCheck)
                    {
                        var currentMovie = _context.Movies.FirstOrDefault(o => o.Id == show.MovieRefId);
                        var showEnd      = show.StartTime + currentMovie.Length + TimeSpan.FromMinutes(15);
                        var invalidTime  =
                            (DateTime.Compare(show.StartTime, newShowStart) < 1 && DateTime.Compare(newShowStart,
                                                                                                    showEnd) < 1) || (DateTime.Compare(show.StartTime, newShowEnd) < 1 &&
                                                                                                                      DateTime.Compare(newShowEnd, showEnd) < 1);

                        if (invalidTime)
                        {
                            return(BadRequest());
                        }
                    }

                    var newShow = new Show()
                    {
                        Movie     = selectedMovie,
                        Room      = selectedRoom,
                        StartTime = DateTime.Parse(item.StartTime)
                    };
                    for (int i = 0; i < newShow.Room.NumOfRows; i++)
                    {
                        for (int j = 0; j < newShow.Room.NumOfCols; j++)
                        {
                            _context.Seats.Add(
                                new Seat()
                            {
                                Row   = i,
                                Col   = j,
                                Room  = newShow.Room,
                                Show  = newShow,
                                State = State.Free
                            });
                        }
                    }

                    _context.Shows.Add(newShow);

                    _context.SaveChanges();
                }
                else
                {
                    return(BadRequest());
                }
            }
            catch (DbUpdateConcurrencyException)
            {
                return(BadRequest());
            }
            catch (DbUpdateException)
            {
                return(BadRequest());
            }
            catch (Exception)
            {
                return(BadRequest());
            }

            return(Ok());
        }
コード例 #26
0
        public async Task <Boolean> SendNewShow(ShowDto newShowData)
        {
            HttpResponseMessage response = await _client.PostAsJsonAsync("api/Show/", newShowData);

            return(response.IsSuccessStatusCode);
        }
コード例 #27
0
ファイル: ShowsController.cs プロジェクト: shtik/Shows
        public async Task <IActionResult> Get(string presenter, string slug, CancellationToken ct)
        {
            var show = await _context.Shows.SingleOrDefaultAsync(s => s.Presenter == presenter && s.Slug == slug, ct).ConfigureAwait(false);

            return(show == null?NotFound() : Ok(ShowDto.FromShow(show)));
        }
コード例 #28
0
ファイル: ShowsController.cs プロジェクト: shtik/Shows
        public async Task <IActionResult> Start([FromBody] Show show, CancellationToken ct)
        {
            try
            {
                _context.Shows.Add(show);
                await _context.SaveChangesAsync(ct).ConfigureAwait(false);

                return(CreatedAtAction("Get", "Shows", new { presenter = show.Presenter, slug = show.Slug }, ShowDto.FromShow(show)));
            }
            catch (System.Exception ex)
            {
                _logger.LogError(EventIds.DatabaseError, ex, ex.Message);
                throw;
            }
        }
コード例 #29
0
 /// <summary>
 /// Deconstructs this to a show and status tuple.
 /// </summary>
 /// <param name="show">The show.</param>
 /// <param name="status">The status.</param>
 public void Deconstruct(out ShowDto show, out HttpStatusCode status)
 {
     show   = this.Show;
     status = this.HttpStatus;
 }
コード例 #30
0
        /// <summary>
        /// Scrapes the single show by its identifier.
        /// </summary>
        /// <param name="showId">The show's identifier.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>A Task with Show and status code.</returns>
        public async Task <ScrapeResult> ScrapeSingleShowById(int showId, CancellationToken cancellationToken = default)
        {
            var sw = Stopwatch.StartNew();

            var(status, json) = await this.apiRepository.RequestJsonForTvMaze(
                new Uri($"/shows/{showId}?embed=cast", UriKind.Relative),
                cancellationToken)
                                .ConfigureAwait(false);

            sw.Stop();
            this.logger.LogInformation("Getting info about show {ShowId} took {Elapsed} msec and returned status {HttpStatus}.", showId, sw.ElapsedMilliseconds, status);

            if (status == Constants.ServerTooBusy)
            {
                // too much, so back off
                this.logger.LogDebug("Server too busy to scrape #{ShowId}, backing off.", showId);
                return(new ScrapeResult {
                    HttpStatus = status
                });
            }

            if (status == HttpStatusCode.OK)
            {
                dynamic jshow = JObject.Parse(json);
                var     show  = new ShowDto
                {
                    Id     = jshow.id,
                    Name   = jshow.name,
                    ImdbId = jshow.externals?.imdb,
                };

                var embedded = jshow._embedded;
                if (embedded is null)
                {
                    this.logger.LogError("Server didn't return the requested embedded data for show {ShowId}.", showId);
                }
                else
                {
                    var jcast = embedded.cast;
                    if (jcast is null)
                    {
                        this.logger.LogError("Server didn't return the requested cast in the embedded data for show {ShowId}.", showId);
                    }
                    else
                    {
                        foreach (var container in jcast)
                        {
                            var person = container.person;
                            var member = new CastMemberDto
                            {
                                Id        = person.id,
                                Name      = person.name,
                                Birthdate = person.birthday,
                            };

                            show.CastMembers.Add(member);
                        }
                    }
                }

                return(new ScrapeResult {
                    Show = show, HttpStatus = status
                });
            }

            return(new ScrapeResult {
                HttpStatus = status
            });
        }