Exemple #1
0
        public static Azure_UserInfo GetUserInfoData(string dashType = "", string vidPlayer = "")
        {
            try
            {
                if (string.IsNullOrEmpty(ServerSettings.AniDB_Username))
                {
                    return(null);
                }

                Azure_UserInfo uinfo = new Azure_UserInfo
                {
                    DateTimeUpdated    = DateTime.Now,
                    DateTimeUpdatedUTC = 0,

                    // Optional JMM Desktop data
                    DashboardType = null,
                    VideoPlayer   = vidPlayer
                };
                System.Reflection.Assembly a = System.Reflection.Assembly.GetEntryAssembly();
                try
                {
                    if (a != null)
                    {
                        uinfo.JMMServerVersion = Utils.GetApplicationVersion(a);
                    }
                }
                catch
                {
                }

                uinfo.UsernameHash   = Utils.GetMd5Hash(ServerSettings.AniDB_Username);
                uinfo.DatabaseType   = ServerSettings.DatabaseType;
                uinfo.WindowsVersion = Utils.GetOSInfo();
                uinfo.TraktEnabled   = ServerSettings.Trakt_IsEnabled ? 1 : 0;
                uinfo.MALEnabled     = string.IsNullOrEmpty(ServerSettings.MAL_Username) ? 0 : 1;

                uinfo.CountryLocation = "";

                // this field is not actually used
                uinfo.LastEpisodeWatchedAsDate = DateTime.Now.AddDays(-5);

                uinfo.LocalUserCount = (int)RepoFactory.JMMUser.GetTotalRecordCount();

                uinfo.FileCount = RepoFactory.VideoLocal.GetTotalRecordCount();

                SVR_AnimeEpisode_User rec = RepoFactory.AnimeEpisode_User.GetLastWatchedEpisode();
                uinfo.LastEpisodeWatched = 0;
                if (rec != null)
                {
                    uinfo.LastEpisodeWatched = AniDB.GetAniDBDateAsSeconds(rec.WatchedDate);
                }

                return(uinfo);
            }
            catch (Exception ex)
            {
                logger.Error(ex, ex.ToString());
                return(null);
            }
        }
        public bool ProcessEpisodeSource(XmlNode node, int anid)
        {
            if (string.IsNullOrEmpty(node?.Attributes?["id"]?.Value))
            {
                return(false);
            }
            if (!int.TryParse(node?.Attributes?["id"]?.Value, out int id))
            {
                return(false);
            }
            EpisodeID = id;
            // default values
            LengthSeconds   = 0;
            Rating          = 0;
            Votes           = 0;
            EpisodeNumber   = 0;
            EpisodeType     = 1;
            RomajiName      = string.Empty;
            KanjiName       = string.Empty;
            EnglishName     = string.Empty;
            AirDate         = 0;
            DateTimeUpdated = DateTime.Now;

            AnimeID = anid;

            string epno = AniDBHTTPHelper.TryGetProperty(node, "epno");

            EpisodeType     = GetEpisodeType(epno);
            EpisodeNumber   = GetEpisodeNumber(epno);
            IsDoubleEpisode = GetIsDoubleEpisode(epno);

            string length = AniDBHTTPHelper.TryGetProperty(node, "length");

            int.TryParse(length, out int lMinutes);
            int secs = lMinutes * 60;

            LengthSeconds = secs;

            NumberStyles style   = NumberStyles.Number;
            CultureInfo  culture = CultureInfo.CreateSpecificCulture("en-GB");

            if (decimal.TryParse(AniDBHTTPHelper.TryGetProperty(node, "rating"), style, culture, out decimal rating))
            {
                Rating = rating;
            }
            if (int.TryParse(AniDBHTTPHelper.TryGetAttribute(node, "rating", "votes"), out int votes))
            {
                Votes = votes;
            }
            EnglishName = AniDBHTTPHelper.TryGetPropertyWithAttribute(node, "title", "xml:lang", "en")?.Replace('`', '\'');
            RomajiName  = AniDBHTTPHelper.TryGetPropertyWithAttribute(node, "title", "xml:lang", "x-jat")?.Replace('`', '\'');
            KanjiName   = AniDBHTTPHelper.TryGetPropertyWithAttribute(node, "title", "xml:lang", "ja")?.Replace('`', '\'');

            string adate = AniDBHTTPHelper.TryGetProperty(node, "airdate");

            AirDate = AniDB.GetAniDBDateAsSeconds(adate, true);
            IsValid = true;
            return(true);
        }
Exemple #3
0
		public void SetCorrectSessionKey()
		{
			AniDB aniDB = new AniDB(9000);

			aniDB.HandleResponse(new AniDBResponse(Encoding.ASCII.GetBytes("abc123 200 Jxqxb LOGIN ACCEPTED"), Encoding.ASCII));

			Assert.That(aniDB.SessionKey, Is.EqualTo("Jxqxb"));
		}
Exemple #4
0
        public void SetCorrectSessionKey()
        {
            AniDB aniDB = new AniDB(9000);

            aniDB.HandleResponse(new AniDBResponse(Encoding.ASCII.GetBytes("abc123 200 Jxqxb LOGIN ACCEPTED"), Encoding.ASCII));

            Assert.That(aniDB.SessionKey, Is.EqualTo("Jxqxb"));
        }
Exemple #5
0
        public void ProcessEpisodeSource(XmlNode node, int anid)
        {
            // default values
            LengthSeconds   = 0;
            Rating          = 0;
            Votes           = 0;
            EpisodeNumber   = 0;
            EpisodeType     = 1;
            RomajiName      = string.Empty;
            KanjiName       = string.Empty;
            EnglishName     = string.Empty;
            AirDate         = 0;
            DateTimeUpdated = DateTime.Now;

            EpisodeID = int.Parse(node.Attributes["id"].Value);
            AnimeID   = anid;

            string epno = AniDBHTTPHelper.TryGetProperty(node, "epno");

            EpisodeType     = GetEpisodeType(epno);
            EpisodeNumber   = GetEpisodeNumber(epno);
            IsDoubleEpisode = GetIsDoubleEpisode(epno);

            string length   = AniDBHTTPHelper.TryGetProperty(node, "length");
            int    lMinutes = 0;

            int.TryParse(length, out lMinutes);
            int secs = lMinutes * 60;

            LengthSeconds = secs;

            decimal rating = 0;
            int     votes  = 0;

            NumberStyles style   = NumberStyles.Number;
            CultureInfo  culture = CultureInfo.CreateSpecificCulture("en-GB");

            //string airdate = TryGetProperty(node, "airdate");
            decimal.TryParse(AniDBHTTPHelper.TryGetProperty(node, "rating"), style, culture, out rating);
            int.TryParse(AniDBHTTPHelper.TryGetAttribute(node, "rating", "votes"), out votes);
            Rating      = rating;
            Votes       = votes;
            EnglishName = AniDBHTTPHelper.TryGetPropertyWithAttribute(node, "title", "xml:lang", "en");
            RomajiName  = AniDBHTTPHelper.TryGetPropertyWithAttribute(node, "title", "xml:lang", "x-jat");
            KanjiName   = AniDBHTTPHelper.TryGetPropertyWithAttribute(node, "title", "xml:lang", "ja");

            /*
             *
             *          <title xml:lang="en">The Adventures of Asahina Mikuru Episode 00</title>
             *          <title xml:lang="lt">Mikuru Asahinos nuotykiai Epizodas 00</title>
             *          <title xml:lang="x-jat">Asahina Mikuru no Bouken Episode 00</title>*/
            string adate = AniDBHTTPHelper.TryGetProperty(node, "airdate");

            AirDate = AniDB.GetAniDBDateAsSeconds(adate, true);

            //BaseConfig.MyAnimeLog.Write("EPISODE: {0}: {1}", epno.Trim(), this.ToString());
        }
Exemple #6
0
        public virtual async Task <ICommandResult> Send()
        {
            //TODO add a Duplicate() method (or something similar)
            if (Sent)
            {
                AniDB.InvokeClientError(new ClientErrorArgs("Cannot send a command that has already been sent!"));
            }

            Sent = true;
            return(await Client.QueueCommand(this));
        }
Exemple #7
0
        public CalendarCollection(string sRecMessage)
        {
            /*
             *          // 297 CALENDAR
             *          6622|1251417600|0
             *          6551|1251417600|0
             *          6652|1252108800|0
             *          6635|1252540800|0
             *          6698|1252627200|0
             *          6489|1253145600|0
             *          6653|1253750400|0
             *          6684|1253836800|0
             *          6781|1253836800|0
             *          6763|1253923200|0
             */

            // DateFlags
            // 0 = normal start and end date (2010-01-31)
            // 1 = start date is year-month (2010-01)
            // 2 = start date is a year (2010)
            // 4 = normal start date, year-month end date
            // 8 = normal start date, year end date
            // 10 = start date is a year (2010)
            // 16 = normal start and end date (2010-01-31)


            // remove the header info
            string[] sDetails = sRecMessage.Substring(0).Split('\n');

            if (sDetails.Length <= 2)
            {
                return;
            }

            for (int i = 1; i < sDetails.Length - 1; i++)
            // first item will be the status command, and last will be empty
            {
                //BaseConfig.MyAnimeLog.Write("s: {0}", sDetails[i]);

                Calendar cal = new Calendar();

                string[] flds = sDetails[i].Substring(0).Split('|');
                cal.AnimeID        = int.Parse(flds[0]);
                cal.ReleaseDateRaw = flds[1];
                cal.DateFlags      = int.Parse(flds[2]);
                cal.ReleaseDate    = AniDB.GetAniDBDateAsDate(flds[1], cal.DateFlags);

                calendars.Add(cal);

                //BaseConfig.MyAnimeLog.Write("grp: {0}", grp);
            }
        }
        public APIResponse(string response)
        {
            Raw = response;
            List <string> data = response.Split(' ').ToList();

            // Get the tag (if present)
            if (CommandTag.TryGetTag(data[0], out Tag))
            {
                // If we had a tag, then remove the tag element
                // don't want to remove it if there's not a tag since it would be removing the return code then
                data.RemoveAt(0);
            }

            // parse the return code into an int
            if (int.TryParse(data[0], out int returnCodeInt) == false)
            {
                // This should really be a int TODO handle better
                throw new Exception($"Couldn't parse {data[0]} into an integer (should be return code)");
            }

            // Wiki says possible server error codes are 600-699
            if (returnCodeInt >= 600 && returnCodeInt <= 699)
            {
                if (returnCodeInt != 601 && returnCodeInt != 602)
                {
                    // We would report this to Ommina, but he said these would almost never happen, so ¯\_(ツ)_/¯
                    // (wiki says report anything other than 601 and 602 to him)
                }

                // Not entirely sure what I should do here, from the sounds of it, it's unlikely I'll get a tag on a 6xx
                // error response, so it's not like I could match the response to a command that was sent, meaning that
                // whatever command caused the 6xx is going to show as timed out instead of server error.
                //
                // For now this is hte best I can think of to ensure that there's *some* way to report we got a 6xx
                AniDB.InvokeServerError(new ServerErrorArgs(response));
            }

            // Get the return code
            if (!Enum.TryParse(data[0], out ReturnCode))
            {
                // Couldn't get the return code? TODO handle
                Console.WriteLine($"no return code? raw: {data[0]}");
            }

            data.RemoveAt(0);

            Data = data;
        }
        public void Init(IHash fileData, bool watched, DateTime?watchedDate)
        {
            FileData  = fileData;
            IsWatched = watched;

            commandID = fileData.Info;

            commandText  = "MYLISTADD lid=" + fileData.MyListID;
            commandText += "&viewed=" + (IsWatched ? "1" : "0"); //viewed
            commandText += "&state=" + (int)ServerSettings.Instance.AniDb.MyList_StorageState;
            if (watchedDate.HasValue)
            {
                commandText += "&viewdate=" + AniDB.GetAniDBDateAsSeconds(watchedDate.Value);
            }
            commandText += "&edit=1";
        }
Exemple #10
0
        public static AniDB GetAniDBInfo(HttpContext ctx, SVR_AniDB_Anime anime)
        {
            var aniDB = new AniDB
            {
                ID          = anime.AnimeID,
                Type        = GetAniDBSeriesType((AnimeType)anime.AnimeType),
                Restricted  = anime.Restricted == 1,
                Description = anime.Description,
                Rating      = new Rating
                {
                    Source   = "AniDB",
                    Value    = anime.Rating,
                    MaxValue = 1000,
                    Votes    = anime.VoteCount
                },
                Title  = anime.MainTitle,
                Titles = anime.GetTitles().Select(title => new Title
                {
                    Language = title.Language, Name = title.Title, Type = title.TitleType
                }).ToList(),
            };

            if (anime.AirDate != null)
            {
                var airdate = anime.AirDate.Value;
                if (airdate != DateTime.MinValue)
                {
                    aniDB.AirDate = airdate;
                }
            }
            if (anime.EndDate != null)
            {
                var enddate = anime.EndDate.Value;
                if (enddate != DateTime.MinValue)
                {
                    aniDB.EndDate = enddate;
                }
            }

            // Add Poster
            Images images = new Images();

            AddAniDBPoster(ctx, images, anime.AnimeID);
            aniDB.Poster = images.Posters.FirstOrDefault();

            return(aniDB);
        }
        public void Init(int animeID, int episodeNumber, AniDBFile_State fileState, DateTime?watchedDate = null)
        {
            // MYLISTADD aid={int4 aid}&generic=1&epno={int4 episode number}

            commandText  = "MYLISTADD aid=" + animeID;
            commandText += "&generic=1";
            commandText += "&epno=" + episodeNumber;
            if (watchedDate == null)
            {
                commandText += "&viewed=0";
            }
            else
            {
                commandText += "&viewed=1";
                commandText += "&viewdate=" + AniDB.GetAniDBDateAsSeconds(watchedDate.Value);
            }
            commandText += "&state=" + (int)fileState;
        }
        public void Init(IHash fileData, int animeID, int epnumber, bool watched, DateTime?watchedDate)
        {
            FileData  = fileData;
            IsWatched = watched;

            commandID = fileData.Info;

            commandText  = "MYLISTADD aid=" + animeID;
            commandText += "&generic=1";
            commandText += "&epno=" + epnumber;
            commandText += "&viewed=" + (IsWatched ? "1" : "0"); //viewed
            commandText += "&state=" + (int)ServerSettings.AniDB_MyList_StorageState;
            if (watchedDate.HasValue)
            {
                commandText += "&viewdate=" + AniDB.GetAniDBDateAsSeconds(watchedDate.Value);
            }
            commandText += "&edit=1";
        }
        public void Init(IHash fileData, AniDBFile_State fileState, DateTime?watchedDate = null)
        {
            FileData = fileData;

            commandID = fileData.Info;

            commandText  = "MYLISTADD size=" + fileData.FileSize;
            commandText += "&ed2k=" + fileData.ED2KHash;
            if (watchedDate == null)
            {
                commandText += "&viewed=0";
            }
            else
            {
                commandText += "&viewed=1";
                commandText += "&viewdate=" + AniDB.GetAniDBDateAsSeconds(watchedDate.Value);
            }
            commandText += "&state=" + (int)fileState;
        }
        public void Init(IHash fileData, bool watched, DateTime?watchedDate, bool isEdit, AniDBFile_State?fileState)
        {
            FileData  = fileData;
            IsWatched = watched;

            commandID = fileData.Info;

            commandText  = "MYLISTADD size=" + fileData.FileSize;
            commandText += "&ed2k=" + fileData.ED2KHash;
            commandText += "&viewed=" + (IsWatched ? "1" : "0"); //viewed
            if (fileState.HasValue)
            {
                commandText += "&state=" + (int)fileState;
            }
            if (watchedDate.HasValue)
            {
                commandText += "&viewdate=" + AniDB.GetAniDBDateAsSeconds(watchedDate.Value);
            }
            if (isEdit)
            {
                commandText += "&edit=1";
            }
        }
        /// <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" }
                    });
                }
            });
        }
        public bool ProcessEpisodeSource(XmlNode node, int anid)
        {
            if (string.IsNullOrEmpty(node?.Attributes?["id"]?.Value))
            {
                return(false);
            }
            if (!int.TryParse(node?.Attributes?["id"]?.Value, out int id))
            {
                return(false);
            }
            EpisodeID = id;
            // default values
            LengthSeconds   = 0;
            Rating          = 0;
            Votes           = 0;
            EpisodeNumber   = 0;
            EpisodeType     = 1;
            AirDate         = 0;
            DateTimeUpdated = DateTime.Now;

            AnimeID = anid;

            string epno = AniDBHTTPHelper.TryGetProperty(node, "epno");

            EpisodeType     = GetEpisodeType(epno);
            EpisodeNumber   = GetEpisodeNumber(epno);
            IsDoubleEpisode = GetIsDoubleEpisode(epno);

            string length = AniDBHTTPHelper.TryGetProperty(node, "length");

            int.TryParse(length, out int lMinutes);
            int secs = lMinutes * 60;

            LengthSeconds = secs;

            NumberStyles style   = NumberStyles.Number;
            CultureInfo  culture = CultureInfo.CreateSpecificCulture("en-GB");

            if (decimal.TryParse(AniDBHTTPHelper.TryGetProperty(node, "rating"), style, culture, out decimal rating))
            {
                Rating = rating;
            }
            if (int.TryParse(AniDBHTTPHelper.TryGetAttribute(node, "rating", "votes"), out int votes))
            {
                Votes = votes;
            }

            // Titles
            foreach (XmlNode nodeChild in node.ChildNodes)
            {
                // Make sure that it's a title and has data
                if (!(nodeChild?.Name.Equals("title") ?? false) ||
                    string.IsNullOrEmpty(nodeChild.InnerText))
                {
                    continue;
                }

                // get language
                string language = nodeChild.Attributes?["xml:lang"]?.Value?.Trim().ToUpperInvariant();
                if (string.IsNullOrEmpty(language))
                {
                    continue;
                }
                string title = nodeChild.InnerText.Trim().Replace('`', '\'');

                AniDB_Episode_Title episodeTitle = new AniDB_Episode_Title
                {
                    AniDB_EpisodeID = id, Language = language, Title = title
                };
                Titles.Add(episodeTitle);
            }

            string adate = AniDBHTTPHelper.TryGetProperty(node, "airdate");

            AirDate = AniDB.GetAniDBDateAsSeconds(adate, true);

            Description = AniDBHTTPHelper.TryGetProperty(node, "summary")?.Replace('`', '\'');
            IsValid     = true;
            return(true);
        }
        /// <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;
                                                       }));
                    }
                });
        }
Exemple #18
0
        public void ToggleWatchedStatus(bool watched, bool updateOnline, DateTime?watchedDate, bool updateStats,
                                        bool updateStatsCache, int userID,
                                        bool syncTrakt, bool updateWatchedDate)
        {
            SVR_JMMUser user = RepoFactory.JMMUser.GetByID(userID);

            if (user == null)
            {
                return;
            }

            List <SVR_JMMUser> aniDBUsers = RepoFactory.JMMUser.GetAniDBUsers();

            // update the video file to watched
            int mywatched = watched ? 1 : 0;

            if (user.IsAniDBUser == 0)
            {
                SaveWatchedStatus(watched, userID, watchedDate, updateWatchedDate);
            }
            else
            {
                // if the user is AniDB user we also want to update any other AniDB
                // users to keep them in sync
                foreach (SVR_JMMUser juser in aniDBUsers)
                {
                    if (juser.IsAniDBUser == 1)
                    {
                        SaveWatchedStatus(watched, juser.JMMUserID, watchedDate, updateWatchedDate);
                    }
                }
            }


            // now lets find all the associated AniDB_File record if there is one
            if (user.IsAniDBUser == 1)
            {
                SVR_AniDB_File aniFile = RepoFactory.AniDB_File.GetByHash(Hash);
                if (aniFile != null)
                {
                    aniFile.IsWatched = mywatched;

                    if (watched)
                    {
                        if (watchedDate.HasValue)
                        {
                            aniFile.WatchedDate = watchedDate;
                        }
                        else
                        {
                            aniFile.WatchedDate = DateTime.Now;
                        }
                    }
                    else
                    {
                        aniFile.WatchedDate = null;
                    }


                    RepoFactory.AniDB_File.Save(aniFile, false);
                }

                if (updateOnline)
                {
                    if ((watched && ServerSettings.AniDB_MyList_SetWatched) ||
                        (!watched && ServerSettings.AniDB_MyList_SetUnwatched))
                    {
                        CommandRequest_UpdateMyListFileStatus cmd = new CommandRequest_UpdateMyListFileStatus(
                            Hash, watched, false,
                            watchedDate.HasValue ? AniDB.GetAniDBDateAsSeconds(watchedDate) : 0);
                        cmd.Save();
                    }
                }
            }

            // now find all the episode records associated with this video file
            // but we also need to check if theer are any other files attached to this episode with a watched
            // status,


            SVR_AnimeSeries ser = null;
            // get all files associated with this episode
            List <CrossRef_File_Episode>      xrefs          = RepoFactory.CrossRef_File_Episode.GetByHash(Hash);
            Dictionary <int, SVR_AnimeSeries> toUpdateSeries = new Dictionary <int, SVR_AnimeSeries>();

            if (watched)
            {
                // find the total watched percentage
                // eg one file can have a % = 100
                // or if 2 files make up one episodes they will each have a % = 50

                foreach (CrossRef_File_Episode xref in xrefs)
                {
                    // get the episodes for this file, may be more than one (One Piece x Toriko)
                    SVR_AnimeEpisode ep = RepoFactory.AnimeEpisode.GetByAniDBEpisodeID(xref.EpisodeID);
                    // get all the files for this episode
                    int epPercentWatched = 0;
                    foreach (CrossRef_File_Episode filexref in ep.FileCrossRefs)
                    {
                        VideoLocal_User vidUser = filexref.GetVideoLocalUserRecord(userID);
                        if (vidUser != null && vidUser.WatchedDate.HasValue)
                        {
                            // if not null means it is watched
                            epPercentWatched += filexref.Percentage;
                        }

                        if (epPercentWatched > 95)
                        {
                            break;
                        }
                    }

                    if (epPercentWatched > 95)
                    {
                        ser = ep.GetAnimeSeries();
                        if (!toUpdateSeries.ContainsKey(ser.AnimeSeriesID))
                        {
                            toUpdateSeries.Add(ser.AnimeSeriesID, ser);
                        }
                        if (user.IsAniDBUser == 0)
                        {
                            ep.SaveWatchedStatus(true, userID, watchedDate, updateWatchedDate);
                        }
                        else
                        {
                            // if the user is AniDB user we also want to update any other AniDB
                            // users to keep them in sync
                            foreach (SVR_JMMUser juser in aniDBUsers)
                            {
                                if (juser.IsAniDBUser == 1)
                                {
                                    ep.SaveWatchedStatus(true, juser.JMMUserID, watchedDate, updateWatchedDate);
                                }
                            }
                        }

                        if (syncTrakt && ServerSettings.Trakt_IsEnabled &&
                            !string.IsNullOrEmpty(ServerSettings.Trakt_AuthToken))
                        {
                            CommandRequest_TraktHistoryEpisode cmdSyncTrakt =
                                new CommandRequest_TraktHistoryEpisode(ep.AnimeEpisodeID, TraktSyncAction.Add);
                            cmdSyncTrakt.Save();
                        }

                        if (!string.IsNullOrEmpty(ServerSettings.MAL_Username) &&
                            !string.IsNullOrEmpty(ServerSettings.MAL_Password))
                        {
                            CommandRequest_MALUpdatedWatchedStatus cmdMAL =
                                new CommandRequest_MALUpdatedWatchedStatus(ser.AniDB_ID);
                            cmdMAL.Save();
                        }
                    }
                }
            }
            else
            {
                // if setting a file to unwatched only set the episode unwatched, if ALL the files are unwatched
                foreach (CrossRef_File_Episode xrefEp in xrefs)
                {
                    // get the episodes for this file, may be more than one (One Piece x Toriko)
                    SVR_AnimeEpisode ep = RepoFactory.AnimeEpisode.GetByAniDBEpisodeID(xrefEp.EpisodeID);
                    ser = ep.GetAnimeSeries();
                    if (!toUpdateSeries.ContainsKey(ser.AnimeSeriesID))
                    {
                        toUpdateSeries.Add(ser.AnimeSeriesID, ser);
                    }
                    // get all the files for this episode
                    int epPercentWatched = 0;
                    foreach (CrossRef_File_Episode filexref in ep.FileCrossRefs)
                    {
                        VideoLocal_User vidUser = filexref.GetVideoLocalUserRecord(userID);
                        if (vidUser != null && vidUser.WatchedDate.HasValue)
                        {
                            epPercentWatched += filexref.Percentage;
                        }

                        if (epPercentWatched > 95)
                        {
                            break;
                        }
                    }

                    if (epPercentWatched < 95)
                    {
                        if (user.IsAniDBUser == 0)
                        {
                            ep.SaveWatchedStatus(false, userID, watchedDate, true);
                        }
                        else
                        {
                            // if the user is AniDB user we also want to update any other AniDB
                            // users to keep them in sync
                            foreach (SVR_JMMUser juser in aniDBUsers)
                            {
                                if (juser.IsAniDBUser == 1)
                                {
                                    ep.SaveWatchedStatus(false, juser.JMMUserID, watchedDate, true);
                                }
                            }
                        }

                        if (syncTrakt && ServerSettings.Trakt_IsEnabled &&
                            !string.IsNullOrEmpty(ServerSettings.Trakt_AuthToken))
                        {
                            CommandRequest_TraktHistoryEpisode cmdSyncTrakt =
                                new CommandRequest_TraktHistoryEpisode(ep.AnimeEpisodeID, TraktSyncAction.Remove);
                            cmdSyncTrakt.Save();
                        }
                    }
                }
                if (!string.IsNullOrEmpty(ServerSettings.MAL_Username) &&
                    !string.IsNullOrEmpty(ServerSettings.MAL_Password))
                {
                    CommandRequest_MALUpdatedWatchedStatus cmdMAL =
                        new CommandRequest_MALUpdatedWatchedStatus(ser.AniDB_ID);
                    cmdMAL.Save();
                }
            }


            // update stats for groups and series
            if (toUpdateSeries.Count > 0 && updateStats)
            {
                foreach (SVR_AnimeSeries s in toUpdateSeries.Values)
                {
                    // update all the groups above this series in the heirarchy
                    s.UpdateStats(true, true, true);
                }
                //ser.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, true);
            }

            //if (ser != null && updateStatsCache)
            //StatsCache.Instance.UpdateUsingSeries(ser.AnimeSeriesID);
        }
