Exemple #1
0
        /*public static List<CrossRef_File_Episode> Get_CrossRefFileEpisode()
         * {
         *  //if (!ServerSettings.WebCache_XRefFileEpisode_Get) return null;
         *
         *  //string username = ServerSettings.AniDB_Username;
         *  //if (ServerSettings.WebCache_Anonymous)
         *  //    username = Constants.AnonWebCacheUsername;
         *
         *  string uri = string.Format(@"http://{0}/api/CrossRef_File_Episode/{1}?p={2}", azureHostBaseAddress, "88D29145F18DCEA4D4C41EF94B950378", "Ilast");
         *  string msg = string.Format("Getting File/Episode Cross Ref From Cache: {0}", "88D29145F18DCEA4D4C41EF94B950378");
         *
         *  DateTime start = DateTime.Now;
         *  JMMService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);
         *
         *  string json = GetDataJson(uri);
         *
         *  TimeSpan ts = DateTime.Now - start;
         *  msg = string.Format("Got File/Episode Cross Ref From Cache: {0} - {1}", "88D29145F18DCEA4D4C41EF94B950378", ts.TotalMilliseconds);
         *  JMMService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);
         *
         *  List<CrossRef_File_Episode> xrefs = JSONHelper.Deserialize<List<CrossRef_File_Episode>>(json);
         *
         *  return xrefs;
         * }*/

        public static List <CrossRef_File_Episode> Get_CrossRefFileEpisode(VideoLocal vid)
        {
            if (!ServerSettings.WebCache_XRefFileEpisode_Get)
            {
                return(null);
            }

            string username = ServerSettings.AniDB_Username;

            if (ServerSettings.WebCache_Anonymous)
            {
                username = Constants.AnonWebCacheUsername;
            }

            string uri = string.Format(@"http://{0}/api/CrossRef_File_Episode/{1}?p={2}", azureHostBaseAddress, vid.Hash,
                                       username);
            string msg = string.Format("Getting File/Episode Cross Ref From Cache: {0}", vid.Hash);

            DateTime start = DateTime.Now;

            JMMService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

            string json = GetDataJson(uri);

            TimeSpan ts = DateTime.Now - start;

            msg = string.Format("Got File/Episode Cross Ref From Cache: {0} - {1}", vid.Hash, ts.TotalMilliseconds);
            JMMService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

            List <CrossRef_File_Episode> xrefs = JSONHelper.Deserialize <List <CrossRef_File_Episode> >(json);

            return(xrefs);
        }
Exemple #2
0
        public static List <CrossRef_AniDB_TvDB> Get_CrossRefAniDBTvDB(int animeID)
        {
            string username = ServerSettings.AniDB_Username;

            if (ServerSettings.WebCache_Anonymous)
            {
                username = Constants.AnonWebCacheUsername;
            }

            string uri = string.Format(@"http://{0}/api/CrossRef_AniDB_TvDB/{1}?p={2}", azureHostBaseAddress, animeID, username);
            string msg = string.Format("Getting AniDB/TvDB Cross Ref From Cache: {0}", animeID);

            DateTime start = DateTime.Now;

            JMMService.LogToDatabase(Constants.DBLogType.APIAzureHTTP, msg);

            string json = GetDataJson(uri);

            TimeSpan ts = DateTime.Now - start;

            msg = string.Format("Got AniDB/TvDB Cross Ref From Cache: {0} - {1}", animeID, ts.TotalMilliseconds);
            JMMService.LogToDatabase(Constants.DBLogType.APIAzureHTTP, msg);

            List <CrossRef_AniDB_TvDB> xrefs = JSONHelper.Deserialize <List <CrossRef_AniDB_TvDB> >(json);

            return(xrefs);
        }
Exemple #3
0
        public static CrossRef_AniDB_Other Get_CrossRefAniDBOther(int animeID, CrossRefType xrefType)
        {
            if (!ServerSettings.WebCache_TvDB_Get)
            {
                return(null);
            }

            string username = ServerSettings.AniDB_Username;

            if (ServerSettings.WebCache_Anonymous)
            {
                username = Constants.AnonWebCacheUsername;
            }

            string uri = string.Format(@"http://{0}/api/CrossRef_AniDB_Other/{1}?p={2}&p2={3}", azureHostBaseAddress,
                                       animeID,
                                       username, (int)xrefType);
            string msg = string.Format("Getting AniDB/Other Cross Ref From Cache: {0}", animeID);

            DateTime start = DateTime.Now;

            JMMService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

            string json = GetDataJson(uri);

            TimeSpan ts = DateTime.Now - start;

            msg = string.Format("Got AniDB/MAL Cross Ref From Cache: {0} - {1}", animeID, ts.TotalMilliseconds);
            JMMService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

            CrossRef_AniDB_Other xref = JSONHelper.Deserialize <CrossRef_AniDB_Other>(json);

            return(xref);
        }
