Esempio n. 1
0
        private void FillMetadataFromElement(HtmlNode node, ChannelItemInfo info)
        {
            var text = node.InnerText ?? string.Empty;

            if (text.StartsWith("(", StringComparison.OrdinalIgnoreCase) && text.EndsWith(")", StringComparison.OrdinalIgnoreCase))
            {
                //var studio = text.Trim('(').Trim(')');

                //if (!string.IsNullOrWhiteSpace(studio))
                //{
                //    info.Studios.Add(studio);
                //}
            }
            else if (text.StartsWith("Director:", StringComparison.OrdinalIgnoreCase))
            {
                //info.People.AddRange(GetTextFromSubNodes(node, "span").Select(i => new PersonInfo
                //{
                //    Name = i,
                //    Type = PersonType.Director
                //}));
            }
            else if (text.StartsWith("Writer:", StringComparison.OrdinalIgnoreCase))
            {
                //info.People.AddRange(GetTextFromSubNodes(node, "span").Select(i => new PersonInfo
                //{
                //    Name = i,
                //    Type = PersonType.Writer

                //}));
            }
            else if (text.StartsWith("Genre:", StringComparison.OrdinalIgnoreCase))
            {
                //info.Genres.AddRange(GetTextFromSubNodes(node, "span"));
            }
            else if (text.StartsWith("Plot:", StringComparison.OrdinalIgnoreCase))
            {
                //info.Overview = GetTextFromSubNodes(node, "span").FirstOrDefault();
            }
            else if (text.StartsWith("Cast:", StringComparison.OrdinalIgnoreCase))
            {
                //info.People.AddRange(GetTextFromSubNodes(node, "a").Select(i => new PersonInfo
                //{
                //    Name = i,
                //    Type = PersonType.Actor

                //}));
            }
            else
            {
                text = GetTextFromSubNodes(node, "span")
                       .FirstOrDefault() ?? string.Empty;

                DateTime dateAdded;

                if (DateTime.TryParse(text, out dateAdded))
                {
                    info.DateCreated = DateTime.SpecifyKind(dateAdded, DateTimeKind.Utc);
                }
            }
        }
Esempio n. 2
0
        private async Task <ChannelItemResult> GetChannelItemsInternal(string userId, CancellationToken cancellationToken)
        {
            var items = new List <ChannelItemInfo>();

            foreach (var s in Plugin.Instance.Configuration.Bookmarks
                     .Where(i => string.Equals(i.UserId, userId, StringComparison.OrdinalIgnoreCase)))
            {
                var item = new ChannelItemInfo
                {
                    Name        = s.Name,
                    ImageUrl    = s.Image,
                    Id          = s.Name,
                    Type        = ChannelItemType.Media,
                    ContentType = ChannelMediaContentType.Clip,
                    MediaType   = ChannelMediaType.Video,

                    MediaSources = new List <ChannelMediaInfo>
                    {
                        new ChannelMediaInfo
                        {
                            Path     = s.Path,
                            Protocol = s.Protocol
                        }
                    }
                };

                items.Add(item);
            }
            return(new ChannelItemResult
            {
                Items = items.ToList()
            });
        }
Esempio n. 3
0
        public static async Task <ChannelItemResult> GetSeasonInfoAsync(InternalChannelItemQuery query, ILogger logger, IMemoryCache memoryCache)
        {
            if (memoryCache.TryGetValue("nrk-categories-seasoninfo-" + query.FolderId, out ChannelItemResult cachedValue))
            {
                logger.LogInformation("Function={function} FolderId={folderId} Cache Hit", nameof(GetSeasonInfoAsync), "nrk-categories-seasoninfo-" + query.FolderId);
                return(cachedValue);
            }
            else
            {
                logger.LogInformation("Function={function} FolderId={folderId} web download", nameof(GetSeasonInfoAsync), "nrk-categories-seasoninfo-" + query.FolderId);
                HttpClient        httpClient = new HttpClient();
                string            json       = new StreamReader(await httpClient.GetStreamAsync(query.FolderId)).ReadToEnd();
                var               root       = Newtonsoft.Json.JsonConvert.DeserializeObject <SeasonInfo.root>(json);
                ChannelItemResult result     = new ChannelItemResult();

                foreach (var emb in root.Embedded.Seasons)
                {
                    ChannelItemInfo info = new ChannelItemInfo()
                    {
                        FolderType  = ChannelFolderType.Container,
                        SeriesName  = root.Sequential.Titles.Title,
                        Name        = emb.Titles.Title,
                        Overview    = root.Sequential.Titles.Subtitle,
                        HomePageUrl = "https://tv.nrk.no" + emb.Links.Series.Href,
                        Id          = "https://psapi.nrk.no" + emb.Links.Self.Href,
                        MediaType   = ChannelMediaType.Video,
                        Type        = ChannelItemType.Folder
                    };
                    result.Items.Add(info);
                    result.TotalRecordCount++;
                }
                memoryCache.Set("nrk-categories-seasoninfo-" + query.FolderId, result, DateTimeOffset.Now.AddDays(7));
                return(result);
            }
        }
Esempio n. 4
0
        private bool Filter(ChannelItemInfo item, ListingResults results)
        {
            item.MediaSources = item.MediaSources
                                .Where(i => Filter(i, results))
                                .ToList();

            return(item.MediaSources.Count > 0);
        }
Esempio n. 5
0
        private void TemplateControl_DataBinding(object sender, EventArgs e)
        {
            var literal   = (Literal)sender;
            var container = (RepeaterItem)literal.NamingContainer;

            var itemInfo = new DbItemInfo(container.DataItem, container.ItemIndex);

            if (_contextType == EContextType.Channel)
            {
                var channelItemInfo = new ChannelItemInfo(SqlUtils.EvalInt(container.DataItem, ChannelAttribute.Id), container.ItemIndex);
                _pageInfo.ChannelItems.Push(channelItemInfo);
                literal.Text = TemplateUtility.GetChannelsItemTemplateString(_templateString, _selectedItems, _selectedValues, container.ClientID, _pageInfo, _contextType, _contextInfo);
            }
            else if (_contextType == EContextType.Content)
            {
                var contentItemInfo = new ContentItemInfo(SqlUtils.EvalInt(container.DataItem, ContentAttribute.ChannelId), SqlUtils.EvalInt(container.DataItem, ContentAttribute.Id), container.ItemIndex);
                _pageInfo.ContentItems.Push(contentItemInfo);
                literal.Text = TemplateUtility.GetContentsItemTemplateString(_templateString, _selectedItems, _selectedValues, container.ClientID, _pageInfo, _contextType, _contextInfo);
            }
            else if (_contextType == EContextType.Comment)
            {
                _pageInfo.CommentItems.Push(itemInfo);
                literal.Text = TemplateUtility.GetCommentsTemplateString(_templateString, container.ClientID, _pageInfo, _contextType, _contextInfo);
            }
            //else if (_contextType == EContextType.InputContent)
            //{
            //    _pageInfo.InputItems.Push(itemInfo);
            //    literal.Text = TemplateUtility.GetInputContentsTemplateString(_templateString, container.ClientID, _pageInfo, _contextType, _contextInfo);
            //}
            else if (_contextType == EContextType.SqlContent)
            {
                _pageInfo.SqlItems.Push(itemInfo);
                literal.Text = TemplateUtility.GetSqlContentsTemplateString(_templateString, _selectedItems, _selectedValues, container.ClientID, _pageInfo, _contextType, _contextInfo);
            }
            else if (_contextType == EContextType.Site)
            {
                _pageInfo.SiteItems.Push(itemInfo);
                literal.Text = TemplateUtility.GetSitesTemplateString(_templateString, container.ClientID, _pageInfo, _contextType, _contextInfo);
            }
            else if (_contextType == EContextType.Each)
            {
                _pageInfo.EachItems.Push(itemInfo);
                literal.Text = TemplateUtility.GetEachsTemplateString(_templateString, _selectedItems, _selectedValues, container.ClientID, _pageInfo, _contextType, _contextInfo);
            }

            if (_separatorRepeat > 1)
            {
                _i++;
                if (_i % _separatorRepeat == 0)
                {
                    literal.Text += _separatorRepeatTemplate;
                }
            }
        }
Esempio n. 6
0
        private DateTime GetDateCreatedForSorting(ChannelItemInfo item)
        {
            var date = item.DateCreated;

            if (date.HasValue)
            {
                // Strip out the time portion in case they were all added at the same time
                // This will allow premiere date to take over
                return(date.Value.Date);
            }

            return(DateTime.MinValue);
        }
Esempio n. 7
0
        private ChannelItemInfo ResultToChannelItemInfo(BluRayPlaylistInfo item)
        {
            ChannelItemInfo info;

            if (item.IsFolder)
            {
                info = new ChannelItemInfo
                {
                    Id       = item.Id,
                    ImageUrl = "",
                    Name     = item.Name,
                    Type     = ChannelItemType.Folder
                };
            }
            else
            {
                info = new ChannelItemInfo
                {
                    ContentType  = ChannelMediaContentType.Movie,
                    Id           = item.Id,
                    ImageUrl     = "",
                    MediaType    = ChannelMediaType.Video,
                    Name         = item.Name,
                    RunTimeTicks = item.Runtime,
                    Type         = ChannelItemType.Media,
                };

                switch (item.Type.ToLower())
                {
                case "extra":
                    info.ContentType = ChannelMediaContentType.MovieExtra;
                    break;

                case "trailer":
                    info.ContentType = ChannelMediaContentType.Trailer;
                    break;

                case "episode":
                    info.ContentType = ChannelMediaContentType.Episode;
                    info.SeriesName  = item.SeriesName;
                    break;

                case "tvextra":
                    info.ContentType = ChannelMediaContentType.TvExtra;
                    info.SeriesName  = item.SeriesName;
                    break;
                }
            }

            return(info);
        }
        public static ChannelItemInfo CreateFolderItem(string title, string id, string url, ChannelItemInfo child)
        {
            var folder = new ChannelItemInfo();

            folder.FolderType = MediaBrowser.Model.Channels.ChannelFolderType.Container;
            folder.Type       = ChannelItemType.Folder;
            folder.Name       = title;
            folder.Id         = string.Format("{0}_{1}", id, url);
            if (child != null)
            {
                folder.ImageUrl = child.ImageUrl;
            }
            return(folder);
        }
Esempio n. 9
0
 private async Task TestItem(ChannelItemInfo item, ListingResults results, CancellationToken cancellationToken)
 {
     foreach (var media in (item.MediaSources ?? new List <ChannelMediaInfo>()))
     {
         try
         {
             await TestMediaInfo(media, results, cancellationToken).ConfigureAwait(false);
         }
         catch (Exception ex)
         {
             _logger.ErrorException("Error testing media info", ex);
         }
     }
 }
Esempio n. 10
0
        private ChannelItemInfo ConvertToChannelItem(MyRecordingInfo item)
        {
            var config = Plugin.Instance.Configuration;

            var channelItem = new ChannelItemInfo
            {
                Id                = item.Id,
                Name              = !string.IsNullOrEmpty(item.EpisodeTitle) && (item.IsSeries || item.EpisodeNumber.HasValue && !item.IsMovie) ? item.EpisodeTitle : item.Name,
                SeriesName        = !string.IsNullOrEmpty(item.EpisodeTitle) && (item.IsSeries || item.EpisodeNumber.HasValue && !item.IsMovie) ? item.Name : null,
                OriginalTitle     = !string.IsNullOrEmpty(item.EpisodeTitle) && item.IsMovie ? item.EpisodeTitle : null,
                IndexNumber       = item.EpisodeNumber,
                ParentIndexNumber = item.SeasonNumber,
                ProductionYear    = item.Year,
                Overview          = item.Overview,
                Genres            = item.Genres,
                ImageUrl          = (item.IsMovie && !string.IsNullOrEmpty(item.TmdbPoster)) ? item.TmdbPoster : item.ImageUrl,
                DateCreated       = item.StartDate,
                DateModified      = item.EndDate,

                Type         = ChannelItemType.Media,
                ContentType  = item.IsMovie ? ChannelMediaContentType.Movie : (item.IsSeries || item.EpisodeNumber != null ? ChannelMediaContentType.Episode : ChannelMediaContentType.Clip),
                MediaType    = item.ChannelType == ChannelType.TV ? ChannelMediaType.Video : ChannelMediaType.Audio,
                IsLiveStream = item.Status == RecordingStatus.InProgress,
                Etag         = item.Status.ToString(),

                MediaSources = new List <MediaSourceInfo>
                {
                    new MediaSourceInfo
                    {
                        Path                  = config.EnableDirectAccess && item.Status != RecordingStatus.InProgress ? item.Path : Plugin.StreamingProxy.GetRecordingStream(item.Id),
                        Protocol              = item.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? MediaProtocol.Http : MediaProtocol.File,
                        Id                    = item.Id,
                        SupportsProbing       = item.Status == RecordingStatus.InProgress ? false : true,
                        IsInfiniteStream      = item.Status == RecordingStatus.InProgress ? true : false,
                        ReadAtNativeFramerate = item.Status == RecordingStatus.InProgress ? true : false,
                        RunTimeTicks          = (item.EndDate - item.StartDate).Ticks,

                        RequiredHttpHeaders = config.RequiresAuthentication ?
                                              new Dictionary <string, string> {
                            { "Authentication", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(String.Format("{0}:{1}", config.UserName, config.Password))) }
                        } :
                        new Dictionary <string, string> {
                        },
                    }
                }
            };

            return(channelItem);
        }
Esempio n. 11
0
        private static ChannelItemInfo getChannelItemInfo(int id)
        {
            int      duration        = _durations[new Random().Next(0, 3)];
            DateTime startDate       = DateTime.Now.AddDays(id * -1);
            var      channelItemInfo = new ChannelItemInfo()
            {
                Id        = Convert.ToString(id),
                Name      = $"Recording {id}",
                Overview  = LoremIpsum,
                StartDate = startDate,
                EndDate   = startDate.AddMinutes(duration)
            };

            return(channelItemInfo);
        }
Esempio n. 12
0
        private async Task <ChannelItemResult> GetChannels(CancellationToken cancellationToken)
        {
            var items = new List <ChannelItemInfo>();

            if (!Plugin.Instance.Registration.IsValid)
            {
                Plugin.Logger.Warn("PodCasts trial has expired.");
                await _notificationManager.SendNotification(new NotificationRequest
                {
                    Description    = "PodCasts trial has expired.",
                    Date           = DateTime.Now,
                    Level          = NotificationLevel.Warning,
                    SendToUserMode = SendToUserType.Admins
                }, cancellationToken);

                return(new ChannelItemResult
                {
                    Items = items.ToList()
                });
            }

            foreach (var feedUrl in Plugin.Instance.Configuration.Feeds)
            {
                var feed = await new RssFeed().GetFeed(_providerManager, _httpClient, feedUrl, cancellationToken).ConfigureAwait(false);

                _logger.Debug(feedUrl);

                var item = new ChannelItemInfo
                {
                    Name     = feed.Title == null ? null : feed.Title.Text,
                    Overview = feed.Description == null ? null : feed.Description.Text,
                    Id       = feedUrl,
                    Type     = ChannelItemType.Folder
                };

                if (feed.ImageUrl != null)
                {
                    item.ImageUrl = feed.ImageUrl.AbsoluteUri;
                }

                items.Add(item);
            }
            return(new ChannelItemResult
            {
                Items = items.ToList()
            });
        }
Esempio n. 13
0
        private async Task <ChannelItemResult> GetChannelItemsInternal(string userId, CancellationToken cancellationToken)
        {
            var user  = string.IsNullOrEmpty(userId) ? null : _user.GetUserById(userId);
            var items = new List <ChannelItemInfo>();

            foreach (var s in Plugin.Instance.Configuration.Bookmarks)
            {
                // Until we have user configuration in the UI, we have to disable this.
                //if (!string.Equals(s.UserId, userId, StringComparison.OrdinalIgnoreCase))
                //{
                //    continue;
                //}
                if (
                    (user.Policy.MaxParentalRating.HasValue && user.Policy.MaxParentalRating >= s.ParentalRating) ||
                    (!user.Policy.MaxParentalRating.HasValue)
                    )
                {
                    var item = new ChannelItemInfo
                    {
                        Name        = s.Name,
                        ImageUrl    = s.Image,
                        Id          = s.Name,
                        Type        = ChannelItemType.Media,
                        ContentType = ChannelMediaContentType.Clip,
                        MediaType   = ChannelMediaType.Video,

                        MediaSources = new List <ChannelMediaInfo>
                        {
                            new ChannelMediaInfo
                            {
                                Path     = s.Path,
                                Protocol = s.Protocol
                            }
                        }
                    };

                    items.Add(item);
                }
            }

            return(new ChannelItemResult
            {
                Items = items.ToList()
            });
        }
