Exemplo n.º 1
0
        public async Task IMDbFilmSearch(string movie)
        {
            var apikey  = _config["imdbkey"].ToString();
            var client  = new RestClient($"https://imdb-internet-movie-database-unofficial.p.rapidapi.com/film/{movie}");
            var request = new RestRequest(Method.GET);

            request.AddHeader("x-rapidapi-host", "imdb-internet-movie-database-unofficial.p.rapidapi.com");
            request.AddHeader("x-rapidapi-key", $"{apikey}");
            IRestResponse response = client.Execute(request);

            IMDb result = JsonConvert.DeserializeObject <IMDb>(response.Content);

            var builder = new EmbedBuilder() // add emojis to the embed
                          .WithTitle($"{result.title}")
                          .WithDescription($"{result.plot}.")
                          .WithImageUrl($"{result.poster}")
                          .AddField("Rating", $"{result.rating}.", true)
                          .AddField("Year", $"{result.year}.", true)
                          .AddField("Lenght", $"{result.length}.", true)
                          .AddField("IMDb ID", $"{result.id}", true)
                          .WithColor(235, 229, 52)
                          .WithFooter("From IMDb");

            var embed = builder.Build();
            await Context.Channel.SendMessageAsync(null, false, embed);

            EconomyHelper.DepositEconomy(Context.User.Id, Context.User.Discriminator, Context.User.Username, 20, _config["brobotapibaseurl"]);
        }
Exemplo n.º 2
0
    /// <summary>
    /// Get movie by title value
    /// </summary>
    /// <param name="title">IMDb Title value
    /// for Example: "tt1371111" or "1371111" in located in url "https://www.imdb.com/title/tt1371111/"</param>
    /// <returns>Return Movie Class in json data format</returns>
    public Movie GetDetailByTitle(string title)
    {
        int    titleNo = 0;
        string url     = string.Empty;

        if (title.ToLower().Replace("\\", "").Replace("/", "").Replace(" ", "").Contains("tt") &&
            title.ToLower().Replace("\\", "").Replace("/", "").Replace(" ", "").IndexOf("tt") == 0)
        {
            if (int.TryParse(title.ToLower().Replace("\\", "").Replace("/", "").Replace(" ", "").Substring(2), out titleNo))
            {
                url = string.Format("https://www.imdb.com/title/tt{0}", titleNo);
            }
        }
        else
        {
            if (int.TryParse(title.ToLower().Replace("\\", "").Replace("/", "").Replace(" ", ""), out titleNo))
            {
                url = string.Format("https://www.imdb.com/title/tt{0}", titleNo);
            }
        }

        if (!string.IsNullOrWhiteSpace(url))
        {
            IMDb imdb = new IMDb(url);
            return(imdb.ReadWebPage());
        }
        else
        {
            return(null);
        }
    }
Exemplo n.º 3
0
        private void IMDB_search(string movieName)
        {
            IMDb imdb = new IMDb(movieName);

            StringBuilder description = new StringBuilder();

            description.Append(imdb.Title + "\n");

            description.Append(imdb.Plot + "\n");


            description.Append(imdb.Storyline);

            textBoxDescription.Text = description.ToString();

            StringBuilder str = new StringBuilder();

            for (int i = 0; i < imdb.Genres.Count; ++i)
            {
                str.Append(imdb.Genres[i]);
                if (i != imdb.Genres.Count - 1)
                {
                    str.Append(", ");
                }
            }
            textBoxGenre.Text = str.ToString();
        }
Exemplo n.º 4
0
        private void SetupDownloadedSubtitleAndIMDbInfo(Uri uri, string resultSub, IMDb imdb, object param2)
        {
            OnlineSubtitleChoices.Clear();
            if (HasVideo == false)
            {
                return;
            }
            IMDb = imdb;

            if (param2 is List <SubtitleMatch> )
            {
                foreach (var st in (List <SubtitleMatch>)param2)
                {
                    OnlineSubtitleChoices.Add(st);
                }
                Main.ShowOsdMessage(string.Format("{0} subtitles found.", OnlineSubtitleChoices.Count));
            }
            FillSubs(uri);

            if (SubtitleStreams.Any(s => s.Path.ToLowerInvariant() == resultSub.ToLowerInvariant()) == false)
            {
                SubtitleStreams.Add(new SubtitleItem(SubtitleItem.SubtitleType.File, SubtitleItem.SubtitleSubType.Srt, resultSub, "Subtitle"));
            }

            var loadSub = (DownloadedSubtitle = SubtitleStreams.FirstOrDefault(s => s.Path.ToLowerInvariant() == resultSub.ToLowerInvariant()));

            ServiceLocator.GetService <IMainView>().DelayedInvoke(() => { SelectedSubtitle = loadSub; }, 200);
        }
Exemplo n.º 5
0
        private static void GetMovieInfoImdbScrapping()
        {
            Console.Write("Movie Title: ");
            var movTitle = Console.ReadLine();

            var mov = new IMDb(movTitle, false);

            Console.WriteLine(mov.ImdbURL);
            Console.WriteLine("\nPress Enter...");
            Console.ReadLine();
        }
Exemplo n.º 6
0
    /// <summary>
    /// Get thumbnail data in Base64 data format
    /// </summary>
    /// <param name="url">full Url path
    /// for Example: "https://www.imdb.com/title/tt1371111/"</param>
    /// <returns>Base64 data in json data format</returns>
    public string GetBase64ThumbnailData(string url)
    {
        IMDb   imdb      = new IMDb(url);
        string posterUrl = imdb.GetMoviePosterThumbnailUrl(url);

        if (!string.IsNullOrWhiteSpace(posterUrl))
        {
            return(imdb.GetBase64Data(posterUrl));
        }

        return(null);
    }
Exemplo n.º 7
0
        private void Extensions_OnSettingsChanged(string guid)
        {
            // settings change occured
            if (guid == PluginSettings.cGuid)
            {
                Logger.Info("Settings updated externally");

                // re-load settings
                PluginSettings.LoadSettings();
                
                // Update Timer settings
                IMDb.UpdateTimer();
            }
        }
Exemplo n.º 8
0
    void connection(String a)
    {
        DataSet   ds = new DataSet();
        DataTable dt = new DataTable();

        using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]))
        {
            connection.Open();
            String            chart_select = "SELECT title FROM movie WHERE id = " + a;
            NpgsqlDataAdapter da           = new NpgsqlDataAdapter(chart_select, connection);
            connection.Close();

            IMDb   imdb  = new IMDb("The Godfather", true);
            String tittl = imdb.Id;
            Label1.Text = Label1.Text + imdb.Title;
        }
    }
        /// <summary>
        /// Gets the cover for the specified show from IMDb.
        /// </summary>
        /// <param name="show">The show to get the cover for.</param>
        /// <returns>
        /// URL to the image on IMDb's server.
        /// </returns>
        public static string GetCoverFromIMDb(string show)
        {
            Log.Debug("Getting cover for " + show + " from IMDb...");

            var imdb = new IMDb();
            var res  = imdb.GetID(show).ToList();

            if (res.Count != 0 && !string.IsNullOrWhiteSpace(res[0].Cover) && !res[0].Cover.EndsWith("/tv_series.gif"))
            {
                return(Regex.Replace(res[0].Cover, @"@@.+\.", "@@."));
            }
            else
            {
                Log.Debug("No shows or covers were found on IMDb matching " + show + ".");
            }

            return(null);
        }
Exemplo n.º 10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String url  = "http://www.omdbapi.com/?s=batman";
            string json = new WebClient().DownloadString(url);

            Debug.WriteLine("JASOOOON: \n" + json.ToString());

            XmlDocument doc = JsonConvert.DeserializeXmlNode(json, "root");

            Debug.WriteLine("\nXMLLLLLLLL: \n" + doc.InnerXml.ToString());

            IMDb imdb = new IMDb("tt0361862", true);

            Debug.WriteLine("TITLE: " + imdb.Poster.ToString());

            string id = imdb.Id.ToString();

            string url2 = "http://lab.abhinayrathore.com/imdb/imdbWebService.php?m=" +
                          id + "&o=xml";
        }
Exemplo n.º 11
0
        public Movie GetMovie(string localFileName, string matchingMovieName)
        {
            var mm = movies.Movie.Where(m => m.LocalName.ToLower() == matchingMovieName.ToLower()).FirstOrDefault();

            if (mm == null)
            {
                mm = new Movie();
                IMDb imdb = GetImdbMovie(matchingMovieName);
                if (imdb != null && imdb.Id != null)
                {
                    mm.Name          = HttpUtility.HtmlDecode(string.IsNullOrWhiteSpace(imdb.OriginalTitle) ? imdb.Title : imdb.OriginalTitle);
                    mm.LocalName     = matchingMovieName;
                    mm.FullLocalPath = localFileName;
                    mm.Rating        = imdb.Rating;
                    //mm.Genre = imdb.Genres.Count > 0 ? string.Format("{0}, {1}", imdb.Genres[0], imdb.Genres[1])  : string.Empty;
                    mm.Genre = imdb.Genres.Count > 0 ? (string.Format("{0}", imdb.Genres.Count > 1 ?
                                                                      string.Format("{0}, {1}", imdb.Genres[0], imdb.Genres[1]) : imdb.Genres[0])) : string.Empty;
                    mm.ImageThumbnail      = imdb.Poster;
                    mm.Id                  = imdb.Id;
                    mm.LocalImageThumbnail = LoadImage(mm);
                    //mm.Year = imdb.Year;
                    //mm.Duration = string.IsNullOrEmpty(imdb.Runtime) ? 0 : int.Parse(imdb.Runtime);
                    //if (mm.Id != imdb.Id)
                    //    mm.LocalImageThumbnail = null;
                    //mm.Id = imdb.Id;
                }
                else
                {
                    mm.Name          = matchingMovieName;
                    mm.FullLocalPath = localFileName;
                    mm.LocalName     = matchingMovieName;
                }
                //mm.ShortName = mm.Name.Length <= 13 ? mm.Name : $"{mm.Name.Substring(0, 10)}...";
                movies.Movie.Add(mm);
            }
            mm.ShortName = mm.Name.Length <= 22 ? mm.Name : $"{mm.Name.Substring(0, 19)}...";
            return(mm);
        }
Exemplo n.º 12
0
        private IMDb GetImdbMovie(string matchingMovieName)
        {
            IMDb imdb = null;

            for (int i = 0; i < 3; i++)
            {
                try
                {
                    sw.Restart();
                    imdb = new IMDb(matchingMovieName);
                    imdb.ParseIMDbPage();
                    sw.Stop();
                    break;
                }
                catch (WebException ex)
                {
                    using (var sw = new StreamWriter(new FileStream("ErrorLog.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
                    {
                        sw.WriteLineAsync(string.Format("Error while getting imdb data for file: {0}. {1}", matchingMovieName, ex.Message));
                    }
                }
            }
            return(imdb);
        }
Exemplo n.º 13
0
        public static IMDb GetMovieMetadata(string strFileName, out string strTitle, out string strTitleAndYear, out string strYear, out int season, out int episode, out Subtitle bestSubtitleGuess, bool bCleanChars = true, bool tryHash = false)
        {
            season            = 0;
            episode           = 0;
            strTitle          = "";
            strYear           = "";
            bestSubtitleGuess = null;

            string sep1 = FindSeasonAndEpisode(strFileName);

            if (sep1 != "")
            {
                var sep = sep1.ToLowerInvariant().Split('s', 'e');
                if (sep.Length == 3)
                {
                    season  = int.Parse(sep[1]);
                    episode = int.Parse(sep[2]);
                }
            }

            string originalFilename = strFileName;

            if (strFileName.ToLowerInvariant().Contains(Path.GetDirectoryName(strFileName).ToLowerInvariant()))
            {
                strFileName = Path.GetFileNameWithoutExtension(strFileName);
            }

            const string videoCleanDateTimeRegExp = "(.*[^ _\\,\\.\\(\\)\\[\\]\\-])[ _\\.\\(\\)\\[\\]\\-]+(19[0-9][0-9]|20[0-1][0-9])([ _\\,\\.\\(\\)\\[\\]\\-]|[^0-9]$)";

            var videoCleanStringRegExps = new List <string>();

            videoCleanStringRegExps.Add("[ _\\,\\.\\(\\)\\[\\]\\-](ac3|dts|custom|dc|remastered|divx|divx5|dsr|dsrip|dutch|dvd|dvd5|dvd9|dvdrip|dvdscr|dvdscreener|screener|dvdivx|cam|fragment|fs|hdtv|hdrip|hdtvrip|internal|limited|multisubs|ntsc|ogg|ogm|pal|pdtv|proper|repack|rerip|retail|r3|r5|bd5|se|svcd|swedish|german|read.nfo|nfofix|unrated|extended|ws|telesync|ts|telecine|tc|brrip|bdrip|480p|480i|576p|576i|720p|720i|1080p|1080i|3d|hrhd|hrhdtv|hddvd|bluray|x264|h264|xvid|xvidvd|xxx|www.www|cd[1-9]|\\[.*\\])([ _\\,\\.\\(\\)\\[\\]\\-]|$)");
            videoCleanStringRegExps.Add("(\\[.*\\])");
            videoCleanStringRegExps.Add("(-.*$)");

            string stringPrefixClean = ("^(ac3|dts|remastered|divx|divx5|dsr|dsrip|dvd|dvd5|dvd9|dvdrip|dvdscr|dvdscreener|screener|dvdivx|hdtv|hdrip|hdtvrip|internal|limited|multisubs|ntsc|ogg|ogm|pal|pdtv|repack|rerip|retail|r3|r5|bd5|se|svcd|read.nfo|nfofix|unrated|ws|telesync|ts|telecine|tc|brrip|bdrip|480p|480i|576p|576i|720p|720i|1080p|1080i|3d|hrhd|hrhdtv|hddvd|bluray|x264|h264|xvid|xvidvd|www.www|cd[1-9]|\\[.*\\])");

            strTitleAndYear = strFileName;

            if (string.IsNullOrEmpty(strFileName) || strFileName.Equals(".."))
            {
                return(null);
            }

            Regex reYear = new Regex(videoCleanDateTimeRegExp, RegexOptions.IgnoreCase);

            if (reYear.IsMatch(strTitleAndYear))
            {
                var m = reYear.Matches(strTitleAndYear);
                strTitleAndYear = m[0].Groups[1].Value;
                strYear         = m[0].Groups[2].Value;
            }

            Regex episodeRegex = new Regex(@"(?<seasonandepisode>S(?<season>\d{1,2})E(?<episode>\d{1,2}))", RegexOptions.IgnoreCase);

            if (episodeRegex.IsMatch(strTitleAndYear))
            {
                strTitleAndYear = strTitleAndYear.Substring(0, episodeRegex.Match(strTitleAndYear).Index);
            }

            for (int i = 0; i < videoCleanStringRegExps.Count; i++)
            {
                Regex reTags = new Regex(videoCleanStringRegExps[i], RegexOptions.IgnoreCase);
                while (reTags.Matches(strTitleAndYear).Count > 0)
                {
                    int start = reTags.Matches(strTitleAndYear)[0].Index;
                    int end   = start + reTags.Matches(strTitleAndYear)[0].Length;
                    strTitleAndYear = strTitleAndYear.Substring(0, start) +
                                      strTitleAndYear.Substring(end - 1, strTitleAndYear.Length - end);
                }
            }

            Regex rePrefix = new Regex(stringPrefixClean, RegexOptions.IgnoreCase);

            while (rePrefix.Matches(strTitleAndYear).Count > 0)
            {
                int start = rePrefix.Matches(strTitleAndYear)[0].Index;
                int end   = start + rePrefix.Matches(strTitleAndYear)[0].Length;
                strTitleAndYear = end + 1 > strTitleAndYear.Length ? "" : strTitleAndYear.Substring(0, start) +
                                  strTitleAndYear.Substring(end + 1, strTitleAndYear.Length - end - 1);
            }

            if (bCleanChars)
            {
                bool initialDots          = true;
                bool alreadyContainsSpace = (strTitleAndYear.Contains(' '));

                for (int i = 0; i < strTitleAndYear.Length; i++)
                {
                    char c = strTitleAndYear[i];

                    if (c != '.')
                    {
                        initialDots = false;
                    }

                    if ((c == '_') || ((!alreadyContainsSpace) && !initialDots && (c == '.')))
                    {
                        var chars = strTitleAndYear.ToCharArray();
                        chars[i]        = ' ';
                        strTitleAndYear = new string(chars);
                    }
                }
            }

            strTitleAndYear = strTitleAndYear.Trim();
            strTitle        = strTitleAndYear;

            if (!string.IsNullOrEmpty(strYear))
            {
                strTitleAndYear = strTitle + " (" + strYear + ")";
            }


            if (tryHash && File.Exists(originalFilename))
            {
                var langs = ServiceLocator.GetService <ISettings>().SubtitleLanguagesCodes.ToArray();
                var ret   = HashMatcher.HashMatcher.Match(originalFilename, langs);
                if (ret.Any(r => !string.IsNullOrEmpty(r.ImdbCode)))
                {
                    try
                    {
                        var bestGuess = ret.GroupBy(g => g.ImdbCode).OrderByDescending(g => g.Count()).First().OrderBy(s => Levenshtein.Compare(Path.GetFileNameWithoutExtension(strFileName), Path.GetFileNameWithoutExtension(s.FileName))).First();

                        string sep2 = FindSeasonAndEpisode(bestGuess.FileName);
                        int    tmpSeason = 0; int tmpEpisode = 0;
                        if (sep2 != "")
                        {
                            var sepx = sep1.ToLowerInvariant().Split('s', 'e');
                            if (sepx.Length == 3)
                            {
                                tmpSeason  = int.Parse(sepx[1]);
                                tmpEpisode = int.Parse(sepx[2]);
                            }
                        }


                        var imdb = new IMDb(Convert.ToInt32(bestGuess.ImdbCode));

                        int imdbYear;
                        if (int.TryParse(imdb.Year, out imdbYear))
                        {
                            int fileYear;
                            if (int.TryParse(strYear, out fileYear))
                            {
                                if (imdbYear != fileYear)
                                {
                                    bestSubtitleGuess = null;
                                    return(null);
                                }
                            }
                        }

                        if (imdb.IsSeries == false && tmpSeason > 0)
                        {
                            imdb.SeriesSeason  = tmpSeason;
                            imdb.SeriesEpisode = tmpEpisode;
                            imdb.IsSeries      = true;
                        }

                        if (imdb.status && (season == 0 || (imdb.SeriesSeason == season && imdb.SeriesEpisode == episode)))
                        {
                            strTitle        = imdb.Title;
                            strTitleAndYear = imdb.Title + " (" + imdb.Year + ")";
                            strYear         = imdb.Year;
                            season          = 0;
                            episode         = 0;
                            if (imdb.IsSeries)
                            {
                                season  = imdb.SeriesSeason;
                                episode = imdb.SeriesEpisode;
                            }

                            var ordered = ret.Where(s => s.ImdbCode == bestGuess.ImdbCode).OrderBy(s => langs.ToList().IndexOf(s.LanguageCode)).ThenBy(s => Levenshtein.Compare(Path.GetFileNameWithoutExtension(strFileName), Path.GetFileNameWithoutExtension(s.FileName))).First();
                            bestSubtitleGuess = new Subtitle(ordered.Id, ordered.ProgramName, ordered.FileName, ordered.LanguageCode);
                            return(imdb);
                        }
                    }
                    catch { }
                }
            }

            return(null);
        }
Exemplo n.º 14
0
        public static string DownloadSubtitle(string fileName, string[] preferredLanguages, string[] preferredServices, out IMDb imdbMatch, out List <SubtitleMatch> otherChoices, Action <string> messageCallback)
        {
            var fn = Path.GetFileName(fileName);

            otherChoices = new List <SubtitleMatch>();
            List <SubtitleMatch> dummyChoices;

            SubtitleMatch subtitle = null;

            if (ServiceLocator.GetService <ISettings>().PreferenceToHashMatchedSubtitle)
            {
                subtitle = FindSubtitleForFilename(fileName, Path.GetDirectoryName(fileName), preferredLanguages, preferredServices, out imdbMatch, out dummyChoices, messageCallback, false, true, true);

                if (subtitle != null)
                {
                    return(DownloadSubtitle(subtitle, fileName));
                }
            }

            subtitle = FindSubtitleForFilename(fn, Path.GetDirectoryName(fileName), preferredLanguages, preferredServices, out imdbMatch, out dummyChoices, messageCallback, false, true, false);

            if (subtitle != null)
            {
                return(DownloadSubtitle(subtitle, fileName));
            }

            return(null);
        }
Exemplo n.º 15
0
        public static SubtitleMatch FindSubtitleForFilename(string filename, string folderName, string[] preferredLanguages, string[] preferredServices, out IMDb imdbMatch, out List <SubtitleMatch> otherChoices, Action <string> messageCallback, bool noFiltering = false, bool needsImdb = true, bool allowBestGuess = false)
        {
            int    season, episode;
            string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()) + @"\.\_";
            string strTitle, strYear, strTitleAndYear;

            Subtitle bestGuessSubtitle = null;

            imdbMatch = GetIMDbFromFilename(filename, folderName, out strTitle, out strTitleAndYear, out strYear, out season, out episode, messageCallback, out bestGuessSubtitle);

            if (bestGuessSubtitle != null && allowBestGuess)
            {
                otherChoices = null;
                return(new SubtitleMatch
                {
                    Subtitle = bestGuessSubtitle,
                    Language = bestGuessSubtitle.LanguageCode,
                    MatchedBy = "Hasher",
                    MatchRelease = "",
                    Releases = new string [] {},
                    Score = 1,
                    Service = "OpenSubtitles"
                });
            }

            filename = Path.GetFileName(filename);
            Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));

            filename = r.Replace(filename, " ");

            filename = Path.GetFileName(filename);
            string sep1 = "";

            if (season != 0)
            {
                sep1 = string.Format("s{0:00}e{1:00}", season, episode);
            }

            if (sep1 != "")
            {
                needsImdb = false;
            }

            if (imdbMatch == null && needsImdb)
            {
                imdbMatch    = null;
                otherChoices = null;
                return(null);
            }

            string[] patterns = new string[imdbMatch == null ? 1 : string.IsNullOrEmpty(imdbMatch.OriginalTitle) || string.IsNullOrEmpty(imdbMatch.Title) ? 2 : 3];
            patterns[0] = filename;
            if (patterns.Length > 1)
            {
                patterns[1] = imdbMatch.Title.TrimStart('\\', '\"').TrimEnd('\\', '\"');
            }
            if (patterns.Length > 2)
            {
                patterns[2] = imdbMatch.OriginalTitle.TrimStart('\\', '\"').TrimEnd('\\', '\"');
            }
            if (imdbMatch != null)
            {
                for (int i = 1; i < patterns.Length; i++)
                {
                    patterns[i] += string.Format(" ({0})", imdbMatch.Year);
                }
            }

            Array.Reverse(patterns); // we like imdb first sicne we might skip searching further on some matches

            var ret = GetOrderedSubsMatches(preferredServices, preferredLanguages, patterns, messageCallback, noFiltering);

            var    settings = ServiceLocator.GetService <ISettings>();
            double minScore = settings != null ? settings.SubtitleMinScore : 0.55;

            ret.RemoveAll(m => m.Score <= minScore); // crap

            if (!needsImdb && imdbMatch == null)
            {
                ret.RemoveAll(m => WordMatches(m.MatchRelease, patterns[0]) <= 0.2 || (sep1 != "" && FindSeasonAndEpisode(m.MatchRelease) != sep1)); // even more crap if no imdb match
            }

            otherChoices = ret;

            var ret2 = ret.Select(s => new { priority = preferredLanguages.ToList().IndexOf(s.Language), Sub = s }).OrderByDescending(s => preferredLanguages.Length - s.priority).FirstOrDefault();

            return(ret2 == null ? null : ret2.Sub);
        }
Exemplo n.º 16
0
        public static IMDb GetIMDbFromFilename(string filename, string folderName, out string strTitle, out string strTitleAndYear, out string strYear, out int season, out int episode, Action <string> messageCallback, out Subtitle bestGuessSubtitle)
        {
            if (messageCallback != null)
            {
                messageCallback("Matching media with IMDb ...");
            }

            bestGuessSubtitle = null;

            // extract meaningful data from the filename
            var imd = GetMovieMetadata(
                filename,
                out strTitle,
                out strTitleAndYear,
                out strYear,
                out season,
                out episode, out bestGuessSubtitle, true, true);

            if (imd != null)
            {
                return(imd);
            }

            if (strTitle != "" && strYear == "")
            {
                int tmpSeason, tmpEpisode;
                // no year, maybe we find one in the folder
                string tmpTitle;
                string tmpTitleAndYear;
                GetMovieMetadata(Path.GetDirectoryName(filename) + ".dummyextension",
                                 out tmpTitle,
                                 out tmpTitleAndYear,
                                 out strYear,
                                 out tmpSeason,
                                 out tmpEpisode, out bestGuessSubtitle, true, false);

                if (tmpSeason != 0)
                {
                    // found season and episode in folder
                    season  = tmpSeason;
                    episode = tmpEpisode;
                }

                if (strYear != "")
                {
                    strTitleAndYear = string.Format("{0} ({1})", strTitle, strYear);
                }
            }

            // cleanup multiple spaces
            strTitle = new Regex(@"\s+").Replace(strTitle, " ");

            IMDb imdb = null;

            if (!string.IsNullOrEmpty(strTitle))
            {
                // scrape imdb to find movie metadata
                if (season != 0)
                {
                    imdb = new IMDb(strTitle, season, episode, strYear, false);
                }
                else
                {
                    imdb = new IMDb(strTitle, strYear, false);
                }
            }

            if (imdb == null || imdb.status == false)
            {
                // if failed try with folder name
                GetMovieMetadata(
                    folderName + ".dummyextension",
                    out strTitle,
                    out strTitleAndYear,
                    out strYear,
                    out season,
                    out episode, out bestGuessSubtitle, true, false);

                // cleanup multiple spaces
                strTitle = new Regex(@"\s+").Replace(strTitle, " ");

                imdb = new IMDb(strTitle, strYear, false);
            }

            if (imdb == null || imdb.status == false)
            {
                // we need imdb match to do something
                return(null);
            }

            char[] punctuation = new char[] { ',', '.', '-', ':', '"', ';', '\'', '(', ')', '[', ']' };
            string imdbTitle   = new string(imdb.DisplayTitle.TrimEnd('.', ',', ' ').ToLowerInvariant().Replace(punctuation, ' ').ToArray());

            imdbTitle = new Regex(@"\s+").Replace(imdbTitle, " ");

            string fileTitle = new string(strTitle.Trim('.', ',', ' ').ToLowerInvariant().Replace(punctuation, ' ').ToArray());

            fileTitle = new Regex(@"\s+").Replace(fileTitle, " ");

            string imdbOrigTitle = new string(imdb.DisplaySubTitle.TrimEnd('.', ',', ' ').Replace(punctuation, ' ').ToArray());

            imdbOrigTitle = new Regex(@"\s+").Replace(imdbOrigTitle, " ");

            if (WordMatches(fileTitle, imdbOrigTitle) >= 0.3 || WordMatches(fileTitle, imdbTitle) >= 0.3)
            {
                return(imdb);
            }
            else
            {
                if ((double)Levenshtein.Compare(fileTitle, imdbTitle) / Math.Max(fileTitle.Length, imdbTitle.Length) < 0.20)
                {
                    return(imdb);
                }
                return(null);
            }
        }
Exemplo n.º 17
0
    void connection(String a)
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]))
        {

            connection.Open();
            String chart_select = "SELECT title FROM movie WHERE id = " + a;
            NpgsqlDataAdapter da = new NpgsqlDataAdapter(chart_select, connection);
            connection.Close();

            IMDb imdb = new IMDb("The Godfather", true);
            String tittl = imdb.Id;
            Label1.Text = Label1.Text + imdb.Title;
        }
    }
Exemplo n.º 18
0
    /// <summary>
    /// Get poster url from requested IMDb title url
    /// </summary>
    /// <param name="url">full Url path
    /// for Example: "https://www.imdb.com/title/tt1371111/"</param>
    /// <returns>returns full photo url in json data format</returns>
    public string GetPosterUrl(string url)
    {
        IMDb imdb = new IMDb(url);

        return(imdb.GetMoviePosterUrl(url));
    }
Exemplo n.º 19
0
    /// <summary>
    /// Gets movie data by entering full imdb url
    /// </summary>
    /// <param name="url">full Url path
    /// for Example: "https://www.imdb.com/title/tt1371111/"</param>
    /// <returns>Return Movie Class in json data format</returns>
    public Movie GetDetailByUrl(string url)
    {
        IMDb imdb = new IMDb(url);

        return(imdb.ReadWebPage());
    }
Exemplo n.º 20
0
        /// <summary>
        /// Gets the cover for the specified show from IMDb.
        /// </summary>
        /// <param name="show">The show to get the cover for.</param>
        /// <returns>
        /// URL to the image on IMDb's server.
        /// </returns>
        public static string GetCoverFromIMDb(string show)
        {
            var imdb = new IMDb();
            var res  = imdb.GetID(show).ToList();

            if (res.Count != 0 && !string.IsNullOrWhiteSpace(res[0].Cover) && !res[0].Cover.EndsWith("/tv_series.gif"))
            {
                return Regex.Replace(res[0].Cover, @"@@.+\.", "@@.");
            }

            return null;
        }
Exemplo n.º 21
0
    /// <summary>
    /// Get thumbnail url from requested IMDb title url
    /// </summary>
    /// <param name="url">full Url path
    /// for Example: "https://www.imdb.com/title/tt1371111/"</param>
    /// <returns>returns full photo url in json data format</returns>
    public string GetThumbnailUrl(string url)
    {
        IMDb imdb = new IMDb(url);

        return(imdb.GetMoviePosterThumbnailUrl(url));
    }
        /// <summary>
        /// Handles the Click event of the searchButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void SearchButtonOnClick(object sender, RoutedEventArgs e)
        {
            if (!_loaded || _sidx == database.SelectedIndex)
            {
                return;
            }

            database.IsEnabled = language.IsEnabled = searchButton.IsEnabled = saveButton.IsEnabled = cancelButton.IsEnabled = nameTextBox.IsEnabled = false;

            Guide guide;

            switch (database.SelectedIndex)
            {
            case 1:
                guide = new TVRage();
                break;

            case 2:
                guide = new TVDB();
                break;

            case 3:
                guide = new TMDb();
                break;

            case 4:
                guide = new Freebase();
                break;

            case 5:
                guide = new TVcom();
                break;

            case 6:
                guide = new EPisodeWorld();
                break;

            case 7:
                guide = new IMDb();
                break;

            case 8:
                guide = new AniDB();
                break;

            case 9:
                guide = new AnimeNewsNetwork();
                break;

            case 11:
                guide = new EPGuides();
                break;

            case 12:
                guide = new EPGuides();
                break;

            default:
                database.IsEnabled = language.IsEnabled = searchButton.IsEnabled = saveButton.IsEnabled = cancelButton.IsEnabled = nameTextBox.IsEnabled = true;
                return;
            }

            new ShowGuideTaskDialog().Search(guide, nameTextBox.Text, (language.SelectedItem as StackPanel).Tag as string, (id, title, lang) =>
            {
                if (id == null)
                {
                    Dispatcher.Invoke((Action)(() =>
                    {
                        switch (Database.TVShows[_id].Source)
                        {
                        case "TVRage":
                            database.SelectedIndex = 1;
                            break;

                        case "TVDB":
                            database.SelectedIndex = 2;
                            break;

                        case "TMDb":
                            database.SelectedIndex = 3;
                            break;

                        case "Freebase":
                            database.SelectedIndex = 4;
                            break;

                        case "TVcom":
                            database.SelectedIndex = 5;
                            break;

                        case "EPisodeWorld":
                            database.SelectedIndex = 6;
                            break;

                        case "IMDb":
                            database.SelectedIndex = 7;
                            break;

                        case "AniDB":
                            database.SelectedIndex = 8;
                            break;

                        case "AnimeNewsNetwork":
                            database.SelectedIndex = 9;
                            break;

                        case "EPGuides":
                            database.SelectedIndex = 12;
                            break;
                        }

                        database.IsEnabled = language.IsEnabled = searchButton.IsEnabled = saveButton.IsEnabled = cancelButton.IsEnabled = nameTextBox.IsEnabled = true;
                    }));

                    TaskDialog.Show(new TaskDialogOptions
                    {
                        MainIcon        = VistaTaskDialogIcon.Error,
                        Title           = "Not found",
                        MainInstruction = _show,
                        Content         = "The currently set show title was not found on the selected guide.\r\nYour selection will be reverted. Try editing the official title.",
                        CustomButtons   = new[] { "OK" }
                    });
                }
                else
                {
                    _newSource = guide.GetType().Name;
                    _newSID    = id;
                    _newLang   = lang;

                    _change = _upReq = true;

                    Dispatcher.Invoke((Action)(() =>
                    {
                        nameTextBox.Text = title;
                        _sidx = database.SelectedIndex;

                        database.IsEnabled = language.IsEnabled = saveButton.IsEnabled = cancelButton.IsEnabled = nameTextBox.IsEnabled = true;
                    }));

                    TaskDialog.Show(new TaskDialogOptions
                    {
                        MainIcon        = VistaTaskDialogIcon.Information,
                        Title           = "Modified",
                        MainInstruction = _show,
                        Content         = "The guide was successfully changed!\r\nAn update will be initiated to this TV show after you click Save.",
                        CustomButtons   = new[] { "OK" }
                    });
                }
            });
        }
Exemplo n.º 23
0
        private void DownloadSubtitleForUriAndQueryIMDB(Uri uri)
        {
            // try online
            BackgroundWorker b = new BackgroundWorker();

            _subtitleIsDownloading     = true;
            IsSubtitleSearchInProgress = true;
            b.DoWork += (sender, args) =>
            {
                DateTime start = DateTime.Now;

                Monitor.Enter(_subtitleSearchLocker);

                IMDb imdb;
                List <SubtitleMatch> otherChoices;
                try
                {
                    string s = SubtitleUtil.DownloadSubtitle(uri.LocalPath, Main.SubtitleLanguages.Select(l => l.Id).ToArray(),
                                                             Main.SubtitleServices.Select(l => l.Id).ToArray(), out imdb, out otherChoices, MessageCallback);
                    if (!string.IsNullOrEmpty(s) && imdb.status)
                    {
                        args.Result = new object[] { s, imdb, otherChoices };
                    }
                    else
                    {
                        args.Result = imdb;
                    }
                }
                catch (WebException)
                {
                    Main.ShowOsdMessage("Internet connection unavailable.");
                    args.Result = null;
                }
                finally
                {
                    Monitor.Exit(_subtitleSearchLocker);
                    if (DateTime.Now - start > TimeSpan.FromSeconds(15))
                    {
                        args.Cancel = true;
                    }
                }
            };
            b.RunWorkerCompleted += (sender, args) =>
            {
                try
                {
                    if (args.Cancelled || args.Error != null || HasVideo == false)
                    {
                        return;
                    }
                    var result = (object)null;
                    try
                    {
                        result = args.Result;
                    }
                    catch { /* bad request etc */ }

                    if (result != null)
                    {
                        if (result is IMDb)
                        {
                            // we got no subtitle but have IMDb
                            IMDb = result as IMDb;
                        }
                        else
                        {
                            // both subtitle and IMDB
                            string resultSub = (string)((object[])result)[0];
                            IMDb   imdb      = (IMDb)((object[])result)[1];
                            var    param2    = ((object[])result)[2];
                            SetupDownloadedSubtitleAndIMDbInfo(uri, resultSub, imdb, param2);
                        }
                    }
                    else
                    {
                        // we got nothing
                        IMDb = null;
                    }
                }
                finally
                {
                    IsSubtitleSearchInProgress = false;
                    _subtitleIsDownloading     = false;
                }
            };
            b.RunWorkerAsync();
        }
Exemplo n.º 24
0
        internal async Task RunAsync(Configuration configuration, int shardId, int shardCount, string dbPath)
        {
            LogLevel level;

            switch (configuration.LogLevel.ToLower())
            {
            case "debug":
                level = LogLevel.Debug;
                break;

            case "warning":
                level = LogLevel.Warning;
                break;

            case "error":
                level = LogLevel.Error;
                break;

            case "critical":
                level = LogLevel.Critical;
                break;

            default:
                level = LogLevel.Info;
                break;
            }

            client = new DiscordClient(new DiscordConfiguration
            {
                AutoReconnect         = true,
                LogLevel              = level,
                Token                 = configuration.Token,
                TokenType             = TokenType.Bot,
                ShardCount            = shardCount,
                ShardId               = shardId,
                UseInternalLogHandler = true
            });

            Events.supportGuildId = configuration.SupportId;

            client.Ready          += Events.OnClientReady;
            client.Resumed        += Events.OnClientResumed;
            client.ClientErrored  += Events.OnClientError;
            client.SocketErrored  += Events.OnClientSocketError;
            client.GuildAvailable += Events.OnGuildJoin;
            client.GuildCreated   += Events.OnGuildJoin;
            client.GuildDeleted   += Events.OnGuildLeave;

            client.MessageCreated += AFK.AFKMessageHandler;

            client.MessageReactionAdded        += Starboard.ReactionAddHandler;
            client.MessageReactionRemoved      += Starboard.ReactionRemoveHandler;
            client.MessageReactionRemovedEmoji += Starboard.ReactionRemoveEmojiHandler;
            client.MessageReactionsCleared     += Starboard.ReactionRemoveAllHandler;

            commands = client.UseCommandsNext(new CommandsNextConfiguration
            {
                CaseSensitive        = true,
                EnableDefaultHelp    = true,
                EnableDms            = true,
                EnableMentionPrefix  = true,
                IgnoreExtraArguments = true,
                StringPrefixes       = configuration.Prefixes,
            });

            commands.SetHelpFormatter <Help>();

            commands.CommandExecuted += Events.OnCommandExecute;
            commands.CommandErrored  += Events.OnCommandError;

            commands.RegisterCommands <Fun>();
            commands.RegisterCommands <Info>();
            commands.RegisterCommands <Moderation>();
            commands.RegisterCommands <NSFW>();
            commands.RegisterCommands <Owner>();
            commands.RegisterCommands <Search>();
            //commands.RegisterCommands<Settings>();

            client.UseInteractivity(new InteractivityConfiguration
            {
                PaginationBehaviour = PaginationBehaviour.Ignore,
                PaginationDeletion  = PaginationDeletion.DeleteEmojis,
                PollBehaviour       = PollBehaviour.DeleteEmojis
            });

            IMDb.InitializeWithKey(configuration.OMDb);
            Managers.Google.InitializeService(configuration.Google.Key, configuration.Google.Cx);

            await Spotify.AuthorizeAsync(configuration.Spotify.ID, configuration.Spotify.Secret, client.DebugLogger);

            await Database.ConnectAsync(dbPath, client.DebugLogger);

            garbage = new GarbageCollection();

            AppDomain.CurrentDomain.ProcessExit += new EventHandler((s, e) => HandleProcessQuit().GetAwaiter().GetResult());

            Emojis.Initialize(configuration.Emojis.Success,
                              configuration.Emojis.Warning,
                              configuration.Emojis.Error,
                              configuration.Emojis.Online,
                              configuration.Emojis.Idle,
                              configuration.Emojis.DoNotDisturb,
                              configuration.Emojis.Offline);

            await client.ConnectAsync(new DiscordActivity(configuration.Status.Name, configuration.Status.Type));

            await Task.Delay(-1);
        }
        /// <summary>
        /// Handles the OnSelectionChanged event of the database control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void DatabaseOnSelectionChanged(object sender, RoutedEventArgs e)
        {
            if (!_loaded || _sidx == database.SelectedIndex)
            {
                return;
            }

            Guide guide;
            switch (database.SelectedIndex)
            {
                case 1:
                    guide = new TVRage();
                    break;

                case 2:
                    guide = new TVDB();
                    break;

                case 3:
                    guide = new TVcom();
                    break;

                case 4:
                    guide = new EPisodeWorld();
                    break;

                case 5:
                    guide = new IMDb();
                    break;

                case 6:
                    guide = new AniDB();
                    break;

                case 7:
                    guide = new AnimeNewsNetwork();
                    break;

                case 9:
                    guide = new EPGuides();
                    break;

                case 10:
                    guide = new EPGuides();
                    break;

                default:
                    return;
            }

            new ShowGuideTaskDialog().Search(guide, nameTextBox.Text, (language.SelectedItem as StackPanel).Tag as string, (id, title, lang) =>
                {
                    if (id == null)
                    {
                        Dispatcher.Invoke((Action)(() =>
                            {
                                switch (Database.TVShows[_id].Source)
                                {
                                    case "TVRage":
                                        database.SelectedIndex = 1;
                                        break;

                                    case "TVDB":
                                        database.SelectedIndex = 2;
                                        break;

                                    case "TVcom":
                                        database.SelectedIndex = 3;
                                        break;

                                    case "EPisodeWorld":
                                        database.SelectedIndex = 4;
                                        break;

                                    case "IMDb":
                                        database.SelectedIndex = 5;
                                        break;

                                    case "AniDB":
                                        database.SelectedIndex = 6;
                                        break;

                                    case "AnimeNewsNetwork":
                                        database.SelectedIndex = 7;
                                        break;

                                    case "EPGuides":
                                        database.SelectedIndex = 10;
                                        break;
                                }
                            }));
                    }
                    else
                    {
                        Database.TVShows[_id].Source   = guide.GetType().Name;
                        Database.TVShows[_id].SourceID = id;
                        Database.TVShows[_id].Title    = title;
                        Database.TVShows[_id].Language = lang;

                        _upReq = true;

                        Dispatcher.Invoke((Action)(() =>
                                                       {
                                                           nameTextBox.Text = title;
                                                           _sidx = database.SelectedIndex;
                                                       }));
                    }
                });
        }