public async Task<Result<YoutubeDownloadResult, string>> DownloadYoutubeVideo(YTEVideoFormat video)
        {
            if(video == null)
                throw new Exception("null video passed to DownloadYoutubeVideo");

            // We combine the VideoID with a DateTime hashcode just incase multiple copies
            // of the same video are being downloaded.  That way there won't be any file clashes.
            string filepath = $"{Guid.NewGuid().ToString()}.temp";

            try
            {
                if(video.YTEVideoInfo.RequiresDecryption)
                    await Task.Run(() => DownloadUrlResolver.DecryptDownloadUrl(video.YTEVideoInfo));
                
                var downloader = new VideoDownloader(video.YTEVideoInfo, filepath);
                await Task.Run(() => downloader.Execute());

                return new YoutubeDownloadResult(filepath);
            }
            catch(WebException e)
            {
                return (e.Response as HttpWebResponse).StatusCode.ToString();
            }
            catch(Exception)
            {
                return string.Empty;
            }
        }
        public void Download()
        {
            IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(Url);

            /*
             * Select the first .mp4 video with 360p resolution
             */
            VideoInfo video = videoInfos
                .First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);

            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            //TODO: check this path! Video names could have a "/" (slash) in them. For example: Joe w/ [shortent with] Jen
            var videoDownloader = new VideoDownloader(video, Constants.TempVideoFile);

            // Register the ProgressChanged event and print the current progress
            videoDownloader.DownloadProgressChanged += VideoDownloader_DownloadProgressChanged;
            videoDownloader.DownloadFinished += VideoDownloader_DownloadFinished;
            videoDownloader.Execute(); //this is synchronous
        }
Exemple #3
0
 public void download()
 {  
     string link = linkBase + id;
     IEnumerable<YoutubeExtractor.VideoInfo> videoInfos = YoutubeExtractor.DownloadUrlResolver.GetDownloadUrls(link);
     VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);
     if (video.RequiresDecryption)
     {
         DownloadUrlResolver.DecryptDownloadUrl(video);
     }
     name = video.Title.Trim(new Char[] { '<', '>', ':', '"', '/', '\\', '|', '?', '*' });
     var videoDownloader = new VideoDownloader(video, Path.Combine(config.workDirectory, name + video.VideoExtension));
     //videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);
     try
     {
         Console.WriteLine("Trying to download: " + name);
         videoDownloader.Execute();
         StreamWriter file = new StreamWriter(Path.Combine(config.workDirectory, "video_download.txt"), true);
         file.WriteLine(id);
         file.Close();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
         if (maxRetry > 0)
         {
             maxRetry--;
             this.download();
         }
         else
         {
             Console.WriteLine("*Video download failed:" + id);
         }
     }
 }
Exemple #4
0
        private static void DownloadVideo(IEnumerable<VideoInfo> videoInfos)
        {
            /*
             * Select the first .mp4 video with 360p resolution
             */
            VideoInfo video = videoInfos
                .OrderByDescending(v => v.Resolution).First(info => info.VideoType == VideoType.Mp4);

            /*
             * If the video has a decrypted signature, decipher it
             */
            if(video.RequiresDecryption) {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            /*
             * Create the video downloader.
             * The first argument is the video to download.
             * The second argument is the path to save the video file.
             */
            var videoDownloader = new VideoDownloader(video,
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                RemoveIllegalPathCharacters(video.Title) + video.VideoExtension));

            // Register the ProgressChanged event and print the current progress
            videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);

            /*
             * Execute the video downloader.
             * For GUI applications note, that this method runs synchronously.
             */
            videoDownloader.Execute();
        }
        private static void DownloadVideo(IEnumerable<VideoInfo> videoInfos)
        {
            /*
             * Select the standard youtube quality
             * See the VideoFormat enum for more info about the quality.
             */
            VideoInfo video = videoInfos
                .First(info => info.VideoFormat == VideoFormat.Standard360);

            /*
             * Create the video downloader.
             * The first argument is the video to download.
             * The second argument is the path to save the video file.
             */
            var videoDownloader = new VideoDownloader(video, Path.Combine("D:/Downloads", video.Title + video.VideoExtension));

            // Register the ProgressChanged event and print the current progress
            videoDownloader.ProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);

            /*
             * Execute the video downloader.
             * For GUI applications note, that this method runs synchronously.
             */
            videoDownloader.Execute();
        }
Exemple #6
0
        private static void DownloadVideo(IEnumerable<VideoInfo> videoInfos)
        {
            /*
             * Select the first .mp4 video with 360p resolution
             */
            VideoInfo video = videoInfos
                .First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);

            /*
             * Create the video downloader.
             * The first argument is the video to download.
             * The second argument is the path to save the video file.
             */
            var videoDownloader = new VideoDownloader(video,
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), video.Title + video.VideoExtension));

            // Register the ProgressChanged event and print the current progress
            videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);

            /*
             * Execute the video downloader.
             * For GUI applications note, that this method runs synchronously.
             */
            videoDownloader.Execute();
        }
        public void ExecuteAction(string value)
        {
            IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(value);
            var video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);
            var videoDownloader = new VideoDownloader(video, Path.Combine("C:/Temp", video.Title + video.VideoExtension));
            videoDownloader.Execute();

            MessageBox.Show("Done downloading video", "Done!", MessageBoxButtons.OK);
        }
Exemple #8
0
        private void DownloadVideo(string path)
        {
            var videoDownloader = new VideoDownloader(this.Video, path);

            videoDownloader.ProgressChanged +=
                (sender, args) => this.OnProgressChanged(new ProgressEventArgs(args.ProgressPercentage / 2));

            videoDownloader.Execute();
        }
Exemple #9
0
        public static async Task DownloadVideoAsync(VideoInfo videoInfo, string downloadPath, IObserver<double> progress)
        {
            string cleanedTitle = RemoveIllegalPathCharacters(videoInfo.Title);
            var downloader = new VideoDownloader(videoInfo, Path.Combine(downloadPath, cleanedTitle + videoInfo.VideoExtension));

            downloader.DownloadProgressChanged += (sender, args) => progress.OnNext(args.ProgressPercentage);

            await DownloadFromYoutube(downloader, new[] { typeof(IOException), typeof(WebException) }, progress);
        }
        private void DownloadVideo()
        {
            if(VideoInfo.RequiresDecryption) {
                DownloadUrlResolver.DecryptDownloadUrl(VideoInfo);
            }

            VideoDownloader videoDownloader = new VideoDownloader(VideoInfo, Path.Combine("D:/Downloads", VideoInfo.Title + VideoInfo.VideoExtension));
            videoDownloader.DownloadProgressChanged += (sender, args) => Progress = Math.Round(args.ProgressPercentage, 1);
            videoDownloader.Execute();
        }
Exemple #11
0
        public void GrabVideo(string link)
        {
            AddedTag = null;

            Tags = new List<byte[]>();

            var videoInfos = DownloadUrlResolver.GetDownloadUrls(link);
            var video = videoInfos.First(info => info.VideoType == VideoType.Flash);

            downloader = new VideoDownloader(video, "");
            downloader.Execute(true);
        }