Exemple #4
0
        public static bool InitDB(this IDatabase database)
        {
            try
            {
                DatabaseFixes.InitFixes();
                if (!database.DatabaseAlreadyExists())
                {
                    database.CreateDatabase();
                    Thread.Sleep(3000);
                }
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(ServerSettings.Culture);

                JMMService.CloseSessionFactory();
                ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_Initializing;
                ISessionFactory temp = JMMService.SessionFactory;
                ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_CreateSchema;
                bool res = database.CreateInitialSchema();
                if (!res)
                {
                    int version = database.GetDatabaseVersion();
                    if (version > database.RequiredVersion)
                    {
                        ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_NotSupportedVersion;
                        return(false);
                    }
                    if (version < database.RequiredVersion)
                    {
                        ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_Backup;
                        database.BackupDatabase(GetDatabaseBackupName(version));
                    }
                }
                ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_ApplySchema;
                database.UpdateSchema();
                RepoFactory.Init();
                DatabaseFixes.ExecuteDatabaseFixes();
                database.PopulateInitialData();

                return(true);
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Could not init database: " + ex.ToString());
                ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Server_DatabaseFail;
                return(false);
            }
        }
Exemple #5
0
        public static XmlDocument GetAnimeXMLFromAPI(int animeID, ref string rawXML)
        {
            try
            {
                string uri = string.Format(AniDBHTTPHelper.AnimeURL, animeID);
                //APIUtils.WriteToLog("GetAnimeXMLFromAPI: " + uri);

                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(ServerSettings.Culture);

                DateTime start = DateTime.Now;
                string   msg   = string.Format(JMMServer.Properties.Resources.AniDB_GettingAnimeXML, animeID);
                JMMService.LogToSystem(Constants.DBLogType.APIAniDBHTTP, msg);

                rawXML = APIUtils.DownloadWebPage(uri);

                TimeSpan ts      = DateTime.Now - start;
                string   content = rawXML;
                if (content.Length > 100)
                {
                    content = content.Substring(0, 100);
                }
                msg = string.Format(JMMServer.Properties.Resources.AniDB_GotAnimeXML, animeID, ts.TotalMilliseconds,
                                    content);
                JMMService.LogToSystem(Constants.DBLogType.APIAniDBHTTP, msg);

                //APIUtils.WriteToLog("GetAnimeXMLFromAPI result: " + rawXML);

                if (rawXML.Trim().Length == 0)
                {
                    return(null);
                }

                XmlDocument docAnime = new XmlDocument();
                docAnime.LoadXml(rawXML);

                return(docAnime);
            }
            catch (Exception ex)
            {
                logger.ErrorException("Error in AniDBHTTPHelper.GetAnimeXMLFromAPI: {0}", ex);
                return(null);
            }
        }
Exemple #6
0
        public static List <Media> Get_Media(string ed2k)
        {
            string uri = string.Format(@"http://{0}/api/Media/{1}/{2}", azureHostBaseAddress, ed2k, VideoLocal.MEDIA_VERSION);
            string msg = string.Format("Getting Media Info From Cache for ED2K: {0} Version : {1}", ed2k, VideoLocal.MEDIA_VERSION);

            DateTime start = DateTime.Now;

            JMMService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

            string json = GetDataJson(uri);

            TimeSpan ts = DateTime.Now - start;

            msg = string.Format("Getting Media Info From Cache for ED2K: {0} - {1}", ed2k, ts.TotalMilliseconds);
            JMMService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

            List <Media> medias = JsonConvert.DeserializeObject <List <Media> >(json) ?? new List <Media>();

            return(medias);
        }