Exemple #19
0
        public static Raw_AniDB_Anime ProcessAnimeDetails(XmlDocument docAnime, int animeID)
        {
            // most of the genral anime data will be over written by the UDP command
            Raw_AniDB_Anime anime = new Raw_AniDB_Anime
            {
                AnimeID = animeID
            };

            // check if there is any data
            if (docAnime?["anime"]?.Attributes["id"]?.Value == null)
            {
                logger.Warn("AniDB ProcessAnimeDetails - Received no or invalid info in XML");
                return(null);
            }

            anime.Description  = TryGetProperty(docAnime, "anime", "description")?.Replace('`', '\'');
            anime.AnimeTypeRAW = TryGetProperty(docAnime, "anime", "type");


            string episodecount = TryGetProperty(docAnime, "anime", "episodecount");

            int.TryParse(episodecount, out int epCount);
            anime.EpisodeCount       = epCount;
            anime.EpisodeCountNormal = epCount;

            int convertedAirDate = AniDB.GetAniDBDateAsSeconds(TryGetProperty(docAnime, "anime", "startdate"), true);
            int convertedEndDate = AniDB.GetAniDBDateAsSeconds(TryGetProperty(docAnime, "anime", "enddate"), false);

            //anime.AirDate = TryGetProperty(docAnime, "anime", "startdate");
            //anime.EndDate = TryGetProperty(docAnime, "anime", "enddate");

            anime.AirDate = AniDB.GetAniDBDateAsDate(convertedAirDate);
            anime.EndDate = AniDB.GetAniDBDateAsDate(convertedEndDate);

            anime.BeginYear = anime.AirDate?.Year ?? 0;
            anime.EndYear   = anime.EndDate?.Year ?? 0;

            //string enddate = TryGetProperty(docAnime, "anime", "enddate");

            string restricted = docAnime["anime"].Attributes["restricted"]?.Value;

            if (bool.TryParse(restricted, out bool res))
            {
                anime.Restricted = res ? 1 : 0;
            }
            else
            {
                anime.Restricted = 0;
            }

            anime.URL     = TryGetProperty(docAnime, "anime", "url");
            anime.Picname = TryGetProperty(docAnime, "anime", "picture");

            anime.DateTimeUpdated     = DateTime.Now;
            anime.DateTimeDescUpdated = anime.DateTimeUpdated;
            anime.ImageEnabled        = 1;

            #region Related Anime

            XmlNodeList raItems = docAnime["anime"]["relatedanime"]?.GetElementsByTagName("anime");
            if (raItems != null)
            {
                anime.RelatedAnimeIdsRAW   = string.Empty;
                anime.RelatedAnimeTypesRAW = string.Empty;

                foreach (XmlNode node in raItems)
                {
                    if (node?.Attributes?["id"]?.Value == null)
                    {
                        continue;
                    }
                    if (!int.TryParse(node.Attributes["id"].Value, out int id))
                    {
                        continue;
                    }
                    int relType = ConvertReltTypeTextToEnum(TryGetAttribute(node, "type"));

                    if (anime.RelatedAnimeIdsRAW.Length > 0)
                    {
                        anime.RelatedAnimeIdsRAW += "'";
                    }
                    if (anime.RelatedAnimeTypesRAW.Length > 0)
                    {
                        anime.RelatedAnimeTypesRAW += "'";
                    }

                    anime.RelatedAnimeIdsRAW   += id.ToString();
                    anime.RelatedAnimeTypesRAW += relType.ToString();
                }
            }

            #endregion

            #region Titles

            XmlNodeList titleItems = docAnime["anime"]["titles"]?.GetElementsByTagName("title");
            if (titleItems != null)
            {
                foreach (XmlNode node in titleItems)
                {
                    string titleType = node?.Attributes?["type"]?.Value?.Trim().ToLower();
                    if (string.IsNullOrEmpty(titleType))
                    {
                        continue;
                    }
                    string languageType = node.Attributes["xml:lang"]?.Value?.Trim().ToLower();
                    if (string.IsNullOrEmpty(languageType))
                    {
                        continue;
                    }
                    string titleValue = node.InnerText.Trim();
                    if (string.IsNullOrEmpty(titleValue))
                    {
                        continue;
                    }

                    if (titleType.Trim().ToUpper().Equals("MAIN"))
                    {
                        anime.MainTitle = titleValue.Replace('`', '\'');
                    }
                }
            }

            #endregion

            #region Ratings

            // init ratings
            anime.VoteCount       = 0;
            anime.TempVoteCount   = 0;
            anime.Rating          = 0;
            anime.TempRating      = 0;
            anime.ReviewCount     = 0;
            anime.AvgReviewRating = 0;

            NumberStyles style   = NumberStyles.Number;
            CultureInfo  culture = CultureInfo.CreateSpecificCulture("en-GB");

            XmlNodeList ratingItems = docAnime["anime"]["ratings"]?.ChildNodes;
            if (ratingItems == null)
            {
                return(anime);
            }
            foreach (XmlNode node in ratingItems)
            {
                string name = node?.Name?.Trim().ToLower();
                if (string.IsNullOrEmpty(name))
                {
                    continue;
                }
                if (!int.TryParse(TryGetAttribute(node, "count"), out int iCount))
                {
                    continue;
                }
                if (!decimal.TryParse(node.InnerText.Trim(), style, culture, out decimal iRating))
                {
                    continue;
                }
                iRating = (int)Math.Round(iRating * 100);

                if (name.Equals("permanent"))
                {
                    anime.VoteCount = iCount;
                    anime.Rating    = (int)iRating;
                }
                else if (name.Equals("temporary"))
                {
                    anime.TempVoteCount = iCount;
                    anime.TempRating    = (int)iRating;
                }
                else if (name.Equals("review"))
                {
                    anime.ReviewCount     = iCount;
                    anime.AvgReviewRating = (int)iRating;
                }
            }

            #endregion

            return(anime);
        }
Exemple #20
0
        // constructor
        // sRecMessage is the message received from ANIDB file info command
        // example response like '220 FILE .....'
        public Raw_AniDB_Anime(string sRecMessage)
        {
            PopulateDefaults();

            // remove the header info
            string[] sDetails = sRecMessage.Substring(10).Split('|');

            //230 ANIME 0|0
            //  0. 6107  ** anime id
            //  1. 2009  ** year
            //  2. TV Series ** type
            //  3. 979 ** related anime id's
            //  4. 32 ** related anime types
            //  5. Magic,Shounen,Manga,Military,Action ** genres
            //  6. 6,6,6,6,4 ** genreRAW weight
            //  7. Hagane no Renkinjutsushi (2009) ** romaji name
            //  8. Kanji Name
            //  9. Full Metal Alchemist: Brotherhood ** english name
            // 10.     * other name
            // 11. FMA2'hagaren2 ** short name list (the apostrophe is the list separator)
            // 12. Fullmetal Alchemist: Brotherhood'Fullmetal Alchemist 2'Full Metal Alchemist 2'???????? ???????: ????????'St?lalkemisten'????????? ??????? ?????? : ??????'2 ????????? ??????? ??????'??????? ????? 2009'Metalinis Alchemikas 2'?????? 2009 ** synonyms
            // 13. 0 ** episodes
            // 14. 5 ** normal episode count
            // 15. 6 ** special episode count
            // 16. 1238889600 ** air date
            // 17. 0 ** end date
            // 18. http://www.hagaren.jp/ ** url
            // 19. 15097.jpg ** pic name
            // 20. 175,5,273,171,4 ** category id list
            // 21. 0 ** rating
            // 22. 0 ** vote count
            // 23. 846 ** temp rating (divide by 100)
            // 24. 416 ** temp vote count
            // 25. 0 ** average review rating
            // 26. 0 ** review count
            // 27. ** Award List
            // 28. 0 ** Restricted 18+
            // 29. 0 Anime Planet ID
            // 30. 0 ANN ID
            // 31. 0 AllCinema ID
            // 32. 0 AnimeNfo ID
            // 33. 1238889600 ** last modified
            // 34. 705,2409,2410,2411,2412,2413,2414,2415 ** character id list
            // 35. 705,2409,2410,2411,2412,2413,2414,2415 ** review id list


            AnimeID            = int.Parse(sDetails[0]);
            AnimeTypeRAW       = AniDBAPILib.ProcessAniDBString(sDetails[2]);
            RelatedAnimeIdsRAW = AniDBAPILib.ProcessAniDBString(sDetails[3]);


            //BaseConfig.MyAnimeLog.Write("relatedAnimeIDs: {0}", sDetails[3]);
            //BaseConfig.MyAnimeLog.Write("relatedAnimeIDs: {0}", AniDBLib.ProcessAniDBString(sDetails[3]));

            RelatedAnimeTypesRAW = AniDBAPILib.ProcessAniDBString(sDetails[4]);
            //genreweight = sDetails[6];
            //RomajiName = AniDBAPILib.ProcessAniDBString(sDetails[7]);
            //BaseConfig.MyAnimeLog.Write("English name old: **{0}**", sDetails[8]);
            //KanjiName = AniDBAPILib.ProcessAniDBString(sDetails[8]);
            //EnglishName = AniDBAPILib.ProcessAniDBString(sDetails[9]);
            //BaseConfig.MyAnimeLog.Write("English name new: **{0}**", englishName);
            //OtherName = AniDBAPILib.ProcessAniDBString(sDetails[10]);
            //ShortNames = AniDBAPILib.ProcessAniDBString(sDetails[11].Replace("'", "|"));
            //Synonyms = AniDBAPILib.ProcessAniDBString(sDetails[12].Replace("'", "|"));
            EpisodeCount        = AniDBAPILib.ProcessAniDBInt(sDetails[13]);
            EpisodeCountNormal  = AniDBAPILib.ProcessAniDBInt(sDetails[14]);
            EpisodeCountSpecial = AniDBAPILib.ProcessAniDBInt(sDetails[15]);

            int airDateSeconds = int.Parse(AniDBAPILib.ProcessAniDBString(sDetails[16]));
            int endDateSeconds = int.Parse(AniDBAPILib.ProcessAniDBString(sDetails[17]));

            AirDate = AniDB.GetAniDBDateAsDate(airDateSeconds);
            EndDate = AniDB.GetAniDBDateAsDate(endDateSeconds);

            URL     = AniDBAPILib.ProcessAniDBString(sDetails[18]);
            Picname = AniDBAPILib.ProcessAniDBString(sDetails[19]);
            //categoryidlist = sDetails[20];
            Rating             = AniDBAPILib.ProcessAniDBInt(sDetails[21]);
            VoteCount          = AniDBAPILib.ProcessAniDBInt(sDetails[22]);
            TempRating         = AniDBAPILib.ProcessAniDBInt(sDetails[23]);
            TempVoteCount      = AniDBAPILib.ProcessAniDBInt(sDetails[24]);
            AvgReviewRating    = AniDBAPILib.ProcessAniDBInt(sDetails[25]);
            ReviewCount        = AniDBAPILib.ProcessAniDBInt(sDetails[26]);
            AwardList          = AniDBAPILib.ProcessAniDBString(sDetails[27]);
            Restricted         = AniDBAPILib.ProcessAniDBInt(sDetails[28]);
            AnimePlanetID      = AniDBAPILib.ProcessAniDBInt(sDetails[29]);
            ANNID              = AniDBAPILib.ProcessAniDBInt(sDetails[30]);
            AllCinemaID        = AniDBAPILib.ProcessAniDBInt(sDetails[31]);
            AnimeNfoID         = AniDBAPILib.ProcessAniDBString(sDetails[32]);
            DateRecordUpdated  = AniDBAPILib.ProcessAniDBString(sDetails[33]);
            CharacterIDListRAW = AniDBAPILib.ProcessAniDBString(sDetails[34]);
            ReviewIDListRAW    = AniDBAPILib.ProcessAniDBString(sDetails[35]);
            //New version number
            VersionNumber = LastVersion;
            //Genres should by right in utf-16
            GenreRAW  = sDetails[5];
            BeginYear = AirDate.HasValue ? AirDate.Value.Year : 0;
            EndYear   = EndDate.HasValue ? EndDate.Value.Year : 0;

            foreach (int rid in this.ReviewIDList)
            {
                //BaseConfig.MyAnimeLog.Write("ReviewID: {0}", rid.ToString());
            }

            /*
             * char[] chars = sDetails[5].ToCharArray();
             *
             * foreach (char c in chars)
             *          {
             *                  if ((int)c > 31 && (int)c < 127)
             *                          genreRAW += c.ToString();
             *          }
             */
        }