Exemple #12
0
 public static void SimpleDownloadVideo(string video_url, string title, string folder_destination, VideoType format, Form1 form)
 {
     IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(video_url);
     VideoInfo video = videoInfos.First(info => info.VideoType == format);
     if (video.RequiresDecryption)
     {
         DownloadUrlResolver.DecryptDownloadUrl(video);
     }
     var videoDownloader = new VideoDownloader(video, Path.Combine(folder_destination, title + video.VideoExtension));
     videoDownloader.DownloadProgressChanged += (sender, args2) => form.SetProgressBarValue(Convert.ToInt32(args2.ProgressPercentage));
     videoDownloader.Execute();
 }
        public void ShoudlDownloadVideo()
        {
            // Arrange
            string link = @"http://www.youtube.com/watch?v=OEF7zYN95A4";
            IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);

            // Act
            VideoInfo video = videoInfos.First(info => info.VideoFormat == VideoFormat.Standard360);

            VideoDownloader videoDownloader = new VideoDownloader(video, "insert path" + video.Title + video.VideoExtension);
            videoDownloader.ProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);
            videoDownloader.Execute();

            // Assert
        }
        public void Download(string link, string targetDir, string targetFname)
        {
            if (link.Contains("youtube"))
            {
                IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);
                VideoInfo video = videoInfos.Where(t => t.VideoType == VideoType.Mp4).First(r => r.Resolution == 360);

                /*
                 * Create the video downloader.
                 * The first argument is the video to download.
                 * The second argument is the path to save the video file.
                 */

                string filePathName = video.Title.RemoveColon() + video.VideoExtension;
                if (string.IsNullOrEmpty(filePathName))
                {
                    filePathName = Path.GetRandomFileName();
                }

                string fname = filePathName.RemoveColon();

                string filepath = Path.Combine(targetDir, fname);

                //ensure it respects mppl
                filepath = Utilities.TrimPathPart(filepath, _edxCourse.Max_path_part_len);

                VideoDownloader videoDownloader = new VideoDownloader(video, filepath);

                //WebHeaderCollection responseHeaders = _edxCourse._client.ResponseHeaders;
                int contentLength = videoDownloader.BytesToDownload ?? 0; // GetContentLength(responseHeaders);
                bool isFileNeeded = IsFileNeeded(filepath, contentLength, fname);

                if (isFileNeeded)
                {

                    // Register the ProgressChanged event and print the current progress
                    videoDownloader.DownloadProgressChanged +=
                        (sender, args) =>
                        Utilities.DrawProgressBar(Convert.ToInt32(args.ProgressPercentage), 100, 40, '=');

                    /*
                     * Execute the video downloader.
                     * For GUI applications note, that this method runs synchronously.
                     */
                    videoDownloader.Execute();
                }
            }
        }
        private void DownloadVideo(string path)
        {
            var videoDownloader = new VideoDownloader(this.Video, path, this.BytesToDownload);

            videoDownloader.DownloadProgressChanged += (sender, args) =>
            {
                if (this.DownloadProgressChanged != null)
                {
                    this.DownloadProgressChanged(this, args);

                    this.isCanceled = args.Cancel;
                }
            };

            videoDownloader.Execute();
        }
        private void DownloadVideo(string path)
        {
            var videoDownloader = new VideoDownloader(this.Video, path);

            // Backwards compatibility
            videoDownloader.ProgressChanged += (sender, args) =>
            {
                this.OnProgressChanged(new ProgressEventArgs(args.ProgressPercentage / 2));
            };

            videoDownloader.DownloadProgressChanged += (sender, args) =>
            {
                if (this.DownloadProgressChanged != null)
                {
                    this.DownloadProgressChanged(this, new ProgressEventArgs(args.ProgressPercentage));
                }
            };

            videoDownloader.Execute();
        }
        private void btnDownload_Click(object sender, EventArgs e)
        {
            // Our test youtube link
            string link = "https://www.youtube.com/watch?v=pv-6rweZR_s";

            /*
             * Get the available video formats.
             * We'll work with them in the video and audio download examples.
             */
            IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);

            /*
             * Select the first .mp4 video with 360p resolution
             */
            VideoInfo video = videoInfos
                .First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);

            /*
             * If the video has a decrypted signature, decipher it
             */
            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            /*
             * Create the video downloader.
             * The first argument is the video to download.
             * The second argument is the path to save the video file.
             */
            var videoDownloader = new VideoDownloader(video, Path.Combine(txtDownloadFolder.Text, video.Title + video.VideoExtension));

            // Register the ProgressChanged event and print the current progress
            //videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);

            /*
             * Execute the video downloader.
             * For GUI applications note, that this method runs synchronously.
             */
            videoDownloader.Execute();
        }
        private void DownloadVideo(string path)
        {
            var videoDownloader = new VideoDownloader(this.Video, path);

            // Backwards compatibility
            videoDownloader.ProgressChanged += (sender, args) =>
            {
                this.OnProgressChanged(new ProgressEventArgs(args.ProgressPercentage / 2));
            };

            videoDownloader.DownloadProgressChanged += (sender, args) =>
            {
                if (this.DownloadProgressChanged != null)
                {
                    this.DownloadProgressChanged(this, args);

                    this.isCanceled = args.Cancel;
                }
            };

            videoDownloader.Execute();
        }
        private static void DownloadVideo(IEnumerable<VideoInfo> videoInfos)
        {
            /*
             * Select the first .mp4 video with 360p resolution
             */
            VideoInfo video = videoInfos
                //.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);
                //.Where(info => info.VideoType == VideoType.Mp4).OrderBy(info => info.Resolution).Last();
                //.SingleOrDefault(x => x.FormatCode == 251);
                .SingleOrDefault(x => x.FormatCode == 249);


            video.DecryptDownloadUrl();

            /*
             * Create the video downloader.
             * The first argument is the video to download.
             * The second argument is the path to save the video file.
             */
            var videoDownloader = new VideoDownloader(video,
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),

                // this.SavePath = "C:\\Users\\Administrator\\Documents\\What is VR Video?"

                video.Title.Replace(":", "_")
                        .Replace("*", "_")
                        .Replace("?", "_") 
                        .Replace("°", "_")
                        + video.VideoExtension));

            // Register the ProgressChanged event and print the current progress
            videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);

            /*
             * Execute the video downloader.
             * For GUI applications note, that this method runs synchronously.
             */
            videoDownloader.Execute();
        }
