private void saveMetadata(string fullpath, YoutubeVideoItem item)
        {
            YoutubeItemMetadata metadata = item.Metadata as YoutubeItemMetadata;

            MediaFileItem fileItem = MediaFileItem.Factory.create(fullpath);

            fileItem.EnterWriteLock();
            try
            {
                YoutubeItemMetadata saveMetadata = metadata.Clone() as YoutubeItemMetadata;

                saveMetadata.Location = fullpath;
                ItemProgress          = 0;
                ItemInfo = "Saving metadata: " + item.Name;

                MetadataFactory.write(saveMetadata, MetadataFactory.WriteOptions.WRITE_TO_DISK, this);

                ItemProgress = 100;
                InfoMessages.Add("Finished saving metadata: " + fullpath);
            }
            finally
            {
                fileItem.ExitWriteLock();
            }

            /*fileItem.EnterUpgradeableReadLock();
             * fileItem.readMetadata_URLock(MetadataFactory.ReadOptions.READ_FROM_DISK, CancellationToken);
             * fileItem.ExitUpgradeableReadLock();*/
        }
        protected override String getKey(MediaItem item)
        {
            String key = "";

            if (item is YoutubeVideoItem)
            {
                YoutubeVideoItem videoItem = item as YoutubeVideoItem;

                YoutubeItemMetadata metadata = item.Metadata as YoutubeItemMetadata;

                if (metadata.Height >= 2160)
                {
                    key += "4";
                }
                else if (metadata.Height >= 1080)
                {
                    key += "0";
                }

                if (videoItem.IsEmbeddedOnly || !videoItem.HasPlayableStreams)
                {
                    key += "1";
                }
            }
            else if (item is YoutubeChannelItem)
            {
                key += "2";
            }
            else if (item is YoutubePlaylistItem)
            {
                key += "3";
            }

            return(key);
        }
示例#3
0
        public static List <YoutubeVideoItem> GetVideos(List <string> videoIds)
        {
            List <YoutubeVideoItem> videos        = new List <YoutubeVideoItem>();
            HttpCacheProvider       cacheProvider = new HttpCacheProvider();

            // Todo: Return result object with status message and result

            try
            {
                var youTube = GetYouTubeService();

                //Build up request
                var videoRequest = youTube.PlaylistItems.List("snippet,contentDetails, statistics");
                videoRequest.MaxResults = _noPerPage;                       //3 per page

                foreach (var videoId in videoIds)
                {
                    var cacheItem = cacheProvider.GetItem <YoutubeVideoItem>(videoId);

                    if (cacheItem != null)
                    {
                        videos.Add(cacheItem);
                        continue;
                    }

                    //Perform request
                    VideoListResponse videoResponse = GetVideo(videoId);

                    if (videoResponse == null && !videoResponse.Items.Any())
                    {
                        continue;
                    }

                    var videoItem = new YoutubeVideoItem()
                    {
                        Title       = videoResponse.Items.FirstOrDefault().Snippet.Title,
                        Id          = videoResponse.Items.FirstOrDefault().Id,
                        PublishDate = videoResponse.Items.FirstOrDefault().Snippet.PublishedAt,
                        Image       = videoResponse.Items.FirstOrDefault().Snippet.Thumbnails.High.Url,
                        Url         = string.Format("https://www.youtube.com/embed/{0}?rel=0", videoResponse.Items.FirstOrDefault().Id),
                        ExternalUrl = string.Format("https://www.youtube.com/watch?v={0}", videoResponse.Items.FirstOrDefault().Id),
                        WatchCount  = videoResponse.Items.FirstOrDefault().Statistics.ViewCount.ToString()
                    };

                    videos.Add(videoItem);

                    cacheProvider.InsertItem <YoutubeVideoItem>(videoId, videoItem, TimeSpan.FromHours(1));
                }
            }
            catch (Exception ex)
            {
                // Todo: Implement error handling
            }


            //Return the list of videos we find
            return(videos);
        }
示例#4
0
        private int?GetLength(YoutubeVideoItem video)
        {
            if (video.ContentDetails == null || string.IsNullOrEmpty(video.ContentDetails.Duration))
            {
                return(null);
            }

            TimeSpan timespan;

            try {
                timespan = XmlConvert.ToTimeSpan(video.ContentDetails.Duration);
            } catch (FormatException) {
                return(null);
            }

            return((int?)timespan.TotalSeconds);
        }