Exemple #21
0
		private static bool SelfCheck() {
			using(new ActivityTraceContext(ts, "SelfCheck")) {

				var waitHandle = new AutoResetEvent(true);
				try {
					waitHandle.WaitOne(10);
				} catch(Exception ex) {
					ColoredWriteLine(ConsoleColor.Red, ".NET 3.5 SP1 probably not installed", true);
					Pause(true);
					return false;
				}
				ts.TraceInformation(".NET 3.5 SP1 or equivalent/higher present");
				waitHandle.Close();

				//#####################################################

				if(Environment.OSVersion.Platform == PlatformID.Unix && !File.Exists(Path.Combine(AppPath, "AVDump2Lib.dll.config"))) {
					ColoredWriteLine(ConsoleColor.Red, "AVDump2Lib.dll.config is missing", true);
					Pause(true);
					return false;
				}
				ts.TraceInformation("AVDump2Lib.dll.config found");

				//#####################################################

				var milFileName = Path.Combine(AppPath, Environment.OSVersion.Platform == PlatformID.Unix ? (IntPtr.Size == 4 ? "libMediaInfo_x86.so" : "libMediaInfo_x64.so") : (IntPtr.Size == 4 ? "MediaInfo_x86.dll" : "MediaInfo_x64.dll"));
				if(!File.Exists(milFileName)) {
					ColoredWriteLine(ConsoleColor.Red, "MediaInfoLib is missing", true);
					Pause(true);
					return false;
				}
				ts.TraceInformation("MediaInfoLib found");

				//#####################################################


#if(HasACreq)
				if(!string.IsNullOrEmpty(username)) {
					try {
						IMediaInfo mi = IntPtr.Size == 8 ? (IMediaInfo)new MediaInfo_x64() : (IMediaInfo)new MediaInfo_x86();
						if(!mi.Option("Info_Version").Equals("MediaInfoLib - v0.7.42")) {
							ColoredWriteLine(ConsoleColor.Red, "Mediainfo library version mismatch. Needed: v0.7.42, Used: " + mi.Option("Info_Version"), true);
							Pause(true);
							return false;
						}
						mi.Close();
					} catch(Exception ex) {
						ColoredWriteLine(ConsoleColor.Red, "Media Info Library not found. Error: " + ex.ToString(), true);
						Pause(true);
						return false;
					}
					ts.TraceInformation("MediaInfoLib version correct");


					if(AniDB.CheckMILHash()) {
						ColoredWriteLine(ConsoleColor.Red, "Mediainfo lib hash mismatch", true);
						Pause(true);
						return false;
					}
					ts.TraceInformation("MediaInfoLib hash correct");

					int tries = 5;
					while(tries != 0) {
						try {
							host = new IPEndPoint(Dns.GetHostAddresses(hostAddress).First(), hostPort);
							break;
						} catch(Exception) { }
						tries--;
					}
					if(host == null) {
						ColoredWriteLine(ConsoleColor.Red, "Couldn't resolve host " + hostAddress, true);
						return false;
					}
					ts.TraceInformation("Target host resolved");

					anidb = new AniDB(AcreqResult, localPort);
					for(int i = 0;i < retries;i++) {
						var result = anidb.TestConnectivity(host, timeout * 1000, "avdumplib", appVersion.Build, username.ToLower(), password);
						if(result.State != ACReq.CommitState.Success) {
							ColoredWriteLine(ConsoleColor.Red, "Couldn't establish session with anidb (" + result.State + ")", true);
							if(result.Error != null) {
								ColoredWriteLine(ConsoleColor.Red, result.Error.Message, true);
								if(result.Error.InnerException != null) ColoredWriteLine(ConsoleColor.Red, result.Error.InnerException.Message, true);
							}

							Pause(true);
							return false;
						} else break;
					}
					ts.TraceInformation("API working");
				}
#endif

				//#####################################################

				return true;
			}
		}
Exemple #22
0
        public static Raw_AniDB_Anime ProcessAnimeDetails(XmlDocument docAnime, int animeID)
        {
            // most of the genral anime data will be over written by the UDP command
            Raw_AniDB_Anime anime = new Raw_AniDB_Anime
            {
                AnimeID = animeID
            };

            // check if there is any data
            try
            {
                string id = docAnime["anime"].Attributes["id"].Value;
            }
            catch
            {
                //BaseConfig.MyAnimeLog.Write("Invalid xml document: {0}", animeID.ToString());
                return(null);
            }

            anime.Description  = TryGetProperty(docAnime, "anime", "description");
            anime.AnimeTypeRAW = TryGetProperty(docAnime, "anime", "type");


            string episodecount = TryGetProperty(docAnime, "anime", "episodecount");

            int.TryParse(episodecount, out int epCount);
            anime.EpisodeCount       = epCount;
            anime.EpisodeCountNormal = epCount;

            int convertedAirDate = AniDB.GetAniDBDateAsSeconds(TryGetProperty(docAnime, "anime", "startdate"), true);
            int convertedEndDate = AniDB.GetAniDBDateAsSeconds(TryGetProperty(docAnime, "anime", "enddate"), false);

            //anime.AirDate = TryGetProperty(docAnime, "anime", "startdate");
            //anime.EndDate = TryGetProperty(docAnime, "anime", "enddate");

            anime.AirDate = AniDB.GetAniDBDateAsDate(convertedAirDate);
            anime.EndDate = AniDB.GetAniDBDateAsDate(convertedEndDate);

            anime.BeginYear = anime.AirDate.HasValue ? anime.AirDate.Value.Year : 0;
            anime.EndYear   = anime.EndDate.HasValue ? anime.EndDate.Value.Year : 0;

            //string enddate = TryGetProperty(docAnime, "anime", "enddate");

            string restricted = docAnime["anime"].Attributes["restricted"].Value;

            bool.TryParse(restricted, out bool res);
            anime.Restricted = res ? 1 : 0;

            anime.URL     = TryGetProperty(docAnime, "anime", "url");
            anime.Picname = TryGetProperty(docAnime, "anime", "picture");

            anime.DateTimeUpdated     = DateTime.Now;
            anime.DateTimeDescUpdated = anime.DateTimeUpdated;
            anime.ImageEnabled        = 1;

            #region Related Anime

            if (docAnime["anime"]["relatedanime"] != null)
            {
                XmlNodeList raItems = docAnime["anime"]["relatedanime"].GetElementsByTagName("anime");
                if (raItems != null)
                {
                    anime.RelatedAnimeIdsRAW   = "";
                    anime.RelatedAnimeTypesRAW = "";

                    foreach (XmlNode node in raItems)
                    {
                        try
                        {
                            int id      = int.Parse(node.Attributes["id"].Value);
                            int relType = ConvertReltTypeTextToEnum(TryGetAttribute(node, "type"));

                            if (anime.RelatedAnimeIdsRAW.Length > 0)
                            {
                                anime.RelatedAnimeIdsRAW += "'";
                            }
                            if (anime.RelatedAnimeTypesRAW.Length > 0)
                            {
                                anime.RelatedAnimeTypesRAW += "'";
                            }

                            anime.RelatedAnimeIdsRAW   += id.ToString();
                            anime.RelatedAnimeTypesRAW += relType.ToString();
                        }
                        catch
                        {
                            //BaseConfig.MyAnimeLog.Write("Error in GetEpisodes: {0}", ex);
                        }
                    }
                }
            }

            #endregion

            #region Titles

            if (docAnime["anime"]["titles"] != null)
            {
                XmlNodeList titleItems = docAnime["anime"]["titles"].GetElementsByTagName("title");
                if (titleItems != null)
                {
                    foreach (XmlNode node in titleItems)
                    {
                        try
                        {
                            string titleType    = node.Attributes["type"].Value.Trim().ToLower();
                            string languageType = node.Attributes["xml:lang"].Value.Trim().ToLower();
                            string titleValue   = node.InnerText.Trim();

                            if (titleType.Trim().ToUpper() == "MAIN")
                            {
                                anime.MainTitle = titleValue;
                            }
                        }
                        catch
                        {
                            //BaseConfig.MyAnimeLog.Write("Error in GetEpisodes: {0}", ex);
                        }
                    }
                }
            }

            #endregion

            #region Ratings

            // init ratings
            anime.VoteCount       = 0;
            anime.TempVoteCount   = 0;
            anime.Rating          = 0;
            anime.TempRating      = 0;
            anime.ReviewCount     = 0;
            anime.AvgReviewRating = 0;

            NumberStyles style   = NumberStyles.Number;
            CultureInfo  culture = CultureInfo.CreateSpecificCulture("en-GB");

            if (docAnime["anime"]["ratings"] != null)
            {
                XmlNodeList ratingItems = docAnime["anime"]["ratings"].ChildNodes;
                if (ratingItems != null)
                {
                    foreach (XmlNode node in ratingItems)
                    {
                        try
                        {
                            if (node.Name.Trim().ToLower() == "permanent")
                            {
                                int.TryParse(TryGetAttribute(node, "count"), out int iCount);
                                anime.VoteCount = iCount;

                                decimal.TryParse(node.InnerText.Trim(), style, culture, out decimal iRating);
                                anime.Rating = (int)(iRating * 100);
                            }
                            if (node.Name.Trim().ToLower() == "temporary")
                            {
                                int.TryParse(TryGetAttribute(node, "count"), out int iCount);
                                anime.TempVoteCount = iCount;

                                decimal.TryParse(node.InnerText.Trim(), style, culture, out decimal iRating);
                                anime.TempRating = (int)(iRating * 100);
                            }
                            if (node.Name.Trim().ToLower() == "review")
                            {
                                int.TryParse(TryGetAttribute(node, "count"), out int iCount);
                                anime.ReviewCount = iCount;

                                decimal.TryParse(node.InnerText.Trim(), style, culture, out decimal iRating);
                                anime.AvgReviewRating = (int)(iRating * 100);
                            }
                        }
                        catch
                        {
                            //BaseConfig.MyAnimeLog.Write("Error in GetEpisodes: {0}", ex);
                        }
                    }
                }
            }

            #endregion

            //anime.VersionNumber = Raw_AniDB_Anime.LastVersion;
            //BaseConfig.MyAnimeLog.Write("Anime: {0}", anime.ToString());
            return(anime);
            //anime.Save(true, createSeriesRecord);

            //AniDB_Anime.UpdateDescription(anime.AnimeID, anime.Description);
        }
