public static VideoListItem Instance(SearchSettings settings, bool showAllFilesVisible) {
     SearchVideoWindow NewForm = new SearchVideoWindow();
     NewForm.settings = settings;
     NewForm.showAllFilesVisible = showAllFilesVisible;
     SessionCore.Instance.Windows.ShowDialog(NewForm);
     return NewForm.selection;
 }
 public async Task InitializationCompleted() {
     settings = SessionCore.Instance.Business.FilterSettings;
     this.DataContext = settings;
     PolarityFocus.ItemsSource = await SessionCore.Instance.Business.GetFocusCategoriesAsync();
     PolarityFocus.SelectedIndex = 0;
     Settings_Changed(null, null);
 }
        /// <summary>
        /// Return a random video from the database matching specified conditions.
        /// </summary>
        /// <param name="data">The list of videos in which to search; generally Entities.Media.</param>
        /// <param name="settings">An object containing various search settings.</param>
        /// <returns>The randomly selected video, or null if no matches are found.</returns>
        public static Media SelectVideo(IQueryable<Media> data, SearchSettings settings) {
            if (settings == null)
                settings = new SearchSettings();
            if (settings.ExcludeVideos == null)
                settings.ExcludeVideos = new List<Guid>();

            var Query = (from v in data
                         where (settings.AllowDownloading || v.FileName != null) &&
                         (v.FileName != null || v.DownloadUrl != "") &&
                         (v.Length == null || ((v.EndPos != null ? v.EndPos.Value : v.Length.Value) - (v.StartPos != null ? v.StartPos.Value : 0)) <= 12 * 60) && // Don't get videos longer than 12 minutes
                         !settings.ExcludeVideos.Contains(v.MediaId) // Don't repeat same videos
                         select v);

            // Apply search filters.
            Query = SearchVideoAccess.ApplySearchFilters(Query, settings, null);

            // Return random result
            int TotalFound = 0;
            Guid? ResultId = SelectRandomId(Query, out TotalFound);
            settings.TotalFound = TotalFound;
            if (TotalFound == 0 || ResultId == null)
                return null;
            else if (TotalFound == 1)
                return Query.FirstOrDefault();
            else 
                return data.Where(v => v.MediaId == ResultId).FirstOrDefault();
        }
 /// <summary>
 /// Returns whether specified video matches specified conditions.
 /// </summary>
 /// <param name="video">The video to evaluate.</param>
 /// <param name="settings">An object containing various search settings.</param>
 /// <returns>True if video matches conditions, otherwise false.</returns>
 public static bool VideoMatchesConditions(Media video, SearchSettings settings) {
     return false;
     //using (Entities context = new Entities()) {
     //    Media Result = SelectVideo(context.Media.Where(v => v.MediaId == video.MediaId), settings);
     //    return (Result != null);
     //}
 }
        /// <summary>
        /// Loads the list of artists.
        /// </summary>
        /// <param name="settings">The filters to apply to the data.</param>
        public async Task<List<SearchCategoryItem>> LoadCategoriesAsync(SearchSettings settings, SearchFilterEnum groupType) {
            List<SearchCategoryItem> Result = new List<SearchCategoryItem>();
            if (settings.ListIsInDatabase != false) {
                Result.Add(new SearchCategoryItem(SearchFilterEnum.All, null, "All"));
                if (groupType != SearchFilterEnum.Artist)
                    Result.Add(new SearchCategoryItem(SearchFilterEnum.Artist, null, "By Artist"));
                if (groupType != SearchFilterEnum.Category)
                    Result.Add(new SearchCategoryItem(SearchFilterEnum.Category, null, "By Category"));
                if (groupType != SearchFilterEnum.Element)
                    Result.Add(new SearchCategoryItem(SearchFilterEnum.Element, null, "By Element"));
            }
            if (settings.ListIsInDatabase != true)
                Result.Add(new SearchCategoryItem(SearchFilterEnum.Files, null, "Other Files"));
            Result.Add(new SearchCategoryItem(SearchFilterEnum.None, null, "---"));

            if (groupType == SearchFilterEnum.Artist) {
                if (string.IsNullOrEmpty(settings.Search)) {
                    Result.Add(new SearchCategoryItem(SearchFilterEnum.Artist, "", "No Artist"));
                    Result.Add(new SearchCategoryItem(SearchFilterEnum.ArtistSingles, null, "Singles"));
                }
                Result.AddRange(await Task.Run(() => SearchVideoAccess.GetCategoryArtists(settings)));
            } else if (groupType == SearchFilterEnum.Category) {
                if (string.IsNullOrEmpty(settings.Search))
                    Result.Add(new SearchCategoryItem(SearchFilterEnum.Category, "", "No Category"));
                Result.AddRange(await Task.Run(() => SearchVideoAccess.GetCategoryCategories(settings)));
            } else if (groupType == SearchFilterEnum.Element)
                Result.AddRange(await Task.Run(() => SearchVideoAccess.GetCategoryElements(settings)));

            return Result;
        }
 private void SelectButton_Click(object sender, RoutedEventArgs e) {
     OkButton.Focus();
     if (!string.IsNullOrEmpty(settings.Search) || (!string.IsNullOrEmpty(settings.RatingCategory) && settings.RatingValue.HasValue)) {
         result = settings;
         this.Close();                
     }  else {
         ErrorText.Visibility = Visibility.Visible;
     }
 }
 public MediaGrid() {
     InitializeComponent();
     Settings = new SearchSettings();
     PopupEnabled = true;
     IsPreferenceVisible = true;
     IsIntensityVisible = true;
     IsCustomVisible = true;
     IsStatusVisible = false;
     AllowMultiSelect = false;
 }
 /// <summary>
 /// Returns the list of elements.
 /// </summary>
 /// <returns>A list of SearchCategoryItem objects.</returns>
 public static List<SearchCategoryItem> GetCategoryElements(SearchSettings settings) {
     using (Entities context = new Entities()) {
         var Query = (from c in context.RatingCategories
                      where (settings.Search == "" || c.Name.Contains(settings.Search))
                      orderby c.Name
                      select new SearchCategoryItem() {
                          FilterType = SearchFilterEnum.Element,
                          FilterValue = c.Name,
                          Text = c.Name
                      });
         return Query.ToList();
     }
 }
        public PlayerBusiness(IMediaPlayerBusiness player) {
            FilterSettings = new SearchSettings();
            FilterSettings.MediaType = MediaType.Video;

            timerSession = new DispatcherTimer();
            timerSession.Interval = TimeSpan.FromSeconds(1);
            timerSession.Tick += sessionTimer_Tick;
            timerChangeConditions = new DispatcherTimer();
            timerChangeConditions.Interval = TimeSpan.FromSeconds(1);
            timerChangeConditions.Tick += timerChangeConditions_Tick;

            if (player != null)
                SetPlayer(player);
        }
 /// <summary>
 /// Applies all search filters to the video selection query.
 /// </summary>
 /// <param name="Query">The video selection query.</param>
 /// <param name="settings">The settings to apply to the query.</param>
 /// <param name="context">The data context to the database.</param>
 /// <returns>The updated query with filters applied.</returns>
 public static IQueryable<Media> ApplySearchFilters(IQueryable<Media> Query, SearchSettings settings, Entities context) {
     // Media type
     if (settings.MediaType != MediaType.None)
         Query = Query.Where(v => v.MediaTypeId == (int)settings.MediaType);
     // Search string
     if (!string.IsNullOrEmpty(settings.Search))
         Query = Query.Where(v => v.Artist.Contains(settings.Search) || v.Title.Contains(settings.Search) || v.FileName.Contains(settings.Search) || v.MediaCategory.Name.Contains(settings.Search));
     // Rating category and value
     foreach (SearchRatingSetting item in settings.RatingFilters) {
         if (!string.IsNullOrEmpty(item.Category) && item.Value.HasValue) {
             Query = Query.Where(GetFilterClause(Query, item, settings.RatingRatio, context));
         }
     }
     // Other conditions
     foreach (SearchConditionSetting item in settings.ConditionFilters) {
         if (item.Value != BoolConditionEnum.None) {
             bool CondValue = (item.Value == BoolConditionEnum.Yes ? true : false);
             if (item.Field == FieldConditionEnum.HasDownloadUrl)
                 Query = Query.Where(v => (v.DownloadUrl != "") == CondValue);
             else if (item.Field == FieldConditionEnum.HasBuyOrDownloadUrl)
                 Query = Query.Where(v => (v.DownloadUrl != "" || v.BuyUrl != "") == CondValue);
             else if (item.Field == FieldConditionEnum.PerformanceProblem)
                 Query = Query.Where(v => (v.DisableMadVr || v.DisableSvp) == CondValue);
             else if (item.Field == FieldConditionEnum.IsPersonal)
                 Query = Query.Where(v => v.IsPersonal == CondValue);
         }
     }
     // Buy Url Domains
     if (settings.BuyUrlDomains != null && settings.BuyUrlDomains.Count() > 0) {
         if (!settings.BuyUrlDomainsNegated)
             Query = Query.Where(v => v.BuyUrl != "" && settings.BuyUrlDomains.Any(d => v.BuyUrl.Contains(d)));
         else
             Query = Query.Where(v => v.BuyUrl != "" && !settings.BuyUrlDomains.Any(d => v.BuyUrl.Contains(d)));
     }
     // Has ratings
     if (settings.HasRating != HasRatingEnum.All) {
         if (settings.HasRating == HasRatingEnum.With)
             Query = Query.Where(v => v.MediaRatings.Any());
         else if (settings.HasRating == HasRatingEnum.Without)
             Query = Query.Where(v => !v.MediaRatings.Any());
         else if (settings.HasRating == HasRatingEnum.Incomplete && context != null)
             Query = Query.Where(v =>
                 (v.MediaRatings.Where(r => r.Height == null || r.Depth == null).Any() ||
                 v.MediaRatings.Where(r => !r.RatingCategory.Custom).Count() < context.RatingCategories.Where(r => !r.Custom).Count()));
     }
     return Query;
 }
 /// <summary>
 /// Returns the list of artists that have more than one song.
 /// </summary>
 /// <returns>A list of SearchCategoryItem objects.</returns>
 public static List<SearchCategoryItem> GetCategoryArtists(SearchSettings settings) {
     using (Entities context = new Entities()) {
         var Query = (from v in context.Media
                      where v.MediaTypeId == (int)settings.MediaType
                      group v by v.Artist into a
                      where a.Key != "" && 
                         a.Count() > 1 && 
                         (settings.Search == "" || a.Key.Contains(settings.Search))
                      orderby a.Key
                      select new SearchCategoryItem() {
                          FilterType = SearchFilterEnum.Artist,
                          FilterValue = a.Key,
                          Text = a.Key + " (" + a.Count() + ")"
                      });
         return Query.ToList();
     }
 }
        /// <summary>
        /// Loads the playlist from the database with specified filter conditions.
        /// </summary>
        /// <param name="settings">The filters to apply to the data.</param>
        /// <param name="forceScanFolder">Whether to scan files in folder to set FileExists.</param>
        /// <returns>A Task object for asynchronous processing.</returns>
        public async Task LoadPlaylistAsync(SearchSettings settings, bool forceScanFolder) {
            bool LoadFilesRequired = !(settings.ConditionField == FieldConditionEnum.IsInDatabase && settings.ConditionValue == BoolConditionEnum.Yes);

            // Load database.
            var DbTask = Task.Run(() => SearchVideoAccess.GetList(settings));

            // Load files.
            if (LoadFilesRequired || forceScanFolder) {
                if (files == null) {
                    // Run both tasks simultaneously.
                    var FilesTask = Task.Run(() => LoadFiles());
                    Task.WaitAll(DbTask, FilesTask);
                }
                playlist = await DbTask;
                await Task.Run(() => MergePlaylist(settings));
            } else
                playlist = await DbTask;
        }
        public static List<VideoListItem> GetList(SearchSettings settings) {
            using (Entities context = new Entities()) {
                var Query = (from v in context.Media select v);

                // Apply all search filters.
                Query = ApplySearchFilters(Query, settings, context);

                // Read necessary fields.
                var Result = QueryVideoListItem(Query, settings);

                // Apply sort.
                string OrderByString = "IsInDatabase DESC, ";
                OrderByString += (string.IsNullOrEmpty(settings.OrderBy) ? "Artist" : settings.OrderBy);
                if (settings.OrderByDirection == ListSortDirection.Descending)
                    OrderByString += " DESC";
                OrderByString += ", Title";
                Result = Result.OrderBy(OrderByString);

                return Result.ToList();
            }
        }
        private async void window_Loaded(object sender, RoutedEventArgs e) {
            this.Left = mainForm.Left;
            this.Top = mainForm.Top;
            this.Title = mainForm.Title + " [Manual Mode]";
            AttachControls();
            SessionCore.Instance.Business.NowPlaying += business_NowPlaying;
            SessionCore.Instance.Business.DisplayPlayTime += business_DisplayPlayTime;
            SessionCore.Instance.Business.Loop = false;

            timerChangeFilters = new DispatcherTimer();
            timerChangeFilters.Interval = TimeSpan.FromSeconds(1);
            timerChangeFilters.Tick += timerChangeFilters_Tick;
            // Keep main window's settings and it will be set back when closing manual mode.
            mainSettings = SessionCore.Instance.Business.FilterSettings;
            MediaList.Settings.RatingRatio = mainSettings.RatingRatio;
            SessionCore.Instance.Business.FilterSettings = MediaList.Settings;
            this.DataContext = MediaList.Settings;

            await MediaList.LoadDataAsync();
            isLoaded = true;
        }
        /// <summary>
        /// Return a random video from the database matching specified conditions.
        /// </summary>
        /// <param name="data">The list of videos in which to search; generally Entities.Media.</param>
        /// <param name="settings">An object containing various search settings.</param>
        /// <param name="count">The quantity of results to return.</param>
        /// <param name="maintainCurrent">If specified, the currently selected video will be kept.</param>
        /// <returns>The randomly selected video, or null if no matches are found.</returns>
        public static List<Media> SelectVideo(IQueryable<Media> data, SearchSettings settings, int count, Media maintainCurrent) {
            if (settings == null)
                settings = new SearchSettings();
            if (settings.ExcludeVideos == null)
                settings.ExcludeVideos = new List<Guid>();

            // Exclude currently selected video so that it doesn't get randomly re-reselected.
            if (maintainCurrent != null) {
                settings.ExcludeVideos = new List<Guid>(settings.ExcludeVideos);
                settings.ExcludeVideos.Add(maintainCurrent.MediaId);
                count--;
            }

            var Query = (from v in data
                         where (settings.AllowDownloading || v.FileName != null) &&
                         (v.FileName != null || v.DownloadUrl != "") &&
                         (v.Length == null || ((v.EndPos != null ? v.EndPos.Value : v.Length.Value) - (v.StartPos != null ? v.StartPos.Value : 0)) <= 12 * 60) && // Don't get videos longer than 12 minutes
                         !settings.ExcludeVideos.Contains(v.MediaId) // Don't repeat same videos
                         select v);

            // Apply search filters.
            Query = SearchVideoAccess.ApplySearchFilters(Query, settings, null);

            // Return random result
            int TotalFound = 0;
            List<Guid> ResultId = SelectRandomId(Query, count, out TotalFound);
            List<Media> Result = new List<Media>();
            if (maintainCurrent != null)
                Result.Add(maintainCurrent);
            settings.TotalFound = TotalFound;
            if (TotalFound > 0 && ResultId.Count() > 0) {
                if (TotalFound <= count)
                    Result.AddRange(Query.Take(count).ToList());
                else
                    Result.AddRange(data.Where(v => ResultId.Contains(v.MediaId)).ToList());
            }
            return Result;
        }
 /// <summary>
 /// Return a random video from the database matching specified conditions.
 /// </summary>
 /// <param name="playedVideos">The list of videos already played.</param>
 /// <param name="settings">An object containing various search settings.</param>
 /// <param name="count">The quantity of results to return.</param>
 /// <param name="maintainCurrent">If specified, the currently selected video will be kept.</param>
 /// <returns>The randomly selected video, or null if no matches are found.</returns>
 public static List<Media> SelectVideo(SearchSettings settings, int count, Media maintainCurrent) {
     using (Entities context = new Entities()) {
         // context.Database.Log = Console.Write;
         return SelectVideo(context.Media.Include("MediaRatings.RatingCategory"), settings, count, maintainCurrent);
     }
 }
 /// <summary>
 /// Loads the playlist from the database with specified filter conditions.
 /// </summary>
 /// <param name="settings">The filters to apply to the data.</param>
 /// <returns>A Task object for asynchronous processing.</returns>
 public async Task LoadPlaylistAsync(SearchSettings settings) {
     await LoadPlaylistAsync(settings, false);
 }
        public async void CommandBinding_PlayFire(object sender, ExecutedRoutedEventArgs e) {
            if (!menuPlayFire.IsEnabled)
                return;

            SearchSettings settings = new SearchSettings();
            settings.MediaType = MediaType.Video;
            settings.RatingRatio = SessionCore.Instance.Main.RatioSlider.Value;
            settings.RatingCategory = "Fire";
            settings.RatingOperator = OperatorConditionEnum.GreaterOrEqual;
            settings.RatingValue = 7.5f;
            settings.RatingFilters.Add(new SearchRatingSetting() {
                Category = "Length",
                Operator = OperatorConditionEnum.Smaller,
                Value = 12
            });

            VideoListItem Result = SearchVideoWindow.Instance(settings);
            if (Result != null)
                await SessionCore.Instance.Business.SetNextVideoFileAsync(PlayerMode.Fire, Result.FileName);
        }
 public static VideoListItem Instance(SearchSettings settings) {
     SearchVideoWindow NewForm = new SearchVideoWindow();
     NewForm.settings = settings;
     SessionCore.Instance.Windows.ShowDialog(NewForm);
     return NewForm.selection;
 }
        private async void CommandBinding_SpecialRequest(object sender, ExecutedRoutedEventArgs e) {
            if (!menuSpecialRequest.IsEnabled)
                return;

            SearchSettings SearchSettings = new SearchSettings() {
                MediaType = MediaType.Video,
                RatingRatio = SessionCore.Instance.Main.RatioSlider.Value
            };
            VideoListItem Result = SearchVideoWindow.Instance(SearchSettings);
            if (Result != null)
                await SessionCore.Instance.Business.SetNextVideoFileAsync(PlayerMode.SpecialRequest, Result.FileName).ConfigureAwait(false);
        }
        private async Task SetRequestCategoryModeAsync(SearchSettings settings) {
            bool active = settings != null;
            menuRequestCategory.IsChecked = active;

            menuSpecialRequest.IsEnabled = !active;
            menuPause.IsEnabled = !active;
            menuPlayFire.IsEnabled = !active;
            menuManualMode.IsEnabled = !active;
            // IntensitySlider.IsEnabled = !menuPause.IsChecked;

            await SessionCore.Instance.Business.SetRequestCategoryAsync(settings);
        }
 private async void menuSelectFile_Click(object sender, RoutedEventArgs e) {
     if (!isNew) {
         // Bind to another file.
         Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
         dlg.InitialDirectory = Settings.NaturalGroundingFolder;
         if (video.MediaType == MediaType.Video)
             string.Format("Video Files|*{0})", string.Join(";*", Settings.VideoExtensions));
         else if (video.MediaType == MediaType.Audio)
             string.Format("Audio Files|*{0})", string.Join(";*", Settings.AudioExtensions));
         else if (video.MediaType == MediaType.Image)
             string.Format("Image Files|*{0})", string.Join(";*", Settings.ImageExtensions));
         if (dlg.ShowDialog(IsLoaded ? this : Owner).Value == true) {
             if (!dlg.FileName.StartsWith(Settings.NaturalGroundingFolder))
                 MessageBox.Show("You must select a file within your Natural Grounding folder.", "Error", MessageBoxButton.OK, MessageBoxImage.Information);
             else {
                 string BindFile = dlg.FileName.Substring(Settings.NaturalGroundingFolder.Length);
                 if (business.GetVideoByFileName(BindFile) == null) {
                     video.FileName = BindFile;
                     video.Length = null;
                     video.Height = null;
                     await LoadMediaInfoAsync();
                     if (isPopup)
                         SaveChanges();
                 } else
                     MessageBox.Show("This file is already in the database.", "Error", MessageBoxButton.OK, MessageBoxImage.Information);
             }
             fileNotFound = false;
         }
     } else {
         // Bind file to an existing entry.
         SearchSettings settings = new SearchSettings() {
             MediaType = (MediaType)video.MediaTypeId,
             ConditionField = FieldConditionEnum.FileExists,
             ConditionValue = BoolConditionEnum.No
         };
         VideoListItem Result = SearchVideoWindow.Instance(settings, false);
         if (Result != null) {
             // Close and re-open selected entry.
             Close();
             EditVideoWindow NewForm = Instance(Result.MediaId, null, player, callback);
             NewForm.video.FileName = video.FileName;
             NewForm.video.Length = null;
             NewForm.video.Height = null;
             await NewForm.LoadMediaInfoAsync();
         }
     }
 }
        /// <summary>
        /// Apply specified search and rating category filters to the next videos.
        /// </summary>
        /// <param name="request">The search filters being requested, or null to disable the request category mode.</param>
        public async Task SetRequestCategoryAsync(SearchSettings request) {
            if (request != null) {
                FilterSettings.Search = request.Search;
                if (!string.IsNullOrEmpty(request.RatingCategory) && request.RatingValue.HasValue) {
                    FilterSettings.RatingCategory = request.RatingCategory;
                    FilterSettings.RatingOperator = request.RatingOperator;
                    FilterSettings.RatingValue = request.RatingValue;
                }

                playMode = PlayerMode.RequestCategory;
            } else {
                FilterSettings.Search = null;
                FilterSettings.RatingCategory = null;
                FilterSettings.RatingValue = null;
                playMode = PlayerMode.Normal;
            }

            await SelectNextVideoAsync(0, false).ConfigureAwait(false);

            Application.Current.Dispatcher.Invoke(() => PlaylistChanged?.Invoke(this, new EventArgs()));
        }
        /// <summary>
        /// Apply specified search and rating category filters to the next videos.
        /// </summary>
        /// <param name="request">The search filters being requested, or null to disable the request category mode.</param>
        public async Task SetRequestCategoryAsync(SearchSettings request) {
            if (request != null) {
                FilterSettings.Search = request.Search;
                if (!string.IsNullOrEmpty(request.RatingCategory) && request.RatingValue.HasValue) {
                    FilterSettings.RatingCategory = request.RatingCategory;
                    FilterSettings.RatingOperator = request.RatingOperator;
                    FilterSettings.RatingValue = request.RatingValue;
                }

                playMode = PlayerMode.RequestCategory;
            } else {
                FilterSettings.Search = null;
                FilterSettings.RatingCategory = null;
                FilterSettings.RatingValue = null;
                playMode = PlayerMode.Normal;
            }

            await SelectNextVideoAsync(0);

            if (PlaylistChanged != null)
                PlaylistChanged(this, new EventArgs());
        }
        public static IQueryable<VideoListItem> QueryVideoListItem(IQueryable<Media> query, SearchSettings settings) {
            if (settings == null)
                settings = new SearchSettings();

            var Result = (from v in query
                          select new VideoListItem() {
                              MediaId = v.MediaId,
                              MediaType = (MediaType)v.MediaTypeId,
                              Artist = v.Artist,
                              Title = v.Title,
                              Album = v.Album,
                              MediaCategoryId = v.MediaCategoryId,
                              FileName = v.FileName,
                              Preference = v.Preference,
                              Length = v.Length,
                              HasDownloadUrl = (v.DownloadUrl != ""),
                              BuyUrl = v.BuyUrl,
                              Intensity = (from r in v.MediaRatings
                                           let val = r.DbGetValue(r.Height, r.Depth, settings.RatingRatio)
                                           orderby val descending
                                           select val).Take(5).Average(),
                              //PhysicalMasculine = (from r in v.MediaRatings
                              //                     where r.RatingCategory.Name == "Physical Masculine"
                              //                     select r.DbGetValue(r.Height, r.Depth, settings.RatingRatio)).FirstOrDefault(),
                              //PhysicalFeminine = (from r in v.MediaRatings
                              //                    where r.RatingCategory.Name == "Physical Feminine"
                              //                    select r.DbGetValue(r.Height, r.Depth, settings.RatingRatio)).FirstOrDefault(),
                              //EmotionalMasculine = (from r in v.MediaRatings
                              //                      where r.RatingCategory.Name == "Emotional Masculine"
                              //                      select r.DbGetValue(r.Height, r.Depth, settings.RatingRatio)).FirstOrDefault(),
                              //EmotionalFeminine = (from r in v.MediaRatings
                              //                     where r.RatingCategory.Name == "Emotional Feminine"
                              //                     select r.DbGetValue(r.Height, r.Depth, settings.RatingRatio)).FirstOrDefault(),
                              //SpiritualMasculine = (from r in v.MediaRatings
                              //                      where r.RatingCategory.Name == "Spiritual Masculine"
                              //                      select r.DbGetValue(r.Height, r.Depth, settings.RatingRatio)).FirstOrDefault(),
                              //SpiritualFeminine = (from r in v.MediaRatings
                              //                     where r.RatingCategory.Name == "Spiritual Feminine"
                              //                     select r.DbGetValue(r.Height, r.Depth, settings.RatingRatio)).FirstOrDefault(),
                              //Love = (from r in v.MediaRatings
                              //        where r.RatingCategory.Name == "Love"
                              //        select r.DbGetValue(r.Height, r.Depth, settings.RatingRatio)).FirstOrDefault(),
                              //Egoless = (from r in v.MediaRatings
                              //           where r.RatingCategory.Name == "Egoless"
                              //           select r.DbGetValue(r.Height, r.Depth, settings.RatingRatio)).FirstOrDefault(),
                              Custom = string.IsNullOrEmpty(settings.RatingCategory) ? null :
                                      (from r in v.MediaRatings
                                       where r.RatingCategory.Name == settings.RatingCategory // && r.RatingCategory.Custom
                                       select r.DbGetValue(r.Height, r.Depth, settings.RatingRatio)).FirstOrDefault(),
                              IsInDatabase = true
                          });
            return Result;
        }
 public GetConditionsEventArgs(SearchSettings conditions) {
     this.Conditions = conditions;
     this.Conditions.RatingFilters = new List<SearchRatingSetting>();
     this.Conditions.RatingFilters.Add(new SearchRatingSetting());
 }
        /// <summary>
        /// Merges the list of files in the folder with the data coming from the database.
        /// </summary>
        /// <param name="settings">The filters to apply to the data.</param>
        private void MergePlaylist(SearchSettings settings) {
            VideoListItem ListItem;
            MediaType ItemType;
            foreach (LocalFileInfo item in files) {
                ItemType = EditVideoBusiness.GetFileType(item.FileName);
                ListItem = playlist.Where(v => string.Equals(v.FileName, item.FileName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (ListItem != null)
                    ListItem.FileExists = true;
                else {
                    // Add file if it matches search settings.
                    if (!item.IsInDatabase && OrphanMatchesConditions(ItemType, item.FileName, settings)) {
                        // Add file to ListView.
                        playlist.Add(new VideoListItem() {
                            MediaId = null,
                            MediaType = ItemType,
                            Title = item.FileName,
                            FileName = item.FileName,
                            FileExists = true,
                            IsInDatabase = false
                        });
                    }
                }
            }

            // Apply FileExists search filter.
            SearchConditionSetting Cond = settings.ConditionFilters.FirstOrDefault(f => f.Field == FieldConditionEnum.FileExists && f.Value != BoolConditionEnum.None);
            if (Cond != null)
                playlist.RemoveAll(v => v.FileExists == (Cond.Value == BoolConditionEnum.No));
            // Apply IsInDatabase search filter.
            if (settings.ConditionFilters.Any(f => f.Field == FieldConditionEnum.IsInDatabase && f.Value == BoolConditionEnum.No))
                playlist.RemoveAll(v => v.IsInDatabase);
        }
 private bool OrphanMatchesConditions(MediaType mediaType, string fileName, SearchSettings settings) {
     bool Result = true;
     Result = (settings.MediaType == MediaType.None || mediaType == settings.MediaType) &&
                 (string.IsNullOrEmpty(settings.Search) || (fileName != null && fileName.IndexOf(settings.Search, StringComparison.OrdinalIgnoreCase) != -1)) &&
                 (string.IsNullOrEmpty(settings.RatingCategory) || !settings.RatingValue.HasValue) &&
                 (settings.HasRating == HasRatingEnum.All || settings.HasRating == HasRatingEnum.Without);
     foreach (SearchConditionSetting item in settings.ConditionFilters) {
         if (!(item.Field == FieldConditionEnum.None || item.Value == BoolConditionEnum.None ||
             (item.Field == FieldConditionEnum.IsInDatabase && item.Value == BoolConditionEnum.No) ||
             (item.Field == FieldConditionEnum.FileExists && item.Value == BoolConditionEnum.Yes) ||
             (item.Field == FieldConditionEnum.HasDownloadUrl && item.Value == BoolConditionEnum.No)))
             Result = false;
     }
     return Result;
 }
 /// <summary>
 /// Automatically binds files in the playlist and load missing info.
 /// </summary>
 public static async Task AutoBindFilesAsync() {
     // Auto-bind files
     EditPlaylistBusiness BindBusiness = new EditPlaylistBusiness();
     SearchSettings BindSettings = new SearchSettings();
     BindSettings.SetCondition(FieldConditionEnum.IsInDatabase, true);
     await BindBusiness.LoadPlaylistAsync(BindSettings);
     await BindBusiness.LoadMediaInfoAsync(null);
 }
        public async Task LoadBuyListAsync(SearchSettings settings, BuyProductType productType, bool showAllFiles) {
            settings.MediaType = MediaType.None;
            if (showAllFiles) {
                settings.ConditionField = FieldConditionEnum.IsInDatabase;
                settings.ConditionValue = BoolConditionEnum.Yes;
            } else {
                settings.ConditionField = FieldConditionEnum.FileExists;
                settings.ConditionValue = BoolConditionEnum.No;
            }
            settings.BuyUrlDomainsNegated = false;
            if (productType == BuyProductType.PremiumProduct)
                settings.BuyUrlDomains = PremiumProductDomains;
            else if (productType == BuyProductType.Videos)
                settings.BuyUrlDomains = VideoDomains;
            else if (productType == BuyProductType.Music)
                settings.BuyUrlDomains = MusicDomains;
            else if (productType == BuyProductType.Other) {
                List<string> AllDomains = new List<string>();
                AllDomains.AddRange(PremiumProductDomains);
                AllDomains.AddRange(VideoDomains);
                AllDomains.AddRange(MusicDomains);
                settings.BuyUrlDomains = AllDomains;
                settings.BuyUrlDomainsNegated = true;
            }

            await LoadPlaylistAsync(settings, true);
        }