示例#5
0
        public override void startVideoPreview(CancellationToken token)
        {
            if (!(Item is YoutubeVideoItem))
            {
                return;
            }

            YoutubeVideoStreamedItem video, audio;

            YoutubeVideoItem videoItem = Item as YoutubeVideoItem;

            videoItem.getStreams(out video, out audio, 500);

            if (video != null)
            {
                MediaProbe.open(video.Location, token);
            }
        }
示例#6
0
 private DateTime?GetPublishDate(YoutubeVideoItem video)
 {
     return(video.Snippet.PublishedAt.HasValue ? (DateTime?)video.Snippet.PublishedAt.Value.Date : null);
 }
示例#7
0
        public YoutubeViewModel(IRegionManager regionManager, IEventAggregator eventAggregator)
        {
            TokenSource = new CancellationTokenSource();

            RegionManager   = regionManager;
            EventAggregator = eventAggregator;
            NrColumns       = 4;

            MediaState = new MediaState();
            MediaStateCollectionView = new YoutubeCollectionView(MediaState);
            MediaState.clearUIState("Empty", DateTime.Now, MediaStateType.SearchResult);

            MediaStateCollectionView.SelectionChanged += mediaStateCollectionView_SelectionChanged;

            ViewCommand = new Command <SelectableMediaItem>((selectableItem) =>
            {
                if (selectableItem.Item.Metadata == null)
                {
                    return;
                }

                if (selectableItem.Item is YoutubeVideoItem)
                {
                    YoutubeVideoItem item = selectableItem.Item as YoutubeVideoItem;

                    if (item.IsEmbeddedOnly)
                    {
                        Process.Start("https://www.youtube.com/watch?v=" + item.VideoId);
                    }
                    else
                    {
                        YoutubeVideoStreamedItem video, audio;
                        item.getStreams(out video, out audio, (int)Properties.Settings.Default.MaxPlaybackResolution);

                        Shell.ShellViewModel.navigateToVideoView(video, null, audio);
                    }
                }
            });

            ViewChannelCommand = new AsyncCommand <SelectableMediaItem>(async(selectableItem) =>
            {
                if (selectableItem.Item.Metadata == null)
                {
                    return;
                }

                YoutubeItem item = selectableItem.Item as YoutubeItem;

                SearchResource.ListRequest searchListRequest = Youtube.Search.List("snippet");
                searchListRequest.ChannelId  = item.ChannelId;
                searchListRequest.MaxResults = YoutubeSearchViewModel.maxResults;
                searchListRequest.Order      = Google.Apis.YouTube.v3.SearchResource.ListRequest.OrderEnum.Date;

                MediaStateCollectionView.FilterModes.MoveCurrentToFirst();

                await searchAsync(searchListRequest, item.ChannelTitle, false);
            });

            ViewPlaylistCommand = new AsyncCommand <SelectableMediaItem>(async(selectableItem) =>
            {
                if (selectableItem.Item.Metadata == null)
                {
                    return;
                }

                YoutubePlaylistItem item = selectableItem.Item as YoutubePlaylistItem;

                PlaylistItemsResource.ListRequest searchListRequest = Youtube.PlaylistItems.List("snippet");
                searchListRequest.PlaylistId = item.PlaylistId;
                searchListRequest.MaxResults = YoutubeSearchViewModel.maxResults;

                MediaStateCollectionView.FilterModes.MoveCurrentToFirst();

                await searchAsync(searchListRequest, item.Name, false);
            });

            SubscribeCommand = new Command <SelectableMediaItem>((selectableItem) =>
            {
                YoutubeChannelItem item = selectableItem.Item as YoutubeChannelItem;

                EventAggregator.GetEvent <AddFavoriteChannelEvent>().Publish(item);
            });

            DownloadCommand = new AsyncCommand <SelectableMediaItem>(async(selectableItem) => {
                List <MediaItem> items = MediaStateCollectionView.getSelectedItems();
                if (items.Count == 0)
                {
                    items.Add(selectableItem.Item);
                }

                String outputPath = null;

                switch (YoutubePlugin.Properties.Settings.Default.VideoSaveMode)
                {
                case MediaViewer.Infrastructure.Constants.SaveLocation.Current:
                    {
                        outputPath = MediaFileWatcher.Instance.Path;
                        break;
                    }

                case MediaViewer.Infrastructure.Constants.SaveLocation.Ask:
                    {
                        DirectoryPickerView directoryPicker = new DirectoryPickerView();
                        directoryPicker.DirectoryPickerViewModel.InfoString   = "Select Output Directory";
                        directoryPicker.DirectoryPickerViewModel.SelectedPath = MediaFileWatcher.Instance.Path;

                        if (directoryPicker.ShowDialog() == false)
                        {
                            return;
                        }

                        outputPath = directoryPicker.DirectoryPickerViewModel.SelectedPath;

                        break;
                    }

                case MediaViewer.Infrastructure.Constants.SaveLocation.Fixed:
                    {
                        outputPath = YoutubePlugin.Properties.Settings.Default.FixedDownloadPath;
                        break;
                    }

                default:
                    break;
                }

                CancellableOperationProgressView progressView = new CancellableOperationProgressView();
                DownloadProgressViewModel vm = new DownloadProgressViewModel();
                progressView.DataContext     = vm;

                progressView.Show();
                vm.OkCommand.IsExecutable     = false;
                vm.CancelCommand.IsExecutable = true;

                await Task.Factory.StartNew(() =>
                {
                    vm.startDownload(outputPath, items);
                });

                vm.OkCommand.IsExecutable     = true;
                vm.CancelCommand.IsExecutable = false;
            });

            LoadNextPageCommand = new AsyncCommand(async() =>
            {
                await searchAsync(CurrentQuery, "", true);
            });

            SelectAllCommand = new Command(() =>
            {
                MediaStateCollectionView.selectAll();
            }, false);

            DeselectAllCommand = new Command(() =>
            {
                MediaStateCollectionView.deselectAll();
            });

            ShutdownCommand = new Command(() =>
            {
                Properties.Settings.Default.Save();
            });

            MediaState.UIMediaCollection.IsLoadingChanged += UIMediaCollection_IsLoadingChanged;

            MediaViewer.Model.Global.Commands.GlobalCommands.ShutdownCommand.RegisterCommand(ShutdownCommand);

            setupViews();

            EventAggregator.GetEvent <SearchEvent>().Subscribe(searchEvent);

            SearchTask = null;
        }
