private void DownloadButton_Click(object sender, RoutedEventArgs e)
 {
     if (IsDownloadRunning)
     {
         MessageBox.Show("Please wait for the current download to complete");
     }
     else
     {
         StatusText.Content = "Downloading...";
         VidDownloader      = new YTDownloader();
         VidDownloader.DownloadProgressChanged += VidDownloader_DownloadProgressChanged;
         VidDownloader.DownloadCompleted       += VidDownloader_DownloadCompleted;
         if (IsDownloadingMP3)
         {
             if (usingMP3Thumbnail)
             {
                 VidDownloader.DownloadVideo(VidURL, DownloadType.MP3Pic, SelectedAudQuality, SelectedVidQuality);
             }
             else
             {
                 VidDownloader.DownloadVideo(VidURL, DownloadType.MP3Only, SelectedAudQuality, SelectedVidQuality);
             }
         }
         else
         {
             DownloadAudQuality = SelectedAudQuality;
             DownloadVidQuality = SelectedVidQuality;
             VidDownloader.DownloadVideo(VidURL, DownloadType.CustomQuality, SelectedAudQuality, SelectedVidQuality);
         }
     }
 }
Ejemplo n.º 2
0
        private async Task ProcessRequest(HttpListenerContext context)
        {
            HttpListenerRequest request = context.Request;

            Log.WriteLog(LogType.Info, "Recieved a request for " + request.Url);
            if (request.RawUrl.Contains("getmetadata"))
            {
StartCheckMaintainance:
                if (File.Exists(downloadPath + "\\maintainance.lck"))
                {
                    Log.WriteLog(LogType.Info, "Delaying request for 4 seconds as maintainance is currently running");
                    Thread.Sleep(4000);
                    goto StartCheckMaintainance;
                }
                string          VidID   = request.QueryString.GetValues(request.QueryString.AllKeys[0])[0];
                string          VidURL  = "https://www.youtube.com/watch?v=" + VidID;
                MetadataScraper scraper = new MetadataScraper();
                MetadataScrape  scrape  = new MetadataScrape();
                scrape = scraper.GetMetadata(VidURL);
                HttpListenerResponse response = context.Response;
                MemoryStream         xmlData  = new MemoryStream();
                //from https://stackoverflow.com/questions/16371037/save-xml-content-to-a-variable answer by Adil and https://csharp.net-tutorials.com/xml/writing-xml-with-the-xmlwriter-class/
                using (XmlWriter writer = XmlWriter.Create(xmlData))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("VideoMetadata");
                    writer.WriteStartElement("VideoID");
                    writer.WriteString(VidID);
                    writer.WriteEndElement();
                    writer.WriteStartElement("Title");
                    writer.WriteString(scrape.VidTitle);
                    writer.WriteEndElement();
                    writer.WriteStartElement("ThumbnailURL");
                    writer.WriteString(scrape.ThumbnailURL);
                    writer.WriteEndElement();
                    writer.WriteStartElement("VideoQualities");
                    foreach (VidQuality quality in scrape.VidQualities)
                    {
                        writer.WriteStartElement("vidquality");
                        writer.WriteAttributeString("format", quality.Format);
                        writer.WriteAttributeString("size", quality.FileSize);
                        writer.WriteAttributeString("resolution", quality.Resolution);
                        writer.WriteAttributeString("ID", quality.VidNo);
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                    writer.WriteStartElement("AudioQualities");
                    foreach (AudQuality quality in scrape.AudQualities)
                    {
                        writer.WriteStartElement("audquality");
                        writer.WriteAttributeString("format", quality.Format);
                        writer.WriteAttributeString("size", quality.FileSize);
                        writer.WriteAttributeString("ID", quality.AudNo);
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                }
                string xmlString = ASCIIEncoding.UTF8.GetString(xmlData.ToArray());
                if (request.HttpMethod == "OPTIONS")
                {
                    response.AddHeader("Access-Control-Allow-Headers", "*");
                }
                response.AppendHeader("Access-Control-Allow-Origin", "*");
                byte[] buffer = Encoding.UTF8.GetBytes(xmlString);
                context.Response.ContentLength64 = buffer.Length;
                context.Response.StatusCode      = (int)HttpStatusCode.OK;
                context.Response.ContentType     = "text/xml; encoding='utf-8'";
                context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                Log.WriteLog(LogType.Info, "Successfully sent output");
                response.Close();
            }
            else if (request.RawUrl.Contains("downloadvid"))
            {
StartCheckMaintainance:
                if (File.Exists(downloadPath + "\\maintainance.lck"))
                {
                    Log.WriteLog(LogType.Info, "Delaying request for 4 seconds as maintainance is currently running");
                    Thread.Sleep(4000);
                    goto StartCheckMaintainance;
                }
                YTDownloader downloader = new YTDownloader();
                downloader.DownloadCompleted       += Downloader_DownloadCompleted;
                downloader.DownloadProgressChanged += Downloader_DownloadProgressChanged;
                string urlID     = request.QueryString.GetValues(request.QueryString.AllKeys[0])[0];
                string isMP3Only = request.QueryString.GetValues(request.QueryString.AllKeys[1])[0];
                if (isMP3Only.ToLower().Contains("true"))
                {
                    string       isUsingThumbnail = request.QueryString.GetValues(request.QueryString.AllKeys[2])[0];
                    DownloadType mp3DownloadType;
                    if (isUsingThumbnail.ToLower().Contains("true"))
                    {
                        mp3DownloadType = DownloadType.MP3Pic;
                    }
                    else
                    {
                        mp3DownloadType = DownloadType.MP3Only;
                    }
                    string     vidURL   = "https://www.youtube.com/watch?v=" + urlID;
                    VidQuality vQuality = new VidQuality();
                    vQuality.VidNo = "MP3-Only";
                    AudQuality aQuality = new AudQuality();
                    aQuality.AudNo = urlID;
                    YTDownload download = new YTDownload();
                    download.context  = context;
                    download.aQuality = aQuality;
                    download.vQuality = vQuality;
                    download.VidID    = urlID;
                    download.DownType = mp3DownloadType;
                    RunningDownloads.Add(download);
                    HttpListenerResponse response = context.Response;
                    if (request.HttpMethod == "OPTIONS")
                    {
                        response.AddHeader("Access-Control-Allow-Headers", "*");
                    }
                    response.AppendHeader("Access-Control-Allow-Origin", "*");
                    context.Response.SendChunked = true;
                    downloader.DownloadVideo(vidURL, mp3DownloadType, aQuality, vQuality);
                }
                else
                {
                    try
                    {
                        int        VidID    = int.Parse(request.QueryString.GetValues(request.QueryString.AllKeys[2])[0]);
                        int        AudID    = int.Parse(request.QueryString.GetValues(request.QueryString.AllKeys[3])[0]);
                        string     vidURL   = "https://www.youtube.com/watch?v=" + urlID;
                        VidQuality vQuality = new VidQuality();
                        vQuality.VidNo = VidID.ToString();
                        AudQuality aQuality = new AudQuality();
                        aQuality.AudNo = AudID.ToString();
                        YTDownload download = new YTDownload();
                        download.aQuality = aQuality;
                        download.vQuality = vQuality;
                        download.VidID    = urlID;
                        download.context  = context;
                        download.DownType = DownloadType.CustomQuality;
                        RunningDownloads.Add(download);
                        HttpListenerResponse response = context.Response;
                        if (request.HttpMethod == "OPTIONS")
                        {
                            response.AddHeader("Access-Control-Allow-Headers", "*");
                        }
                        response.AppendHeader("Access-Control-Allow-Origin", "*");
                        context.Response.SendChunked = true;
                        downloader.DownloadVideo(vidURL, DownloadType.CustomQuality, aQuality, vQuality);
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLog(LogType.Error, ex.ToString());
                    }
                }
            }
            else if (request.RawUrl.Contains("download"))
            {
StartCheckMaintainance:
                if (File.Exists(downloadPath + "\\maintainance.lck"))
                {
                    Log.WriteLog(LogType.Info, "Delaying request for 4 seconds as maintainance is currently running");
                    Thread.Sleep(4000);
                    goto StartCheckMaintainance;
                }
                try
                {
                    HttpListenerResponse response = context.Response;
                    string linkName = request.QueryString.GetValues(request.QueryString.AllKeys[0])[0];
                    string fileName = linkName.Replace('*', ' ');
                    fileName = fileName.Replace('|', '&');
                    fileName = fileName.Replace('<', '=');
                    if (request.HttpMethod == "OPTIONS")
                    {
                        response.AddHeader("Access-Control-Allow-Headers", "*");
                    }
                    response.AppendHeader("Access-Control-Allow-Origin", "*");
                    if (File.Exists(downloadPath + "\\" + fileName))
                    {
                        string   contentType = "";
                        FileInfo info        = new FileInfo(fileName);
                        if (info.Extension.ToLower().Contains("mp4"))
                        {
                            contentType = "video/mp4";
                        }
                        else if (info.Extension.ToLower().Contains("mp3"))
                        {
                            contentType = "audio/mpeg";
                        }
                        else if (info.Extension.ToLower().Contains("webm"))
                        {
                            contentType = "video/webm";
                        }
                        else if (info.Extension.ToLower().Contains("mkv"))
                        {
                            contentType = "video/x-matroska";
                        }
                        response.StatusCode = (int)HttpStatusCode.OK;
                        using (FileStream stream = File.OpenRead(downloadPath + "\\" + fileName))
                        {
                            response.ContentType     = contentType;
                            response.ContentLength64 = info.Length;
                            response.AddHeader(
                                "Content-Disposition",
                                "Attachment; filename=\"" + Path.GetFileName(downloadPath + "\\" + fileName) + "\"");
                            stream.CopyTo(response.OutputStream);
                        }
                    }
                    else
                    {
                        response.StatusCode = (int)HttpStatusCode.NotFound;
                        string responseString = "File not found";
                        byte[] data           = Encoding.UTF8.GetBytes(responseString);
                        response.OutputStream.Write(data, 0, data.Length);
                    }
                    response.Close();
                }
                catch (Exception ex)
                {
                    Log.WriteLog(LogType.Error, "Error while downloading a file from server: " + ex.ToString());
                }
            }
        }
        private void Downloader_DownloadCompleted(DownloadProgress ProgData)
        {
            string documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            if (File.Exists(AppPath + "\\" + FileName))
            {
                if (IsDefaultSaveLoc)
                {
                    if (File.Exists(documents + "\\" + FileName))
                    {
                        MessageBoxResult reply = MessageBox.Show("File already exists in My documents, would you like to overwrite it?", "File exists", MessageBoxButton.YesNo, MessageBoxImage.Information);
                        if (reply == MessageBoxResult.Yes)
                        {
                            File.Delete(documents + "\\" + FileName);
                            File.Copy(AppPath + "\\" + FileName, documents + "\\" + FileName);
                            File.Delete(AppPath + "\\" + FileName);
                        }
                        else
                        {
                            File.Copy(AppPath + "\\" + FileName, documents + "\\" + FileName + "-NEW-" + DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + " " + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + "." + Fileformat);
                            File.Delete(AppPath + "\\" + FileName);
                        }
                    }
                    else
                    {
                        File.Copy(AppPath + "\\" + FileName, documents + "\\" + FileName);
                        File.Delete(AppPath + "\\" + FileName);
                    }
                }
                else
                {
                    if (Directory.Exists(SaveLoc))
                    {
                        if (File.Exists(SaveLoc + "\\" + FileName))
                        {
                            MessageBoxResult result = MessageBox.Show("File already exists in save location, would you like to overwrite it?", "File exists", MessageBoxButton.YesNo, MessageBoxImage.Information);
                            if (result == MessageBoxResult.Yes)
                            {
                                File.Delete(SaveLoc + "\\" + FileName);
                                File.Copy(AppPath + "\\" + FileName, SaveLoc + "\\" + FileName);
                                File.Delete(AppPath + "\\" + FileName);
                            }
                            else
                            {
                                File.Copy(AppPath + "\\" + FileName, SaveLoc + "\\" + FileName + "-NEW-" + DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + " " + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + "." + Fileformat);
                                File.Delete(AppPath + "\\" + FileName);
                            }
                        }
                        else
                        {
                            File.Copy(AppPath + "\\" + FileName, SaveLoc + "\\" + FileName);
                            File.Delete(AppPath + "\\" + FileName);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Save directory could not be found, saving to My Documents", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                        if (File.Exists(documents + "\\" + FileName))
                        {
                            MessageBoxResult reply = MessageBox.Show("File already exists in My documents, would you like to overwrite it?", "File exists", MessageBoxButton.YesNo, MessageBoxImage.Information);
                            if (reply == MessageBoxResult.Yes)
                            {
                                File.Delete(documents + "\\" + FileName);
                                File.Copy(AppPath + "\\" + FileName, documents + "\\" + FileName);
                                File.Delete(AppPath + "\\" + FileName);
                            }
                            else
                            {
                                File.Copy(AppPath + "\\" + FileName, documents + "\\" + FileName + "-NEW-" + DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + " " + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + "." + Fileformat);
                                File.Delete(AppPath + "\\" + FileName);
                            }
                        }
                        else
                        {
                            File.Copy(AppPath + "\\" + FileName, documents + "\\" + FileName);
                            File.Delete(AppPath + "\\" + FileName);
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Failed to download the following video:\nhttps://www.youtube.com/watch/?v=" + ProgData.VidID + "\nfrom the playlist", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            VideoQualityInfo CurrentVid = new VideoQualityInfo();

            foreach (VideoQualityInfo info in AllVideosInfoList)
            {
                if (info.VidID == ProgData.VidID)
                {
                    CurrentVid = info;
                }
            }
            AllVideosInfoList.Remove(CurrentVid);
            if (AllVideosInfoList.Count > 0)
            {
                CurrentVideo = CurrentVideo + 1;
                PlaylistStatus.Dispatcher.Invoke(new Action(() => PlaylistStatus.Content = "Status: [" + CurrentVideo.ToString() + "/" + TotalVideos.ToString() + "] Downloading youtube.com/watch?v=" + AllVideosInfoList[0].VidID));
                downloader = new YTDownloader();
                downloader.DownloadCompleted       += Downloader_DownloadCompleted;
                downloader.DownloadProgressChanged += Downloader_DownloadProgressChanged;
                if (AllVideosInfoList[0].IsMP3Only)
                {
                    IsdownloadingMP3 = true;
                    if (IsUsingMP3Thumbnail)
                    {
                        CurrentDownloadID   = AllVideosInfoList[0].VidID;
                        CurrentDownloadType = DownloadType.MP3Pic;
                        downloader.DownloadVideo("https://www.youtube.com/watch?v=" + AllVideosInfoList[0].VidID, DownloadType.MP3Pic);
                    }
                    else
                    {
                        CurrentDownloadID   = AllVideosInfoList[0].VidID;
                        CurrentDownloadType = DownloadType.MP3Only;
                        downloader.DownloadVideo("https://www.youtube.com/watch?v=" + AllVideosInfoList[0].VidID, DownloadType.MP3Only);
                    }
                }
                else
                {
                    IsdownloadingMP3    = false;
                    CurrentDownloadType = DownloadType.CustomQuality;
                    CurrentDownloadID   = AllVideosInfoList[0].VidID;
                    VideoQualityInfo NewDownloadInfo = AllVideosInfoList[0];
                    AudQuality       aQuality        = new AudQuality();
                    aQuality.AudNo = NewDownloadInfo.SelectedAudQuality.ToString();
                    VidQuality vQuality = new VidQuality();
                    vQuality.VidNo = NewDownloadInfo.SelectedVidQuality.ToString();
                    foreach (VidQuality quality in NewDownloadInfo.VidQualityList)
                    {
                        if (quality.VidNo == vQuality.VidNo)
                        {
                            vQuality.Format = quality.Format;
                        }
                    }
                    foreach (AudQuality quality in NewDownloadInfo.AudQualityList)
                    {
                        if (quality.AudNo == aQuality.AudNo)
                        {
                            aQuality.Format = quality.Format;
                        }
                    }
                    IsCrossFormat     = NewDownloadInfo.IsCrossFormat;
                    CurrentAudQuality = aQuality;
                    CurrentVidQuality = vQuality;
                    downloader.DownloadVideo("https://www.youtube.com/watch/?v=" + NewDownloadInfo.VidID, DownloadType.CustomQuality, aQuality, vQuality);
                }
            }
            else
            {
                PlaylistStatus.Dispatcher.Invoke(new Action(() => PlaylistStatus.Content = "Status:"));
                MessageBox.Show("Completed playlist download", "Finished", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }