Click here to Skip to main content
15,886,067 members
Articles / Mobile Apps / Windows Phone 7

The Big Bang Transcripts Viewer

Rate me:
Please Sign up or sign in to vote.
4.95/5 (52 votes)
12 Jan 2012CPOL10 min read 167.9K   1.4K   60  
Learn how to download your favorite TV transcripts and format it in your Smartphone.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Xml.Linq;
using System.Xml;
using TBBT.Core;
using System.Windows;
using System.Net.NetworkInformation;

namespace WikiDev.Core
{
    public class WebHelper
    {
        static WebHelper instance = null;

        public WebHelper()
        {
        }

        public static WebHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new WebHelper();
                }
                return instance;
            }
        }

        private void DownloadString(string url, Action<string> onDownloadCompleted, Action onConnectionFailed, Action<int> onProgressChanged)
        {
            try
            {
                var webClient = new WebClient();
                webClient.DownloadStringCompleted += (sender, e) =>
                    {
                        try
                        {
                            onDownloadCompleted(e.Result);
                        }
                        catch (Exception exc)
                        {
                            //ShowUnexpectedError();
                            onConnectionFailed();
                        }
                    };
                webClient.DownloadProgressChanged += (sender, e) =>
                    {
                        onProgressChanged(e.ProgressPercentage);
                    };
                webClient.AllowReadStreamBuffering = true;
                webClient.DownloadStringAsync(new Uri(url), webClient);
            }
            catch (Exception exc)
            {
                //ShowUnexpectedError();
                onConnectionFailed();
            }
        }

        public void DownloadEpisodeList(Action<List<Episode>> onContentReady, Action onConnectionFailed, Action<int> onProgressChanged)
        {
            if (!InternetIsAvailable())
                onConnectionFailed();

            DownloadString("http://bigbangtrans.wordpress.com/",
                (content) =>
                {
                    var episodes = new List<Episode>();

                    var linkRegex = new Regex("<a[^>]+href\\s*=\\s*[\"\\'](?!(?:#|javascript\\s*:))([^\"\\']+)[^>]*>(.*?)<\\/a>");
                    MatchCollection matches = linkRegex.Matches(content);

                    var episodeId = 1;
                    for (var i = 0; i < matches.Count; i++)
                    {
                        var match = matches[i];
                        var linkValue = match.Groups[1].Value;
                        var nameValue = match.Groups[2].Value.Replace("&nbsp;", " ");

                        var nameRegex = new Regex("^Series ([0-9]) Episode ([0-9][0-9]) &#8211; (.*)");
                        if (nameRegex.IsMatch(nameValue))
                        {
                            var season = int.Parse(nameRegex.Matches(nameValue)[0].Groups[1].Value);
                            var number = int.Parse(nameRegex.Matches(nameValue)[0].Groups[2].Value);
                            var name = nameRegex.Matches(nameValue)[0].Groups[3].Value;
                            if (nameRegex.IsMatch(nameValue))
                            {
                                episodes.Add(new Episode()
                                {
                                    Id = episodeId,
                                    Number = number,
                                    Description = "",
                                    Link = linkValue,
                                    Name = name,
                                    Season = season,
                                    CreatedOn = DateTime.Now
                                });
                            }
                        }
                        episodeId++;
                    }

                    onContentReady(episodes);
                },
                () =>
                {
                    onConnectionFailed();
                },
                (percentage) => {
                    onProgressChanged(percentage);
                });
        }

        public void DownloadEpisodeTranscript(Episode episode, Action<EpisodeTranscript> onContentReady, Action onConnectionFailed, Action<int> onProgressChanged)
        {
            if (!InternetIsAvailable())
                onConnectionFailed();

            DownloadString(episode.Link,
                (content) =>
                {
                    var episodeTranscript = new EpisodeTranscript()
                    {

                        Number = episode.Number,
                        Description = episode.Description,
                        Link = episode.Link,
                        Name = episode.Name,
                        Season = episode.Season,
                    };

                    episodeTranscript.Quotes = new List<Quote>();

                    var linkRegex = new Regex("(<p>|<span style=\"font-size:small;font-family:Calibri;\">|<span style=\"font-family:Calibri;\">)(.*?)(<\\/p>|<\\/span>)");
                    MatchCollection matches = linkRegex.Matches(content);
                    
                    for (var i = 0; i < matches.Count; i++)
                    {
                        var match = matches[i];
                        var quoteValue = match.Groups[2].Value;

                        quoteValue = quoteValue.Replace("<span>", "");
                        quoteValue = quoteValue.Replace("</span>", "");
                        quoteValue = quoteValue.Replace("<em>", "");
                        quoteValue = quoteValue.Replace("</em>", "");
                        quoteValue = quoteValue.Replace("&#8230;", "...");
                        quoteValue = quoteValue.Replace("&#8217;", "'");
                        quoteValue = quoteValue.Replace("&amp;", "&");

                        var quoteRegex = new Regex("(.*):(.*)");
                        MatchCollection matches2 = quoteRegex.Matches(quoteValue);

                        var character = "";
                        var speech = "";

                        if (matches2.Count == 0)
                        {
                            speech = quoteValue;
                        }
                        else
                        {
                            var quoteMatch = matches2[0];
                            if (quoteMatch.Groups[1].Value.Contains("<img") ||
                                quoteMatch.Groups[1].Value.Contains("<a href"))
                                break;

                            character = (quoteMatch.Groups[1].Value + "(").Split('(')[0].Trim();
                            speech = quoteMatch.Groups[2].Value;
                        }

                        episodeTranscript.Quotes.Add(new Quote()
                        {
                            Id = episodeTranscript.Quotes.Count() + 1,
                            Season = episode.Season,
                            Number = episode.Number,
                            Image = string.Format(@"/Images/{0}.png", character),
                            Character = character,
                            Speech = speech,
                            CreatedOn = DateTime.Now
                        });
                    }

                    onContentReady(episodeTranscript);
                },
                () =>
                {
                    onConnectionFailed();
                },
                (percentage) =>
                {
                    onProgressChanged(percentage);
                });
        }

        public static bool InternetIsAvailable()
        {
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                MessageBox.Show(@"You currently have no network connection. You can still read the previously downloaded episodes!", "Cached Mode", MessageBoxButton.OK);
                return false;
            }
            return true;
        }

        private static void ShowUnexpectedError()
        {
            MessageBox.Show(@"We're sorry, but an unexpected connection error occurred. Please try again later.", "Oops!", MessageBoxButton.OK);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Instructor / Trainer Alura Cursos Online
Brazil Brazil

Comments and Discussions