Exemple #7
0
        public static List <AnimeIDTitle> Get_AnimeTitle(string query)
        {
            //if (!ServerSettings.WebCache_XRefFileEpisode_Send) return;
            string uri = string.Format(@"http://{0}/api/animeidtitle/{1}", azureHostBaseAddress, query);
            string msg = string.Format("Getting Anime Title Data From Cache: {0}", query);

            DateTime start = DateTime.Now;

            JMMService.LogToDatabase(Constants.DBLogType.APIAzureHTTP, msg);

            string json = GetDataJson(uri);

            TimeSpan ts = DateTime.Now - start;

            msg = string.Format("Got Anime Title Data From Cache: {0} - {1}", query, ts.TotalMilliseconds);
            JMMService.LogToDatabase(Constants.DBLogType.APIAzureHTTP, msg);

            List <AnimeIDTitle> titles = JSONHelper.Deserialize <List <AnimeIDTitle> >(json);

            return(titles);
        }
Exemple #8
0
        /// <summary>
        /// Get File hash details from the web cache
        /// When the hash type is a CRC, the hash details value should be a combination of the CRC and the FileSize with an under score in between
        /// e.g. CRC32 = 8b4b52f4, File Size = 380580947.......hashDetails = 8b4b52f4_380580947
        /// </summary>
        /// <param name="hashType"></param>
        /// <param name="hashDetails"></param>
        /// <returns></returns>
        public static List <FileHash> Get_FileHash(FileHashType hashType, string hashDetails)
        {
            string uri = string.Format(@"http://{0}/api/FileHash/{1}?p={2}", azureHostBaseAddress, (int)hashType,
                                       hashDetails);
            string msg = string.Format("Getting File Hash From Cache: {0} - {1}", hashType, hashDetails);

            DateTime start = DateTime.Now;

            JMMService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

            string json = GetDataJson(uri);

            TimeSpan ts = DateTime.Now - start;

            msg = string.Format("Got File Hash From Cache: {0} - {1}", hashDetails, ts.TotalMilliseconds);
            JMMService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

            List <FileHash> hashes = JSONHelper.Deserialize <List <FileHash> >(json);

            return(hashes);
        }
Exemple #9
0
        public static XmlDocument GetAnimeXMLFromAPI(int animeID, ref string rawXML)
        {
            try
            {
                string uri = string.Format(AniDBHTTPHelper.AnimeURL, animeID);
                //APIUtils.WriteToLog("GetAnimeXMLFromAPI: " + uri);

                DateTime start = DateTime.Now;
                string   msg   = string.Format("Getting Anime XML Data From ANIDB: {0}", animeID);
                JMMService.LogToDatabase(Constants.DBLogType.APIAniDBHTTP, msg);

                rawXML = APIUtils.DownloadWebPage(uri);

                TimeSpan ts      = DateTime.Now - start;
                string   content = rawXML;
                if (content.Length > 100)
                {
                    content = content.Substring(0, 100);
                }
                msg = string.Format("Got Anime XML Data From ANIDB: {0} - {1} - {2}", animeID, ts.TotalMilliseconds, content);
                JMMService.LogToDatabase(Constants.DBLogType.APIAniDBHTTP, msg);

                //APIUtils.WriteToLog("GetAnimeXMLFromAPI result: " + rawXML);

                if (rawXML.Trim().Length == 0)
                {
                    return(null);
                }

                XmlDocument docAnime = new XmlDocument();
                docAnime.LoadXml(rawXML);

                return(docAnime);
            }
            catch (Exception ex)
            {
                logger.ErrorException("Error in AniDBHTTPHelper.GetAnimeXMLFromAPI: {0}", ex);
                return(null);
            }
        }
Exemple #10
0
        public static string Get_AnimeXML(int animeID)
        {
            //if (!ServerSettings.WebCache_XRefFileEpisode_Send) return;

            string uri = string.Format(@"http://{0}/api/animexml/{1}", azureHostBaseAddress, animeID);

            DateTime start = DateTime.Now;
            string   msg   = string.Format("Getting Anime XML Data From Cache: {0}", animeID);

            JMMService.LogToDatabase(Constants.DBLogType.APIAzureHTTP, msg);

            string xml = GetDataXML(uri);

            // remove the string container
            int iStart = xml.IndexOf("<?xml");

            if (iStart > 0)
            {
                string end  = "</string>";
                int    iEnd = xml.IndexOf(end);
                if (iEnd > 0)
                {
                    xml = xml.Substring(iStart, iEnd - iStart - 1);
                }
            }

            TimeSpan ts      = DateTime.Now - start;
            string   content = xml;

            if (content.Length > 100)
            {
                content = content.Substring(0, 100);
            }
            msg = string.Format("Got Anime XML Data From Cache: {0} - {1} - {2}", animeID, ts.TotalMilliseconds, content);
            JMMService.LogToDatabase(Constants.DBLogType.APIAzureHTTP, msg);

            return(xml);
        }
