private void CloseForm()
        {
            CloseFromMethod = true;

            if (Downloads.Default.CloseDownloaderAfterFinish != chkDownloaderCloseAfterDownload.Checked && !BatchDownload)
            {
                Downloads.Default.CloseDownloaderAfterFinish = chkDownloaderCloseAfterDownload.Checked;
                Downloads.Default.Save();
            }


            if (DownloadErrored)
            {
                if (BatchDownload)
                {
                    this.DialogResult = System.Windows.Forms.DialogResult.No;
                }
                else
                {
                    this.Dispose();
                }
            }
            if (!DownloadFinished)
            {
                try {
                    if (!DownloadProcess.HasExited)
                    {
                        DownloadProcess.Kill();
                    }
                    if (DownloadThread.IsAlive)
                    {
                        DownloadThread.Abort();
                    }
                }
                catch (Exception ex) {
                    ErrorLog.ReportException(ex);
                }
            }

            if (DownloadAborted)
            {
                if (BatchDownload)
                {
                    this.DialogResult = System.Windows.Forms.DialogResult.Abort;
                }
                else
                {
                    this.Dispose();
                }
            }
            else if (DownloadFinished)
            {
                if (DownloadProcess.ExitCode == 0)
                {
                    if (BatchDownload)
                    {
                        this.DialogResult = System.Windows.Forms.DialogResult.Yes;
                    }
                    else
                    {
                        this.Dispose();
                    }
                }
                else
                {
                    if (BatchDownload)
                    {
                        this.DialogResult = System.Windows.Forms.DialogResult.No;
                    }
                }
            }
            else
            {
                if (BatchDownload)
                {
                    this.DialogResult = System.Windows.Forms.DialogResult.No;
                }
            }
        }
        private void BeginDownload()
        {
            Debug.Print("BeginDownload()");
            if (string.IsNullOrEmpty(DownloadUrl))
            {
                MessageBox.Show("The URL is null or empty. Please enter a URL or Download path.");
                return;
            }
            rtbConsoleOutput.AppendText("Beginning download, this box will output progress\n");
            if (BatchDownload)
            {
                chkDownloaderCloseAfterDownload.Checked = true;
            }

            if (DownloadUrl.StartsWith("http://"))
            {
                DownloadUrl = "https" + DownloadUrl.Substring(4);
            }

            string YoutubeDlFileName   = null;
            string ArgumentsBuffer     = string.Empty;
            string QualityFormatBuffer = string.Empty;
            string hlsFF     = string.Empty;
            string webFolder = string.Empty;
            bool   usehlsFF  = Downloads.Default.fixReddit;

            #region youtube-dl path
            if (General.Default.UseStaticYtdl && File.Exists(General.Default.ytdlPath))
            {
                YoutubeDlFileName = General.Default.ytdlPath;
            }
            else
            {
                YoutubeDlFileName = verif.YoutubeDlPath;
            }
            if (YoutubeDlFileName == null)
            {
                rtbConsoleOutput.AppendText("Youtube-DL has not been found\nA rescan for youtube-dl was called");
                verif.RefreshYoutubeDlLocation();
                if (verif.YoutubeDlPath != null)
                {
                    rtbConsoleOutput.AppendText("try redownloading the video, it seems to be detected now.");
                }
                else
                {
                    rtbConsoleOutput.AppendText("still couldnt find youtube-dl.");
                }
                return;
            }
            rtbConsoleOutput.AppendText("Youtube-DL has been found and set\n");
            #endregion

            #region Output
            rtbConsoleOutput.AppendText("Generating output directory structure\n");
            if (Downloads.Default.separateIntoWebsiteURL)
            {
                webFolder = Download.getUrlBase(DownloadUrl) + "\\";
            }
            ArgumentsBuffer = DownloadUrl + " -o \"" + Downloads.Default.downloadPath + BatchTime + "\\" + webFolder + "{0}" + Downloads.Default.fileNameSchema + "\"";

            if (Downloads.Default.separateDownloads)
            {
                switch (DownloadType)
                {
                case 0:
                    ArgumentsBuffer = ArgumentsBuffer.Replace("{0}", "Video\\");
                    break;

                case 1:
                    ArgumentsBuffer = ArgumentsBuffer.Replace("{0}", "Audio\\");
                    break;

                case 2:
                    ArgumentsBuffer = ArgumentsBuffer.Replace("{0}", "Custom\\");
                    break;

                default:
                    rtbConsoleOutput.AppendText("Unable to determine what download type to use (expected 0, 1, or 2)");
                    return;
                }
            }
            else
            {
                ArgumentsBuffer = ArgumentsBuffer.Replace("{0}", "");
            }
            rtbConsoleOutput.AppendText("The output was generated and will be used\n");
            #endregion

            #region Quality + format
            switch (DownloadType)
            {
            case 0: {
                if (DownloadQuality == 0)
                {
                    if (DownloadVideoAudio)
                    {
                        if (DownloadFormat == 4)
                        {
                            ArgumentsBuffer += DownloadFormats.VideoFormatArgsArrayOld[0];
                        }
                        else
                        {
                            ArgumentsBuffer += DownloadFormats.VideoArgs[0];
                        }
                    }
                    else
                    {
                        if (DownloadFormat == 4)
                        {
                            ArgumentsBuffer += DownloadFormats.VideoFormatArgsArrayNoSoundOld[0];
                        }
                        else
                        {
                            ArgumentsBuffer += DownloadFormats.VideoArgsNoSound[0];
                        }
                    }
                }
                else
                {
                    if (DownloadVideoAudio)
                    {
                        ArgumentsBuffer += DownloadFormats.GetVideoFormatArgs(DownloadQuality, Set60FPS);
                    }
                    else
                    {
                        ArgumentsBuffer += DownloadFormats.GetVideoFormatArgsNoSound(DownloadQuality, Set60FPS);
                    }
                }
                break;
            }

            case 1: {
                if (UseVBR)
                {
                    if (DownloadQuality == 0)
                    {
                        ArgumentsBuffer += " -f bestaudio --extract-audio --audio-quality 0";
                    }
                    else
                    {
                        ArgumentsBuffer += " --extract-audio --audio-quality " + DownloadQuality;
                    }
                }
                else
                {
                    if (DownloadQuality == 0)
                    {
                        ArgumentsBuffer += " -f bestaudio --extract-audio --audio-quality 0";
                    }
                    else
                    {
                        ArgumentsBuffer += " --extract-audio --audio-quality " + DownloadFormats.AudioQualityNamesArray[DownloadQuality];
                    }
                }
                break;
            }

            case 2: {
                rtbConsoleOutput.AppendText("Custom was requested, skipping quality + format");
                ArgumentsBuffer += " " + DownloadArguments;
                break;
            }

            default: {
                rtbConsoleOutput.AppendText("Expected a downloadtype (Quality + Format)");
                return;
            }
            }

            if (DownloadFormat > 0 && DownloadType == 0 && DownloadFormat != 4)
            {
                ArgumentsBuffer += DownloadFormats.VideoFormatsArray[DownloadFormat - 1];
            }
            else if (DownloadType == 1)
            {
                ArgumentsBuffer += " --audio-format " + DownloadFormats.AudioFormatsArray[DownloadFormat];
            }

            rtbConsoleOutput.AppendText("The quality and format has been set\n");
            #endregion

            #region Arguments
            if (Downloads.Default.fixReddit)
            {
                if (verif.FFmpegPath == null)
                {
                    rtbConsoleOutput.AppendText("Fix v.redd.it was requested, but ffmpeg hasn't been found\n");
                }
                else if (Download.isReddit(DownloadUrl) && usehlsFF)
                {
                    rtbConsoleOutput.AppendText("Fix v.redd.it has been set; looking for ffmpeg\n");
                    if (General.Default.UseStaticFFmpeg && File.Exists(General.Default.ffmpegPath))
                    {
                        ArgumentsBuffer += " --ffmpeg-location \"" + General.Default.ffmpegPath + "\\ffmpeg.exe\" --hls-prefer-ffmpeg";
                    }
                    else
                    {
                        ArgumentsBuffer += " --ffmpeg-location \"" + verif.FFmpegPath + "\\ffmpeg.exe\" --hls-prefer-ffmpeg";
                    }
                    rtbConsoleOutput.AppendText("ffmpeg has been found and set\n");
                }
            }
            if (DownloadType != 2)
            {
                if (Downloads.Default.SaveSubtitles)
                {
                    ArgumentsBuffer += " --all-subs";
                    if (!string.IsNullOrEmpty(Downloads.Default.SubtitleFormat))
                    {
                        ArgumentsBuffer += "--sub-format " + Downloads.Default.SubtitleFormat + " ";
                    }
                    if (Downloads.Default.EmbedSubtitles && DownloadType == 0 && DownloadFormat == 3 || DownloadFormat == 4 || DownloadFormat == 6)
                    {
                        ArgumentsBuffer += " --embed-subs";
                    }
                }
                if (Downloads.Default.SaveVideoInfo)
                {
                    ArgumentsBuffer += " --write-info-json";
                }
                if (Downloads.Default.SaveDescription)
                {
                    ArgumentsBuffer += " --write-description";
                }
                if (Downloads.Default.SaveAnnotations)
                {
                    ArgumentsBuffer += " --write-annotations";
                }
                if (Downloads.Default.SaveThumbnail)
                {
                    // ArgumentsBuffer += "--write-all-thumbnails "; // Maybe?
                    ArgumentsBuffer += " --write-thumbnail";
                    if (Downloads.Default.EmbedThumbnails)
                    {
                        switch (DownloadType)
                        {
                        case 0:
                            if (DownloadFormat == 4)
                            {
                                ArgumentsBuffer += " --embed-thumbnail";
                            }
                            else
                            {
                                rtbConsoleOutput.AppendText("!!!!!!!! WARNING !!!!!!!!\nCannot embed thumbnail to non-mp4 videos files\n");
                            }
                            break;

                        case 1:
                            if (DownloadFormat == 3 || DownloadFormat == 4)
                            {
                                ArgumentsBuffer += " --embed-thumbnail";
                            }
                            else
                            {
                                rtbConsoleOutput.AppendText("!!!!!!!! WARNING !!!!!!!!\nCannot embed thumbnail to non-m4a/mp3 audio files\n");
                            }
                            break;
                        }
                    }
                }
                if (Downloads.Default.WriteMetadata)
                {
                    ArgumentsBuffer += " --add-metadata";
                }

                if (Downloads.Default.KeepOriginalFiles)
                {
                    ArgumentsBuffer += " -k";
                }

                if (Downloads.Default.LimitDownloads && Downloads.Default.DownloadLimit > 0)
                {
                    ArgumentsBuffer += " --limit-rate " + Downloads.Default.DownloadLimit;
                    switch (Downloads.Default.DownloadLimitType)
                    {
                    case 0: {     // kb
                        ArgumentsBuffer += "K ";
                        break;
                    }

                    case 1: {     // mb
                        ArgumentsBuffer += "M ";
                        break;
                    }

                    case 2: {     // gb
                        ArgumentsBuffer += "G ";
                        break;
                    }

                    default: {     // kb default
                        ArgumentsBuffer += "K ";
                        break;
                    }
                    }
                }

                if (Downloads.Default.RetryAttempts != 10 && Downloads.Default.RetryAttempts > 0)
                {
                    ArgumentsBuffer += " --retries " + Downloads.Default.RetryAttempts;
                }

                if (Downloads.Default.ForceIPv4)
                {
                    ArgumentsBuffer += " --force-ipv4";
                }
                else if (Downloads.Default.ForceIPv6)
                {
                    ArgumentsBuffer += " --force-ipv6";
                }

                if (Downloads.Default.UseProxy && Downloads.Default.ProxyType > -1 && !string.IsNullOrEmpty(Downloads.Default.ProxyIP) && !string.IsNullOrEmpty(Downloads.Default.ProxyPort))
                {
                    ArgumentsBuffer += " --proxy " + Download.ProxyProtocols[Downloads.Default.ProxyType] + Downloads.Default.ProxyIP + ":" + Downloads.Default.ProxyPort + "/ ";
                }
            }

            rtbConsoleOutput.AppendText("Arguments have been generated and are readonly in the textbox\n");
            txtArgumentsGenerated.Text = ArgumentsBuffer;
            #endregion

            #region Download thread
            if (Program.IsDebug && Debugging && !BatchDownload)
            {
                rtbConsoleOutput.Text = ArgumentsBuffer.Replace(' ', '\n');
                return;
            }
            rtbConsoleOutput.AppendText("Creating download thread\n");
            DownloadThread = new Thread(() => {
                try {
                    DownloadProcess = new System.Diagnostics.Process()
                    {
                        StartInfo = new System.Diagnostics.ProcessStartInfo(YoutubeDlFileName)
                        {
                            UseShellExecute        = false,
                            RedirectStandardOutput = true,
                            RedirectStandardError  = true,
                            CreateNoWindow         = true,
                            Arguments = ArgumentsBuffer
                        }
                    };

                    DownloadProcess.OutputDataReceived += (s, e) => {
                        this.BeginInvoke(new MethodInvoker(() => {
                            if (e.Data != null && rtbConsoleOutput != null)
                            {
                                rtbConsoleOutput.AppendText(e.Data + "\n");
                            }
                        }));
                    };
                    DownloadProcess.ErrorDataReceived += (s, e) => {
                        this.BeginInvoke(new MethodInvoker(() => {
                            if (e.Data != null && rtbConsoleOutput != null)
                            {
                                rtbConsoleOutput.AppendText("Error:\n");
                                rtbConsoleOutput.AppendText(e.Data + "\n");
                            }
                        }));
                    };

                    DownloadProcess.Start();
                    DownloadProcess.BeginOutputReadLine();
                    DownloadProcess.BeginErrorReadLine();
                    DownloadProcess.WaitForExit();

                    DownloadFinished = true;

                    if (DownloadProcess.ExitCode == 0)
                    {
                        DownloadFinished = true;
                        DownloadAborted  = false;
                        DownloadErrored  = false;
                    }
                    else
                    {
                        DownloadErrored  = true;
                        DownloadFinished = false;
                    }
                }
                catch (ThreadAbortException) {
                    DownloadAborted  = true;
                    DownloadFinished = false;
                    return;
                }
                catch (Exception ex) {
                    ErrorLog.ReportException(ex);
                    DownloadErrored = true;
                }
                finally {
                    ThreadExit();
                }
            });
            rtbConsoleOutput.AppendText("Created, starting download thread\n");
            DownloadThread.Start();
            #endregion
        }