示例#8
0
        private async Task search(IClientServiceRequest request, String searchInfo, bool isNextPage, CancellationToken token)
        {
            SearchListResponse       searchResponse       = null;
            PlaylistItemListResponse playlistItemResponse = null;
            PlaylistListResponse     playlistResponse     = null;

            SearchResource.ListRequest        searchRequest        = request as SearchResource.ListRequest;
            PlaylistItemsResource.ListRequest playlistItemsRequest = request as PlaylistItemsResource.ListRequest;
            PlaylistsResource.ListRequest     playlistRequest      = request as PlaylistsResource.ListRequest;

            List <YoutubeItem> items = new List <YoutubeItem>();
            int relevance;

            if (isNextPage)
            {
                if (NextPageToken == null)
                {
                    // Final page
                    return;
                }

                if (searchRequest != null)
                {
                    searchRequest.PageToken = NextPageToken;
                }
                else if (playlistItemsRequest != null)
                {
                    playlistItemsRequest.PageToken = NextPageToken;
                }
                else if (playlistRequest != null)
                {
                    playlistRequest.PageToken = NextPageToken;
                }

                relevance = MediaState.UIMediaCollection.Count;
            }
            else
            {
                MediaState.clearUIState(searchInfo, DateTime.Now, MediaStateType.SearchResult);

                CurrentQuery = request;
                relevance    = 0;
            }

            // Call the search.list method to retrieve results matching the specified query term.
            if (searchRequest != null)
            {
                searchResponse = await searchRequest.ExecuteAsync(token);

                NextPageToken = searchResponse.NextPageToken;

                foreach (SearchResult searchResult in searchResponse.Items)
                {
                    YoutubeItem newItem = null;

                    switch (searchResult.Id.Kind)
                    {
                    case "youtube#video":
                        newItem = new YoutubeVideoItem(searchResult, relevance);
                        break;

                    case "youtube#channel":
                        newItem = new YoutubeChannelItem(searchResult, relevance);
                        break;

                    case "youtube#playlist":
                        newItem = new YoutubePlaylistItem(searchResult, relevance);
                        break;

                    default:
                        break;
                    }

                    if (newItem == null || MediaState.UIMediaCollection.Contains(newItem))
                    {
                        continue;
                    }

                    items.Add(newItem);

                    relevance++;
                }
            }

            if (playlistItemsRequest != null)
            {
                playlistItemResponse = await playlistItemsRequest.ExecuteAsync(token);

                NextPageToken = playlistItemResponse.NextPageToken;

                foreach (PlaylistItem playlistItem in playlistItemResponse.Items)
                {
                    YoutubeVideoItem newItem = new YoutubeVideoItem(playlistItem, relevance);

                    items.Add(newItem);

                    relevance++;
                }
            }

            if (playlistRequest != null)
            {
                playlistResponse = await playlistRequest.ExecuteAsync(token);

                NextPageToken = playlistResponse.NextPageToken;

                foreach (Playlist playlist in playlistResponse.Items)
                {
                    YoutubePlaylistItem newItem = new YoutubePlaylistItem(playlist, relevance);

                    if (!items.Contains(newItem))
                    {
                        items.Add(newItem);
                    }

                    relevance++;
                }
            }

            // Add each result to the appropriate list, and then display the lists of
            // matching videos, channels, and playlists.
            MediaState.addUIState(items);
        }