Esempio n. 14
0
        private ChannelItemInfo ConvertToChannelItem(RecordingInfo item)
        {
            var path = string.IsNullOrEmpty(item.Path) ? item.Url : item.Path;

            var channelItem = new ChannelItemInfo
            {
                Name            = string.IsNullOrEmpty(item.EpisodeTitle) ? item.Name : item.EpisodeTitle,
                SeriesName      = !string.IsNullOrEmpty(item.EpisodeTitle) || item.IsSeries ? item.Name : null,
                OfficialRating  = item.OfficialRating,
                CommunityRating = item.CommunityRating,
                ContentType     = item.IsMovie ? ChannelMediaContentType.Movie : (item.IsSeries ? ChannelMediaContentType.Episode : ChannelMediaContentType.Clip),
                Genres          = item.Genres,
                ImageUrl        = item.ImageUrl,
                //HomePageUrl = item.HomePageUrl
                Id = item.Id,
                //IndexNumber = item.IndexNumber,
                MediaType    = item.ChannelType == ChannelType.TV ? ChannelMediaType.Video : ChannelMediaType.Audio,
                MediaSources = new List <MediaSourceInfo>
                {
                    new MediaSourceInfo
                    {
                        Path                  = path,
                        Protocol              = path.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? MediaProtocol.Http : MediaProtocol.File,
                        Id                    = item.Id,
                        SupportsProbing       = !(item.Status == RecordingStatus.InProgress),
                        IsInfiniteStream      = item.Status == RecordingStatus.InProgress,
                        ReadAtNativeFramerate = item.Status == RecordingStatus.InProgress,
                        RunTimeTicks          = (item.EndDate - item.StartDate).Ticks
                    }
                },
                //ParentIndexNumber = item.ParentIndexNumber,
                PremiereDate = item.OriginalAirDate,
                //ProductionYear = item.ProductionYear,
                //Studios = item.Studios,
                Type         = ChannelItemType.Media,
                DateModified = item.DateLastUpdated,
                Overview     = item.Overview,
                //People = item.People
                IsLiveStream = item.Status == RecordingStatus.InProgress,
                Etag         = item.Status.ToString()
            };

            return(channelItem);
        }
Esempio n. 15
0
        private Task <ChannelItemResult> GetChannelItemsInternal(CancellationToken cancellationToken)
        {
            var items = new List <ChannelItemInfo>();

            foreach (var s in Plugin.Instance.Configuration.Bookmarks)
            {
                // Until we have user configuration in the UI, we have to disable this.
                //if (!string.Equals(s.UserId, userId, StringComparison.OrdinalIgnoreCase))
                //{
                //    continue;
                //}

                var item = new ChannelItemInfo
                {
                    Name        = s.Name,
                    ImageUrl    = s.Image,
                    Id          = s.Name,
                    Type        = ChannelItemType.Media,
                    ContentType = ChannelMediaContentType.Clip,
                    MediaType   = ChannelMediaType.Video,

                    MediaSources = new List <MediaSourceInfo>
                    {
                        new ChannelMediaInfo
                        {
                            Path     = s.Path,
                            Protocol = s.Protocol
                        }.ToMediaSource()
                    }
                };

                items.Add(item);
            }

            return(Task.FromResult(new ChannelItemResult
            {
                Items = items
            }));
        }
Esempio n. 16
0
        private async Task <IEnumerable <ChannelItemInfo> > GetChannelItemsInternal(string feedUrl, CancellationToken cancellationToken)
        {
            var items = new List <ChannelItemInfo>();

            var rssItems = await new RssFeed().Refresh(_providerManager, _httpClient, feedUrl, _notificationManager, cancellationToken).ConfigureAwait(false);

            foreach (var child in rssItems)
            {
                var podcast = (IHasRemoteImage)child;

                var item = new ChannelItemInfo
                {
                    Name        = child.Name,
                    Overview    = child.Overview,
                    ImageUrl    = podcast.RemoteImagePath ?? "https://raw.githubusercontent.com/MediaBrowser/MediaBrowser.Channels/master/Podcasts/Images/thumb.png",
                    Id          = child.Id.ToString("N"),
                    Type        = ChannelItemType.Media,
                    ContentType = ChannelMediaContentType.Podcast,
                    MediaType   = child is Video ? ChannelMediaType.Video : ChannelMediaType.Audio,

                    MediaSources = new List <ChannelMediaInfo>
                    {
                        new ChannelMediaInfo
                        {
                            Path = child.Path
                        }
                    },

                    DateCreated  = child.DateCreated,
                    PremiereDate = child.PremiereDate,

                    RunTimeTicks   = child.RunTimeTicks,
                    OfficialRating = child.OfficialRating
                };

                items.Add(item);
            }
            return(items);
        }
        private static ChannelItemInfo ParseFolderArticle(HtmlNode node)
        {
            var info = new ChannelItemInfo();

            info.FolderType = MediaBrowser.Model.Channels.ChannelFolderType.Container;
            info.Type       = ChannelItemType.Folder;
            var nameNode = node.SelectSingleNode(".//h2[contains(@class, 'play_h4')]");

            info.Name = nameNode != null ? nameNode.InnerText : "";

            var a = node.SelectSingleNode(".//a[contains(@class, 'play_videolist-element__link')]");

            if (a == null || a.Attributes["href"] == null)
            {
                return(null);
            }

            info.Id = a.Attributes["href"].Value;

            var img = node.SelectSingleNode(".//img");

            if (img != null && img.Attributes["src"] != null)
            {
                var imgsource = img.Attributes["src"].Value;

                if (!imgsource.StartsWith("http://"))
                {
                    info.ImageUrl = "http://www.svtplay.se" + imgsource;
                }
                else
                {
                    info.ImageUrl = imgsource;
                }
            }

            return(info);
        }
        private async Task <ChannelItemInfo> GetTrailerFromUrl(string url, TrailerType type, CancellationToken cancellationToken)
        {
            var html = await EntryPoint.Instance.GetAndCacheResponse(url, TimeSpan.FromDays(14), cancellationToken)
                       .ConfigureAwait(false);

            var document = new HtmlDocument();

            document.LoadHtml(html);

            var titleElement = document.DocumentNode.SelectSingleNode("//h1");

            var links     = document.DocumentNode.SelectNodes("//a");
            var linksList = links == null ? new List <HtmlNode>() : links.ToList();

            var info = new ChannelItemInfo
            {
                ContentType  = ChannelMediaContentType.MovieExtra,
                ExtraType    = ExtraType.Trailer,
                TrailerTypes = new List <TrailerType> {
                    type
                },
                Id           = url,
                MediaType    = ChannelMediaType.Video,
                Type         = ChannelItemType.Media,
                Name         = titleElement == null ? null : titleElement.InnerText,
                MediaSources = GetMediaInfo(linksList, html),
                DateCreated  = DateTime.UtcNow
            };

            // For older trailers just rely on core image providers
            if (TrailerType != TrailerType.ComingSoonToTheaters)
            {
                info.ImageUrl = null;
            }

            return(info);
        }
Esempio n. 19
0
        public ChannelItemResult GetChannelPlaylists(InternalChannelItemQuery query)
        {
            var playlists = Plugin.Instance.Configuration.Playlists;

            var channelItems = new List <ChannelItemInfo>();

            foreach (var playlist in playlists)
            {
                var item = new ChannelItemInfo()
                {
                    Id   = ChannelFolder.GetUrl(ChannelFolderType.Playlist, playlist.IdentifierId.ToString()),
                    Type = ChannelItemType.Folder,
                    Name = playlist.Name,
                };

                channelItems.Add(item);
            }

            return(new ChannelItemResult()
            {
                Items = channelItems.OrderBy(i => i.Name).ToList(),
                TotalRecordCount = channelItems.Count
            });
        }
Esempio n. 20
0
        private async Task <BaseItem> GetChannelItemEntity(ChannelItemInfo info)
        {
            BaseItem item;

            Guid id;

            if (info.Type == ChannelItemType.Category)
            {
                id   = info.Id.GetMBId(typeof(ChannelCategoryItem));
                item = new ChannelCategoryItem();
            }
            else if (info.MediaType == ChannelMediaType.Audio)
            {
                id   = info.Id.GetMBId(typeof(ChannelCategoryItem));
                item = new ChannelAudioItem();
            }
            else
            {
                id   = info.Id.GetMBId(typeof(ChannelVideoItem));
                item = new ChannelVideoItem();
            }

            item.Id              = id;
            item.Name            = info.Name;
            item.Genres          = info.Genres;
            item.CommunityRating = info.CommunityRating;
            item.OfficialRating  = info.OfficialRating;
            item.Overview        = info.Overview;
            item.People          = info.People;
            item.PremiereDate    = info.PremiereDate;
            item.ProductionYear  = info.ProductionYear;
            item.RunTimeTicks    = info.RunTimeTicks;
            item.ProviderIds     = info.ProviderIds;

            return(item);
        }