Example #3
0
        private void BeginDownload()
        {
            Debug.Print("BeginDownload()");
            if (string.IsNullOrEmpty(CurrentDownload.DownloadURL))
            {
                MessageBox.Show("The URL is null or empty. Please enter a URL or Download path.");
                return;
            }
            CurrentDownload.Status = DownloadStatus.GeneratingArguments;
            rtbConsoleOutput.AppendText("Beginning download, this box will output progress\n");
            if (CurrentDownload.BatchDownload)
            {
                chkDownloaderCloseAfterDownload.Checked = true;
            }

            #region URL cleaning
            if (!CurrentDownload.DownloadURL.StartsWith("https://"))
            {
sanitizecheck:
                if (CurrentDownload.DownloadURL.StartsWith("\\'") ||  // single quote
                    CurrentDownload.DownloadURL.StartsWith("\\\"") || // double quote
                    CurrentDownload.DownloadURL.StartsWith("\\n") ||  // newline
                    CurrentDownload.DownloadURL.StartsWith("\\r") ||  // carriage-return
                    CurrentDownload.DownloadURL.StartsWith("\\t") ||  // tab
                    CurrentDownload.DownloadURL.StartsWith("\\0") ||  // null char
                    CurrentDownload.DownloadURL.StartsWith("\\b") ||  // backspace
                    CurrentDownload.DownloadURL.StartsWith("\\"))     // backslash
                {
                    CurrentDownload.DownloadURL = CurrentDownload.DownloadURL.Substring(4);
                    goto sanitizecheck;
                }

                if (CurrentDownload.DownloadURL.StartsWith("http://"))
                {
                    CurrentDownload.DownloadURL = "https" + CurrentDownload.DownloadURL.Substring(4);
                }
            }
            #endregion

            string YoutubeDlFileName   = null;
            string ArgumentsBuffer     = string.Empty;
            string PreviewArguments    = string.Empty;
            string QualityFormatBuffer = string.Empty;
            string hlsFF     = string.Empty;
            string webFolder = string.Empty;

            #region youtube-dl path
            if (General.Default.UseStaticYtdl && File.Exists(General.Default.ytdlPath))
            {
                YoutubeDlFileName = General.Default.ytdlPath;
            }
            else
            {
                YoutubeDlFileName = verif.YoutubeDlPath;
            }
            if (YoutubeDlFileName == null)
            {
                rtbConsoleOutput.AppendText("Youtube-DL has not been found\nA rescan for youtube-dl was called\n");
                verif.RefreshYoutubeDlLocation();
                if (verif.YoutubeDlPath != null)
                {
                    rtbConsoleOutput.AppendText("Rescan finished and found, continuing\n");
                }
                else
                {
                    rtbConsoleOutput.AppendText("still couldnt find youtube-dl.");
                    CurrentDownload.Status = DownloadStatus.ProgramError;
                    return;
                }
            }
            rtbConsoleOutput.AppendText("Youtube-DL has been found and set\n");
            #endregion

            #region Output
            rtbConsoleOutput.AppendText("Generating output directory structure\n");

            if (Downloads.Default.separateIntoWebsiteURL)
            {
                webFolder = Download.getUrlBase(CurrentDownload.DownloadURL) + "\\";
            }

            string OutputDirectory = "\"" + Downloads.Default.downloadPath;
            if (CurrentDownload.BatchDownload && Downloads.Default.SeparateBatchDownloads)
            {
                OutputDirectory += "\\# Batch Downloads #";
                if (Downloads.Default.AddDateToBatchDownloadFolders)
                {
                    OutputDirectory += "\\" + CurrentDownload.BatchTime;
                }
            }
            OutputDirectory += "\\" + webFolder + "{0}" + Downloads.Default.fileNameSchema + "\"";

            ArgumentsBuffer = CurrentDownload.DownloadURL + " -o " + OutputDirectory;

            if (Downloads.Default.separateDownloads)
            {
                switch (CurrentDownload.Type)
                {
                case DownloadType.Video:
                    ArgumentsBuffer = ArgumentsBuffer.Replace("{0}", "Video\\");
                    break;

                case DownloadType.Audio:
                    ArgumentsBuffer = ArgumentsBuffer.Replace("{0}", "Audio\\");
                    break;

                case DownloadType.Custom:
                    ArgumentsBuffer = ArgumentsBuffer.Replace("{0}", "Custom\\");
                    break;

                default:
                    rtbConsoleOutput.AppendText("Unable to determine what download type to use (expected 0, 1, or 2)");
                    CurrentDownload.Status = DownloadStatus.ProgramError;
                    return;
                }
            }
            else
            {
                ArgumentsBuffer = ArgumentsBuffer.Replace("{0}", "");
            }
            rtbConsoleOutput.AppendText("The output was generated and will be used\n");
            #endregion

            #region Quality + format
            switch (CurrentDownload.Type)
            {
            case DownloadType.Video: {
                if (CurrentDownload.SkipAudioForVideos)
                {
                    ArgumentsBuffer += DownloadFormats.GetVideoQualityArgsNoSound(CurrentDownload.VideoQuality);
                }
                else
                {
                    ArgumentsBuffer += DownloadFormats.GetVideoQualityArgs(CurrentDownload.VideoQuality);
                }

                ArgumentsBuffer += DownloadFormats.GetVideoRecodeInfo(CurrentDownload.VideoFormat);
                break;
            }

            case DownloadType.Audio: {
                if (CurrentDownload.AudioCBRQuality == AudioCBRQualityType.best || CurrentDownload.AudioVBRQuality == AudioVBRQualityType.q0)
                {
                    ArgumentsBuffer += " -f  -x --audio-format best --audio-quality 0";
                }
                else
                {
                    if (CurrentDownload.UseVBR)
                    {
                        if (CurrentDownload.AudioVBRQuality == AudioVBRQualityType.q0)
                        {
                            ArgumentsBuffer += " -f bestaudio --extract-audio --audio-quality 0";
                        }
                        else
                        {
                            ArgumentsBuffer += " --extract-audio --audio-quality " + CurrentDownload.AudioVBRQuality;
                        }
                    }
                    else
                    {
                        if (CurrentDownload.AudioCBRQuality == AudioCBRQualityType.best)
                        {
                            ArgumentsBuffer += " -f bestaudio --extract-audio --audio-quality 0";
                        }
                        else
                        {
                            ArgumentsBuffer += " --extract-audio --audio-quality " + DownloadFormats.GetAudioQuality(CurrentDownload.AudioCBRQuality);
                        }
                    }
                }
                break;
            }

            case DownloadType.Custom: {
                rtbConsoleOutput.AppendText("Custom was requested, skipping quality + format");
                ArgumentsBuffer += " " + CurrentDownload.DownloadArguments;
                break;
            }

            default: {
                rtbConsoleOutput.AppendText("Expected a downloadtype (Quality + Format)");
                CurrentDownload.Status = DownloadStatus.ProgramError;
                return;
            }
            }

            rtbConsoleOutput.AppendText("The quality and format has been set\n");
            #endregion

            #region Arguments
            if (CurrentDownload.Type != DownloadType.Custom)
            {
                switch (CurrentDownload.PlaylistSelection)
                {
                case PlaylistSelectionType.PlaylistStartPlaylistEnd:     // playlist-start and playlist-end
                    if (CurrentDownload.PlaylistSelectionIndexStart > 0)
                    {
                        ArgumentsBuffer += " --playlist-start " + CurrentDownload.PlaylistSelectionIndexStart;
                    }

                    if (CurrentDownload.PlaylistSelectionIndexEnd > 0)
                    {
                        ArgumentsBuffer += " --playlist-end " + (CurrentDownload.PlaylistSelectionIndexStart + CurrentDownload.PlaylistSelectionIndexEnd);
                    }
                    break;

                case PlaylistSelectionType.PlaylistItems:     // playlist-items
                    ArgumentsBuffer += " --playlist-items " + CurrentDownload.PlaylistSelectionArg;
                    break;

                case PlaylistSelectionType.DateBefore:     // datebefore
                    ArgumentsBuffer += " --datebefore " + CurrentDownload.PlaylistSelectionArg;
                    break;

                case PlaylistSelectionType.DateDuring:     // date
                    ArgumentsBuffer += " --date " + CurrentDownload.PlaylistSelectionArg;
                    break;

                case PlaylistSelectionType.DateAfter:     // dateafter
                    ArgumentsBuffer += " --dateafter " + CurrentDownload.PlaylistSelectionArg;
                    break;
                }

                if (Downloads.Default.PreferFFmpeg || Download.isReddit(CurrentDownload.DownloadURL) && Downloads.Default.fixReddit)
                {
                    rtbConsoleOutput.AppendText("Looking for ffmpeg\n");
                    if (verif.FFmpegPath != null)
                    {
                        if (General.Default.UseStaticFFmpeg)
                        {
                            ArgumentsBuffer += " --ffmpeg-location \"" + General.Default.ffmpegPath + "\\ffmpeg.exe\"";
                        }
                        else
                        {
                            ArgumentsBuffer += " --ffmpeg-location \"" + verif.FFmpegPath + "\\ffmpeg.exe\" --hls-prefer-ffmpeg";
                        }
                        rtbConsoleOutput.AppendText("ffmpeg was found\n");
                    }
                    else
                    {
                        rtbConsoleOutput.AppendText("ffmpeg path is null, downloading may be affected\n");
                    }
                }

                if (Downloads.Default.SaveSubtitles)
                {
                    ArgumentsBuffer += " --all-subs";
                    if (!string.IsNullOrEmpty(Downloads.Default.SubtitleFormat))
                    {
                        ArgumentsBuffer += " --sub-format " + Downloads.Default.SubtitleFormat + " ";
                    }
                    if (Downloads.Default.EmbedSubtitles && CurrentDownload.Type == DownloadType.Video)
                    {
                        switch (CurrentDownload.VideoFormat)
                        {
                        case VideoFormatType.flv:
                        case VideoFormatType.mkv:
                            break;
                        }
                        ArgumentsBuffer += " --embed-subs";
                    }
                }
                if (Downloads.Default.SaveVideoInfo)
                {
                    ArgumentsBuffer += " --write-info-json";
                }
                if (Downloads.Default.SaveDescription)
                {
                    ArgumentsBuffer += " --write-description";
                }
                if (Downloads.Default.SaveAnnotations)
                {
                    ArgumentsBuffer += " --write-annotations";
                }
                if (Downloads.Default.SaveThumbnail)
                {
                    // ArgumentsBuffer += "--write-all-thumbnails "; // Maybe?
                    //ArgumentsBuffer += " --write-thumbnail";
                    if (Downloads.Default.EmbedThumbnails)
                    {
                        switch (CurrentDownload.Type)
                        {
                        case DownloadType.Video:
                            if (CurrentDownload.VideoFormat == VideoFormatType.mp4)
                            {
                                ArgumentsBuffer += " --embed-thumbnail";
                            }
                            else
                            {
                                rtbConsoleOutput.AppendText("!!!!!!!! WARNING !!!!!!!!\nCannot embed thumbnail to non-mp4 videos files\n");
                            }
                            break;

                        case DownloadType.Audio:
                            if (CurrentDownload.AudioFormat == AudioFormatType.m4a || CurrentDownload.AudioFormat == AudioFormatType.mp3)
                            {
                                ArgumentsBuffer += " --embed-thumbnail";
                            }
                            else
                            {
                                rtbConsoleOutput.AppendText("!!!!!!!! WARNING !!!!!!!!\nCannot embed thumbnail to non-m4a/mp3 audio files\n");
                            }
                            break;
                        }
                    }
                    //if (Downloads.Default.EmbedThumbnails) {
                    //    switch (DownloadType) {
                    //        case 0:
                    //            if (DownloadFormat != 4) {
                    //                rtbConsoleOutput.AppendText("!!!!!!!! WARNING !!!!!!!!\nCannot embed thumbnail to non-mp4 videos files\nWill try anyway.\n");
                    //            }
                    //            break;
                    //        case 1:
                    //            if (DownloadFormat != 3 && DownloadFormat != 4) {
                    //                rtbConsoleOutput.AppendText("!!!!!!!! WARNING !!!!!!!!\nCannot embed thumbnail to non-m4a/mp3 audio files\nWill try anyway.\n");
                    //            }
                    //            break;
                    //    }
                    //    ArgumentsBuffer += " --embed-thumbnail";
                    //}
                }
                if (Downloads.Default.WriteMetadata)
                {
                    ArgumentsBuffer += " --add-metadata";
                }

                if (Downloads.Default.KeepOriginalFiles)
                {
                    ArgumentsBuffer += " -k";
                }

                if (Downloads.Default.LimitDownloads && Downloads.Default.DownloadLimit > 0)
                {
                    ArgumentsBuffer += " --limit-rate " + Downloads.Default.DownloadLimit;
                    switch (Downloads.Default.DownloadLimitType)
                    {
                    case 0: {     // kb
                        ArgumentsBuffer += "K ";
                        break;
                    }

                    case 1: {     // mb
                        ArgumentsBuffer += "M ";
                        break;
                    }

                    case 2: {     // gb
                        ArgumentsBuffer += "G ";
                        break;
                    }

                    default: {     // kb default
                        ArgumentsBuffer += "K ";
                        break;
                    }
                    }
                }

                if (Downloads.Default.RetryAttempts != 10 && Downloads.Default.RetryAttempts > 0)
                {
                    ArgumentsBuffer += " --retries " + Downloads.Default.RetryAttempts;
                }

                if (Downloads.Default.ForceIPv4)
                {
                    ArgumentsBuffer += " --force-ipv4";
                }
                else if (Downloads.Default.ForceIPv6)
                {
                    ArgumentsBuffer += " --force-ipv6";
                }

                if (Downloads.Default.UseProxy && Downloads.Default.ProxyType > -1 && !string.IsNullOrEmpty(Downloads.Default.ProxyIP) && !string.IsNullOrEmpty(Downloads.Default.ProxyPort))
                {
                    ArgumentsBuffer += " --proxy " + Download.ProxyProtocols[Downloads.Default.ProxyType] + Downloads.Default.ProxyIP + ":" + Downloads.Default.ProxyPort + "/ ";
                }
            }
            #endregion

            #region Authentication
            // Set the preview arguments to what is present in the arguments buffer.
            // This is so the arguments buffer can have sensitive information and
            // the preview arguments won't include it in case anyone creates an issue.
            PreviewArguments = ArgumentsBuffer;

            if (CurrentDownload.AuthUsername != null)
            {
                ArgumentsBuffer += " --username " + CurrentDownload.AuthUsername;
                CurrentDownload.AuthUsername = null;
                PreviewArguments            += " --username ***";
            }
            if (CurrentDownload.AuthPassword != null)
            {
                ArgumentsBuffer += " --password " + CurrentDownload.AuthPassword;
                CurrentDownload.AuthPassword = null;
                PreviewArguments            += " --password ***";
            }
            if (CurrentDownload.Auth2Factor != null)
            {
                ArgumentsBuffer            += " --twofactor " + CurrentDownload.Auth2Factor;
                CurrentDownload.Auth2Factor = null;
                PreviewArguments           += " --twofactor ***";
            }
            if (CurrentDownload.AuthVideoPassword != null)
            {
                ArgumentsBuffer += " --video-password " + CurrentDownload.AuthVideoPassword;
                CurrentDownload.AuthVideoPassword = null;
                PreviewArguments += " --video-password ***";
            }
            if (CurrentDownload.AuthNetrc)
            {
                CurrentDownload.AuthNetrc = false;
                ArgumentsBuffer          += " --netrc";
                PreviewArguments         += " --netrc";
            }
            #endregion

            rtbConsoleOutput.AppendText("Arguments have been generated and are readonly in the textbox\n");
            txtArgumentsGenerated.Text = PreviewArguments;

            #region Download thread
            //if (Program.IsDebug) {
            //    rtbConsoleOutput.Text = "===ARGUMENTS===\n" + ArgumentsBuffer.Replace(' ', '\n') + "\n\n===PREVIEW ARGUMENTS===\n" + PreviewArguments.Replace(' ', '\n');
            //    return;
            //}
            rtbConsoleOutput.AppendText("Creating download thread\n");
            DownloadThread = new Thread(() => {
                try {
                    while (true)
                    {
                        Debug.Print("Sleeping");
                        Thread.Sleep(2000);
                    }
                    DownloadProcess = new Process()
                    {
                        StartInfo = new System.Diagnostics.ProcessStartInfo(YoutubeDlFileName)
                        {
                            UseShellExecute        = false,
                            RedirectStandardOutput = true,
                            RedirectStandardError  = true,
                            CreateNoWindow         = true,
                            Arguments = ArgumentsBuffer
                        }
                    };

                    DownloadProcess.OutputDataReceived += (s, e) => {
                        this.BeginInvoke(new MethodInvoker(() => {
                            if (e.Data != null && rtbConsoleOutput != null)
                            {
                                rtbConsoleOutput.AppendText(e.Data + "\n");
                            }
                        }));
                    };
                    DownloadProcess.ErrorDataReceived += (s, e) => {
                        this.BeginInvoke(new MethodInvoker(() => {
                            if (e.Data != null && rtbConsoleOutput != null)
                            {
                                rtbConsoleOutput.AppendText("Error:\n");
                                rtbConsoleOutput.AppendText(e.Data + "\n");
                            }
                        }));
                    };

                    DownloadProcess.Start();

                    ArgumentsBuffer  = null;
                    PreviewArguments = null;

                    DownloadProcess.BeginOutputReadLine();
                    DownloadProcess.BeginErrorReadLine();
                    DownloadProcess.WaitForExit();

                    if (DownloadProcess.ExitCode == 0)
                    {
                        CurrentDownload.Status = DownloadStatus.Finished;
                    }
                    else
                    {
                        CurrentDownload.Status = DownloadStatus.YtdlError;
                    }
                }
                catch (ThreadAbortException) {
                    this.BeginInvoke((MethodInvoker) delegate() {
                        CurrentDownload.Status = DownloadStatus.Aborted;
                        if (DownloadProcess != null && !DownloadProcess.HasExited)
                        {
                            DownloadProcess.Kill();
                        }
                        System.Media.SystemSounds.Hand.Play();
                        rtbConsoleOutput.AppendText("Downloading was aborted by the user.");
                    });
                }
                catch (Exception ex) {
                    ErrorLog.ReportException(ex);
                    CurrentDownload.Status = DownloadStatus.ProgramError;
                }
                finally {
                    this.BeginInvoke((MethodInvoker) delegate() {
                        DownloadFinished();
                    });
                }
            });
            rtbConsoleOutput.AppendText("Created, starting download thread\n");
            DownloadThread.Name = "Downloading video";
            DownloadThread.Start();
            #endregion
        }
Example #4
0
        /// <summary>
        /// Merges 2 files together
        /// </summary>
        /// <param name="input1">An input to merge</param>
        /// <param name="input2">The second input to merge</param>
        /// <param name="output">The file to produce</param>
        /// <param name="mergeAudio">Should audio be merged?</param>
        /// <param name="deleteAfterMerge">Should the inputs be deleted after merge?</param>
        /// <returns></returns>
        public static bool mergeFiles(string input1, string input2, string output, bool mergeAudio, bool deleteAfterMerge)
        {
            try {
                string[] formatsV      = { ".avi", ".flv", ".mkv", ".mov", ".mp4", ".webm", ".wmv" };
                bool     input1IsVideo = false; // is input1 video?

                Process ffMerge = new Process();
                ffMerge.StartInfo.UseShellExecute = true;
                ffMerge.StartInfo.FileName        = "ffmpeg.exe";
                for (int i = 0; i < formatsV.Length; i++)
                {
                    if (input1.EndsWith(formatsV[i]))
                    {
                        input1IsVideo = true;
                        break;
                    }
                }

                if (mergeAudio)
                {
                    if (input1IsVideo)
                    {
                        ffMerge.StartInfo.Arguments = " -i \"" + input1 + "\" \"" + Path.GetDirectoryName(input1) + "\\tempaudio.mp3\"";
                    }
                    else
                    {
                        ffMerge.StartInfo.Arguments = " -i \"" + input2 + "\" \"" + Path.GetDirectoryName(input2) + "\\tempaudio.mp3\"";
                    }

                    ffMerge.Start();
                    ffMerge.WaitForExit();


                    if (input1IsVideo)
                    {
                        ffMerge.StartInfo.Arguments = " -i \"" + input2 + "\" -i \"" + Path.GetDirectoryName(input1) + "\\tempaudio.mp3\" -filter_complex amix=inputs=2:duration=longest \"" + Path.GetDirectoryName(input1) + "\\final.mp3\"";
                    }
                    else
                    {
                        ffMerge.StartInfo.Arguments = " -i \"" + input1 + "\" -i \"" + Path.GetDirectoryName(input2) + "\\tempaudio.mp3\" -filter_complex amix=inputs=2:duration=longest \"" + Path.GetDirectoryName(input2) + "\\final.mp3\"";
                    }
                    ffMerge.Start();
                    ffMerge.WaitForExit();

                    if (input1IsVideo)
                    {
                        ffMerge.StartInfo.Arguments = " -i \"" + input1 + "\" -i \"" + Path.GetDirectoryName(input1) + "\\final.mp3\" -map 0:v -map 1:a -longest -c copy -y \"" + output + "\"";
                    }
                    else
                    {
                        ffMerge.StartInfo.Arguments = " -i \"" + input2 + "\" -i \"" + Path.GetDirectoryName(input2) + "\\final.mp3\" -map 0:v -map 1:a -longest -c copy -y \"" + output + "\"";
                    }

                    ffMerge.Start();
                    ffMerge.WaitForExit();
                }
                else
                {
                    if (input1IsVideo)
                    {
                        ffMerge.StartInfo.Arguments = " -i \"" + input1 + "\" -i \"" + input2 + "\" -map 0:v -map 1:a -c copy -y \"" + output + "\"";
                    }
                    else
                    {
                        ffMerge.StartInfo.Arguments = " -i \"" + input1 + "\" -i \"" + input2 + "\" -map 1:v -map 0:a -c copy -y \"" + output + "\"";
                    }

                    ffMerge.Start();
                    ffMerge.WaitForExit();
                }

                if (deleteAfterMerge)
                {
                    File.Delete(input1);
                    File.Delete(input2);
                }

                return(true);
            }
            catch (Exception ex) {
                ErrorLog.ReportException(ex);
                return(false);
            }
        }
Example #5
0
        /// <summary>
        /// Converts a file using ffmpeg
        /// </summary>
        /// <param name="input">The full-path input file</param>
        /// <param name="output">The full-path output</param>
        /// <param name="convType">Determines what conversion it'll attempt to do; To-Video, To-Audio, To-Custom, To-Automatic</param>
        /// <returns>A boolean based on the success of the conversion</returns>
        public static bool convertFile(string input, string output, int convType = -1)
        {
            /// -1 = Automatic
            /// 0 = Video
            /// 1 = Audio
            /// 2 = Custom
            /// 6 = No params at all, just an option to look back to. aka ffmpeg auto

            try {
                Process startConvert = new Process();
                if (General.Default.UseStaticFFmpeg && File.Exists(General.Default.ffmpegPath))
                {
                    startConvert.StartInfo.FileName = General.Default.ffmpegPath;
                }
                else
                {
                    if (verif.FFmpegPath == null)
                    {
                        throw new Exception("FFmpegPath is null. Cannot convert. If you do not have ffmpeg, consider downloading it.");
                    }
                    startConvert.StartInfo.FileName = verif.FFmpegPath + "\\ffmpeg.exe";
                }

                string convertArguments = "-i \"" + input + "\"";
                switch (convType)
                {
                case 0:
                    if (Converts.Default.videoUseBitrate)
                    {
                        convertArguments += " -b:v " + Converts.Default.videoBitrate.ToString() + "k";
                    }

                    if (Converts.Default.videoUsePreset)
                    {
                        convertArguments += " -preset " + getVideoPreset(Converts.Default.videoPreset);
                    }

                    if (Converts.Default.videoUseCRF)
                    {
                        convertArguments += " -crf " + Converts.Default.videoCRF.ToString();
                    }

                    if (!output.EndsWith(".wmv") && Converts.Default.videoUseProfile)
                    {
                        convertArguments += " -profile:v " + getVideoProfile(Converts.Default.videoProfile);
                    }

                    if (Converts.Default.videoFastStart)
                    {
                        convertArguments += " -faststart";
                    }

                    break;

                case 1:
                    if (Converts.Default.audioUseBitrate)
                    {
                        convertArguments += " -ab " + (Converts.Default.audioBitrate * 1000);
                    }

                    break;

                case 2:
                    convertArguments += " " + Saved.Default.convertCustom;
                    break;

                case 6:
                    // FFmpeg default
                    break;

                default:
                    if (Converts.Default.detectFiletype)
                    {
                        switch (getFiletype(output))
                        {
                        case 0:
                            if (Converts.Default.videoUseBitrate)
                            {
                                convertArguments += " -b:v " + Converts.Default.videoBitrate.ToString() + "k";
                            }

                            if (Converts.Default.videoUsePreset)
                            {
                                convertArguments += " -preset " + getVideoPreset(Converts.Default.videoPreset);
                            }

                            if (Converts.Default.videoUseCRF)
                            {
                                convertArguments += " -crf " + Converts.Default.videoCRF.ToString();
                            }

                            if (!output.EndsWith(".wmv") && Converts.Default.videoUseProfile)
                            {
                                convertArguments += " -profile:v " + getVideoProfile(Converts.Default.videoProfile);
                            }

                            if (Converts.Default.videoFastStart)
                            {
                                convertArguments += " -faststart";
                            }
                            break;

                        case 1:
                            if (Converts.Default.audioUseBitrate)
                            {
                                convertArguments += " -ab " + (Converts.Default.audioBitrate * 1000);
                            }

                            break;

                        default:
                            convertArguments += " -preset fast -b 3000k";
                            break;
                        }
                    }
                    else
                    {
                        convertArguments += " -preset fast -b 3000k";
                    }
                    break;
                }

                if (Converts.Default.hideFFmpegCompile && convType != 2)
                {
                    convertArguments += " -hide_banner";
                }

                convertArguments += " \"" + output + "\"";

                startConvert.StartInfo.Arguments = convertArguments;
                startConvert.Start();
                //startConvert.WaitForExit();

                return(true);
            }
            catch (Exception ex) {
                ErrorLog.ReportException(ex);
                return(false);
            }
        }