示例#9
0
 private static void parseFeed(YouTubeFeed feed, List<Item> videos)
 {
     string description = "";
     string url = null;
     foreach(YouTubeEntry entry in feed.Entries)
     {
         description = "";
         url = String.Format(youtubeWatchUrlTemplate, entry.VideoId);
         if (entry.Media.Description != null)
         {
             description = entry.Media.Description.Value;
         }
         YoutubeVideoItem video = new YoutubeVideoItem(entry.Title.Text, url, description);
         videos.Add(video);
     }
 }
示例#10
0
        public static List <YoutubeVideoItem> GetLastestVideosForPlayLists(List <string> playListIds)
        {
            List <YoutubeVideoItem> videos        = new List <YoutubeVideoItem>();
            HttpCacheProvider       cacheProvider = new HttpCacheProvider();

            var youTube = GetYouTubeService();

            //Build up request
            var videoRequest = youTube.PlaylistItems.List("snippet,contentDetails");

            videoRequest.MaxResults = _noPerPage;                       //3 per page

            foreach (var playlistId in playListIds)
            {
                var cacheItem = cacheProvider.GetItem <YoutubeVideoItem>(playlistId);

                if (cacheItem != null)
                {
                    videos.Add(cacheItem);
                    continue;
                }

                videoRequest.PlaylistId = playlistId;  //Get videos for playlist only

                //Perform request
                var videoResponse = videoRequest.Execute();

                var currentPlayList = videoResponse.Items.FirstOrDefault();

                if (currentPlayList == null)
                {
                    continue;
                }

                int y = 1;

                while (currentPlayList != null && currentPlayList.Snippet.Title == "Private video")
                {
                    if (y > videoResponse.Items.Count())
                    {
                        break;
                    }

                    currentPlayList = videoResponse.Items.ElementAt(y);
                    y++;
                }


                Tuple <string, DateTime?> extraInfo = GetExtraInfo(currentPlayList.ContentDetails.VideoId);
                if (extraInfo == null)
                {
                    continue;
                }

                var videoItem = new YoutubeVideoItem()
                {
                    Title       = currentPlayList.Snippet.Title,
                    Id          = currentPlayList.ContentDetails.VideoId,
                    PublishDate = extraInfo.Item2,
                    Image       = currentPlayList.Snippet.Thumbnails != null ? currentPlayList.Snippet.Thumbnails.Maxres != null ? currentPlayList.Snippet.Thumbnails.Maxres.Url : currentPlayList.Snippet.Thumbnails.Standard?.Url : string.Empty,
                    Url         = string.Format("https://www.youtube.com/embed/{0}?rel=0", currentPlayList.ContentDetails.VideoId),
                    ExternalUrl = string.Format("https://www.youtube.com/watch?v={0}", currentPlayList.ContentDetails.VideoId),
                    WatchCount  = extraInfo.Item1
                };

                videos.Add(videoItem);
                cacheProvider.InsertItem <YoutubeVideoItem>(playlistId, videoItem, TimeSpan.FromHours(1));
            }

            //Return the list of videos we find
            return(videos);
        }