Exemple #11
0
        public static bool InitDB()
        {
            try
            {
                if (ServerSettings.DatabaseType.Trim().ToUpper() == "SQLSERVER")
                {
                    if (!SQLServer.DatabaseAlreadyExists())
                    {
                        logger.Error("Database: {0} does not exist", ServerSettings.DatabaseName);
                        SQLServer.CreateDatabase();
                        Thread.Sleep(3000);
                    }

                    JMMService.CloseSessionFactory();
                    ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_Initializing;
                    ISessionFactory temp = JMMService.SessionFactory;

                    ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_CreateSchema;
                    SQLServer.CreateInitialSchema();

                    ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_ApplySchema;
                    SQLServer.UpdateSchema();

                    PopulateInitialData();
                    DatabaseHelper.CreateInitialCustomTags();

                    return(true);
                }
                else if (ServerSettings.DatabaseType.Trim().ToUpper() == "SQLITE")
                {
                    ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_CreateDatabase;
                    SQLite.CreateDatabase();

                    JMMService.CloseSessionFactory();
                    ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_Initializing;
                    ISessionFactory temp = JMMService.SessionFactory;

                    ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_CreateSchema;
                    SQLite.CreateInitialSchema();

                    ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_ApplySchema;
                    SQLite.UpdateSchema();

                    PopulateInitialData();
                    DatabaseHelper.CreateInitialCustomTags();

                    return(true);
                }
                else if (ServerSettings.DatabaseType.Trim().ToUpper() == "MYSQL")
                {
                    logger.Trace("Database - Creating Database...");
                    ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_CreateDatabase;
                    MySQL.CreateDatabase();

                    logger.Trace("Initializing Session Factory...");
                    JMMService.CloseSessionFactory();
                    ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_Initializing;
                    ISessionFactory temp = JMMService.SessionFactory;

                    logger.Trace("Database - Creating Initial Schema...");
                    ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_CreateSchema;
                    MySQL.CreateInitialSchema();

                    logger.Trace("Database - Applying Schema Patches...");
                    ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_ApplySchema;
                    MySQL.UpdateSchema();
                    //MySQL.UpdateSchema_Fix();

                    PopulateInitialData();
                    DatabaseHelper.CreateInitialCustomTags();

                    return(true);
                }

                return(false);
            }
            catch (Exception ex)
            {
                logger.ErrorException("Could not init database: " + ex.ToString(), ex);
                return(false);
            }
        }