Exemple #20
0
        static void Main(string[] args)
        {
            try
            {
                //var link = new List<string>();
                //link.Add("https://www.youtube.com/watch?v=GlGuLcQhrWg");
                string link = @"https://www.youtube.com/watch?v=YzC-FYg66xA&list=PL0kIvpOlieSNWR3YPSjh9P2p43SFnNBlB&index=1";
                //foreach (var item in link)
                //{

                IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls("https://www.youtube.com/watch?v=YzC-FYg66xA&list=PL0kIvpOlieSNWR3YPSjh9P2p43SFnNBlB&index=1");
                VideoInfo video           = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 720);
                var       videoDownloader = new VideoDownloader(video, Path.Combine(@"C:\Users\lalomarquez\Desktop\", video.Title + video.VideoExtension));

                videoDownloader.DownloadProgressChanged += (sender, argss) => Console.WriteLine(argss.ProgressPercentage);
                videoDownloader.Execute();
                //}
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        public static async Task<Result<YoutubeDownloadResult, string>> DownloadYoutubeVideoOld(YoutubeExtractor.VideoInfo video)
        {
            // We combine the VideoID with a DateTime hashcode just incase multiple copies
            // of the same video are being downloaded.  That way there won't be any file clashes.
            string filepath = $"{Guid.NewGuid().ToString()}.temp";

            try
            {
                var downloader = new YoutubeExtractor.VideoDownloader(video, filepath);
                await downloader.ExecuteAsync();
                return new YoutubeDownloadResult
                {
                    Filepath = filepath,
                };
            }
            catch(WebException e)
            {
                return (e.Response as HttpWebResponse).StatusCode.ToString();
            }
            catch(Exception e)
            {
                return string.Empty;
            }
        }
Exemple #22
0
        public static void Main(string[] args2)
        {
            Console.WriteLine("YouTubeFeast version "+System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
            Console.WriteLine("(C) Daniel Kirstenpfad 2012 - http://www.technology-ninja.com");
            Console.WriteLine();

            YouTubeFeastConfiguration.ReadConfiguration("YouTubeFeast.configuration");

            Console.WriteLine();
            Console.WriteLine("to quit please use control-c.");
            Console.WriteLine();

            while (true)
            {
                // we have to decide if there is a job we need to work on

                foreach(ChannelJob job in YouTubeFeastConfiguration.DownloadJobs)
                {
                    TimeSpan SinceLastRun = DateTime.Now - job.LastDownload;
                    TimeSpan theInterval = new TimeSpan(job.Interval,0,0);
                    if ( SinceLastRun  >= theInterval )
                    {
                        //Console.WriteLine("Updating: "+job.ChannelURL);
                        // we should download something... or at least look for new stuff
                        List<String> DownloadURLs = YoutubeDownload.GenerateDownloadURLsFromChannel(job.ChannelURL);
                        job.LastDownload = DateTime.Now;

                        // it seems that we got a nice list here, now let's
                        if (DownloadURLs.Count > 0)
                        {
                            // start the downloadings...
                            // oh there is a policy: the first file that already exists leads to the abortion of this particular channel download
                            // that's because this tool expects the new files to appear first on the channel page and the old ones to be listed later
                            // on the page

                            if (job.SearchBottom)
                            {
                                //Console.WriteLine("reversed: " + job.ChannelURL);
                                DownloadURLs.Reverse();
                            }

                            foreach (String url in DownloadURLs)
                            {
                                VideoInfo video = null;
                                IEnumerable<VideoInfo> videoInfos = null;
                                try
                                {
                                    // get all the available video formats for this one...
                                    videoInfos = DownloadUrlResolver.GetDownloadUrls(url);
                                    video = videoInfos.First(info => info.VideoFormat == job.DownloadVideoFormat);
                                }
                                catch(Exception)
                                {
                                    //videoInfos = DownloadUrlResolver.GetDownloadUrls(url);
                                    //video = videoInfos.First(info => info.VideoFormat == VideoFormat.Standard360);
                                    //Console.WriteLine("Error: Video with the desired resolution is not available ("+job.ChannelDownloadDirectory+")");
                                    //video = videoInfos.First(info => info.VideoFormat == VideoFormat.Standard360);
                                    continue;
                                }

                                if (video != null)
                                {
                                    String filename = Path.Combine(job.ChannelDownloadDirectory, video.Title + video.VideoExtension);

                                    // check if there is a keyword present we should look for when choosing to-be-downloaded files
                                    if (job.SearchKeyword != "")
                                    {
                                        // if we do not find it in the name, skip
                                        //Console.WriteLine("checking: " + video.Title);
                                        if (!video.Title.Contains(job.SearchKeyword))
                                            continue;
                                    }

                                    if (File.Exists(filename))
                                    {
                                        //Console.WriteLine("File: "+filename+" already exists - we stop this channel job now.");
                                        //Console.WriteLine("\t\tNotice: We are finished with this channel.");
                                        break;
                                    }
                                    else
                                    {
                                        Console.Write("Downloading: " + ShortenString.LimitCharacters(video.Title, 40) + "...");
                                        var videoDownloader = new VideoDownloader(video, filename);

                                        Int32 left = Console.CursorLeft;
                                        Int32 top = Console.CursorTop;

                                        videoDownloader.ProgressChanged += (sender, args) => DisplayProgress(left,top,args.ProgressPercentage);
                                        try
                                        {
                                            videoDownloader.Execute();
                                            FileInfo f2 = new FileInfo(filename);
                                            long s2 = f2.Length;
                                            if (s2 == 0)
                                            {
                                                File.Delete(filename);
                                                Console.WriteLine("zeroed...");
                                            }
                                        }
                                        catch(Exception e)
                                        {
                                            Console.WriteLine("Error: "+ShortenString.LimitCharacters(e.Message,40));
                                            //video = videoInfos.First(info => info.VideoFormat == VideoFormat.Standard360);
                                        }
                                        Console.WriteLine("done    ");
                                    }
                                }
                            }
                        }
                    }
                }

                Thread.Sleep(60000);
            }
        }
        private void DownloadVideo (IEnumerable<VideoInfo> videoInfos, int resolution, int position, VideoType format)
        {
            /*
             * Select the first .mp4 video with 360p resolution
             */
            VideoInfo video = videoInfos
                .First(info => info.VideoType == format && info.Resolution == resolution);

            /*
             * If the video has a decrypted signature, decipher it
             */
            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            /*
             * Create the video downloader.
             * The first argument is the video to download.
             * The second argument is the path to save the video file.
             */
            
            var videoName = RemoveIllegalPathCharacters(video.Title) + video.VideoExtension;
			
            var videoPath = Path.Combine(MainForm.TempDownloadLocation, videoName);
            
            var finalPath = Path.Combine(MainForm.DownloadLocation, videoName);
			
            if (!File.Exists(finalPath))
            {
				
                var videoDownloader = new VideoDownloader (video, videoPath);
	
                // Register the ProgressChanged event and print the current progress
                videoDownloader.DownloadProgressChanged += (sender, args) => MainForm.DownloadFinishedPercent = (int)args.ProgressPercentage;
	
                /*
	             * Execute the video downloader.
	             * For GUI applications note, that this method runs synchronously.
	             */
                videoDownloader.Execute();
                
                File.Move(videoPath, finalPath);
				
            }
            else
            {
            	
                MainForm.StatusBar = string.Format(CultureInfo.InstalledUICulture, "{0}({1}) already exists! Download process has been aborted and considered successful.", Truncate(video.Title, 18), position).ToLower(CultureInfo.InstalledUICulture);
            	
            }
			
        }
        private void DownloadVideo(string path)
        {
            var videoDownloader = new VideoDownloader(this.Video, path, this.BytesToDownload);

            videoDownloader.Execute();
        }
        private static void DownloadVideo0(IEnumerable<VideoInfo> videoInfos)
        {
            var mp4 = videoInfos.Where(x => x.VideoType == VideoType.Mp4);
            var mp4video = mp4.Where(x => x.Resolution > 0).OrderBy(x => x.Resolution).ToArray();
            var mp4audio = mp4video.Where(x => x.AudioBitrate > 0).OrderBy(x => x.Resolution).ToArray();


            VideoInfo video = //videoInfos.FirstOrDefault(k => k.FormatCode == 299)
             mp4audio.OrderBy(info => info.Resolution).Last();

            video.DecryptDownloadUrl();



            // old name
            var Title =
                  video.Title
                //.Replace("/", " ")
                //.Replace("\\", " ")
                .Replace("\"", "'")
                //.Replace(":", " ")
                .Replace("&", " and ")
                //.Replace("*", " ")
                ;

            // http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars(v=vs.110).aspx

            foreach (var item in
                Path.GetInvalidFileNameChars())
            {
                Title = Title.Replace(item, ' ');

            }

            // https://code.google.com/p/android/issues/detail?id=8185
            // http://stackoverflow.com/questions/18596245/in-c-how-can-i-detect-if-a-character-is-a-non-ascii-character

            var apkfriendlytitle = new string(
                Title.Select(x => x < 127 ? x : '_').ToArray()
                );

            // apkfriendlytitle = "___360_ - __________find the truth 360 degree trick movie ."



            var px = Path.Combine(
                //Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                "x:/media",

                Title + video.VideoExtension);

            var pxa = Path.Combine(
                 //Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                 "x:/media",

                 apkfriendlytitle + video.VideoExtension);


            if (!File.Exists(pxa))
                if (File.Exists(px))
                {
                    // upgrade old naming to apk friendly.
                    File.Move(px, pxa);
                }

            var pxa_mp3 = Path.ChangeExtension(pxa, ".mp3");
            var pxa_mp4_mp4 = Path.ChangeExtension(pxa, ".mp4.mp4");
            var pxa_mp3_mp4 = Path.ChangeExtension(pxa, ".mp3.mp4");


            // do we have the end result?

            if (File.Exists(pxa_mp3_mp4))
            {
                // all done
                Debugger.Break();
            }


            if (File.Exists(pxa))
            {
            }
            else
            {
                var videoDownloader = new VideoDownloader(video, pxa);
                videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);
                videoDownloader.Execute();
            }

            // any reason to attempt upgrade?

            if (mp4video.Last().Resolution > mp4audio.Last().Resolution)
            {
                var ffmpeg = @"X:\util\ffmpeg-20150609-git-7c9fcdf-win64-static\ffmpeg-20150609-git-7c9fcdf-win64-static\bin\ffmpeg.exe";

                if (!File.Exists(pxa_mp4_mp4))
                {
                    var videoDownloader = new VideoDownloader(mp4video.Last(), pxa_mp4_mp4);
                    videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);
                    videoDownloader.Execute();
                }

                // extract mp3

                // "X:\util\ffmpeg-20150609-git-7c9fcdf-win64-static\ffmpeg-20150609-git-7c9fcdf-win64-static\bin\ffmpeg.exe" -i "X:\media\Dolphins 360° 4K.mp4" "C:\Users\Administrator\Documents\Dolphins 360_ 4K.mp3"


                // "X:\util\ffmpeg-20150609-git-7c9fcdf-win64-static\ffmpeg-20150609-git-7c9fcdf-win64-static\bin\ffmpeg.exe" -i "C:\Users\Administrator\Documents\Dolphins 360_ 4K.mp4" -i "C:\Users\Administrator\Documents\Dolphins 360_ 4K.mp3" -shortest "C:\Users\Administrator\Documents\Dolphins 360_ 4K.mp3.mp4"

                if (!File.Exists(pxa_mp3))
                    Process.Start(ffmpeg,
                        "-i \"" + pxa + "\""
                        + " \"" + pxa_mp3 + "\"").WaitForExit();

                // merge and delete

                // Additional information: The operation was canceled by the user

                Process.Start(ffmpeg,
                   " -i \"" + pxa_mp3 + "\""
                   + " -i \"" + pxa_mp4_mp4 + "\""
                   + " -c:v copy -shortest -shortest \"" + pxa_mp3_mp4 + "\"").WaitForExit();

                File.Delete(pxa_mp3);
                File.Delete(pxa_mp4_mp4);
                File.Delete(pxa);
            }

            // X:\jsc.svn\examples\merge\Test\TestYouTubeExtractor\xffmpeg\Program.cs
        }
Exemple #26
0
        private void DownloadMp4(LinkInfo link, string downloadDir)
        {
            Directory.CreateDirectory(downloadDir);

            IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link.Link);

	        VideoInfo video;
	        switch (link.QualityInfo)
	        {
		        case Quality.Low:
					video = videoInfos.Where(info => info.Resolution < 480).OrderByDescending(info => info.Resolution).First();
					break;
		        case Quality.Medium:
					video = videoInfos.Where(info => info.Resolution < 720).OrderByDescending(info => info.Resolution).First();
					break;
		        case Quality.High:
			        video = videoInfos.Where(info => info.Resolution < 1080).OrderByDescending(info => info.Resolution).First();
                    break;
		        case Quality.SuperHigh:
					video = videoInfos.OrderByDescending(info => info.Resolution).First();
					break;
		        default:
			        throw new ArgumentOutOfRangeException();
	        }
	        if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            var videoDownloader = new VideoDownloader(video, Path.Combine(downloadDir, RemoveIllegalPathCharacters(video.Title) + "-" + video.Resolution + video.VideoExtension));
            videoDownloader.DownloadStarted += (sender, argss) => Console.WriteLine("Started downloading " + video.Title + "-" + video.Resolution + video.VideoExtension);

            videoDownloader.DownloadProgressChanged += (sender, argss) =>
            {
                downloader.ReportProgress((int)argss.ProgressPercentage);

            };

            videoDownloader.Execute();
        }
Exemple #27
0
        static void DownloadMP4(string link, string downloadDir)
        {
            Directory.CreateDirectory(downloadDir);

            IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);

            VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 720);

            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            var videoDownloader = new VideoDownloader(video, Path.Combine(downloadDir, RemoveIllegalPathCharacters(video.Title) + video.VideoExtension));
            videoDownloader.DownloadStarted += (sender, argss) => Console.WriteLine("Started downloading " + video.Title + video.VideoExtension);

            int ticks = 0;
            videoDownloader.DownloadProgressChanged += (sender, argss) =>
            {
                ticks++;

                if (ticks > 1000)
                {
                    Console.Write("#");
                    ticks -= 1000;
                }

            };
            videoDownloader.DownloadFinished += (sender, argss) => Console.WriteLine("Finished downloading " + video.Title + video.VideoExtension);

            videoDownloader.Execute();
        }
Exemple #28
0
        private void DownloadFile()
        {
            if (radioAudio.Checked)
            {
                try
                {
                    setTextProgress("Iniciando Download...");
                    IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(txtLink.Text);
                    VideoInfo video = videoInfos
                        .Where(info => info.CanExtractAudio)
                        .OrderByDescending(info => info.AudioBitrate)
                        .First();

                    if (video.RequiresDecryption)
                    {
                        DownloadUrlResolver.DecryptDownloadUrl(video);
                    }
                    setTextMediaInfo(video.Title);
                    setTextProgress("Baixando " + video.Title);
                    string outputTitle = video.Title;
                    foreach (char c in System.IO.Path.GetInvalidFileNameChars())
                    {
                        outputTitle = outputTitle.Replace(c, '_');
                    }
                    var audioDownloader = new AudioDownloader(video, Path.Combine("C:/Downloads", outputTitle + video.AudioExtension));
                    audioDownloader.DownloadProgressChanged += (sender, args) => this.Invoke((MethodInvoker)delegate {
                        progressFile.Value = (int)(args.ProgressPercentage * 0.85);
                        lblprogress.Text = Math.Round(args.ProgressPercentage * 0.85, 2).ToString() + "%";
                    });
                    audioDownloader.AudioExtractionProgressChanged += (sender, args) => this.Invoke((MethodInvoker)delegate {
                        progressFile.Value = (int)(85 + args.ProgressPercentage * 0.15);
                        lblprogress.Text = Math.Round(85 + args.ProgressPercentage * 0.15, 2).ToString() + "%";
                    });
                    audioDownloader.DownloadFinished += (sender, args) => this.Invoke((MethodInvoker)delegate {
                        progressFile.Value = 0;
                        lblprogress.Text = ("Download Finalizado!");
                    });
                    audioDownloader.Execute();
                }
                catch (Exception e)
                {
                    this.Invoke((MethodInvoker)delegate
                    {
                        MetroMessageBox.Show(this,"Falha ao Baixar o audio " + e.Message);
                    });
                }
            }
            else
            {
                try {
                setTextProgress("Iniciando Download...");
                IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(txtLink.Text);
                VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);
                if (video.RequiresDecryption)
                {
                    DownloadUrlResolver.DecryptDownloadUrl(video);
                }
                setTextProgress("Baixando " + video.Title);
                setTextMediaInfo(video.Title);
                string outputTitle = video.Title;
                foreach (char c in System.IO.Path.GetInvalidFileNameChars())
                {
                    outputTitle = outputTitle.Replace(c, '_');
                }
                var videoDownloader = new VideoDownloader(video, Path.Combine("C:/Downloads", outputTitle + video.VideoExtension));
                videoDownloader.DownloadProgressChanged += (sender2, args) => this.Invoke((MethodInvoker)delegate {
                    progressFile.Value = (int)(Math.Round(args.ProgressPercentage, 2));
                    lblprogress.Text = Math.Round(args.ProgressPercentage, 2) + "%";
                });
                videoDownloader.DownloadFinished += (sender2, args) => this.Invoke((MethodInvoker)delegate {
                    progressFile.Value = 0;
                    lblprogress.Text = ("Download Finalizado!");
                });
                videoDownloader.Execute();
            }
            catch (Exception e)
            {
                this.Invoke((MethodInvoker)delegate
                {
                    MetroMessageBox.Show(this,"Falha ao Baixar o vídeo " + e.Message);
                });
            }
            }
        }
        private void DownloadYoutubeVideo(string url)
        {
            var infos = DownloadUrlResolver.GetDownloadUrls(url).ToArray();
            var info = infos
                .Where(i => i.VideoType == VideoType.Mp4)
                .OrderByDescending(i => i.Resolution)
                .OrderByDescending(i => AudioTypePriority(i.AudioType))
                .FirstOrDefault();
            if (info == null)
            {
                Console.WriteLine("No appropriate stream found for {0}.", url);
            }
            else
            {
                string fileName = Path.Combine(OutputDirectory, fileNameCleaner(info.Title + ".mp4"));
                if (File.Exists(fileName))
                {
                    Console.WriteLine("File with name {0} already exists. File will not be downloaded.", fileName);
                }
                else
                {
                    string fileNameDownload = fileName + ".download";
                    var downloader = new VideoDownloader(info, fileNameDownload);

                    int lastProgress = -1;
                    downloader.DownloadProgressChanged += (sender, eventArgs) =>
                    {
                        if (eventArgs.ProgressPercentage > lastProgress + 1)
                        {
                            lastProgress++;
                            Console.Write("\rGetting '{0}'. {1}% complete.", downloader.Video.Title, lastProgress);
                        }
                    };
                    downloader.DownloadFinished += (sender, eventArgs) =>
                    {
                        if (downloader.BytesToDownload == null)
                        {
                            File.Move(fileNameDownload, fileName);
                            Console.WriteLine("\r'{0}' downloaded to {1}", downloader.Video.Title, fileName);
                        }
                        else
                        {
                            Console.WriteLine("Failed to download {0}.", downloader.Video.Title);
                        }
                    };
                    downloader.Execute();
                }
            }
        }
        private static void DownloadVideo1(string link, IEnumerable<VideoInfo> videoInfos)
        {
            // Show Details	Severity	Code	Description	Project	File	Line
            //Error CS0246  The type or namespace name 'ICSharpCode' could not be found(are you missing a using directive or an assembly reference?)	taglib-sharp File.cs 878


            // Show Details	Severity	Code	Description	Project	File	Line
            //Error Error opening icon file X:\opensource\github\taglib - sharp\src-- Access to the path 'X:\opensource\github\taglib-sharp\src' is denied.taglib - sharp    CSC

            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150609/360
            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150608
            var mp4 = videoInfos.Where(x => x.VideoType == VideoType.Mp4);
            var mp4video = mp4.Where(x => x.Resolution > 0).OrderBy(x => x.Resolution).ToArray();
            var mp4audio = mp4video.Where(x => x.AudioBitrate > 0).OrderBy(x => x.Resolution).ToArray();

            /*
             * Select the first .mp4 video with 360p resolution
             */
            //VideoInfo video = mp4audio.OrderByDescending(info => info.Resolution).First();
            // 300MB?
            //VideoInfo video = mp4audio.OrderBy(info => info.Resolution).First();
            //VideoInfo video = mp4video.OrderBy(info => info.Resolution).Last();
            //VideoInfo video = videoInfos.FirstOrDefault(k => k.FormatCode == 315)
            VideoInfo video = //videoInfos.FirstOrDefault(k => k.FormatCode == 299)
                mp4audio.OrderBy(info => info.Resolution).Last();


            video.DecryptDownloadUrl();

            var Title =
                  video.Title
                //.Replace("/", " ")
                //.Replace("\\", " ")
                .Replace("\"", "'")
                //.Replace(":", " ")
                .Replace("&", " and ")
                //.Replace("*", " ")
                ;

            // http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars(v=vs.110).aspx

            foreach (var item in
                Path.GetInvalidFileNameChars())
            {
                Title = Title.Replace(item, ' ');

            }

            var px = Path.Combine(
                //Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
               "x:/media",

             Title + video.VideoExtension);

#if REMOTE
            var p = Path.Combine(
                //Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                "r:/media",

               Title + video.VideoExtension);

            Console.WriteLine(px);

            // https://msdn.microsoft.com/en-us/library/windows/desktop/aa385480(v=vs.85).aspx
            // https://msdn.microsoft.com/en-us/library/windows/desktop/aa385485(v=vs.85).aspx
            // http://stackoverflow.com/questions/8629760/how-to-force-windows-to-reconnect-to-network-drive
            // https://msdn.microsoft.com/en-us/library/windows/desktop/aa385453(v=vs.85).aspx

            try
            {
                var ee = Directory.GetFileSystemEntries("r:\\");
            }
            catch
            {
                // \\192.168.43.12\x$

                //                [Window Title]
                //        Location is not available

                //        [Content]
                //R:\ is unavailable.If the location is on this PC, make sure the device or drive is connected or the disc is inserted, and then try again.If the location is on a network, make sure you’re connected to the network or Internet, and then try again.If the location still can’t be found, it might have been moved or deleted.

                //[OK]

                // ---------------------------
                //Error
                //-------------------------- -
                //This network connection does not exist.


                //-------------------------- -
                //OK
                //-------------------------- -

                IntPtr hWnd = new IntPtr(0);
                int res = WNetRestoreSingleConnection(hWnd, "r:", true);
            }
#endif

            // res = 86
            // res = 0

            //            ---------------------------
            //            Restoring Network Connections
            //---------------------------
            //An error occurred while reconnecting r:
            //                to
            //\\RED\x$
            //Microsoft Windows Network: The local device name is already in use.


            //This connection has not been restored.
            //---------------------------
            //OK
            //-------------------------- -

#if REMOTE
            if (!File.Exists(p))
#endif

            {
                if (!File.Exists(px))
                {
                    /*
                     * Create the video downloader.
                     * The first argument is the video to download.
                     * The second argument is the path to save the video file.
                     */
                    var videoDownloader = new VideoDownloader(video, px);

                    // Register the ProgressChanged event and print the current progress
                    videoDownloader.DownloadProgressChanged += (sender, args) =>
                    {
                        //ScriptCoreLib.Desktop.TaskbarProgress.SetMainWindowProgress(0.01 * args.ProgressPercentage);



                        Console.Title = "%" + args.ProgressPercentage.ToString("0.0");
                    }
                    ;


                    /*
                     * Execute the video downloader.
                     * For GUI applications note, that this method runs synchronously.
                     */
                    videoDownloader.Execute();

                    // modify the mp4 tag only if we just fetched it...

                    // Additional information: The process cannot access the file 'C:\Users\Arvo\Documents\Dido - Don't Believe In Love.mp4' because it is being used by another process.

                    // http://stackoverflow.com/questions/18250281/reading-writing-metadata-of-audio-video-files

                    Console.WriteLine("TagLib... " + new { new FileInfo(px).Length });

                    // what about webm?
                    TagLib.File videoFile = TagLib.File.Create(px);
                    //TagLib.Mpeg4.AppleTag customTag = (TagLib.Mpeg4.Comm)videoFile.GetTag(TagLib.TagTypes.Apple);
                    TagLib.Mpeg4.AppleTag customTag = (TagLib.Mpeg4.AppleTag)videoFile.GetTag(TagLib.TagTypes.Apple);


                    //customTag.SetDashBox("Producer", "Producer1",link);
                    //customTag.Comment = link;
                    customTag.Album = link;
                    videoFile.Save();
                    videoFile.Dispose();
                }

                // http://stackoverflow.com/questions/13847669/file-move-progress-bar

#if REMOTE
                Console.WriteLine("Move... " + new { p });

                //File.Move(px, p);

                //err = System.IO.IOException: Cannot create a file when that file already exists

                // map network drive via ip. as the aias can be forgotten by the network

                // http://www.peerwisdom.org/2013/04/03/large-send-offload-and-network-performance/
                // 350 KBps???
                // http://blogs.msdn.com/b/heaths/archive/2006/04/07/571138.aspx
                // https://www.microsoft.com/en-us/download/details.aspx?id=11876
                // http://serverfault.com/questions/248728/eseutil-exe-version-8-3-106-1
                // http://blogs.technet.com/b/askperf/archive/2007/05/08/slow-large-file-copy-issues.aspx#pi169128=4
                // http://mygrassvalleyportal.force.com/gvknowledge/articles/KB_Article/Disabling-Large-Send-Offload-Enhance-Network-Bandwidth-on-Summit-9-x
                //  disable File and Printer sharing for the IPv6 interface. (press alt in ncpa.cpl, then advanced\advanced settings\Ethernet\Bindings for Ethernet - disable IPv6 File & Print sharing)

                // http://blogs.msdn.com/b/granth/archive/2010/05/10/how-to-copy-very-large-files-across-a-slow-or-unreliable-network.aspx

                //  /J           Copies using unbuffered I/O. Recommended for very large files.
                // http://www.xxcopy.com/xxcopy30.htm
                // http://stackoverflow.com/questions/48679/copy-a-file-without-using-the-windows-file-cache

                // https://github.com/SQLServerIO/UBCopy/blob/master/UBCopy/AsyncUnbuffCopyStatic.cs

                // takes forever?
                ////Process.Start(
                ////    "cmd",

                ////    "  /K xcopy \"" + px + "\" \"r:\\media\\\" /J"
                ////);


                // slow but atleast we have a progressbar?
                //new Thread(

                //    delegate ()
                //    {
                Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(px, p, Microsoft.VisualBasic.FileIO.UIOption.AllDialogs);
#endif

                //    }
                //)
                //{ ApartmentState = ApartmentState.STA }.Start();

                //Thread.Yield();



                //                Does R:/ media\The Illusion Of Time -Documentary.mp4 specify a file name
                //or directory name on the target
                //(F = file, D = directory)?

                //err = { "Could not find a part of the path 'r:\\media'."}
                // System.IO.DirectoryNotFoundException: Could not find a part of the path 'r:\media'.
                // System.IO.IOException: The specified network name is no longer available.
                // Systxem.IO.IOException: The system cannot move the file to a different disk drive

                //Move... { p = r:/ media\KRYON 'Evolution Revealed' - Lee Carroll.mp4 }
                //{
                //    err = System.IO.DirectoryNotFoundException: Could not find a part of the path
                //'r:\media'.
                //   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
                //   at System.IO.Directory.InternalCreateDirectory(String fullPath, String path,
                //Object dirSecurityObj, Boolean checkHost)
                //   at System.IO.Directory.InternalCreateDirectoryHelper(String path, Boolean che
                //ckHost)
                //   at System.IO.Directory.CreateDirectory(String path)
                //   at Microsoft.VisualBasic.FileIO.FileSystem.CopyOrMoveFile(CopyOrMove operatio
                //n, String sourceFileName, String destinationFileName, Boolean overwrite, UIOptio
                //nInternal showUI, UICancelOption onUserCancel)
                //   at Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(String sourceFileName, St
                //ring destinationFileName, UIOption showUI)
            }
        }
        // { err = System.IO.FileNotFoundException: Could not load file or assembly 'taglib-sharp,
        private static void DownloadVideo(
            string chname,


            // not detected via metadata?
            projection Spherical,
            string link,
            IEnumerable<VideoInfo> videoInfos)
        {
            //Error	3	The type 'System.Windows.UIElement' is defined in an assembly that is not referenced. You must add a reference to assembly 'PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.	Z:\jsc.svn\examples\merge\Test\TestYouTubeExtractor\TestYouTubeExtractor\Program.cs	75	13	TestYouTubeExtractor
            //Error	4	The type 'System.Windows.Forms.Control' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.	Z:\jsc.svn\examples\merge\Test\TestYouTubeExtractor\TestYouTubeExtractor\Program.cs	75	13	TestYouTubeExtractor

            var mp4 = videoInfos.Where(x => x.VideoType == VideoType.Mp4);
            var mp4video = mp4.Where(x => x.Resolution > 0).OrderBy(x => x.Resolution).ToArray();
            var mp4audio = mp4video.Where(x => x.AudioBitrate > 0).OrderBy(x => x.Resolution).ToArray();


            VideoInfo video = //videoInfos.FirstOrDefault(k => k.FormatCode == 299)
             mp4audio.OrderBy(info => info.Resolution).Last();


            //RequiresDecryption = false

            
            Console.WriteLine(video.Title);

            if (video.RequiresDecryption)
            {
                Console.WriteLine("cant");
                return;
                video.DecryptDownloadUrl();
            }

            // old name
            var Title =
                  video.Title
                //.Replace("/", " ")
                //.Replace("\\", " ")
                .Replace("\"", "'")
                //.Replace(":", " ")
                .Replace("&", " and ")
                //.Replace("*", " ")
                ;

            // http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars(v=vs.110).aspx

            foreach (var item in
                Path.GetInvalidFileNameChars())
            {
                Title = Title.Replace(item, ' ');

            }

            // https://code.google.com/p/android/issues/detail?id=8185
            // http://stackoverflow.com/questions/18596245/in-c-how-can-i-detect-if-a-character-is-a-non-ascii-character


            var apkfriendlytitle_old3 = default(string);

            var apkfriendlytitle = new string(
                Title.Select(x => x < 127 ? x : '_').ToArray()
                );

            // apkfriendlytitle = "___360_ - __________find the truth 360 degree trick movie ."

            // prefix it, and loose the keyword later to be less redundant...
            if (Spherical == projection.x360)
                apkfriendlytitle = "360 " + (apkfriendlytitle.Replace("360", " ")).Trim();
            else if (Spherical == projection.x360TB)
            {
                apkfriendlytitle_old3 = "360 " + (apkfriendlytitle.Replace("360", " ")).Trim();
                apkfriendlytitle = "360 3D " + (apkfriendlytitle.Replace("360", " ")).Trim();
            }

            //apkfriendlytitle = "360 " + (apkfriendlytitle.Replace("360", " ")).Trim() + "_TB";
            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20151106


            if (!string.IsNullOrEmpty(chname))
                apkfriendlytitle_old3 += " by " + new string(chname.Select(x => x < 127 && char.IsLetterOrDigit(x) ? x : '_').ToArray());

            // remedy for bug run
            var apkfriendlytitle_old2 = apkfriendlytitle;
            if (!string.IsNullOrEmpty(chname))
                apkfriendlytitle_old2 += " by " + (chname.Select(x => x < 127 && char.IsLetterOrDigit(x) ? x : '_').ToArray());

            var apkfriendlytitle_old = apkfriendlytitle;
            if (!string.IsNullOrEmpty(chname))
                apkfriendlytitle_old += " by " + chname;




            // pxa_mp4 = "x:/media\\HD Video 1080p - Time Lapse with Sunsets, Clouds, Stars by LoungeV studio : Relaxing Nature Videos.mp4"
            if (!string.IsNullOrEmpty(chname))
                apkfriendlytitle += " by " + new string(chname.Select(x => x < 127 && char.IsLetterOrDigit(x) ? x : '_').ToArray());
            //if (Spherical == projection.x360TB)
            //    apkfriendlytitle += "_TB";

            // 
            //apkfriendlytitle = apkfriendlytitle.Replace("360", "_");



            //  System.IO.DirectoryNotFoundException: Could not find a part of the path 'x:\media\360 tape columns 4096x3840x2160p60 py by zproxy.mp4'.

            // clean slate?
            new DirectoryInfo("x:/media").Create();



            // px = "x:/media\\OVRMyCubeWorldNDK WASDC PointerLock.mp4"
            var px_old = Path.Combine("x:/media", apkfriendlytitle_old + video.VideoExtension);
            var px_old2 = Path.Combine("x:/media", apkfriendlytitle_old2 + video.VideoExtension);

            // "X:\media\360 What is VR Video by Jessica_Brillhart.mp3.mp4"
            var px_old3 = Path.ChangeExtension(Path.Combine("x:/media", apkfriendlytitle_old3 + video.VideoExtension), ".mp3.mp4");


            // pxa_mp4 = "x:/media\\OVRMyCubeWorldNDK WASDC PointerLock.mp4"
            var pxa_mp4 = Path.Combine("x:/media", apkfriendlytitle + video.VideoExtension);



            // pxa_mp3 = "x:/media\\OVRMyCubeWorldNDK WASDC PointerLock.mp3"
            var pxa_mp3 = Path.ChangeExtension(pxa_mp4, ".mp3");
            // pxa_mp4_mp4 = "x:/media\\OVRMyCubeWorldNDK WASDC PointerLock.mp4.mp4"
            var pxa_mp4_mp4 = Path.ChangeExtension(pxa_mp4, ".mp4.mp4");

            // pxa_mp3_mp4 = "x:/media\\OVRMyCubeWorldNDK WASDC PointerLock.mp3.mp4"
            var pxa_mp3_mp4 = Path.ChangeExtension(pxa_mp4,

                (Spherical == projection.x360TB) ?

                ".mp3._TB.mp4" :

                ".mp3.mp4"
            );

            // "X:\media\360 3D What is VR Video by Jessica_Brillhart_TB.mp4"
            var pxa_old_mp3_mp4 = Path.ChangeExtension(px_old, ".mp3.mp4");



            if (!File.Exists(pxa_mp4))
                if (File.Exists(px_old3))
                {
                    Console.WriteLine("renamed " + new { pxa_mp3_mp4 });
                    // upgrade old naming to apk friendly.
                    File.Move(px_old3, pxa_mp3_mp4);
                }



            if (!File.Exists(pxa_mp4))
                if (File.Exists(px_old2))
                {
                    Console.WriteLine("renamed " + new { pxa_mp4 });
                    // upgrade old naming to apk friendly.
                    File.Move(px_old2, pxa_mp4);
                }




            if (!File.Exists(pxa_mp4))
                if (File.Exists(px_old))
                {
                    Console.WriteLine("renamed " + new { pxa_mp4 });
                    // upgrade old naming to apk friendly.
                    File.Move(px_old, pxa_mp4);
                }


            if (!File.Exists(pxa_mp3_mp4))
                if (File.Exists(pxa_old_mp3_mp4))
                {
                    Console.WriteLine("renamed " + new { pxa_mp3_mp4 });
                    // upgrade old naming to apk friendly.
                    File.Move(pxa_old_mp3_mp4, pxa_mp3_mp4);
                }


            // do we have the end result?

            if (File.Exists(pxa_mp3_mp4))
            {
                Console.WriteLine("all done: " + pxa_mp3_mp4);

                // all done
                //Debugger.Break();
                return;
            }

            var awaitingToBeTagged = false;

            if (!File.Exists(pxa_mp4))
            {
            retry: ;

                try
                {
                    // ?????369:Timelapse of Sahara @Morocco

                    // pxa_mp4 = "x:/media\\HD Video 1080p - Time Lapse with Sunsets, Clouds, Stars by LoungeV studio : Relaxing Nature Videos.mp4"

                    var videoDownloader = new VideoDownloader(video, pxa_mp4);
                    videoDownloader.DownloadProgressChanged += (sender, args) =>
                    {
                        //ScriptCoreLib.Desktop.TaskbarProgress.SetMainWindowProgress(0.01 * args.ProgressPercentage);



                        Console.Title = "%" + args.ProgressPercentage.ToString("0.0");
                    }
                        ;
                    videoDownloader.Execute();
                    awaitingToBeTagged = true;
                }
                catch (Exception err)
                {
                    Console.WriteLine(new { video, err });

                    //                        url = http://youtube.com/watch?v=V0MWPJqVoUc }
                    //{
                    //                            url = http://s.ytimg.com/yts/jsbin/html5player-new-et_EE-vfl2stSNK/html5player-new.js }
                    //25 Flat Geo Earth claims that 'Rocked' my world view 2 / 5
                    //{
                    //                                video = Full Title: 25 Flat Geo Earth claims that 'Rocked' my world view 2 / 5.mp4, Type: Mp4, Resolution: 720p, err = System.Net.WebException: The remote server returned an error: (403) Forbidden.

                    return;

                    Debugger.Break();

                    // retry?
                    video = //videoInfos.FirstOrDefault(k => k.FormatCode == 299)
                        mp4audio.OrderBy(info => info.Resolution).Take(mp4audio.Count() - 1).LastOrDefault();

                    if (video == null)
                        return;

                    goto retry;
                }
            }

            ;

            #region any reason to attempt upgrade?

            // upgrade { link = //www.youtube.com/embed/E-SDNGMYB80 } from 360 to 480


            if (mp4video.Last().Resolution > mp4audio.Last().Resolution)

                // dont care about non HD
                if (mp4video.Last().Resolution >= 1080)
                {
                    // fk u visual studio, for closing IDE for stale license.

                    Console.WriteLine("upgrade " + new { link } + " from " + mp4audio.Last().Resolution + " to " + mp4video.Last().Resolution);


                    var ffmpeg = @"X:\util\ffmpeg-20150609-git-7c9fcdf-win64-static\ffmpeg-20150609-git-7c9fcdf-win64-static\bin\ffmpeg.exe";

                    if (File.Exists(pxa_mp4_mp4))
                        if (

                            // 15m is the timeout to not conitnue
                            (DateTime.UtcNow - File.GetLastWriteTimeUtc(pxa_mp4_mp4)).TotalMinutes > 15
                            )
                        {
                            File.Delete(pxa_mp4_mp4);

                        }

                    if (File.Exists(pxa_mp3))
                        if (

                            // 15m is the timeout to not conitnue
                            (DateTime.UtcNow - File.GetLastWriteTimeUtc(pxa_mp3)).TotalMinutes > 15
                            )
                        {
                            File.Delete(pxa_mp3);

                        }


                    if (!File.Exists(pxa_mp4_mp4))
                    {
                        var upgradeTargets = new Stack<VideoInfo>(mp4video.ToList());
                    // +		upgradeTargets.Peek()	{Full Title: Noa Neal ‘Graffiti’ 4K 360° Music Video Clip.mp4, Type: Mp4, Resolution: 2160p}	YoutubeExtractor.VideoInfo
                    // +		upgradeTargets.Peek()	{Full Title: Noa Neal ‘Graffiti’ 4K 360° Music Video Clip.mp4, Type: Mp4, Resolution: 1440p}	YoutubeExtractor.VideoInfo
                    // +		upgradeTargets.Peek()	{Full Title: Noa Neal ‘Graffiti’ 4K 360° Music Video Clip.mp4, Type: Mp4, Resolution: 1080p}	YoutubeExtractor.VideoInfo
                    // +		upgradeTargets.Peek()	{Full Title: Noa Neal ‘Graffiti’ 4K 360° Music Video Clip.mp4, Type: Mp4, Resolution: 720p}	YoutubeExtractor.VideoInfo

                        // video = {Full Title: Noa Neal ‘Graffiti’ 4K 360° Music Video Clip.mp4, Type: Mp4, Resolution: 720p}

                        retry_lesser:

                        var videoDownloader = new VideoDownloader(upgradeTargets.Peek(), pxa_mp4_mp4);
                        videoDownloader.DownloadProgressChanged += (sender, args) =>
                        {
                            //ScriptCoreLib.Desktop.TaskbarProgress.SetMainWindowProgress(0.01 * args.ProgressPercentage);



                            Console.Title = "%" + args.ProgressPercentage.ToString("0.0");
                        }
                       ;

                        // some videos may not allow that?
                        // err = {"The remote server returned an error: (403) Forbidden."}
                        try
                        {
                            videoDownloader.Execute();
                        }
                        catch (Exception err)
                        {
                            upgradeTargets.Pop();
                            // the others are also blocked?

                            //goto retry_lesser;
                            throw;
                        }
                    }

                    // extract mp3

                    // "X:\util\ffmpeg-20150609-git-7c9fcdf-win64-static\ffmpeg-20150609-git-7c9fcdf-win64-static\bin\ffmpeg.exe" -i "X:\media\Dolphins 360° 4K.mp4" "C:\Users\Administrator\Documents\Dolphins 360_ 4K.mp3"


                    // "X:\util\ffmpeg-20150609-git-7c9fcdf-win64-static\ffmpeg-20150609-git-7c9fcdf-win64-static\bin\ffmpeg.exe" -i "C:\Users\Administrator\Documents\Dolphins 360_ 4K.mp4" -i "C:\Users\Administrator\Documents\Dolphins 360_ 4K.mp3" -shortest "C:\Users\Administrator\Documents\Dolphins 360_ 4K.mp3.mp4"

                    if (!File.Exists(pxa_mp3))
                        Process.Start(ffmpeg,
                            "-i \"" + pxa_mp4 + "\""
                            + " \"" + pxa_mp3 + "\"").WaitForExit();

                    // merge and delete

                    // Additional information: The operation was canceled by the user

                    // http://superuser.com/questions/227433/whats-the-difference-between-ffmpegs-vcodec-copy-and-sameq

                    Process.Start(ffmpeg,
                       " -i \"" + pxa_mp3 + "\""
                       + " -i \"" + pxa_mp4_mp4 + "\""
                       + " -c:v copy -shortest \"" + pxa_mp3_mp4 + "\"").WaitForExit();

                    awaitingToBeTagged = true;



                    File.Delete(pxa_mp3);
                    File.Delete(pxa_mp4_mp4);
                    File.Delete(pxa_mp4);
                }
            #endregion

            // we did not upgrade.. assume it was already tagged...
            if (!awaitingToBeTagged)
                return;

            // X:\jsc.svn\examples\merge\Test\TestYouTubeExtractor\xffmpeg\Program.cs

            var pxatagged_mp4 = File.Exists(pxa_mp3_mp4) ? pxa_mp3_mp4 : pxa_mp4;

            Console.WriteLine("TagLib... " + new { new FileInfo(pxatagged_mp4).Length });

            // what about webm?
            TagLib.File videoFile = TagLib.File.Create(pxatagged_mp4);
            //TagLib.Mpeg4.AppleTag customTag = (TagLib.Mpeg4.Comm)videoFile.GetTag(TagLib.TagTypes.Apple);
            TagLib.Mpeg4.AppleTag customTag = (TagLib.Mpeg4.AppleTag)videoFile.GetTag(TagLib.TagTypes.Apple);


            //customTag.SetDashBox("Producer", "Producer1",link);
            //customTag.Comment = link;
            customTag.Album = link;
            videoFile.Save();
            videoFile.Dispose();

            // all done now..

        }
Exemple #32
0
 static string DownloadVideo()
 {
     string link = ArgList.Get(Arg.YOUTUBE).AsString();
       IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);
       VideoInfo vi = videoInfos.OrderByDescending(x => x.Resolution).First(x => x.VideoType == VideoType.Mp4 && x.AudioExtension != null);
       if (vi.RequiresDecryption)
     DownloadUrlResolver.DecryptDownloadUrl(vi);
       VideoDownloader vd = new VideoDownloader(vi, Path.Combine(Environment.CurrentDirectory, vi.Title + vi.VideoExtension));
       using (Mutex mutex = new Mutex())
       {
     vd.DownloadFinished += (sender, e) => { try { mutex.ReleaseMutex(); } catch { } };
     vd.DownloadProgressChanged += (sender, e) => { Console.WriteLine("Downloading {0}%", e.ProgressPercentage); };
     vd.Execute();
     mutex.WaitOne();
       }
       return vd.SavePath;
 }
        private async Task DownloadVideoAsync(DownloadItem downloadInfo, DownloadItem.FileProgress fileInfo, EventHandler<DownloadCompletedEventArgs> callback) {
            downloadInfo.Status = DownloadStatus.Downloading;
            VideoDownloader YTD = new VideoDownloader(fileInfo.Source, fileInfo.Destination);
            YTD.DownloadProgressChanged += (sender, e) => {
                if (downloadInfo.IsCanceled)
                    e.Cancel = true;
                else {
                    fileInfo.BytesTotal = YTD.DownloadSize;
                    fileInfo.BytesDownloaded = e.ProgressBytes;
                    downloadInfo.UpdateProgress();
                }
            };

            // Run downloader task.
            await Task.Run(() => {
                try {
                    YTD.Execute();
                } catch {
                    downloadInfo.Status = DownloadStatus.Failed;
                }
            }).ConfigureAwait(false);

            // Detect whether this is the last file.
            fileInfo.Done = true;
            if (downloadInfo.Files.Any(d => !d.Done) == false) {
                var NextDownload = StartNextDownloadAsync().ConfigureAwait(false);

                // Raise events for the last file part only.
                if (downloadInfo.IsCompleted) {
                    try {
                        await DownloadCompletedAsync(downloadInfo).ConfigureAwait(false);
                    } catch {
                        downloadInfo.Status = DownloadStatus.Failed;
                    }
                } else if (downloadInfo.IsCanceled)
                    DownloadCanceled(downloadInfo);
                RaiseCallback(downloadInfo);

                await NextDownload;
            }
        }