Esempio n. 21
0
        private BaseItem GetChannelItemEntity(ChannelItemInfo info, IChannel channelProvider, Guid internalChannelId, BaseItem parentFolder, CancellationToken cancellationToken)
        {
            var parentFolderId = parentFolder.Id;

            BaseItem item;
            bool     isNew;
            bool     forceUpdate = false;

            if (info.Type == ChannelItemType.Folder)
            {
                if (info.FolderType == ChannelFolderType.MusicAlbum)
                {
                    item = GetItemById <MusicAlbum>(info.Id, channelProvider.Name, out isNew);
                }
                else if (info.FolderType == ChannelFolderType.MusicArtist)
                {
                    item = GetItemById <MusicArtist>(info.Id, channelProvider.Name, out isNew);
                }
                else if (info.FolderType == ChannelFolderType.PhotoAlbum)
                {
                    item = GetItemById <PhotoAlbum>(info.Id, channelProvider.Name, out isNew);
                }
                else if (info.FolderType == ChannelFolderType.Series)
                {
                    item = GetItemById <Series>(info.Id, channelProvider.Name, out isNew);
                }
                else if (info.FolderType == ChannelFolderType.Season)
                {
                    item = GetItemById <Season>(info.Id, channelProvider.Name, out isNew);
                }
                else
                {
                    item = GetItemById <Folder>(info.Id, channelProvider.Name, out isNew);
                }
            }
            else if (info.MediaType == ChannelMediaType.Audio)
            {
                if (info.ContentType == ChannelMediaContentType.Podcast)
                {
                    item = GetItemById <AudioBook>(info.Id, channelProvider.Name, out isNew);
                }
                else
                {
                    item = GetItemById <Audio>(info.Id, channelProvider.Name, out isNew);
                }
            }
            else
            {
                if (info.ContentType == ChannelMediaContentType.Episode)
                {
                    item = GetItemById <Episode>(info.Id, channelProvider.Name, out isNew);
                }
                else if (info.ContentType == ChannelMediaContentType.Movie)
                {
                    item = GetItemById <Movie>(info.Id, channelProvider.Name, out isNew);
                }
                else if (info.ContentType == ChannelMediaContentType.Trailer || info.ExtraType == ExtraType.Trailer)
                {
                    item = GetItemById <Trailer>(info.Id, channelProvider.Name, out isNew);
                }
                else
                {
                    item = GetItemById <Video>(info.Id, channelProvider.Name, out isNew);
                }
            }

            var enableMediaProbe = channelProvider is ISupportsMediaProbe;

            if (info.IsLiveStream)
            {
                item.RunTimeTicks = null;
            }

            else if (isNew || !enableMediaProbe)
            {
                item.RunTimeTicks = info.RunTimeTicks;
            }

            if (isNew)
            {
                item.Name              = info.Name;
                item.Genres            = info.Genres.ToArray();
                item.Studios           = info.Studios.ToArray();
                item.CommunityRating   = info.CommunityRating;
                item.Overview          = info.Overview;
                item.IndexNumber       = info.IndexNumber;
                item.ParentIndexNumber = info.ParentIndexNumber;
                item.PremiereDate      = info.PremiereDate;
                item.ProductionYear    = info.ProductionYear;
                item.ProviderIds       = info.ProviderIds;
                item.OfficialRating    = info.OfficialRating;
                item.DateCreated       = info.DateCreated ?? DateTime.UtcNow;
                item.Tags              = info.Tags.ToArray();
                item.OriginalTitle     = info.OriginalTitle;
            }
            else if (info.Type == ChannelItemType.Folder && info.FolderType == ChannelFolderType.Container)
            {
                // At least update names of container folders
                if (item.Name != info.Name)
                {
                    item.Name   = info.Name;
                    forceUpdate = true;
                }
            }

            var hasArtists = item as IHasArtist;

            if (hasArtists != null)
            {
                hasArtists.Artists = info.Artists.ToArray();
            }

            var hasAlbumArtists = item as IHasAlbumArtist;

            if (hasAlbumArtists != null)
            {
                hasAlbumArtists.AlbumArtists = info.AlbumArtists.ToArray();
            }

            var trailer = item as Trailer;

            if (trailer != null)
            {
                if (!info.TrailerTypes.SequenceEqual(trailer.TrailerTypes))
                {
                    _logger.LogDebug("Forcing update due to TrailerTypes {0}", item.Name);
                    forceUpdate = true;
                }
                trailer.TrailerTypes = info.TrailerTypes.ToArray();
            }

            if (info.DateModified > item.DateModified)
            {
                item.DateModified = info.DateModified;
                _logger.LogDebug("Forcing update due to DateModified {0}", item.Name);
                forceUpdate = true;
            }

            // was used for status
            //if (!string.Equals(item.ExternalEtag ?? string.Empty, info.Etag ?? string.Empty, StringComparison.Ordinal))
            //{
            //    item.ExternalEtag = info.Etag;
            //    forceUpdate = true;
            //    _logger.LogDebug("Forcing update due to ExternalEtag {0}", item.Name);
            //}

            if (!internalChannelId.Equals(item.ChannelId))
            {
                forceUpdate = true;
                _logger.LogDebug("Forcing update due to ChannelId {0}", item.Name);
            }
            item.ChannelId = internalChannelId;

            if (!item.ParentId.Equals(parentFolderId))
            {
                forceUpdate = true;
                _logger.LogDebug("Forcing update due to parent folder Id {0}", item.Name);
            }
            item.ParentId = parentFolderId;

            var hasSeries = item as IHasSeries;

            if (hasSeries != null)
            {
                if (!string.Equals(hasSeries.SeriesName, info.SeriesName, StringComparison.OrdinalIgnoreCase))
                {
                    forceUpdate = true;
                    _logger.LogDebug("Forcing update due to SeriesName {0}", item.Name);
                }
                hasSeries.SeriesName = info.SeriesName;
            }

            if (!string.Equals(item.ExternalId, info.Id, StringComparison.OrdinalIgnoreCase))
            {
                forceUpdate = true;
                _logger.LogDebug("Forcing update due to ExternalId {0}", item.Name);
            }
            item.ExternalId = info.Id;

            var channelAudioItem = item as Audio;

            if (channelAudioItem != null)
            {
                channelAudioItem.ExtraType = info.ExtraType;

                var mediaSource = info.MediaSources.FirstOrDefault();
                item.Path = mediaSource == null ? null : mediaSource.Path;
            }

            var channelVideoItem = item as Video;

            if (channelVideoItem != null)
            {
                channelVideoItem.ExtraType = info.ExtraType;

                var mediaSource = info.MediaSources.FirstOrDefault();
                item.Path = mediaSource == null ? null : mediaSource.Path;
            }

            if (!string.IsNullOrEmpty(info.ImageUrl) && !item.HasImage(ImageType.Primary))
            {
                item.SetImagePath(ImageType.Primary, info.ImageUrl);
                _logger.LogDebug("Forcing update due to ImageUrl {0}", item.Name);
                forceUpdate = true;
            }

            if (!info.IsLiveStream)
            {
                if (item.Tags.Contains("livestream", StringComparer.OrdinalIgnoreCase))
                {
                    item.Tags = item.Tags.Except(new[] { "livestream" }, StringComparer.OrdinalIgnoreCase).ToArray();
                    _logger.LogDebug("Forcing update due to Tags {0}", item.Name);
                    forceUpdate = true;
                }
            }
            else
            {
                if (!item.Tags.Contains("livestream", StringComparer.OrdinalIgnoreCase))
                {
                    item.Tags = item.Tags.Concat(new[] { "livestream" }).ToArray();
                    _logger.LogDebug("Forcing update due to Tags {0}", item.Name);
                    forceUpdate = true;
                }
            }

            item.OnMetadataChanged();

            if (isNew)
            {
                _libraryManager.CreateItem(item, parentFolder);

                if (info.People != null && info.People.Count > 0)
                {
                    _libraryManager.UpdatePeople(item, info.People);
                }
            }
            else if (forceUpdate)
            {
                item.UpdateToRepository(ItemUpdateType.None, cancellationToken);
            }

            if ((isNew || forceUpdate) && info.Type == ChannelItemType.Media)
            {
                if (enableMediaProbe && !info.IsLiveStream && item.HasPathProtocol)
                {
                    SaveMediaSources(item, new List <MediaSourceInfo>());
                }
                else
                {
                    SaveMediaSources(item, info.MediaSources);
                }
            }

            if (isNew || forceUpdate || item.DateLastRefreshed == default(DateTime))
            {
                _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.Normal);
            }

            return(item);
        }