Exemple #23
0
        private static void Main(string[] args)
        {
            using (AniDB aniDB = new AniDB(9001))
            {
                Console.WriteLine("Before");

                var request = aniDB.Ping(true);
                Console.WriteLine("Request:");
                Console.WriteLine(request);
                request.Response.Wait();
                var response = request.Response.Result;
                Console.WriteLine("Response:");
                Console.WriteLine(response.OriginalString);
                Console.WriteLine(response);

                Console.WriteLine("After");

                Console.ReadKey();

                request = aniDB.ChangeEncoding("UTF-8");
                Console.WriteLine("Request:");
                Console.WriteLine(request);
                request.Response.Wait();
                response = request.Response.Result;
                Console.WriteLine("Response:");
                Console.WriteLine(response.OriginalString);
                Console.WriteLine(response);

                Console.ReadKey();

                //return;

                //var fileHash = new ED2KHash(args[0], 2);

                //new Thread(fileHash.CalculateHash).Start();

                //do
                //{
                //	Console.WriteLine(
                //					  "{0," + fileHash.ChunkCount.ToString(CultureInfo.CurrentCulture).Length +
                //					  "}/{1," + fileHash.ChunkCount.ToString(CultureInfo.CurrentCulture).Length +
                //					  "}", fileHash.Complete, fileHash.ChunkCount);
                //	Thread.Sleep(250);
                //} while (fileHash.Complete < fileHash.ChunkCount);

                //Console.WriteLine(fileHash.Hash);

                //Console.ReadKey();

                //ManualResetEvent waitHandle = new ManualResetEvent(false);

                //aniDB.Auth("aaron552", args[1], (res) =>
                //									   {
                //										Console.WriteLine(res.ToString());
                //										waitHandle.Set();
                //									   });



                //waitHandle.WaitOne();
                //waitHandle.Reset();

                //if (((AniDB)aniDB).SessionKey == "")
                //{
                //	Console.ReadKey();
                //	return;
                //}

                //AniDBFile.FMask fMask = new AniDBFile.FMask(AniDBFile.FMask.FMaskValues.AID |
                //											AniDBFile.FMask.FMaskValues.EID |
                //											AniDBFile.FMask.FMaskValues.GID |
                //											AniDBFile.FMask.FMaskValues.VideoCodec |
                //											AniDBFile.FMask.FMaskValues.VideoBitrate |
                //											AniDBFile.FMask.FMaskValues.AudioCodecs |
                //											AniDBFile.FMask.FMaskValues.AudioBitrates |
                //											AniDBFile.FMask.FMaskValues.DubLanguage |
                //											AniDBFile.FMask.FMaskValues.SubLanguage);

                //AniDBFile.AMask aMask = new AniDBFile.AMask(AniDBFile.AMask.AMaskValues.KanjiName |
                //											AniDBFile.AMask.AMaskValues.RomanjiName |
                //											AniDBFile.AMask.AMaskValues.EnglishName |
                //											AniDBFile.AMask.AMaskValues.ShortNameList |
                //											AniDBFile.AMask.AMaskValues.GroupShortName |
                //											AniDBFile.AMask.AMaskValues.GroupName |
                //											AniDBFile.AMask.AMaskValues.EpNo |
                //											AniDBFile.AMask.AMaskValues.TotalEpisodes |
                //											AniDBFile.AMask.AMaskValues.HighestEpisodeNumber |
                //											AniDBFile.AMask.AMaskValues.Year);

                //aniDB.File((new FileInfo(args[0])).Length, fileHash.Hash, fMask, aMask,
                //		   (res) =>
                //		   {
                //			try
                //			{
                //				Console.WriteLine(new AniDBFile(res, fMask, aMask));
                //			}
                //			catch (Exception e)
                //			{
                //				Console.WriteLine(e.ToString());
                //				Console.WriteLine(res);
                //			}
                //			waitHandle.Set();
                //		   });

                //waitHandle.WaitOne();
                //waitHandle.Reset();

                //aniDB.Logout((res) =>
                //			 {
                //				Console.WriteLine(res.ToString());
                //				waitHandle.Set();
                //			 });

                //waitHandle.WaitOne();

                //Console.ReadKey();
            }
        }