Example #6
0
        public static void CheckForUpdate(bool ForceCheck = false)
        {
            if (Program.IsDebug && !ForceCheck)
            {
                Debug.Print("-version " + GitData.UpdateVersion + " -name " + System.AppDomain.CurrentDomain.FriendlyName);
            }
            else
            {
                if (!General.Default.CheckForUpdatesOnLaunch && !ForceCheck)
                {
                    return;
                }


                if (GitData.UpdateAvailable)
                {
                    using (frmUpdateAvailable Update = new frmUpdateAvailable()) {
                        Update.BlockSkip = GitData.UpdateAvailable;
                        switch (Update.ShowDialog())
                        {
                        case DialogResult.Yes:
                            try {
                                UpdateApplication();
                            }
                            catch (Exception ex) {
                                ErrorLog.ReportException(ex);
                                return;
                            }
                            break;
                        }
                    }
                }
                else
                {
                    Thread checkUpdates = new Thread(() => {
                        if (GitData.UpdateVersion == "-1" || ForceCheck)
                        {
                            decimal GitVersion = UpdateChecker.GetGitVersion(0);
                            if (UpdateChecker.IsUpdateAvailable(GitVersion))
                            {
                                if (GitVersion != Properties.Settings.Default.SkippedVersion || ForceCheck)
                                {
                                    using (frmUpdateAvailable Update = new frmUpdateAvailable()) {
                                        Update.BlockSkip = ForceCheck;
                                        switch (Update.ShowDialog())
                                        {
                                        case DialogResult.Yes:
                                            try {
                                                UpdateApplication();
                                            }
                                            catch (Exception ex) {
                                                ErrorLog.ReportException(ex);
                                                return;
                                            }
                                            break;

                                        case DialogResult.Ignore:
                                            Properties.Settings.Default.SkippedVersion = GitVersion;
                                            Properties.Settings.Default.Save();
                                            break;
                                        }
                                    }
                                }
                            }
                            else if (ForceCheck)
                            {
                                MessageBox.Show("No updates available.");
                            }
                        }
                    });
                    checkUpdates.Start();
                }
            }
        }