Esempio n. 22
0
        private async Task <ChannelItemResult> GetChannelItemsInternal()
        {
            var newItems = new List <ChannelItemInfo>();

            /*return await Task.FromResult(new ChannelItemResult
             * {
             *  Items = newItems.ToList()
             * });*/
            var channel = LibraryManager.GetItemList(new InternalItemsQuery
            {
                Name = Name
            });

            var libraryItems = LibraryManager.GetInternalItemIds(new InternalItemsQuery
            {
                ParentIds = new[] { channel[0].InternalId }
            }).ToList();

            var users = UserManager.Users.Where(u => UserHelper.GetTraktUser(u) != null).ToList();

            // No point going further if we don't have users.
            if (users.Count == 0)
            {
                Logger.Info("No Users returned");
                return(new ChannelItemResult());
            }

            foreach (var user in users)
            {
                Logger.Info(user.Name);
            }
            var adminUser          = users.Single(x => x.Name == "Administrator");
            var adminUserTraktUser = UserHelper.GetTraktUser(adminUser.Id);

            //var listData = client.Users.GetCustomListItemsAsync("movistapp", "horror").Result;
            var listData = await TraktApi.GetTraktUserListItems(adminUserTraktUser, ListConfig.ListUserName, ListConfig.ListName, new CancellationToken());

            Logger.Info($"Count of items on list {listData.Count}");
            //_logger.Info(_jsonSerializer.SerializeToString(data));

            var mediaItems =
                LibraryManager.GetItemList(
                    new InternalItemsQuery()
            {
                IncludeItemTypes = new[] { nameof(Movie) },
                IsVirtualItem    = false,
                OrderBy          = new[]
                {
                    new ValueTuple <string, SortOrder>(ItemSortBy.SeriesSortName, SortOrder.Ascending),
                    new ValueTuple <string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending)
                }
            })
                .ToList();

            Logger.Info($"Count of items in emby {mediaItems.Count}");

            foreach (var movie in mediaItems.OfType <Movie>())
            {
                //Logger.Info($"Movie {movie.Name}");

                if (libraryItems.Contains(movie.InternalId))
                {
                    continue;
                }

                var foundMovie = Match.FindMatch(movie, listData);

                if (foundMovie != null)
                {
                    //Logger.Info($"Movie {movie.Name} found");

                    var embyMove = LibraryManager.GetItemById(movie.Id);
                    if (embyMove != null)
                    {
                        Logger.Info($"Emby Movie {embyMove}");
                        // if(string.IsNullOrEmpty(embyMove.Path)){
                        var newMovie = new ChannelItemInfo
                        {
                            Name         = embyMove.Name,
                            ImageUrl     = embyMove.PrimaryImagePath,
                            Id           = embyMove.Id.ToString(),
                            Type         = ChannelItemType.Media,
                            ContentType  = ChannelMediaContentType.Movie,
                            MediaType    = ChannelMediaType.Video,
                            IsLiveStream = false,
                            MediaSources = new List <MediaSourceInfo>
                            {
                                new ChannelMediaInfo
                                {
                                    Path = embyMove.Path, Protocol = MediaProtocol.File
                                }.ToMediaSource()
                            },
                            OriginalTitle = embyMove.OriginalTitle
                        };
                        newItems.Add(newMovie);
                        // }
                    }
                }
                else
                {
                    //Logger.Debug($"Movie {movie.Name} not found");
                }
            }

            Logger.Info($"Count of items in List to add {newItems.Count}");


            return(await Task.FromResult(new ChannelItemResult
            {
                Items = newItems.ToList()
            }));
        }
        /// <summary>
        ///     Get list of qualities
        /// </summary>
        /// <param name="sport">Selected sports</param>
        /// <param name="date">Selected date</param>
        /// <param name="gameId">Selected game id</param>
        /// <param name="feedId">Selected feed id</param>
        /// <returns></returns>
        private async Task <ChannelItemResult> GetQualityItems(string sport, string date, string gameId, string feedId)
        {
            _logger.Debug($"[GetQualityItems] Sport: {sport}, Date: {date}, GameId: {gameId}, FeedId: {feedId}");

            var gameList = await GetGameListAsync(sport, date).ConfigureAwait(false);

            if (gameList == null)
            {
                return(new ChannelItemResult());
            }

            // Locate game
            var foundGame = gameList.FirstOrDefault(g => g.GameId == gameId);

            if (foundGame == null)
            {
                return(new ChannelItemResult());
            }

            // Locate feed
            var foundFeed = foundGame.Feeds.FirstOrDefault(f => f.Id == feedId);

            if (foundFeed == null)
            {
                return(new ChannelItemResult());
            }

            var gameDateTime = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture);

            var itemInfoList = new List <ChannelItemInfo>();

            var(status, response) = await _powerSportsApi.GetPlaylistUrlAsync(
                sport,
                gameDateTime,
                feedId,
                PluginConfiguration.Cdn
                ).ConfigureAwait(false);

            if (!status)
            {
                return(new ChannelItemResult
                {
                    Items = new List <ChannelItemInfo>
                    {
                        new ChannelItemInfo
                        {
                            Id = $"{sport}_{date}_{gameId}_{feedId}_null_null",
                            Name = response,
                            ContentType = ChannelMediaContentType.Clip,
                            Type = ChannelItemType.Media,
                            MediaType = ChannelMediaType.Photo
                        }
                    },
                    TotalRecordCount = 1
                });
            }



            foreach (var quality in PluginConfiguration.FeedQualities)
            {
                var id       = $"{sport}_{date}_{gameId}_{feedId}_{quality.Key}";
                var itemInfo = new ChannelItemInfo
                {
                    Id           = id,
                    Name         = quality.Value.Title,
                    ContentType  = ChannelMediaContentType.Movie,
                    Type         = ChannelItemType.Media,
                    MediaType    = ChannelMediaType.Video,
                    ImageUrl     = "",
                    IsLiveStream = true
                };

                itemInfoList.Add(itemInfo);
            }

            return(new ChannelItemResult
            {
                Items = itemInfoList,
                TotalRecordCount = itemInfoList.Count
            });
        }
        public async Task <IEnumerable <ChannelItemInfo> > GetChannelItems(CancellationToken cancellationToken)
        {
            var hdTrailers = await TrailerListingDownloader.GetTrailerList(_logger,
                                                                           true,
                                                                           cancellationToken)
                             .ConfigureAwait(false);

            var sdTrailers = await TrailerListingDownloader.GetTrailerList(_logger,
                                                                           false,
                                                                           cancellationToken)
                             .ConfigureAwait(false);

            var list = new List <ChannelItemInfo>();

            foreach (var i in hdTrailers)
            {
                // Avoid duplicates
                if (list.Any(l => string.Equals(i.Name, l.Name, StringComparison.OrdinalIgnoreCase)))
                {
                    continue;
                }

                var channelItem = new ChannelItemInfo
                {
                    CommunityRating  = i.CommunityRating,
                    ContentType      = ChannelMediaContentType.Trailer,
                    Genres           = i.Genres,
                    ImageUrl         = i.HdImageUrl ?? i.ImageUrl,
                    IsInfiniteStream = false,
                    MediaType        = ChannelMediaType.Video,
                    Name             = i.Name,
                    OfficialRating   = i.OfficialRating,
                    Overview         = i.Overview,
                    People           = i.People,
                    Type             = ChannelItemType.Media,
                    Id             = i.TrailerUrl.GetMD5().ToString("N"),
                    PremiereDate   = i.PremiereDate,
                    ProductionYear = i.ProductionYear,
                    Studios        = i.Studios,
                    RunTimeTicks   = i.RunTimeTicks,
                    DateCreated    = i.PostDate,

                    MediaSources = new List <ChannelMediaInfo>
                    {
                        GetMediaInfo(i, true)
                    }
                };

                var sdVersion = sdTrailers
                                .FirstOrDefault(l => string.Equals(i.Name, l.Name, StringComparison.OrdinalIgnoreCase));

                if (sdVersion != null)
                {
                    channelItem.MediaSources.Add(GetMediaInfo(sdVersion, false));
                }

                list.Add(channelItem);
            }

            return(list);
        }
