How I taught parents to download Turkish TV shows with one click

Good afternoon!
Many of us have parents who are not very friends with technology, and we have to be friends for them. My whole family is watching the series "The Magnificent Century ", the series of which are released once a week. It seems not so often, but on Saturday after Saturday, hearing “Go check if there is a series”, looking for distribution, launching a torrent and so on became tiring, and I decided to shift this onto the digital shoulders of the fourth .NetFramework.
What we need:
- Visual Studio 2010 or higher
- Console torrent client Aria2c .

Caution, in some places there is a Hindu code! I warned.

The task before me was this: the application starts, downloads the torrent and feeds it to the console torrent client, which downloads the series to a USB flash drive (the USB flash drive is inserted into the TV).

First we need to understand what series we want to download. The series is released in Turkey on Wednesdays, with our translation on Saturday-Sunday. The other day released 96 series. Now the calendar is 18 weeks. This means that you need to add 78 to the number of the current week if the program is launched on a weekday, and 79 if on the weekend.
It will look like this:
        DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
        DateTime date1 = DateTime.Now;
        Calendar cal = dfi.Calendar;
        var week = cal.GetWeekOfYear(date1, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
        var day = (int)cal.GetDayOfWeek(date1) == 0 ? 6 : (int)cal.GetDayOfWeek(date1) - 1; //В США недели начинаются с воскресения, поэтому метод GetDayOfWeek возвращает 0 для воскресения, расставим  дни в привычном порядке. GetWeekOfYear же возвращаем правильное значание, так как применена локаль
        var epnumber = week + 79 - ((day < 5) ? 1 : 0);


Now that we know the series number, we can go to the tracker.
First you need to log in, for this we create a POST request to the login.php page, and pass him a login-password pair.

byte[] buffer = Encoding.ASCII.GetBytes("login_username=ВАШ_ЛОГИН&login_password=ВАШ_ПАРОЛЬ&login=%C2%F5%EE%E4");
        HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create("http://login.rutracker.org/forum/login.php");//Строка для Post-запроса
        var cc = new CookieContainer();
        WebReq.CookieContainer = cc;//включаем куки
        WebReq.Method = "POST";
        WebReq.ContentType = "application/x-www-form-urlencoded";
        WebReq.ContentLength = buffer.Length;
        HttpWebResponse WebResp;
        try
        {
            Stream PostData = WebReq.GetRequestStream();
            PostData.Write(buffer, 0, buffer.Length);
            PostData.Close();
            WebResp = (HttpWebResponse)WebReq.GetResponse();
        }
        catch (Exception e)
        {
            MessageBox.Show("Ошибка сети", " ", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }

The server in response spat in us with an authorization cookie, which is stored in our cc. Now with this cookie you can make a request to search for a series:
        var url = @"http://rutracker.org/forum/tracker.php?nm=%D0%92%D0%B5%D0%BB%D0%B8%D0%BA%D0%BE%D0%BB%D0%B5%D0%BF%D0%BD%D1%8B%D0%B9%20%D0%B2%D0%B5%D0%BA%20sub%20"+epnumber;
 WebReq = (HttpWebRequest)WebRequest.Create(url);
        WebReq.CookieContainer = cc;
        WebReq.Method = "GET";
        WebReq.ContentType = "application/x-www-form-urlencoded";
        WebResp = (HttpWebResponse)WebReq.GetResponse();
        string result;
        Encoding responseEncoding = Encoding.GetEncoding(WebResp.CharacterSet);
        try
        {
            using (StreamReader sr = new StreamReader(WebResp.GetResponseStream(), responseEncoding))
            {
                result = sr.ReadToEnd();
            }
        }
        catch (Exception e)
        {
            MessageBox.Show("Ошибка сети", "Заголовок сообщения", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }


Parsing search page for links to torrent files of the form dl.rutracker.org/forum/dl.php?12345 :

 string pattern = @"http://dl.rutracker.org/forum/dl.php\?t=\d+";
        Regex regex = new Regex(pattern);
        Match match = regex.Match(result);
        if (match.Length == 0)
        {
            MessageBox.Show("Новая серия еще не вышла!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }
        else 
          AutoClosingMessageBox.Show("Новая серия вышла! Начинаем закачку.", "Caption", 3000);


The torrent file is found, save it to your hard drive:
 try
        {
            WebReq = (HttpWebRequest)WebRequest.Create(match.ToString());
            WebReq.CookieContainer = cc;
            WebReq.AllowAutoRedirect = false;
            WebReq.Method = "POST";
            WebReq.Referer = url;
            WebReq.ContentType = "application/x-www-form-urlencoded";
            /*Пишем его в файл*/
            Stream ReceiveStream = WebReq.GetResponse().GetResponseStream();
            string filename = @"C:\123.torrent";
            byte[] buffer1 = new byte[1024];
            FileStream outFile = new FileStream(filename, FileMode.Create);
            int bytesRead;
            while ((bytesRead = ReceiveStream.Read(buffer1, 0, buffer.Length)) != 0)
                outFile.Write(buffer1, 0, bytesRead);
            outFile.Close();
            ReceiveStream.Close();
        }
        catch (Exception e)
        {
            MessageBox.Show("Ошибка при скачке торрент-файла!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }


Now we check whether the unlucky relatives forgot to insert the USB flash drive, and if there is enough space on it:

string letter = "";
        foreach (DriveInfo i in System.IO.DriveInfo.GetDrives())
        {
            try
            {
                if (i.DriveType.ToString() == "Removable" && i.ToString() != "A:\\")
                {
                    if (i.TotalFreeSpace < 3000000000)
                    {
                        MessageBox.Show("На флешке мало место, нужно 3гб!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    letter = String.Copy(i.ToString());
                    break;
                }
                //Console.WriteLine(i.DriveType);
            }
            catch (Exception E)
            {
                return;
            }
        }
        if (letter == "")
        {
            MessageBox.Show("Вставь флешку!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }


Finally, everything is ready for the jump, you can start!

 string par = @"--seed-time=0 -d " + letter + " --select-file="+(epnumber-3)+ @" ""C:\123.torrent"" ";
//--seed-time=0 - выход сразу после загрузки, не сидируя. Нужно для сигнализации о завершения загрузки, да простят меня личи.
//-d - указывает в качестве папки загрузки найденную ранее свободную флешку
//--select-file - номер файла, нужного для скачки. В раздаче три серии пропущены, поэтому уменьшаем индекс на 3.
        Process P = Process.Start(@"C:\aria2-1.17.0-win-32bit-build1\aria2-1.17.0-win-32bit-build1\aria2c.exe", par);
        P.WaitForExit();
        int result1 = P.ExitCode;
        Console.WriteLine(result1);
        if (result1 == 0)
        {
            MessageBox.Show("Фильм скачан! Можно вытаскивать флешку!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else
        {
            MessageBox.Show("Неизвестная ошибка!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }


That's it, the series has been downloaded and is waiting to be watched.
The full text of the script is at http://pastebin.com/8L03vkJg .
Take care of your parents.

PS Yes, it is clear that in Per / PHP / Python / ... you can reduce the number of lines by several times. The code is written for the purpose of self-education.

Also popular now: