Exemplo n.º 1
0
        public static DownloadList Create(DownloadInfo currentItem)
        {
            DownloadList di = (DownloadList)CrossDomain.OnlineVideosAppDomain.Domain.CreateInstanceAndUnwrap(typeof(DownloadList).Assembly.FullName, typeof(DownloadList).FullName, false, System.Reflection.BindingFlags.CreateInstance | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic, null, null, null, null);

            di.CurrentItem = currentItem;
            return(di);
        }
Exemplo n.º 2
0
 public string Remove(DownloadList dlList)
 {
     lock (_locker)
     {
         int index = _currentDownloadsParallel.IndexOf(dlList);
         if (index >= 0)
         {
             _currentDownloadsParallel.RemoveAt(index);
         }
         else
         {
             foreach (var item in _currentDownloadsQueuedPerSite)
             {
                 index = item.Value.IndexOf(dlList);
                 if (index >= 0)
                 {
                     item.Value.RemoveAt(index);
                     if (item.Value.Count == 0)
                     {
                         _currentDownloadsQueuedPerSite.Remove(item.Key);
                     }
                     else
                     {
                         return(item.Key); // return the name of the site on which this list was queued if there are more lists to download
                     }
                     break;
                 }
             }
         }
         return(null);
     }
 }
Exemplo n.º 3
0
 public void Add(string site, DownloadList downloadList)
 {
     lock (_locker)
     {
         if (string.IsNullOrEmpty(site))
         {
             _currentDownloadsParallel.Add(downloadList);
         }
         else
         {
             List <DownloadList> dlList;
             if (!_currentDownloadsQueuedPerSite.TryGetValue(site, out dlList))
             {
                 _currentDownloadsQueuedPerSite.Add(site, new List <DownloadList>()
                 {
                     downloadList
                 });
             }
             else
             {
                 dlList.Add(downloadList);
             }
         }
     }
 }
        private void OnDownloadFileCompleted(DownloadList saveItems, Exception error)
        {
            // notify the Util of the downloaded video that the download has stopped
            try
            {
                if (saveItems.CurrentItem != null && saveItems.CurrentItem.Util != null)
                {
                    saveItems.CurrentItem.Util.OnDownloadEnded(saveItems.CurrentItem.VideoInfo, saveItems.CurrentItem.Url, (double)saveItems.CurrentItem.PercentComplete / 100.0d, error != null);
                }
            }
            catch (Exception ex)
            {
                Log.Warn("Error on Util.OnDownloadEnded: {0}", ex.ToString());
            }

            bool preventMessageDuetoAdult = (saveItems.CurrentItem.Util != null && saveItems.CurrentItem.Util.Settings.ConfirmAge && OnlineVideoSettings.Instance.UseAgeConfirmation && !OnlineVideoSettings.Instance.AgeConfirmed);

            if (error != null && !saveItems.CurrentItem.Downloader.Cancelled)
            {
                if (!preventMessageDuetoAdult)
                {
                    notification.Show(Translation.Instance.Error, string.Format(Translation.Instance.DownloadFailed, saveItems.CurrentItem.Title));
                }
            }
            else
            {
                try
                {
                    // if the image given was an url -> check if thumb exists otherwise download
                    if (saveItems.CurrentItem.ThumbFile.ToLower().StartsWith("http"))
                    {
                        string thumbFile = FileUtils.GetThumbFile(saveItems.CurrentItem.ThumbFile);
                        if (System.IO.File.Exists(thumbFile)) saveItems.CurrentItem.ThumbFile = thumbFile;
                        else if (ImageDownloader.DownloadAndCheckImage(saveItems.CurrentItem.ThumbFile, thumbFile)) saveItems.CurrentItem.ThumbFile = thumbFile;
                    }
                    // save thumb for this video as well if it exists
                    if (!saveItems.CurrentItem.ThumbFile.ToLower().StartsWith("http") && System.IO.File.Exists(saveItems.CurrentItem.ThumbFile))
                    {
                        string localImageName = System.IO.Path.Combine(
                            System.IO.Path.GetDirectoryName(saveItems.CurrentItem.LocalFile),
                            System.IO.Path.GetFileNameWithoutExtension(saveItems.CurrentItem.LocalFile))
                            + System.IO.Path.GetExtension(saveItems.CurrentItem.ThumbFile);
                        System.IO.File.Copy(saveItems.CurrentItem.ThumbFile, localImageName, true);
                    }
                }
                catch (Exception ex)
                {
                    Log.Warn("Error saving thumbnail for download: {0}", ex.ToString());
                }

                // get file size
                int fileSize = saveItems.CurrentItem.KbTotal;
                if (fileSize <= 0)
                {
                    try { fileSize = (int)((new System.IO.FileInfo(saveItems.CurrentItem.LocalFile)).Length / 1024); }
                    catch { }
                }

                Log.Info("{3} download of '{0}' - {1} KB in {2}", saveItems.CurrentItem.LocalFile, fileSize, (DateTime.Now - saveItems.CurrentItem.Start).ToString(), saveItems.CurrentItem.Downloader.Cancelled ? "Cancelled" : "Finished");

                if (!preventMessageDuetoAdult)
                {
                    notification.Show(saveItems.CurrentItem.Downloader.Cancelled ? Translation.Instance.DownloadCancelled : Translation.Instance.DownloadComplete,
                        string.Format("{0}{1}", saveItems.CurrentItem.Title, fileSize > 0 ? " ( " + fileSize.ToString("n0") + " KB)" : ""));
                }
            }

            // download the next if list not empty and not last in list and not cancelled by the user
            string site = null;
            if (saveItems.DownloadItems != null && saveItems.DownloadItems.Count > 1 && !saveItems.CurrentItem.Downloader.Cancelled)
            {
                int currentDlIndex = saveItems.DownloadItems.IndexOf(saveItems.CurrentItem);
                if (currentDlIndex >= 0 && currentDlIndex + 1 < saveItems.DownloadItems.Count)
                {
                    saveItems.CurrentItem = saveItems.DownloadItems[currentDlIndex + 1];
                    SaveVideo_Step1(saveItems, null);
                }
                else
                {
                    site = DownloadManager.Instance.Remove(saveItems);
                }
            }
            else
            {
                site = DownloadManager.Instance.Remove(saveItems);
            }

            Dispatcher.Invoke((Action)(() =>
            {
                downloadNotifier.GetBindingExpression(TextBlock.TextProperty).UpdateTarget();
                downloadNotifier.GetBindingExpression(TextBlock.VisibilityProperty).UpdateTarget();
            }));

            if (!string.IsNullOrEmpty(site))
            {
                var continuationList = DownloadManager.Instance.GetNext(site);
                if (continuationList != null)
                {
                    SaveVideo_Step1(continuationList, null);
                }
            }
        }
        private void SaveVideo_Step3(DownloadList saveItems, string url, bool? enque)
        {
            // check for valid url and cut off additional parameter
            if (String.IsNullOrEmpty(url) ||
                !UriUtils.IsValidUri((url.IndexOf(SimpleUrl.ParameterSeparator) > 0) ? url.Substring(0, url.IndexOf(SimpleUrl.ParameterSeparator)) : url))
            {
                notification.Show(Translation.Instance.Error, Translation.Instance.UnableToDownloadVideo);
                return;
            }

            saveItems.CurrentItem.Url = url;
            if (string.IsNullOrEmpty(saveItems.CurrentItem.Title)) saveItems.CurrentItem.Title = saveItems.CurrentItem.VideoInfo.Title;

            if (!string.IsNullOrEmpty(saveItems.CurrentItem.OverrideFolder))
            {
                if (!string.IsNullOrEmpty(saveItems.CurrentItem.OverrideFileName))
                    saveItems.CurrentItem.LocalFile = System.IO.Path.Combine(saveItems.CurrentItem.OverrideFolder, saveItems.CurrentItem.OverrideFileName);
                else
                    saveItems.CurrentItem.LocalFile = System.IO.Path.Combine(saveItems.CurrentItem.OverrideFolder, saveItems.CurrentItem.Util.GetFileNameForDownload(saveItems.CurrentItem.VideoInfo, saveItems.CurrentItem.Category, url));
            }
            else
            {
                saveItems.CurrentItem.LocalFile = System.IO.Path.Combine(System.IO.Path.Combine(OnlineVideoSettings.Instance.DownloadDir, saveItems.CurrentItem.Util.Settings.Name), saveItems.CurrentItem.Util.GetFileNameForDownload(saveItems.CurrentItem.VideoInfo, saveItems.CurrentItem.Category, url));
            }

            if (saveItems.DownloadItems != null && saveItems.DownloadItems.Count > 1)
            {
                saveItems.CurrentItem.LocalFile = string.Format(@"{0}\{1} - {2}#{3}{4}",
                    System.IO.Path.GetDirectoryName(saveItems.CurrentItem.LocalFile),
                    System.IO.Path.GetFileNameWithoutExtension(saveItems.CurrentItem.LocalFile),
                    (saveItems.DownloadItems.IndexOf(saveItems.CurrentItem) + 1).ToString().PadLeft((saveItems.DownloadItems.Count).ToString().Length, '0'),
                    (saveItems.DownloadItems.Count).ToString(),
                    System.IO.Path.GetExtension(saveItems.CurrentItem.LocalFile));
            }

            saveItems.CurrentItem.LocalFile = FileUtils.GetNextFileName(saveItems.CurrentItem.LocalFile);
            saveItems.CurrentItem.ThumbFile = string.IsNullOrEmpty(saveItems.CurrentItem.VideoInfo.ThumbnailImage) ? saveItems.CurrentItem.VideoInfo.Thumb : saveItems.CurrentItem.VideoInfo.ThumbnailImage;

            // make sure the target dir exists
            if (!(System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(saveItems.CurrentItem.LocalFile))))
            {
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(saveItems.CurrentItem.LocalFile));
            }

            if (enque == true)
                DownloadManager.Instance.Add(saveItems.CurrentItem.Util.Settings.Name, saveItems);
            else if (enque == false)
                DownloadManager.Instance.Add(null, saveItems);

            downloadNotifier.GetBindingExpression(TextBlock.TextProperty).UpdateTarget();
            downloadNotifier.GetBindingExpression(TextBlock.VisibilityProperty).UpdateTarget();

            System.Threading.Thread downloadThread = new System.Threading.Thread((System.Threading.ParameterizedThreadStart)delegate(object o)
            {
                DownloadList dlList = o as DownloadList;
                try
                {
                    IDownloader dlHelper = null;
                    if (dlList.CurrentItem.Url.ToLower().StartsWith("mms://")) dlHelper = new MMSDownloader();
                    else dlHelper = new OnlineVideos.MPUrlSourceFilter.Downloader();
                    dlList.CurrentItem.Downloader = dlHelper;
                    dlList.CurrentItem.Start = DateTime.Now;
                    Log.Info("Starting download of '{0}' to '{1}' from Site '{2}'", dlList.CurrentItem.Url, dlList.CurrentItem.LocalFile, dlList.CurrentItem.Util.Settings.Name);
                    Exception exception = dlHelper.Download(dlList.CurrentItem);
                    if (exception != null) Log.Warn("Error downloading '{0}', Msg: {1}", dlList.CurrentItem.Url, exception.Message);
                    OnDownloadFileCompleted(dlList, exception);
                }
                catch (System.Threading.ThreadAbortException)
                {
                    // the thread was aborted on purpose, let it finish gracefully
                    System.Threading.Thread.ResetAbort();
                }
                catch (Exception ex)
                {
                    Log.Warn("Error downloading '{0}', Msg: {1}", dlList.CurrentItem.Url, ex.Message);
                    OnDownloadFileCompleted(dlList, ex);
                }
            });
            downloadThread.IsBackground = true;
            downloadThread.Name = "OVDownload";
            downloadThread.Start(saveItems);
        }
        private void SaveVideo_Step2(DownloadList saveItems, List<String> loUrlList, bool? enque)
        {
            RemoveInvalidUrls(loUrlList);

            // if no valid urls were returned show error msg
            if (loUrlList == null || loUrlList.Count == 0)
            {
                notification.Show(Translation.Instance.Error, Translation.Instance.UnableToDownloadVideo);
                return;
            }

            // create download list if more than one url
            if (loUrlList.Count > 1)
            {
                saveItems.DownloadItems = new List<DownloadInfo>();
                foreach (string url in loUrlList)
                {
                    VideoInfo vi = saveItems.CurrentItem.VideoInfo.CloneForPlaylist(url, url == loUrlList[0]);
                    string url_new = url;
                    if (url == loUrlList[0])
                    {
                        url_new = saveItems.CurrentItem.Util.GetPlaylistItemVideoUrl(vi, string.Empty);
                    }
                    DownloadInfo pli = DownloadInfo.Create(vi, saveItems.CurrentItem.Category, saveItems.CurrentItem.Util);
                    pli.Title = string.Format("{0} - {1} / {2}", vi.Title, (saveItems.DownloadItems.Count + 1).ToString(), loUrlList.Count);
                    pli.Url = url_new;
                    pli.OverrideFolder = saveItems.CurrentItem.OverrideFolder;
                    pli.OverrideFileName = saveItems.CurrentItem.OverrideFileName;
                    saveItems.DownloadItems.Add(pli);
                }
                // make the first item the current to be saved now
                saveItems.CurrentItem = saveItems.DownloadItems[0];
                loUrlList = new List<string>(new string[] { saveItems.CurrentItem.Url });
            }
            // if multiple quality choices are available show a selection dialogue
            string urlToSave = loUrlList[0];
            if (saveItems.CurrentItem.VideoInfo.PlaybackOptions != null && saveItems.CurrentItem.VideoInfo.PlaybackOptions.Count > 0)
            {
                string choice = null;
                if (saveItems.CurrentItem.VideoInfo.PlaybackOptions.Count > 1)
                {
                    PlaybackChoices dlg = new PlaybackChoices();
                    dlg.Owner = this;
                    dlg.lvChoices.ItemsSource = saveItems.CurrentItem.VideoInfo.PlaybackOptions.Keys;
                    var preSelectedItem = saveItems.CurrentItem.VideoInfo.PlaybackOptions.FirstOrDefault(kvp => kvp.Value == urlToSave);
                    if (!string.IsNullOrEmpty(preSelectedItem.Key)) dlg.lvChoices.SelectedValue = preSelectedItem.Key;
                    if (dlg.lvChoices.SelectedIndex < 0) dlg.lvChoices.SelectedIndex = 0;
                    if (dlg.ShowDialog() == true) choice = dlg.lvChoices.SelectedItem.ToString();
                }
                else
                {
                    choice = saveItems.CurrentItem.VideoInfo.PlaybackOptions.Keys.First();
                }

                if (choice != null)
                {
                    waitCursor.Visibility = System.Windows.Visibility.Visible;
                    Gui2UtilConnector.Instance.ExecuteInBackgroundAndCallback(delegate()
                    {
                        return saveItems.CurrentItem.VideoInfo.GetPlaybackOptionUrl(choice);
                    },
                    delegate(Gui2UtilConnector.ResultInfo resultInfo)
                    {
                        waitCursor.Visibility = System.Windows.Visibility.Hidden;
                        if (ReactToResult(resultInfo, Translation.Instance.GettingPlaybackUrlsForVideo))
                        {
                            SaveVideo_Step3(saveItems, resultInfo.ResultObject as string, enque);
                        }
                    }, true);
                }
            }
            else
            {
                SaveVideo_Step3(saveItems, urlToSave, enque);
            }
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="saveItems"></param>
 /// <param name="enque">null : download the next item in a DownloadList that is already in the Manager</param>
 private void SaveVideo_Step1(DownloadList saveItems, bool? enque = false)
 {
     if (enque != null) 
     {
         // when the DownloadManager already contains the current DownloadInfo of the given list - show already downloading message
         if (DownloadManager.Instance.Contains(saveItems.CurrentItem))
         {
             notification.Show(Translation.Instance.Error, Translation.Instance.AlreadyDownloading);
             return;
         }
         // check if there is already a download running from this site - yes? -> enque | no -> start now
         if (enque == true && DownloadManager.Instance.Contains(saveItems.CurrentItem.Util.Settings.Name))
         {
             DownloadManager.Instance.Add(saveItems.CurrentItem.Util.Settings.Name, saveItems);
             return;
         }
     }
     if (!string.IsNullOrEmpty(saveItems.CurrentItem.Url))
     {
         waitCursor.Visibility = System.Windows.Visibility.Visible;
         Gui2UtilConnector.Instance.ExecuteInBackgroundAndCallback(
             delegate()
             {
                 return saveItems.CurrentItem.Util.GetPlaylistItemVideoUrl(saveItems.CurrentItem.VideoInfo, saveItems.ChosenPlaybackOption);
             },
             delegate(Gui2UtilConnector.ResultInfo resultInfo)
             {
                 waitCursor.Visibility = System.Windows.Visibility.Hidden;
                 if (ReactToResult(resultInfo, Translation.Instance.GettingPlaybackUrlsForVideo))
                 {
                     SaveVideo_Step2(saveItems, new List<string>() { resultInfo.ResultObject as string }, enque);
                 }
             }
         );
     }
     else
     {
         waitCursor.Visibility = System.Windows.Visibility.Visible;
         Gui2UtilConnector.Instance.ExecuteInBackgroundAndCallback(
             delegate()
             {
                 return saveItems.CurrentItem.Util.GetMultipleVideoUrls(saveItems.CurrentItem.VideoInfo);
             },
             delegate(Gui2UtilConnector.ResultInfo resultInfo)
             {
                 waitCursor.Visibility = System.Windows.Visibility.Hidden;
                 if (ReactToResult(resultInfo, Translation.Instance.GettingPlaybackUrlsForVideo))
                 {
                     SaveVideo_Step2(saveItems, resultInfo.ResultObject as List<String>, enque);
                 }
             }
         );
     }
 }
        private void OnDownloadFileCompleted(DownloadList saveItems, Exception error)
        {
            // notify the Util of the downloaded video that the download has stopped
            try
            {
                if (saveItems.CurrentItem != null && saveItems.CurrentItem.Util != null)
                {
                    saveItems.CurrentItem.Util.OnDownloadEnded(saveItems.CurrentItem.VideoInfo, saveItems.CurrentItem.Url, (double)saveItems.CurrentItem.PercentComplete / 100.0d, error != null);
                }
            }
            catch (Exception ex)
            {
                Log.Instance.Warn("Error on Util.OnDownloadEnded: {0}", ex.ToString());
            }

            bool preventMessageDuetoAdult = (saveItems.CurrentItem.Util != null && saveItems.CurrentItem.Util.Settings.ConfirmAge && OnlineVideoSettings.Instance.UseAgeConfirmation && !OnlineVideoSettings.Instance.AgeConfirmed);

            if (error != null && !saveItems.CurrentItem.Downloader.Cancelled)
            {
                if (!preventMessageDuetoAdult)
                {
					GUIWindowManager.SendThreadCallbackAndWait((p1, p2, dataCurrentItemTitle) => 
					{
						GUIDialogNotify loDlgNotify = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
						if (loDlgNotify != null)
						{
							loDlgNotify.Reset();
							loDlgNotify.SetImage(SiteImageExistenceCache.GetImageForSite("OnlineVideos", type: "Icon"));
							loDlgNotify.SetHeading(Translation.Instance.Error);
							loDlgNotify.SetText(string.Format(Translation.Instance.DownloadFailed, (string)dataCurrentItemTitle));
							loDlgNotify.DoModal(GUIWindowManager.ActiveWindow);
						}
						return 0; },
					0, 0, saveItems.CurrentItem.Title);
                }
            }
            else
            {
                try
                {
                    // if the image given was an url -> check if thumb exists otherwise download
                    if (saveItems.CurrentItem.ThumbFile.ToLower().StartsWith("http"))
                    {
                        string thumbFile = Helpers.FileUtils.GetThumbFile(saveItems.CurrentItem.ThumbFile);
                        if (File.Exists(thumbFile)) saveItems.CurrentItem.ThumbFile = thumbFile;
                        else if (ImageDownloader.DownloadAndCheckImage(saveItems.CurrentItem.ThumbFile, thumbFile)) saveItems.CurrentItem.ThumbFile = thumbFile;
                    }
                    // save thumb for this video as well if it exists
                    if (!saveItems.CurrentItem.ThumbFile.ToLower().StartsWith("http") && File.Exists(saveItems.CurrentItem.ThumbFile))
                    {
                        string localImageName = Path.Combine(
                            Path.GetDirectoryName(saveItems.CurrentItem.LocalFile),
                            Path.GetFileNameWithoutExtension(saveItems.CurrentItem.LocalFile))
                            + Path.GetExtension(saveItems.CurrentItem.ThumbFile);
                        File.Copy(saveItems.CurrentItem.ThumbFile, localImageName, true);
                    }
					// save subtitles if SubtitlesUrl was set
					SaveSubtitles(saveItems.CurrentItem.VideoInfo, Path.ChangeExtension(saveItems.CurrentItem.LocalFile, ".srt"));
					// save matroska tag
					string niceTitle = saveItems.CurrentItem.Util.GetFileNameForDownload(saveItems.CurrentItem.VideoInfo, saveItems.CurrentItem.Category, null);
					File.WriteAllText(Path.ChangeExtension(saveItems.CurrentItem.LocalFile, ".xml"), saveItems.CurrentItem.VideoInfo.CreateMatroskaXmlTag(niceTitle), System.Text.Encoding.UTF8);
                }
                catch (Exception ex)
                {
                    Log.Instance.Warn("Error saving additional files for download: {0}", ex.ToString());
                }

                // get file size
                int fileSize = saveItems.CurrentItem.KbTotal;
                if (fileSize <= 0)
                {
                    try { fileSize = (int)((new FileInfo(saveItems.CurrentItem.LocalFile)).Length / 1024); }
                    catch { }
                }

                Log.Instance.Info("{3} download of '{0}' - {1} KB in {2}", saveItems.CurrentItem.LocalFile, fileSize, (DateTime.Now - saveItems.CurrentItem.Start).ToString(), saveItems.CurrentItem.Downloader.Cancelled ? "Cancelled" : "Finished");

                if (!preventMessageDuetoAdult)
                {
					GUIWindowManager.SendThreadCallbackAndWait((p1, dataFileSize, dataCurrentItem) => 
					{
						GUIDialogNotify loDlgNotify = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
						if (loDlgNotify != null)
						{
							loDlgNotify.Reset();
							loDlgNotify.SetImage(SiteImageExistenceCache.GetImageForSite("OnlineVideos", type: "Icon"));
							if (((DownloadInfo)dataCurrentItem).Downloader.Cancelled)
								loDlgNotify.SetHeading(Translation.Instance.DownloadCancelled);
							else
								loDlgNotify.SetHeading(Translation.Instance.DownloadComplete);
							loDlgNotify.SetText(string.Format("{0}{1}", ((DownloadInfo)dataCurrentItem).Title, dataFileSize > 0 ? " ( " + dataFileSize.ToString("n0") + " KB)" : ""));
							loDlgNotify.DoModal(GUIWindowManager.ActiveWindow);
						}
						return 0; },
					0, fileSize, saveItems.CurrentItem);
                }

                // invoke VideoDownloaded event
                if (VideoDownloaded != null)
                {
                    try
                    {
                        VideoDownloaded(saveItems.CurrentItem.LocalFile, saveItems.CurrentItem.Util.Settings.Name, saveItems.CurrentItem.Category != null ? saveItems.CurrentItem.Category.RecursiveName() : "", saveItems.CurrentItem.Title);
                    }
                    catch (Exception ex)
                    {
                        Log.Instance.Warn("Error invoking external VideoDownloaded event handler: {0}", ex.ToString());
                    }
                }
            }

            // download the next if list not empty and not last in list and not cancelled by the user
            string site = null;
            if (saveItems.DownloadItems != null && saveItems.DownloadItems.Count > 1 && !saveItems.CurrentItem.Downloader.Cancelled)
            {
                int currentDlIndex = saveItems.DownloadItems.IndexOf(saveItems.CurrentItem);
                if (currentDlIndex >= 0 && currentDlIndex + 1 < saveItems.DownloadItems.Count)
                {
                    saveItems.CurrentItem = saveItems.DownloadItems[currentDlIndex + 1];
                    GUIWindowManager.SendThreadCallbackAndWait((p1, p2, data) => { SaveVideo_Step1(saveItems, null); return 0; }, 0, 0, null);
                }
                else
                {
                    site = DownloadManager.Instance.Remove(saveItems);
                }
            }
            else
            {
                site = DownloadManager.Instance.Remove(saveItems);
            }

            if (!string.IsNullOrEmpty(site))
            {
                var continuationList = DownloadManager.Instance.GetNext(site);
                if (continuationList != null)
                {
                    GUIWindowManager.SendThreadCallbackAndWait((p1, p2, data) => { SaveVideo_Step1(continuationList, null); return 0; }, 0, 0, null);
                }
            }

            GUIPropertyManager.SetProperty("#OnlineVideos.currentDownloads", DownloadManager.Instance.Count.ToString());
        }
        private void SaveVideo_Step3(DownloadList saveItems, string url, bool? enque)
        {
            // check for valid url and cut off additional parameter
            if (String.IsNullOrEmpty(url) ||
                !Helpers.UriUtils.IsValidUri((url.IndexOf(MPUrlSourceFilter.SimpleUrl.ParameterSeparator) > 0) ? url.Substring(0, url.IndexOf(MPUrlSourceFilter.SimpleUrl.ParameterSeparator)) : url))
            {
                GUIDialogNotify dlg = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
                if (dlg != null)
                {
                    dlg.Reset();
                    dlg.SetImage(SiteImageExistenceCache.GetImageForSite("OnlineVideos", type: "Icon"));
                    dlg.SetHeading(Translation.Instance.Error);
                    dlg.SetText(Translation.Instance.UnableToDownloadVideo);
                    dlg.DoModal(GUIWindowManager.ActiveWindow);
                }
                return;
            }

            saveItems.CurrentItem.Url = url;
            if (string.IsNullOrEmpty(saveItems.CurrentItem.Title)) saveItems.CurrentItem.Title = saveItems.CurrentItem.VideoInfo.Title;

            if (!string.IsNullOrEmpty(saveItems.CurrentItem.OverrideFolder))
            {
                if (!string.IsNullOrEmpty(saveItems.CurrentItem.OverrideFileName))
                    saveItems.CurrentItem.LocalFile = Path.Combine(saveItems.CurrentItem.OverrideFolder, saveItems.CurrentItem.OverrideFileName);
                else
                    saveItems.CurrentItem.LocalFile = Path.Combine(saveItems.CurrentItem.OverrideFolder, saveItems.CurrentItem.Util.GetFileNameForDownload(saveItems.CurrentItem.VideoInfo, saveItems.CurrentItem.Category, url));
            }
            else
            {
                saveItems.CurrentItem.LocalFile = Path.Combine(Path.Combine(OnlineVideoSettings.Instance.DownloadDir, saveItems.CurrentItem.Util.Settings.Name), saveItems.CurrentItem.Util.GetFileNameForDownload(saveItems.CurrentItem.VideoInfo, saveItems.CurrentItem.Category, url));
            }

            if (saveItems.DownloadItems != null && saveItems.DownloadItems.Count > 1)
            {
                saveItems.CurrentItem.LocalFile = string.Format(@"{0}\{1} - {2}#{3}{4}",
                    Path.GetDirectoryName(saveItems.CurrentItem.LocalFile),
                    Path.GetFileNameWithoutExtension(saveItems.CurrentItem.LocalFile),
                    (saveItems.DownloadItems.IndexOf(saveItems.CurrentItem) + 1).ToString().PadLeft((saveItems.DownloadItems.Count).ToString().Length, '0'),
                    (saveItems.DownloadItems.Count).ToString(),
                    Path.GetExtension(saveItems.CurrentItem.LocalFile));
            }

            saveItems.CurrentItem.LocalFile = Helpers.FileUtils.GetNextFileName(saveItems.CurrentItem.LocalFile);
            saveItems.CurrentItem.ThumbFile = string.IsNullOrEmpty(saveItems.CurrentItem.VideoInfo.ThumbnailImage) ? saveItems.CurrentItem.VideoInfo.Thumb : saveItems.CurrentItem.VideoInfo.ThumbnailImage;

            // make sure the target dir exists
            if (!(Directory.Exists(Path.GetDirectoryName(saveItems.CurrentItem.LocalFile))))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(saveItems.CurrentItem.LocalFile));
            }

            if (enque == true)
                DownloadManager.Instance.Add(saveItems.CurrentItem.Util.Settings.Name, saveItems);
            else if (enque == false)
                DownloadManager.Instance.Add(null, saveItems);

            GUIPropertyManager.SetProperty("#OnlineVideos.currentDownloads", DownloadManager.Instance.Count.ToString());

            System.Threading.Thread downloadThread = new System.Threading.Thread((System.Threading.ParameterizedThreadStart)delegate(object o)
            {
                DownloadList dlList = o as DownloadList;
                try
                {
                    IDownloader dlHelper = null;
                    if (dlList.CurrentItem.Url.ToLower().StartsWith("mms://")) dlHelper = new MMSDownloader();
                    else dlHelper = new OnlineVideos.MPUrlSourceFilter.Downloader();
                    dlList.CurrentItem.Downloader = dlHelper;
                    dlList.CurrentItem.Start = DateTime.Now;
                    Log.Instance.Info("Starting download of '{0}' to '{1}' from Site '{2}'", dlList.CurrentItem.Url, dlList.CurrentItem.LocalFile, dlList.CurrentItem.Util.Settings.Name);
                    Exception exception = dlHelper.Download(dlList.CurrentItem);
                    if (exception != null) Log.Instance.Warn("Error downloading '{0}', Msg: {1}", dlList.CurrentItem.Url, exception.Message);
                    OnDownloadFileCompleted(dlList, exception);
                }
                catch (System.Threading.ThreadAbortException)
                {
                    // the thread was aborted on purpose, let it finish gracefully
                    System.Threading.Thread.ResetAbort();
                }
                catch (Exception ex)
                {
                    Log.Instance.Warn("Error downloading '{0}', Msg: {1}", dlList.CurrentItem.Url, ex.Message);
                    OnDownloadFileCompleted(dlList, ex);
                }
            });
            downloadThread.IsBackground = true;
            downloadThread.Name = "OVDownload";
            downloadThread.Start(saveItems);

            GUIDialogNotify dlgNotify = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
            if (dlgNotify != null)
            {
                dlgNotify.Reset();
                dlgNotify.SetImage(SiteImageExistenceCache.GetImageForSite("OnlineVideos", type: "Icon"));
                dlgNotify.SetHeading(Translation.Instance.DownloadStarted);
                dlgNotify.SetText(saveItems.CurrentItem.Title);
                dlgNotify.DoModal(GUIWindowManager.ActiveWindow);
            }
        }
        private void SaveVideo_Step2(DownloadList saveItems, List<String> loUrlList, bool? enque)
        {
            Helpers.UriUtils.RemoveInvalidUrls(loUrlList);

            // if no valid urls were returned show error msg
            if (loUrlList == null || loUrlList.Count == 0)
            {
                GUIDialogNotify dlg = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
                if (dlg != null)
                {
                    dlg.Reset();
                    dlg.SetImage(SiteImageExistenceCache.GetImageForSite("OnlineVideos", type: "Icon"));
                    dlg.SetHeading(Translation.Instance.Error);
                    dlg.SetText(Translation.Instance.UnableToDownloadVideo);
                    dlg.DoModal(GUIWindowManager.ActiveWindow);
                }
                return;
            }

            // create download list if more than one url
            if (loUrlList.Count > 1)
            {
                saveItems.DownloadItems = new List<DownloadInfo>();
                foreach (string url in loUrlList)
                {
                    VideoInfo vi = saveItems.CurrentItem.VideoInfo.CloneForPlaylist(url, url == loUrlList[0]);
                    string url_new = url;
                    if (url == loUrlList[0])
                    {
                        url_new = saveItems.CurrentItem.Util.GetPlaylistItemVideoUrl(vi, string.Empty);
                    }
                    DownloadInfo pli = DownloadInfo.Create(vi, saveItems.CurrentItem.Category, saveItems.CurrentItem.Util);
                    pli.Title = string.Format("{0} - {1} / {2}", vi.Title, (saveItems.DownloadItems.Count + 1).ToString(), loUrlList.Count);
                    pli.Url = url_new;
                    pli.OverrideFolder = saveItems.CurrentItem.OverrideFolder;
                    pli.OverrideFileName = saveItems.CurrentItem.OverrideFileName;
                    saveItems.DownloadItems.Add(pli);
                }
                // make the first item the current to be saved now
                saveItems.CurrentItem = saveItems.DownloadItems[0];
                loUrlList = new List<string>(new string[] { saveItems.CurrentItem.Url });
            }
            // if multiple quality choices are available show a selection dialogue
            string lsUrl = loUrlList[0];
            bool resolve = DisplayPlaybackOptions(saveItems.CurrentItem.VideoInfo, ref lsUrl, enque == null); // skip dialog when downloading an item of a queue
            if (lsUrl == "-1") return; // user canceled the dialog -> don't download
            if (resolve)
            {
                saveItems.ChosenPlaybackOption = lsUrl;
                if (saveItems.CurrentItem.VideoInfo.GetType().FullName == typeof(VideoInfo).FullName)
                {
                    SaveVideo_Step3(saveItems, saveItems.CurrentItem.VideoInfo.GetPlaybackOptionUrl(lsUrl), enque);
                }
                else
                {
                    // display wait cursor as GetPlaybackOptionUrl might do webrequests when overridden
                    Gui2UtilConnector.Instance.ExecuteInBackgroundAndCallback(delegate()
                    {
                        return saveItems.CurrentItem.VideoInfo.GetPlaybackOptionUrl(lsUrl);
                    },
                    delegate(bool success, object result)
                    {
                        if (success) SaveVideo_Step3(saveItems, result as string, enque);
                    }
                    , Translation.Instance.GettingPlaybackUrlsForVideo, true);
                }
            }
            else
            {
                SaveVideo_Step3(saveItems, lsUrl, enque);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="saveItems"></param>
        /// <param name="enque">null : download the next item in a DownloadList that is already in the Manager</param>
        private void SaveVideo_Step1(DownloadList saveItems, bool? enque = false)
        {
            if (string.IsNullOrEmpty(OnlineVideoSettings.Instance.DownloadDir))
            {
                GUIDialogNotify dlg = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
                if (dlg != null)
                {
                    dlg.Reset();
                    dlg.SetImage(SiteImageExistenceCache.GetImageForSite("OnlineVideos", type: "Icon"));
                    dlg.SetHeading(Translation.Instance.Error);
                    dlg.SetText(Translation.Instance.SetDownloadFolderInConfig);
                    dlg.DoModal(GUIWindowManager.ActiveWindow);
                }
                return;
            }

            if (enque != null) // when the DownloadManager already contains the current DownloadInfo of the given list - show already downloading message
            {
                if (DownloadManager.Instance.Contains(saveItems.CurrentItem))
                {
                    GUIDialogNotify dlg = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
                    if (dlg != null)
                    {
                        dlg.Reset();
                        dlg.SetImage(SiteImageExistenceCache.GetImageForSite("OnlineVideos", type: "Icon"));
                        dlg.SetHeading(Translation.Instance.Error);
                        dlg.SetText(Translation.Instance.AlreadyDownloading);
                        dlg.DoModal(GUIWindowManager.ActiveWindow);
                    }
                    return;
                }
                // check if there is already a download running from this site - yes? -> enque | no -> start now
                if (enque == true && DownloadManager.Instance.Contains(saveItems.CurrentItem.Util.Settings.Name))
                {
                    DownloadManager.Instance.Add(saveItems.CurrentItem.Util.Settings.Name, saveItems);
                    return;
                }
            }
            if (!string.IsNullOrEmpty(saveItems.CurrentItem.Url))
            {
                Gui2UtilConnector.Instance.ExecuteInBackgroundAndCallback(delegate()
                {
                    return saveItems.CurrentItem.Util.GetPlaylistItemVideoUrl(saveItems.CurrentItem.VideoInfo, saveItems.ChosenPlaybackOption);
                },
                delegate(bool success, object result)
                {
                    if (success) SaveVideo_Step2(saveItems, new List<string>() { result as string }, enque);
                },
                Translation.Instance.GettingPlaybackUrlsForVideo, true);
            }
            else
            {
                Gui2UtilConnector.Instance.ExecuteInBackgroundAndCallback(delegate()
                {
                    return saveItems.CurrentItem.Util.GetMultipleVideoUrls(saveItems.CurrentItem.VideoInfo);
                },
                delegate(bool success, object result)
                {
                    if (success) SaveVideo_Step2(saveItems, result as List<String>, enque);
                },
                Translation.Instance.GettingPlaybackUrlsForVideo, true);
            }
        }
Exemplo n.º 12
0
		static void SaveVideo_Step2(DownloadList saveItems, List<String> urls, bool? enque)
		{
            Helpers.UriUtils.RemoveInvalidUrls(urls);

			// if no valid urls were returned show error msg
			if (urls == null || urls.Count == 0)
			{				
				ServiceRegistration.Get<IDialogManager>().ShowDialog("[OnlineVideos.Error]", "[OnlineVideos.UnableToDownloadVideo]", DialogType.OkDialog, false, DialogButtonType.Ok);
				return;
			}

			// create download list if more than one url
			if (urls.Count > 1)
			{
				saveItems.DownloadItems = new List<DownloadInfo>();
				foreach (string url in urls)
				{
					VideoInfo vi = saveItems.CurrentItem.VideoInfo.CloneForPlaylist(url, url == urls[0]);
					string url_new = url;
					if (url == urls[0])
					{
						url_new = saveItems.CurrentItem.Util.GetPlaylistItemVideoUrl(vi, string.Empty);
					}
					DownloadInfo pli = DownloadInfo.Create(vi, saveItems.CurrentItem.Category, saveItems.CurrentItem.Util);
					pli.Title = string.Format("{0} - {1} / {2}", vi.Title, (saveItems.DownloadItems.Count + 1).ToString(), urls.Count);
					pli.Url = url_new;
					pli.OverrideFolder = saveItems.CurrentItem.OverrideFolder;
					pli.OverrideFileName = saveItems.CurrentItem.OverrideFileName;
					saveItems.DownloadItems.Add(pli);
				}
				// make the first item the current to be saved now
				saveItems.CurrentItem = saveItems.DownloadItems[0];
				urls = new List<string>(new string[] { saveItems.CurrentItem.Url });
			}
			// show selection dialog for playback options
			VideoViewModel tempVi = new VideoViewModel(saveItems.CurrentItem.VideoInfo, saveItems.CurrentItem.Category, saveItems.CurrentItem.Util.Settings.Name, saveItems.CurrentItem.Util.Settings.UtilName, false);
			tempVi.ChoosePlaybackOptions(urls[0], (url) => { SaveVideo_Step3(saveItems, url, enque); }, enque == null); // skip dialog when downloading an item of a queue
		}
Exemplo n.º 13
0
		static void SaveVideo_Step1(DownloadList saveItems, bool? enque = false)
		{
			if (enque != null)
			{
				if (DownloadManager.Instance.Contains(saveItems.CurrentItem))
				{
					// when the DownloadManager already contains the current DownloadInfo of the given list - show already downloading message
					ServiceRegistration.Get<IDialogManager>().ShowDialog("[OnlineVideos.Error]", "[OnlineVideos.AlreadyDownloading]", DialogType.OkDialog, false, DialogButtonType.Ok);
					return;
				}

				// check if there is already a download running from this site - yes? -> enque | no -> start now
				if (enque == true && DownloadManager.Instance.Contains(saveItems.CurrentItem.Util.Settings.Name))
				{
					DownloadManager.Instance.Add(saveItems.CurrentItem.Util.Settings.Name, saveItems);
					return;
				}
			}

			try
			{
				if (!string.IsNullOrEmpty(saveItems.CurrentItem.Url))
				{
					var result = saveItems.CurrentItem.Util.GetPlaylistItemVideoUrl(saveItems.CurrentItem.VideoInfo, saveItems.ChosenPlaybackOption);
					SaveVideo_Step2(saveItems, new List<string>() { result }, enque);
				}
				else
				{
					var result = saveItems.CurrentItem.Util.GetMultipleVideoUrls(saveItems.CurrentItem.VideoInfo);
					SaveVideo_Step2(saveItems, result, enque);
				}
			}
			catch (Exception ex)
			{
				Log.Warn("Error getting Urls for Download: '{0}'", ex.Message);
				ServiceRegistration.Get<IDialogManager>().ShowDialog("[OnlineVideos.Error]", "[OnlineVideos.GettingPlaybackUrlsForVideo]", DialogType.OkDialog, false, DialogButtonType.Ok);
			}
		}
Exemplo n.º 14
0
        static void OnDownloadFileCompleted(DownloadList saveItems, Exception error)
        {
            // notify the Util of the downloaded video that the download has stopped
            try
            {
                if (saveItems.CurrentItem != null && saveItems.CurrentItem.Util != null)
                {
                    saveItems.CurrentItem.Util.OnDownloadEnded(saveItems.CurrentItem.VideoInfo, saveItems.CurrentItem.Url, saveItems.CurrentItem.PercentComplete / 100.0d, error != null);
                }
            }
            catch (Exception ex)
            {
                Log.Warn("Error on Util.OnDownloadEnded: {0}", ex.ToString());
            }

            bool preventMessageDuetoAdult = saveItems.CurrentItem.Util != null && saveItems.CurrentItem.Util.Settings.ConfirmAge && OnlineVideoSettings.Instance.UseAgeConfirmation && !OnlineVideoSettings.Instance.AgeConfirmed;

            if (error != null && !saveItems.CurrentItem.Downloader.Cancelled)
            {
                if (!preventMessageDuetoAdult)
                {
                    /* // todo : show download failed notification?
                    GUIDialogNotify loDlgNotify = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
                    if (loDlgNotify != null)
                    {
                        loDlgNotify.Reset();
                        loDlgNotify.SetImage(SiteImageExistenceCache.GetImageForSite("OnlineVideos", type: "Icon"));
                        loDlgNotify.SetHeading(Translation.Instance.Error);
                        loDlgNotify.SetText(string.Format(Translation.Instance.DownloadFailed, saveItems.CurrentItem.Title));
                        loDlgNotify.DoModal(GUIWindowManager.ActiveWindow);
                    }*/
                }
            }
            else
            {
                try
                {
                    // if the image given was an url -> check if thumb exists otherwise download
                    if (saveItems.CurrentItem.ThumbFile.ToLower().StartsWith("http"))
                    {
                        string thumbFile = Helpers.FileUtils.GetThumbFile(saveItems.CurrentItem.ThumbFile);
                        if (File.Exists(thumbFile)) saveItems.CurrentItem.ThumbFile = thumbFile;
                        else if (ImageDownloader.DownloadAndCheckImage(saveItems.CurrentItem.ThumbFile, thumbFile)) saveItems.CurrentItem.ThumbFile = thumbFile;
                    }
                    // save thumb for this video as well if it exists
                    if (!saveItems.CurrentItem.ThumbFile.ToLower().StartsWith("http") && File.Exists(saveItems.CurrentItem.ThumbFile))
                    {
                        string localImageName = Path.Combine(
                            Path.GetDirectoryName(saveItems.CurrentItem.LocalFile),
                            Path.GetFileNameWithoutExtension(saveItems.CurrentItem.LocalFile))
                            + Path.GetExtension(saveItems.CurrentItem.ThumbFile);
                        File.Copy(saveItems.CurrentItem.ThumbFile, localImageName, true);
                    }
                }
                catch (Exception ex)
                {
                    Log.Warn("Error saving thumbnail for download: {0}", ex.ToString());
                }

                // get file size
                int fileSize = saveItems.CurrentItem.KbTotal;
                if (fileSize <= 0)
                {
                    try { fileSize = (int)(new FileInfo(saveItems.CurrentItem.LocalFile).Length / 1024); }
                    catch { }
                }

                Log.Info("{3} download of '{0}' - {1} KB in {2}", saveItems.CurrentItem.LocalFile, fileSize, (DateTime.Now - saveItems.CurrentItem.Start).ToString(), saveItems.CurrentItem.Downloader.Cancelled ? "Cancelled" : "Finished");

                if (!preventMessageDuetoAdult)
                {
                    /* // todo : show download canceled or completed notification?
                    GUIDialogNotify loDlgNotify = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
                    if (loDlgNotify != null)
                    {
                        loDlgNotify.Reset();
                        loDlgNotify.SetImage(SiteImageExistenceCache.GetImageForSite("OnlineVideos", type: "Icon"));
                        if (saveItems.CurrentItem.Downloader.Cancelled)
                            loDlgNotify.SetHeading(Translation.Instance.DownloadCancelled);
                        else
                            loDlgNotify.SetHeading(Translation.Instance.DownloadComplete);
                        loDlgNotify.SetText(string.Format("{0}{1}", saveItems.CurrentItem.Title, fileSize > 0 ? " ( " + fileSize.ToString("n0") + " KB)" : ""));
                        loDlgNotify.DoModal(GUIWindowManager.ActiveWindow);
                    }*/
                }

                // invoke VideoDownloaded event
                /*if (VideoDownloaded != null)
                {
                    try
                    {
                        VideoDownloaded(saveItems.CurrentItem.LocalFile, saveItems.CurrentItem.Util.Settings.Name, saveItems.CurrentItem.Category != null ? saveItems.CurrentItem.Category.RecursiveName() : "", saveItems.CurrentItem.Title);
                    }
                    catch (Exception ex)
                    {
                        Log.Warn("Error invoking external VideoDownloaded event handler: {0}", ex.ToString());
                    }
                }*/
            }

            // download the next if list not empty and not last in list and not cancelled by the user
            string site = null;
            if (saveItems.DownloadItems != null && saveItems.DownloadItems.Count > 1 && !saveItems.CurrentItem.Downloader.Cancelled)
            {
                int currentDlIndex = saveItems.DownloadItems.IndexOf(saveItems.CurrentItem);
                if (currentDlIndex >= 0 && currentDlIndex + 1 < saveItems.DownloadItems.Count)
                {
                    saveItems.CurrentItem = saveItems.DownloadItems[currentDlIndex + 1];
                    SaveVideo_Step1(saveItems, null);
                }
                else
                {
                    site = DownloadManager.Instance.Remove(saveItems);
                }
            }
            else
            {
                site = DownloadManager.Instance.Remove(saveItems);
            }

            if (!string.IsNullOrEmpty(site))
            {
                var continuationList = DownloadManager.Instance.GetNext(site);
                if (continuationList != null)
                {
                    SaveVideo_Step1(continuationList, null);
                }
            }
        }