Esempio n. 25
0
        public async Task <ChannelItemResult> GetChannelItemResult(IUserManager userManager,
                                                                   ILibraryManager libraryManager, TraktChannel channelToConfigure, ILogger logger, TraktApi traktApi,
                                                                   CancellationToken cancellationToken)
        {
            //await Plugin.Instance.SchedTaskResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

            try
            {
                var users = userManager.Users;

                var channels = libraryManager.GetItemList(new InternalItemsQuery
                {
                    Recursive        = true,
                    IncludeItemTypes = new[] { "Channel" }
                }).Where(x => !string.IsNullOrEmpty(x.Name)).ToList();


                var currentChannel = channels.First(x => x.Name == channelToConfigure.ChannelName).Id.ToString()
                                     .Replace("-", string.Empty);

                if (!channelToConfigure.Enabled)
                {
                    foreach (var user in users)
                    {
                        user.Policy.EnableAllChannels = false;

                        var enabledChannels = user.Policy.EnabledChannels != null
                            ? user.Policy.EnabledChannels.ToList()
                            : new List <string>();

                        var disabledChannels = user.Policy.BlockedChannels != null
                            ? user.Policy.BlockedChannels.ToList()
                            : new List <string>();

                        //Logger.Info("Enabled " + string.Join(",", enabledChannels.Select(x => x.ToString()).ToArray()));
                        //Logger.Info("Blocked " + string.Join(",", disabledChannels.Select(x => x.ToString()).ToArray()));

                        if (!disabledChannels.Contains(currentChannel))
                        {
                            disabledChannels.Add(currentChannel);
                        }
                        //Logger.Info("Added To Disabled " + currentChannel);

                        if (enabledChannels.Any())
                        {
                            if (enabledChannels.Contains(currentChannel))
                            {
                                enabledChannels.Remove(currentChannel);
                            }
                        }
                        else
                        {
                            foreach (var channel in channels.Where(x => x.Name != channelToConfigure.ChannelName))
                            {
                                enabledChannels.Add(channel.Id.ToString().Replace("-", string.Empty));
                            }
                        }

                        user.Policy.EnabledChannels = enabledChannels.ToArray();
                        user.Policy.BlockedChannels = disabledChannels.ToArray();

                        logger.Info("Enabled " + string.Join(",", enabledChannels.Select(x => x.ToString()).ToArray()));
                        logger.Info("Blocked " +
                                    string.Join(",", disabledChannels.Select(x => x.ToString()).ToArray()));

                        userManager.UpdateUser(user);
                    }
                }
                else
                {
                    foreach (var user in users)
                    {
                        user.Policy.EnableAllChannels = false;

                        var enabledChannels = user.Policy.EnabledChannels != null
                            ? user.Policy.EnabledChannels.ToList()
                            : new List <string>();

                        var disabledChannels = user.Policy.BlockedChannels != null
                            ? user.Policy.BlockedChannels.ToList()
                            : new List <string>();

                        //Logger.Info("Enabled " + string.Join(",", enabledChannels.Select(x => x.ToString()).ToArray()));
                        //Logger.Info("Blocked " + string.Join(",", disabledChannels.Select(x => x.ToString()).ToArray()));

                        if (disabledChannels.Contains(currentChannel))
                        {
                            disabledChannels.Remove(currentChannel);
                        }

                        if (enabledChannels.Any())
                        {
                            if (enabledChannels.Contains(currentChannel))
                            {
                                continue;
                            }

                            enabledChannels.Add(currentChannel);
                        }
                        else
                        {
                            foreach (var channel in channels)
                            {
                                enabledChannels.Add(channel.Id.ToString().Replace("-", string.Empty));
                            }
                        }

                        user.Policy.EnabledChannels = enabledChannels.ToArray();
                        user.Policy.BlockedChannels = disabledChannels.ToArray();

                        logger.Info("Enabled " + string.Join(",", enabledChannels.Select(x => x.ToString()).ToArray()));
                        logger.Info("Blocked " +
                                    string.Join(",", disabledChannels.Select(x => x.ToString()).ToArray()));

                        userManager.UpdateUser(user);
                    }
                }

                var newItems = new List <ChannelItemInfo>();

                if (channelToConfigure.Enabled == false)
                {
                    return(await Task.FromResult(new ChannelItemResult
                    {
                        Items = newItems.ToList()
                    }));
                }

                if (string.IsNullOrEmpty(Plugin.Instance.PluginConfiguration.Pin) &&
                    string.IsNullOrEmpty(Plugin.Instance.PluginConfiguration.TraktUser.AccessToken))
                {
                    return(await Task.FromResult(new ChannelItemResult
                    {
                        Items = newItems.ToList()
                    }));
                }

                var channelLibraryItem = libraryManager.GetItemList(new InternalItemsQuery
                {
                    Name = channelToConfigure.ChannelName
                });

                logger.Info(channelToConfigure.ChannelName);
                logger.Info("Found " + channelLibraryItem.Length.ToString());


                var libraryItems = libraryManager.GetInternalItemIds(new InternalItemsQuery
                {
                    ParentIds = new[] { channelLibraryItem[0].InternalId }
                }).ToList();

                if (!string.IsNullOrEmpty(Plugin.Instance.PluginConfiguration.Pin))
                {
                    Plugin.Instance.PluginConfiguration.TraktUser.PIN = Plugin.Instance.PluginConfiguration.Pin;
                }

                var listData = await traktApi.GetTraktUserListItems(Plugin.Instance.PluginConfiguration.TraktUser,
                                                                    channelToConfigure.TraktListUserName, channelToConfigure.TraktListName, new CancellationToken());

                logger.Info($"Count of items on list {listData.Count}");

                var mediaItems =
                    libraryManager.GetItemList(
                        new InternalItemsQuery
                {
                    IncludeItemTypes = new[] { nameof(Movie) },
                    IsVirtualItem    = false,
                    OrderBy          = new[]
                    {
                        new ValueTuple <string, SortOrder>(ItemSortBy.SeriesSortName, SortOrder.Ascending),
                        new ValueTuple <string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending)
                    }
                })
                    .ToList();

                logger.Info($"Count of items in emby {mediaItems.Count}");

                var foundMovies = new List <string>();
                //var notFoundMovies = new List<string>();

                logger.Info("Internal Ids: " + string.Join(", ", libraryItems.Select(x => x.ToString()).ToArray()));

                foreach (var movie in mediaItems.OfType <Movie>().OrderBy(x => x.DateCreated))
                {
                    if (channels.Select(x => x.ParentId).Contains(movie.Parent.ParentId))
                    {
                        continue;
                    }

                    //Logger.Info($"Movie {movie.Name}");

                    //logger.Info(movie.InternalId.ToString());

                    if (libraryItems.Contains(movie.InternalId))
                    {
                        continue;
                    }

                    var foundMovie = Match.FindMatch(movie, listData);

                    if (foundMovie != null)
                    {
                        //Logger.Info($"Movie {movie.Name} found");

                        var embyMove = libraryManager.GetItemById(movie.Id);
                        if (embyMove != null)
                        {
                            foundMovies.Add(embyMove.Name);
                            //logger.Info($"Emby Movie {embyMove} found!");
                            // if(string.IsNullOrEmpty(embyMove.Path)){
                            var newMovie = new ChannelItemInfo
                            {
                                Name         = embyMove.Name,
                                ImageUrl     = embyMove.PrimaryImagePath,
                                Id           = embyMove.Id.ToString(),
                                Type         = ChannelItemType.Media,
                                ContentType  = ChannelMediaContentType.Movie,
                                MediaType    = ChannelMediaType.Video,
                                IsLiveStream = false,
                                MediaSources = new List <MediaSourceInfo>
                                {
                                    new ChannelMediaInfo
                                    {
                                        Path = embyMove.Path, Protocol = MediaProtocol.File
                                    }.ToMediaSource()
                                },
                                OriginalTitle = embyMove.OriginalTitle
                            };
                            if (!newItems.Any(x => x.Id == embyMove.Id.ToString()))
                            {
                                newItems.Add(newMovie);
                            }

                            // }
                        }
                    }
                }

                logger.Info($"Count of items in List to add {newItems.Count}");

                var distinctItems = newItems.Distinct().ToList();

                logger.Info($"Count of distinct items in List to add {distinctItems.Count}");

                logger.Info("Found Movies: " + string.Join(", ", foundMovies.Select(x => x.ToString()).ToArray()));
                //logger.Info("Not Found Movies: " + string.Join(", ", notFoundMovies.Select(x => x.ToString()).ToArray()));

                logger.Info(
                    "Not Found Movies: " + string.Join(", ", distinctItems.Select(x => x.Id.ToString()).ToArray()));


                return(await Task.FromResult(new ChannelItemResult
                {
                    Items = distinctItems.ToList()
                }));
            }
            finally
            {
                //Plugin.Instance.SchedTaskResourcePool.Release();
            }
        }