Example #7
0
        public static void UpdateYoutubeDl()
        {
            GetGitVersionString(1);

            if (Downloads.Default.useYtdlUpdater && General.Default.UseStaticYtdl && !string.IsNullOrEmpty(General.Default.ytdlPath) && File.Exists(General.Default.ytdlPath) || File.Exists(Environment.CurrentDirectory + "\\youtube-dl.exe"))
            {
                Process UpdateYoutubeDl = new Process();
                UpdateYoutubeDl.StartInfo.Arguments = "-U";

                if (!General.Default.UseStaticYtdl || string.IsNullOrEmpty(General.Default.ytdlPath))
                {
                    UpdateYoutubeDl.StartInfo.FileName = Environment.CurrentDirectory + "\\youtube-dl.exe";
                    UpdateYoutubeDl.Start();
                    UpdateYoutubeDl.WaitForExit();
                }
                else
                {
                    UpdateYoutubeDl.StartInfo.FileName = General.Default.ytdlPath;
                    UpdateYoutubeDl.Start();
                    UpdateYoutubeDl.WaitForExit();
                }
            }
            else
            {
                if (!General.Default.UseStaticYtdl || string.IsNullOrEmpty(General.Default.ytdlPath))
                {
                    Thread DownloadYoutubeDl = new Thread(() => {
                        using (WebClient wc = new WebClient()) {
                            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                            wc.Headers.Add("User-Agent: " + Program.UserAgent);
                            try {
                                string ytdlDownloadPath = null;
                                if (General.Default.UseStaticYtdl && !string.IsNullOrEmpty(General.Default.ytdlPath))
                                {
                                    ytdlDownloadPath = General.Default.ytdlPath;
                                }
                                else
                                {
                                    ytdlDownloadPath = Environment.CurrentDirectory + "\\youtube-dl.exe";
                                }
                                wc.DownloadFile(string.Format(GitData.GitLinks.ApplicationDownloadUrl, GitData.GitLinks.Users[1], GitData.GitLinks.ApplciationNames[1], GitData.YoutubeDlVersion), ytdlDownloadPath);
                                if (GitData.YoutubeDlVersion != Properties.Settings.Default.YoutubeDlVersion)
                                {
                                    Properties.Settings.Default.YoutubeDlVersion = GitData.YoutubeDlVersion;
                                    Properties.Settings.Default.Save();
                                }
                                MessageBox.Show("Youtube-dl has been updated.");
                            }
                            catch (WebException webex) {
                                ErrorLog.ReportWebException(webex, string.Format(GitData.GitLinks.ApplicationDownloadUrl, GitData.GitLinks.Users[1], GitData.GitLinks.ApplciationNames[1], GitData.YoutubeDlVersion));
                            }
                            catch (Exception ex) {
                                ErrorLog.ReportException(ex);
                            }
                        }
                    });
                    DownloadYoutubeDl.Start();
                }
                else
                {
                    Thread DownloadYoutubeDl = new Thread(() => {
                        using (WebClient wc = new WebClient()) {
                            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                            wc.Headers.Add("User-Agent: " + Program.UserAgent);
                            try {
                                wc.DownloadFile(string.Format(GitData.GitLinks.ApplicationDownloadUrl, GitData.GitLinks.Users[1], GitData.GitLinks.ApplciationNames[1], GitData.YoutubeDlVersion), General.Default.ytdlPath);
                                if (GitData.YoutubeDlVersion != Properties.Settings.Default.YoutubeDlVersion)
                                {
                                    Properties.Settings.Default.YoutubeDlVersion = GitData.YoutubeDlVersion;
                                    Properties.Settings.Default.Save();
                                }
                                MessageBox.Show("Youtube-dl has been updated.");
                            }
                            catch (WebException webex) {
                                ErrorLog.ReportWebException(webex, string.Format(GitData.GitLinks.ApplicationDownloadUrl, GitData.GitLinks.Users[1], GitData.GitLinks.ApplciationNames[1], GitData.YoutubeDlVersion));
                            }
                            catch (Exception ex) {
                                ErrorLog.ReportException(ex);
                            }
                        }
                    });
                    DownloadYoutubeDl.Start();
                }
            }
        }