Exemple #12
0
        public void ProcessCommand(ref Socket soUDP,
                                   ref IPEndPoint remoteIpEndPoint, string sessionID, Encoding enc)
        {
            this.sessionID = sessionID;
            Encoding changeencoding = null;

            encoding = enc;
            EndPoint RemotePoint = (remoteIpEndPoint);

            mcommandText  = commandText;
            errorOccurred = false;

            if (commandType != enAniDBCommandType.Ping)
            {
                if (commandType != enAniDBCommandType.Login)
                {
                    if (commandType != enAniDBCommandType.Logout && commandType != enAniDBCommandType.GetMyListStats)
                    {
                        mcommandText += "&";
                    }
                    mcommandText += "s=" + sessionID;
                }
                else
                {
                    encoding       = System.Text.Encoding.ASCII;
                    changeencoding = enc;
                    string encod = changeencoding.EncodingName;
                    if (changeencoding.EncodingName.StartsWith("Unicode"))
                    {
                        encod = "utf-16";
                    }
                    mcommandText += "&enc=" + encod;
                }
            }
            bool     multipart     = false;
            int      part          = 0;
            int      maxpart       = 1;
            string   fulldesc      = "";
            string   decodedstring = "";
            DateTime start         = DateTime.Now;

            do
            {
                if (part > 0)
                {
                    mcommandText = mcommandText.Replace("part=" + (part - 1).ToString(), "part=" + part.ToString());
                    Thread.Sleep(2300);
                }
                if (commandType != enAniDBCommandType.Login)
                {
                    string msg = string.Format("UDP_COMMAND: {0}", mcommandText);
                    JMMService.LogToSystem(Constants.DBLogType.APIAniDBUDP, msg);
                }
                else
                {
                    //string msg = commandText.Replace(MainWindow.settings.Username, "******");
                    //msg = msg.Replace(MainWindow.settings.Password, "******");
                    //MyAnimeLog.Write("commandText: {0}", msg);
                }
                bool   repeatcmd;
                int    received;
                Byte[] byReceivedAdd = new Byte[2000];                 // max length should actually be 1400
                do
                {
                    repeatcmd = false;
                    // Send Message
                    Byte[] SendByteAdd = Encoding.GetBytes(mcommandText.ToCharArray());

                    try
                    {
                        JMMService.LastAniDBMessage    = DateTime.Now;
                        JMMService.LastAniDBUDPMessage = DateTime.Now;
                        if (commandType != enAniDBCommandType.Ping)
                        {
                            JMMService.LastAniDBMessageNonPing = DateTime.Now;
                        }
                        else
                        {
                            JMMService.LastAniDBPing = DateTime.Now;
                        }

                        soUDP.SendTo(SendByteAdd, remoteIpEndPoint);
                    }
                    catch (Exception ex)
                    {
                        logger.ErrorException(ex.ToString(), ex);
                        //MyAnimeLog.Write(ex.ToString());
                        errorOccurred = true;
                        errorMessage  = ex.ToString();
                    }


                    // Receive Response
                    received = 0;
                    try
                    {
                        //MyAnimeLog.Write("soUDP.ReceiveTimeout = {0}", soUDP.ReceiveTimeout.ToString());


                        received = soUDP.ReceiveFrom(byReceivedAdd, ref RemotePoint);
                        JMMService.LastAniDBMessage    = DateTime.Now;
                        JMMService.LastAniDBUDPMessage = DateTime.Now;
                        if (commandType != enAniDBCommandType.Ping)
                        {
                            JMMService.LastAniDBMessageNonPing = DateTime.Now;
                        }
                        else
                        {
                            JMMService.LastAniDBPing = DateTime.Now;
                        }

                        //MyAnimeLog.Write("Buffer length = {0}", received.ToString());
                        if ((received > 2) && ((byReceivedAdd[0] == 0) && (byReceivedAdd[1] == 0)))
                        {
                            //deflate
                            Byte[] buff  = new byte[65536];
                            Byte[] input = new byte[received - 2];
                            Array.Copy(byReceivedAdd, 2, input, 0, received - 2);
                            Inflater inf = new Inflater(false);
                            inf.SetInput(input);
                            inf.Inflate(buff);
                            byReceivedAdd = buff;
                            received      = (int)inf.TotalOut;
                        }
                    }
                    catch (SocketException sex)
                    {
                        // most likely we have timed out
                        logger.ErrorException(sex.ToString(), sex);
                        errorOccurred = true;
                        errorMessage  = sex.ToString();
                    }
                    catch (Exception ex)
                    {
                        logger.ErrorException(ex.ToString(), ex);
                        errorOccurred = true;
                        errorMessage  = ex.ToString();
                    }
                    if ((commandType == enAniDBCommandType.Login) && (byReceivedAdd[0] == 0xFE) && (byReceivedAdd[1] == 0xFF) && (byReceivedAdd[3] == 53) && (byReceivedAdd[5] != 53) && (!Encoding.EncodingName.ToLower().StartsWith("unicode")) && (changeencoding != null) && (changeencoding.EncodingName.ToLower().StartsWith("unicode")))
                    {
                        //Previous Session used utf-16 and was not logged out, AniDB was not yet issued a timeout.
                        //AUTH command was not understand because it was encoded in ASCII.
                        encoding  = changeencoding;
                        repeatcmd = true;
                    }
                } while (repeatcmd);

                if (!errorOccurred)
                {
                    if (changeencoding != null)
                    {
                        encoding = changeencoding;
                    }
                    System.Text.Encoding enco;
                    if ((byReceivedAdd[0] == 0xFE) && (byReceivedAdd[1] == 0xFF))
                    {
                        enco = encoding;
                    }
                    else
                    {
                        enco = Encoding.ASCII;
                    }
                    decodedstring = enco.GetString(byReceivedAdd, 0, received);

                    if (decodedstring[0] == 0xFEFF)                     // remove BOM
                    {
                        decodedstring = decodedstring.Substring(1);
                    }
                    if (commandType == enAniDBCommandType.GetAnimeDescription || commandType == enAniDBCommandType.GetReview)
                    {
                        //Lets handle multipart
                        part++;
                        string[] sp1 = decodedstring.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

                        if (sp1[0].StartsWith("233 ANIMEDESC") || sp1[0].StartsWith("233  ANIMEDESC"))
                        {
                            string[] sp2 = sp1[1].Split('|');
                            fulldesc += sp2[2];
                            maxpart   = int.Parse(sp2[1]);
                        }

                        if (sp1[0].StartsWith("234 REVIEW") || sp1[0].StartsWith("234  REVIEW"))
                        {
                            string[] sp2 = sp1[1].Split('|');

                            if (sp2.Length == 3)
                            {
                                fulldesc += sp2[2];
                            }
                            else
                            {
                                for (int i = 2; i < sp2.Length; i++)
                                {
                                    fulldesc += "|" + sp2[i];
                                }
                            }


                            maxpart = int.Parse(sp2[1]);
                        }
                        multipart = true;
                        if (part == maxpart)
                        {
                            decodedstring = sp1[0] + "\n0|1|" + fulldesc + "\n";
                            multipart     = false;
                        }
                    }
                }
            } while ((multipart) && (!errorOccurred));

            if (errorOccurred)
            {
                socketResponse = string.Empty;
            }
            else
            {
                // there should be 2 newline characters in each response
                // the first is after the command .e.g "220 FILE"
                // the second is at the end of the data
                int i = 0, ipos = 0, foundpos = 0;
                foreach (char c in decodedstring)
                {
                    if (c == '\n')
                    {
                        //MyAnimeLog.Write("NEWLINE FOUND AT: {0}", ipos);
                        i++;
                        foundpos = ipos;
                    }
                    ipos++;
                }

                if (i != 2)
                {
                    socketResponse = decodedstring;

                    TimeSpan ts  = DateTime.Now - start;
                    string   msg = string.Format("UDP_RESPONSE in {0} ms - {1} ", ts.TotalMilliseconds, socketResponse);
                    JMMService.LogToSystem(Constants.DBLogType.APIAniDBUDP, msg);
                }
                else
                {
                    socketResponse = decodedstring.Substring(0, foundpos + 1);

                    TimeSpan ts  = DateTime.Now - start;
                    string   msg = string.Format("UDP_RESPONSE_TRUNC in {0}ms - {1} ", ts.TotalMilliseconds, socketResponse);
                    JMMService.LogToSystem(Constants.DBLogType.APIAniDBUDP, msg);
                }
            }
            int val = 0;

            if (socketResponse.Length > 2)
            {
                int.TryParse(socketResponse.Substring(0, 3), out val);
            }
            this.ResponseCode = val;

            // if we get banned pause the command processor for a while
            // so we don't make the ban worse
            if (ResponseCode == 555)
            {
                JMMService.AnidbProcessor.IsBanned  = true;
                JMMService.AnidbProcessor.BanOrigin = "UDP";
            }
            else
            {
                JMMService.AnidbProcessor.IsBanned  = false;
                JMMService.AnidbProcessor.BanOrigin = "";
            }

            // 598 UNKNOWN COMMAND usually means we had connections issue
            // 506 INVALID SESSION
            // 505 ILLEGAL INPUT OR ACCESS DENIED
            // reset login status to start again
            if (ResponseCode == 598 || ResponseCode == 506 || ResponseCode == 506)
            {
                JMMService.AnidbProcessor.IsInvalidSession = true;
                logger.Trace("FORCING Logout because of invalid session");
                ForceReconnection();
            }

            // 600 INTERNAL SERVER ERROR
            // 601 ANIDB OUT OF SERVICE - TRY AGAIN LATER
            // 602 SERVER BUSY - TRY AGAIN LATER
            // 604 TIMEOUT - DELAY AND RESUBMIT
            if (ResponseCode == 600 || ResponseCode == 601 || ResponseCode == 602 || ResponseCode == 604)
            {
                string errormsg = "";
                switch (ResponseCode)
                {
                case 600: errormsg = "600 INTERNAL SERVER ERROR"; break;

                case 601: errormsg = "601 ANIDB OUT OF SERVICE - TRY AGAIN LATER"; break;

                case 602: errormsg = "602 SERVER BUSY - TRY AGAIN LATER"; break;

                case 604: errormsg = "TIMEOUT - DELAY AND RESUBMIT"; break;
                }
                logger.Trace("FORCING Logout because of invalid session");
                JMMService.AnidbProcessor.ExtendPause(300, errormsg);
            }
        }