Esempio n. 26
0
        private async Task <ChannelItemResult> GetChannels(CancellationToken cancellationToken)
        {
            var items = new List <ChannelItemInfo>();

            if (!Plugin.Instance.Registration.IsValid)
            {
                Plugin.Logger.Warn("PodCasts trial has expired.");
                await _notificationManager.SendNotification(new NotificationRequest
                {
                    Description    = "PodCasts trial has expired.",
                    Date           = DateTime.Now,
                    Level          = NotificationLevel.Warning,
                    SendToUserMode = SendToUserType.Admins
                }, cancellationToken);

                return(new ChannelItemResult
                {
                    Items = items.ToList()
                });
            }

            foreach (var feedUrl in Plugin.Instance.Configuration.Feeds)
            {
                try
                {
                    var options = new HttpRequestOptions
                    {
                        Url = feedUrl,
                        CancellationToken = cancellationToken,

                        // Seeing some deflate stream errors
                        EnableHttpCompression  = false,
                        EnableDefaultUserAgent = true
                    };

                    using (var stream = await _httpClient.Get(options).ConfigureAwait(false))
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            XDocument document = XDocument.Parse(reader.ReadToEnd());
                            var       root     = document.Root.Element("channel");

                            var item = new ChannelItemInfo
                            {
                                Name     = GetValue(root, "title"),
                                Overview = GetValue(root, "description"),
                                Id       = feedUrl,
                                Type     = ChannelItemType.Folder
                            };

                            if (!string.IsNullOrWhiteSpace(item.Name))
                            {
                                _logger.Debug("Found rss channel: {0}", item.Name);

                                var imageElement = root.Element("image");
                                if (imageElement != null)
                                {
                                    item.ImageUrl = GetValue(imageElement, "url");
                                }

                                items.Add(item);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error getting feed", ex);
                }
            }
            return(new ChannelItemResult
            {
                Items = items.ToList()
            });
        }
Esempio n. 27
0
        private async Task <BaseItem> GetChannelItemEntity(ChannelItemInfo info, IChannel channelProvider, Guid internalChannelId, CancellationToken cancellationToken)
        {
            BaseItem item;
            Guid     id;
            var      isNew = false;

            var idToHash = GetIdToHash(info.Id, channelProvider);

            if (info.Type == ChannelItemType.Folder)
            {
                id = idToHash.GetMBId(typeof(ChannelFolderItem));

                item = _libraryManager.GetItemById(id) as ChannelFolderItem;

                if (item == null)
                {
                    isNew = true;
                    item  = new ChannelFolderItem();
                }
            }
            else if (info.MediaType == ChannelMediaType.Audio)
            {
                id = idToHash.GetMBId(typeof(ChannelAudioItem));

                item = _libraryManager.GetItemById(id) as ChannelAudioItem;

                if (item == null)
                {
                    isNew = true;
                    item  = new ChannelAudioItem();
                }
            }
            else
            {
                id = idToHash.GetMBId(typeof(ChannelVideoItem));

                item = _libraryManager.GetItemById(id) as ChannelVideoItem;

                if (item == null)
                {
                    isNew = true;
                    item  = new ChannelVideoItem();
                }
            }

            item.Id           = id;
            item.RunTimeTicks = info.RunTimeTicks;

            if (isNew)
            {
                item.Name              = info.Name;
                item.Genres            = info.Genres;
                item.Studios           = info.Studios;
                item.CommunityRating   = info.CommunityRating;
                item.OfficialRating    = info.OfficialRating;
                item.Overview          = info.Overview;
                item.IndexNumber       = info.IndexNumber;
                item.ParentIndexNumber = info.ParentIndexNumber;
                item.People            = info.People;
                item.PremiereDate      = info.PremiereDate;
                item.ProductionYear    = info.ProductionYear;
                item.ProviderIds       = info.ProviderIds;

                item.DateCreated = info.DateCreated.HasValue ?
                                   info.DateCreated.Value :
                                   DateTime.UtcNow;
            }

            var channelItem = (IChannelItem)item;

            channelItem.OriginalImageUrl = info.ImageUrl;
            channelItem.ExternalId       = info.Id;
            channelItem.ChannelId        = internalChannelId.ToString("N");
            channelItem.ChannelItemType  = info.Type;

            if (isNew)
            {
                channelItem.Tags = info.Tags;
            }

            var channelMediaItem = item as IChannelMediaItem;

            if (channelMediaItem != null)
            {
                channelMediaItem.ContentType         = info.ContentType;
                channelMediaItem.ChannelMediaSources = info.MediaSources;

                var mediaSource = info.MediaSources.FirstOrDefault();

                item.Path = mediaSource == null ? null : mediaSource.Path;

                item.DisplayMediaType = channelMediaItem.ContentType.ToString();
            }

            if (isNew)
            {
                await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);

                _libraryManager.RegisterItem(item);
            }

            return(item);
        }
Esempio n. 28
0
        private async Task <ChannelItemInfo> GetTrailerFromUrl(string url, TrailerType type, CancellationToken cancellationToken)
        {
            var html = await EntryPoint.Instance.GetAndCacheResponse(url, TimeSpan.FromDays(14), cancellationToken)
                       .ConfigureAwait(false);

            var document = new HtmlDocument();

            document.LoadHtml(html);

            var titleElement = document.DocumentNode.SelectSingleNode("//title");
            var name         = titleElement == null ? string.Empty : (titleElement.InnerText ?? string.Empty);

            name = name.Replace("Movie Trailer", string.Empty, StringComparison.OrdinalIgnoreCase)
                   .Replace("Movie-List.com", string.Empty, StringComparison.OrdinalIgnoreCase)
                   .Replace("Movie-List", string.Empty, StringComparison.OrdinalIgnoreCase)
                   .Replace("|", string.Empty, StringComparison.OrdinalIgnoreCase)
                   .Trim();

            var posterElement = document.DocumentNode.SelectSingleNode("//a[@rel='prettyPhoto[posters]']//img");

            if (posterElement == null)
            {
                posterElement = document.DocumentNode.SelectSingleNode("//section[@class='content-box']//img");
            }
            var imageSrc = posterElement == null ? null : posterElement.GetAttributeValue("src", null);

            var links     = document.DocumentNode.SelectNodes("//a");
            var linksList = links == null ? new List <HtmlNode>() : links.ToList();

            var info = new ChannelItemInfo
            {
                ContentType  = ChannelMediaContentType.MovieExtra,
                ExtraType    = ExtraType.Trailer,
                TrailerTypes = new List <TrailerType> {
                    type
                },
                Id           = url,
                MediaType    = ChannelMediaType.Video,
                Type         = ChannelItemType.Media,
                Name         = name,
                ImageUrl     = string.IsNullOrWhiteSpace(imageSrc) ? null : (BaseUrl + imageSrc.TrimStart('/')),
                MediaSources = GetMediaInfo(linksList, html),
                DateCreated  = DateTime.UtcNow
            };

            // For older trailers just rely on core image providers
            if (type != TrailerType.ComingSoonToTheaters)
            {
                info.ImageUrl = null;
            }

            if (random.Next(1, 10) < 2)
            {
                info.TrailerTypes.Add(TrailerType.ComingSoonToStreaming);
            }

            var metadataElements = document.DocumentNode.SelectNodes("//*[contains(@class,'cast-meta')]");

            if (metadataElements != null)
            {
                foreach (var elem in metadataElements)
                {
                    FillMetadataFromElement(elem, info);
                }
            }

            var imdbId = GetImdbId(linksList);

            if (!string.IsNullOrWhiteSpace(imdbId))
            {
                info.SetProviderId(MetadataProviders.Imdb, imdbId);
            }

            return(info);
        }
Esempio n. 29
0
        private async Task FillMetadata(ChannelItemInfo item, List <TrailerMetadata> metadataList, CancellationToken cancellationToken)
        {
            var             imdbId   = item.GetProviderId(MetadataProviders.Imdb);
            TrailerMetadata metadata = null;

            if (!string.IsNullOrWhiteSpace(imdbId))
            {
                metadata = metadataList.FirstOrDefault(i => string.Equals(imdbId, i.GetProviderId(MetadataProviders.Imdb), StringComparison.OrdinalIgnoreCase));
            }

            if (metadata == null)
            {
                var tmdbId = item.GetProviderId(MetadataProviders.Tmdb);

                if (!string.IsNullOrWhiteSpace(tmdbId))
                {
                    metadata = metadataList.FirstOrDefault(i => string.Equals(tmdbId, i.GetProviderId(MetadataProviders.Tmdb), StringComparison.OrdinalIgnoreCase));
                }
            }

            if (metadata == null)
            {
                var searchResults =
                    await _providerManager.GetRemoteSearchResults <Movie, MovieInfo>(new RemoteSearchQuery <MovieInfo>
                {
                    IncludeDisabledProviders = true,
                    SearchInfo = new MovieInfo
                    {
                        Name        = item.Name,
                        Year        = item.ProductionYear,
                        ProviderIds = item.ProviderIds
                    }
                }, cancellationToken).ConfigureAwait(false);

                var result = searchResults.FirstOrDefault();

                if (result != null)
                {
                    metadata = new TrailerMetadata
                    {
                        Name           = result.Name,
                        PremiereDate   = result.PremiereDate,
                        ProductionYear = result.ProductionYear,
                        ProviderIds    = result.ProviderIds
                    };

                    metadataList.Add(metadata);
                }
            }

            if (metadata != null)
            {
                item.Name           = metadata.Name ?? item.Name;
                item.ProductionYear = metadata.ProductionYear ?? item.ProductionYear;
                item.PremiereDate   = metadata.PremiereDate ?? item.PremiereDate;

                // Merge provider id's
                foreach (var id in metadata.ProviderIds)
                {
                    item.SetProviderId(id.Key, id.Value);
                }
            }
        }
Esempio n. 30
0
        public async Task <ChannelItemResult> GetItems(bool inChannel, InternalChannelItemQuery query, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var config = await BlurNTasks.CheckIfResetDatabaseRequested(cancellationToken, _json, _appPaths, _fileSystem).ConfigureAwait(false);

            if (inChannel)
            {
                Plugin.DebugLogger("Entered BlurN channel list");
            }

            User user = query.UserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(query.UserId);

            Dictionary <string, BaseItem> libDict = (user == null) ? new Dictionary <string, BaseItem>() : Library.BuildLibraryDictionary(cancellationToken, _libraryManager, new InternalItemsQuery()
            {
                HasAnyProviderId = new[] { "Imdb" },
                User             = user,
                //SourceTypes = new SourceType[] { SourceType.Library }
            });

            Plugin.DebugLogger($"Found {libDict.Count} items in movies library");

            BlurNItems items    = new BlurNItems();
            string     dataPath = Path.Combine(_appPaths.PluginConfigurationsPath, "MediaBrowser.Channels.BlurN.Data.json");

            if (_fileSystem.FileExists(dataPath))
            {
                items.List = _json.DeserializeFromFile <List <BlurNItem> >(dataPath);
            }

            if (inChannel)
            {
                Plugin.DebugLogger("Retrieved items");
            }

            if (items == null)
            {
                if (inChannel)
                {
                    Plugin.DebugLogger("Items is null, set to new list");
                }
                items = new BlurNItems();
                Plugin.Instance.SaveConfiguration();
            }

            for (int i = 0; i < items.List.Count; i++)
            {
                BlurNItem blurNItem = items.List[i];

                BaseItem libraryItem;
                bool     foundInLibrary = libDict.TryGetValue(blurNItem.ImdbId, out libraryItem);
                if (foundInLibrary)
                {
                    if (config.HidePlayedMovies && user != null && libraryItem.IsPlayed(user))
                    {
                        items.List.RemoveAt(i);
                        i--;
                        if (inChannel)
                        {
                            Plugin.DebugLogger($"Hiding movie '{blurNItem.Title}' from BlurN channel list as watched by user");
                        }
                    }
                    else if (!config.AddItemsAlreadyInLibrary)
                    {
                        items.List.RemoveAt(i);
                        i--;
                        if (inChannel)
                        {
                            Plugin.DebugLogger($"Hiding movie '{blurNItem.Title}' from BlurN channel list as availabile in library");
                        }
                    }
                    else
                    {
                        blurNItem.LibraryItem = libraryItem;
                    }
                }
            }

            switch (query.SortBy)
            {
            case ChannelItemSortField.Name:
                if (query.SortDescending)
                {
                    items.List.OrderByDescending(i => i.Title);
                }
                else
                {
                    items.List.OrderBy(i => i.Title);
                }
                break;

            case ChannelItemSortField.DateCreated:
                if (query.SortDescending)
                {
                    items.List.OrderByDescending(i => i.BluRayReleaseDate);
                }
                else
                {
                    items.List.OrderBy(i => i.BluRayReleaseDate);
                }
                break;

            case ChannelItemSortField.CommunityRating:
                if (query.SortDescending)
                {
                    items.List.OrderByDescending(i => i.ImdbRating).ThenByDescending(i => i.ImdbVotes);
                }
                else
                {
                    items.List.OrderBy(i => i.ImdbRating).ThenBy(i => i.ImdbVotes);
                }
                break;

            case ChannelItemSortField.PremiereDate:
                if (query.SortDescending)
                {
                    items.List.OrderByDescending(i => i.Released);
                }
                else
                {
                    items.List.OrderBy(i => i.Released);
                }
                break;

            case ChannelItemSortField.Runtime:
                if (query.SortDescending)
                {
                    items.List.OrderByDescending(i => i.RuntimeTicks);
                }
                else
                {
                    items.List.OrderBy(i => i.RuntimeTicks);
                }
                break;

            default:
                if (query.SortDescending)
                {
                    items.List.Reverse();
                }
                break;
            }

            BlurNItems showList = new BlurNItems();

            if (query.StartIndex.HasValue && query.Limit.HasValue && query.Limit.Value > 0)
            {
                int index = query.StartIndex.Value;
                int limit = query.Limit.Value;

                if (items.List.Count < index + limit)
                {
                    limit = items.List.Count - index;
                }

                showList.List = items.List.GetRange(index, limit);
                if (inChannel)
                {
                    Plugin.DebugLogger($"Showing range with index {index} and limit {limit}");
                }
            }
            else
            {
                showList.List = items.List;
                if (inChannel)
                {
                    Plugin.DebugLogger("Showing full list");
                }
            }

            ChannelItemResult result = new ChannelItemResult()
            {
                TotalRecordCount = items.List.Count
            };

            for (int i = 0; i < showList.List.Count; i++)
            {
                BlurNItem blurNItem = showList.List[i];

                if (inChannel)
                {
                    Plugin.DebugLogger($"Showing movie '{blurNItem.Title}' to BlurN channel list");
                }

                var directors = CSVParse(blurNItem.Director);
                var writers   = CSVParse(blurNItem.Writer);
                var actors    = CSVParse(blurNItem.Actors);

                var people = new List <PersonInfo>();
                foreach (var director in directors)
                {
                    people.Add(new PersonInfo()
                    {
                        Name = director, Role = "Director"
                    });
                }
                foreach (var writer in writers)
                {
                    people.Add(new PersonInfo()
                    {
                        Name = writer, Role = "Writer"
                    });
                }
                foreach (string actor in actors)
                {
                    people.Add(new PersonInfo()
                    {
                        Name = actor, Role = "Actor"
                    });
                }

                var genres = CSVParse(blurNItem.Genre).ToList();

                var cii = new ChannelItemInfo()
                {
                    Id              = $"{config.ChannelRefreshCount.ToString()}-{blurNItem.ImdbId}",
                    IndexNumber     = i,
                    CommunityRating = (float)blurNItem.ImdbRating,
                    ContentType     = ChannelMediaContentType.Movie,
                    DateCreated     = blurNItem.BluRayReleaseDate,
                    Genres          = genres,
                    ImageUrl        = (blurNItem.Poster == "N/A") ? null : blurNItem.Poster,
                    MediaType       = ChannelMediaType.Video,
                    Name            = blurNItem.Title,
                    OfficialRating  = (blurNItem.Rated == "N/A") ? null : blurNItem.Rated,
                    Overview        = (blurNItem.Plot == "N/A") ? null : blurNItem.Plot,
                    People          = people,
                    PremiereDate    = blurNItem.Released,
                    ProductionYear  = blurNItem.Released.Year,
                    RunTimeTicks    = blurNItem.RuntimeTicks,
                    Type            = ChannelItemType.Media,
                    DateModified    = blurNItem.BluRayReleaseDate,
                    IsLiveStream    = false
                };

                cii.SetProviderId(MetadataProviders.Imdb, blurNItem.ImdbId);
                if (blurNItem.TmdbId.HasValue)
                {
                    cii.SetProviderId(MetadataProviders.Tmdb, blurNItem.TmdbId.Value.ToString());
                }

                if (blurNItem.LibraryItem != null)
                {
                    var mediaStreams = _mediaSourceManager.GetMediaStreams(blurNItem.LibraryItem.InternalId).ToList();

                    var audioStream = mediaStreams.FirstOrDefault(ms => ms.Type == MediaStreamType.Audio && ms.IsDefault);
                    var videoStream = mediaStreams.FirstOrDefault(ms => ms.Type == MediaStreamType.Video && ms.IsDefault);

                    ChannelMediaInfo cmi = new ChannelMediaInfo()
                    {
                        Path               = _libraryManager.GetPathAfterNetworkSubstitution(blurNItem.LibraryItem.Path, blurNItem.LibraryItem),
                        Container          = blurNItem.LibraryItem.Container,
                        RunTimeTicks       = blurNItem.LibraryItem.RunTimeTicks,
                        SupportsDirectPlay = true,
                        Id       = blurNItem.LibraryItem.Id.ToString(),
                        Protocol = Model.MediaInfo.MediaProtocol.File
                    };

                    if (audioStream != null)
                    {
                        cmi.AudioBitrate    = audioStream.BitRate;
                        cmi.AudioChannels   = audioStream.Channels;
                        cmi.AudioCodec      = audioStream.Codec;
                        cmi.AudioSampleRate = audioStream.SampleRate;
                    }
                    if (videoStream != null)
                    {
                        cmi.Framerate    = videoStream.RealFrameRate;
                        cmi.Height       = videoStream.Height;
                        cmi.IsAnamorphic = videoStream.IsAnamorphic;
                        cmi.VideoBitrate = videoStream.BitRate;
                        cmi.VideoCodec   = videoStream.Codec;
                        if (videoStream.Level.HasValue)
                        {
                            cmi.VideoLevel = (float)videoStream.Level.Value;
                        }
                        cmi.VideoProfile = videoStream.Profile;
                        cmi.Width        = videoStream.Width;
                    }
                    Plugin.DebugLogger($"Linked movie {blurNItem.Title} to library. Path: {blurNItem.LibraryItem.Path}, Substituted Path: {cmi.Path}");
                    cii.MediaSources = new List <MediaSourceInfo>()
                    {
                        cmi.ToMediaSource()
                    };
                }

                result.Items.Add(cii);

                if (inChannel)
                {
                    Plugin.DebugLogger($"Added movie '{blurNItem.Title}' to BlurN channel list");
                }
            }

            if (inChannel)
            {
                Plugin.DebugLogger($"Set total record count ({(int)result.TotalRecordCount})");
            }

            return(result);
        }