Example #1
0
        public static List <Azure_CrossRef_File_Episode> Get_CrossRefFileEpisode(SVR_VideoLocal vid)
        {
            try
            {
                if (!ServerSettings.Instance.WebCache.XRefFileEpisode_Get)
                {
                    return(new List <Azure_CrossRef_File_Episode>());
                }

                string username = Constants.AnonWebCacheUsername;

                string uri = $@"http://{azureHostBaseAddress}/api/CrossRef_File_Episode/{vid.Hash}?p={username}";
                string msg = $"Getting File/Episode Cross Ref From Cache: {vid.Hash}";

                DateTime start = DateTime.Now;
                ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

                string json = GetDataJson(uri);

                TimeSpan ts = DateTime.Now - start;
                msg = $"Got File/Episode Cross Ref From Cache: {vid.Hash} - {ts.TotalMilliseconds}";
                ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

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

                return(xrefs ?? new List <Azure_CrossRef_File_Episode>());
            }
            catch
            {
                return(new List <Azure_CrossRef_File_Episode>());
            }
        }
Example #2
0
        public static Azure_CrossRef_AniDB_Other Get_CrossRefAniDBOther(int animeID, CrossRefType xrefType)
        {
            try
            {
                if (!ServerSettings.Instance.WebCache.TvDB_Get)
                {
                    return(null);
                }

                string username = Constants.AnonWebCacheUsername;

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

                DateTime start = DateTime.Now;
                ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

                string json = GetDataJson(uri);

                TimeSpan ts = DateTime.Now - start;
                msg = $"Got AniDB/MAL Cross Ref From Cache: {animeID} - {ts.TotalMilliseconds}";
                ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

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

                return(xref);
            }
            catch
            {
                return(null);
            }
        }
Example #3
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 <Azure_CrossRef_File_Episode> Get_CrossRefFileEpisode(SVR_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;

            ShokoService.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);
            ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

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

            return(xrefs);
        }
Example #4
0
        public static List <Azure_AnimeIDTitle> Get_AnimeTitle(string query)
        {
            try
            {
                //if (!ServerSettings.Instance.WebCache.XRefFileEpisode_Send) return;
                string uri = $@"http://{azureHostBaseAddress}/api/animeidtitle/{query}";
                string msg = $"Getting Anime Title Data From Cache: {query}";

                DateTime start = DateTime.Now;
                ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

                string json = GetDataJson(uri);

                TimeSpan ts = DateTime.Now - start;
                msg = $"Got Anime Title Data From Cache: {query} - {ts.TotalMilliseconds}";
                ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

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

                return(titles ?? new List <Azure_AnimeIDTitle>());
            }
            catch
            {
                return(new List <Azure_AnimeIDTitle>());
            }
        }
Example #5
0
        // TODO wrap the rest of these in timeout tasks
        public static async Task <List <Azure_FileHash> > Get_FileHashWithTaskAsync(FileHashType hashType, string hashDetails)
        {
            Task <List <Azure_FileHash> > task = new Task <List <Azure_FileHash> >(() =>
            {
                try
                {
                    string uri = $@"http://{azureHostBaseAddress}/api/FileHash/{(int) hashType}?p={hashDetails}";
                    string msg = $"Getting File Hash From Cache: {hashType} - {hashDetails}";

                    DateTime start = DateTime.Now;
                    ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

                    string json = GetDataJson(uri);

                    TimeSpan ts = DateTime.Now - start;
                    msg         = $"Got File Hash From Cache: {hashDetails} - {ts.TotalMilliseconds}";
                    ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

                    return(JSONHelper.Deserialize <List <Azure_FileHash> >(json));
                }
                catch
                {
                    return(new List <Azure_FileHash>());
                }
            });

            if (await Task.WhenAny(task, Task.Delay(30000)) == task)
            {
                return(await task);
            }
            return(await Task.FromResult(new List <Azure_FileHash>()));
        }
Example #6
0
        public static List <Azure_Media> Get_Media(string ed2k)
        {
            if (string.IsNullOrEmpty(ed2k))
            {
                return(new List <Azure_Media>());
            }
            try
            {
                string uri = $@"http://{azureHostBaseAddress}/api/Media/{ed2k}/{SVR_VideoLocal.MEDIA_VERSION}";
                string msg = $"Getting Media Info From Cache for ED2K: {ed2k} Version : {SVR_VideoLocal.MEDIA_VERSION}";

                DateTime start = DateTime.Now;
                ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

                string json = GetDataJson(uri);

                TimeSpan ts = DateTime.Now - start;
                msg = $"Getting Media Info From Cache for ED2K: {ed2k} - {ts.TotalMilliseconds}";
                ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

                List <Azure_Media> medias = JSONHelper.Deserialize <List <Azure_Media> >(json) ??
                                            new List <Azure_Media>();

                return(medias);
            }catch
            {
                return(new List <Azure_Media>());
            }
        }
Example #7
0
        public static List <Azure_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;

            ShokoService.LogToSystem(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);
            ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

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

            return(xrefs);
        }
Example #8
0
        public static XmlDocument GetAnimeXMLFromAPI(int animeID)
        {
            try
            {
                if (ShokoService.AnidbProcessor.IsHttpBanned)
                {
                    logger.Info("GetAnimeXMLFromAPI: banned, not getting");
                    return(null);
                }
                ShokoService.LastAniDBMessage     = DateTime.Now;
                ShokoService.LastAniDBHTTPMessage = DateTime.Now;

                var      anime      = Repo.Instance.AniDB_AnimeUpdate.GetByAnimeID(animeID);
                DateTime?prevUpdate = anime?.UpdatedAt;

                string uri = string.Format(AnimeURL, animeID);
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(ServerSettings.Instance.Culture);
                DateTime start = DateTime.Now;
                string   msg   = string.Format(Resources.AniDB_GettingAnimeXML, animeID) + "; prevUpdate: " + prevUpdate;
                ShokoService.LogToSystem(Constants.DBLogType.APIAniDBHTTP, msg);

                string rawXML = APIUtils.DownloadWebPage(uri);

                // Putting this here for no chance of error. It is ALWAYS created or updated when AniDB is called!
                var update = Repo.Instance.AniDB_AnimeUpdate.GetByAnimeID(animeID);
                using (var upd = Repo.Instance.AniDB_AnimeUpdate.BeginAddOrUpdate(() => Repo.Instance.AniDB_AnimeUpdate.GetByAnimeID(animeID), () => new AniDB_AnimeUpdate {
                    AnimeID = animeID
                }))
                {
                    upd.Entity.UpdatedAt = DateTime.Now;
                    upd.Commit();
                }

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

                XmlDocument docAnime = null;
                if (0 < rawXML.Trim().Length&& !CheckForBan(rawXML))
                {
                    APIUtils.WriteAnimeHTTPToFile(animeID, rawXML);

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

                return(docAnime);
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Error in AniDBHTTPHelper.GetAnimeXMLFromAPI: {0}");
                return(null);
            }
        }
Example #9
0
        public static List <Azure_CrossRef_AniDB_TvDB> Get_CrossRefAniDBTvDB(int animeID)
        {
            try
            {
                string username = ServerSettings.Instance.AniDb.Username;
                if (ServerSettings.Instance.WebCache.Anonymous)
                {
                    username = Constants.AnonWebCacheUsername;
                }


                string uri = $@"http://{azureHostBaseAddress}/api/CrossRef_AniDB_TvDB/{animeID}?p={username}";
                string msg = $"Getting AniDB/TvDB Cross Ref From Cache: {animeID}";

                DateTime start = DateTime.Now;
                ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

                string json = GetDataJson(uri);

                TimeSpan ts = DateTime.Now - start;
                msg = $"Got AniDB/TvDB Cross Ref From Cache: {animeID} - {ts.TotalMilliseconds}";
                ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

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

                return(xrefs ?? new List <Azure_CrossRef_AniDB_TvDB>());
            }
            catch
            {
                return(new List <Azure_CrossRef_AniDB_TvDB>());
            }
        }
Example #10
0
        public static Azure_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;

            ShokoService.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);
            ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

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

            return(xref);
        }
Example #11
0
        public static Azure_CrossRef_AniDB_MAL Get_CrossRefAniDBMAL(int animeID)
        {
            if (!ServerSettings.WebCache_MAL_Get)
            {
                return(null);
            }

            string username = ServerSettings.AniDB_Username;

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

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

            DateTime start = DateTime.Now;

            ShokoService.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);
            ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

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

            xref.Self = string.Format(CultureInfo.CurrentCulture, "api/crossRef_anidb_mal/{0}",
                                      xref.CrossRef_AniDB_MALID);
            return(xref);
        }
Example #12
0
        // TODO wrap the rest of these in timeout tasks
        public static async Task <List <Azure_FileHash> > Get_FileHashWithTaskAsync(FileHashType hashType, string hashDetails)
        {
            Task <List <Azure_FileHash> > task = new Task <List <Azure_FileHash> >(() =>
            {
                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;
                ShokoService.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);
                ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

                return(JsonConvert.DeserializeObject <List <Azure_FileHash> >(json) ??
                       new List <Azure_FileHash>());
            });

            if (await Task.WhenAny(task, Task.Delay(30000)) == task)
            {
                return(await task);
            }
            return(await Task.FromResult(new List <Azure_FileHash>()));
        }
Example #13
0
        public static XmlDocument GetAnimeXMLFromAPI(int animeID, ref string rawXML)
        {
            try
            {
                string uri = string.Format(AnimeURL, animeID);
                //APIUtils.WriteToLog("GetAnimeXMLFromAPI: " + uri);

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

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

                rawXML = APIUtils.DownloadWebPage(uri);

                // Putting this here for no chance of error. It is ALWAYS created or updated when AniDB is called!
                var update = RepoFactory.AniDB_AnimeUpdate.GetByAnimeID(animeID);
                if (update == null)
                {
                    update = new AniDB_AnimeUpdate {
                        AnimeID = animeID, UpdatedAt = DateTime.Now
                    }
                }
                ;
                else
                {
                    update.UpdatedAt = DateTime.Now;
                }
                RepoFactory.AniDB_AnimeUpdate.Save(update);

                TimeSpan ts      = DateTime.Now - start;
                string   content = rawXML;
                if (content.Length > 100)
                {
                    content = content.Substring(0, 100);
                }
                msg = string.Format(Resources.AniDB_GotAnimeXML, animeID, ts.TotalMilliseconds,
                                    content);
                ShokoService.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.Error(ex, "Error in AniDBHTTPHelper.GetAnimeXMLFromAPI: {0}");
                return(null);
            }
        }
Example #14
0
        public static XmlDocument GetAnimeXMLFromAPI(int animeID, ref string rawXML)
        {
            try
            {
                string uri = string.Format(AnimeURL, animeID);
                //APIUtils.WriteToLog("GetAnimeXMLFromAPI: " + uri);

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

                DateTime start = DateTime.Now;
                string   msg   = string.Format(Resources.AniDB_GettingAnimeXML, animeID);
                ShokoService.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(Resources.AniDB_GotAnimeXML, animeID, ts.TotalMilliseconds,
                                    content);
                ShokoService.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.Error(ex, "Error in AniDBHTTPHelper.GetAnimeXMLFromAPI: {0}");
                return(null);
            }
        }
Example #15
0
        public static string Get_AnimeXML(int animeID)
        {
            try
            {
                //if (!ServerSettings.Instance.WebCache.XRefFileEpisode_Send) return;

                string uri = $@"http://{azureHostBaseAddress}/api/animexml/{animeID}";

                DateTime start = DateTime.Now;
                string   msg   = $"Getting Anime XML Data From Cache: {animeID}";
                ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

                string xml = GetDataXML(uri);

                // remove the string container
                int iStart = xml.IndexOf("<?xml", StringComparison.Ordinal);
                if (iStart > 0)
                {
                    int iEnd = xml.IndexOf("</string>", StringComparison.Ordinal);
                    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 = $"Got Anime XML Data From Cache: {animeID} - {ts.TotalMilliseconds} - {content}";
                ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

                return(xml);
            }
            catch
            {
                return(null);
            }
        }
Example #16
0
        public static List <Azure_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;

            ShokoService.LogToSystem(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);
            ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

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

            return(titles);
        }
Example #17
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);

            ShokoService.LogToSystem(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);
            ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

            return(xml);
        }
Example #18
0
        public static List <Azure_Media> Get_Media(string ed2k)
        {
            string uri = string.Format(@"http://{0}/api/Media/{1}/{2}", azureHostBaseAddress, ed2k,
                                       SVR_VideoLocal.MEDIA_VERSION);
            string msg = string.Format("Getting Media Info From Cache for ED2K: {0} Version : {1}", ed2k,
                                       SVR_VideoLocal.MEDIA_VERSION);

            DateTime start = DateTime.Now;

            ShokoService.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);
            ShokoService.LogToSystem(Constants.DBLogType.APIAzureHTTP, msg);

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

            return(medias);
        }
Example #19
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;

            StaticRateLimiter.UDP.EnsureRate();

            if (commandType != enAniDBCommandType.Ping)
            {
                if (commandType != enAniDBCommandType.Login)
                {
                    if (commandType != enAniDBCommandType.Logout && commandType != enAniDBCommandType.GetMyListStats)
                    {
                        mcommandText += "&";
                    }
                    mcommandText += "s=" + sessionID;
                }
                else
                {
                    encoding       = 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.Empty;
            string   decodedstring = string.Empty;
            DateTime start         = DateTime.Now;

            do
            {
                if (commandType != enAniDBCommandType.Login)
                {
                    string msg = string.Format("UDP_COMMAND: {0}", mcommandText);
                    ShokoService.LogToSystem(Constants.DBLogType.APIAniDBUDP, 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
                    {
                        ShokoService.LastAniDBMessage    = DateTime.Now;
                        ShokoService.LastAniDBUDPMessage = DateTime.Now;
                        if (commandType != enAniDBCommandType.Ping)
                        {
                            ShokoService.LastAniDBMessageNonPing = DateTime.Now;
                        }
                        else
                        {
                            ShokoService.LastAniDBPing = DateTime.Now;
                        }

                        soUDP.SendTo(SendByteAdd, remoteIpEndPoint);
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex, ex.ToString());
                        //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);
                        ShokoService.LastAniDBMessage    = DateTime.Now;
                        ShokoService.LastAniDBUDPMessage = DateTime.Now;
                        if (commandType != enAniDBCommandType.Ping)
                        {
                            ShokoService.LastAniDBMessageNonPing = DateTime.Now;
                        }
                        else
                        {
                            ShokoService.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.Error(sex, sex.ToString());
                        errorOccurred = true;
                        errorMessage  = sex.ToString();
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex, ex.ToString());
                        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;
                    }
                    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[] { '\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);
                    ShokoService.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);
                    ShokoService.LogToSystem(Constants.DBLogType.APIAniDBUDP, msg);
                }
            }
            int val = 0;

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

            // if we get banned pause the command processor for a while
            // so we don't make the ban worse
            ShokoService.AnidbProcessor.IsUdpBanned = ResponseCode == 555;

            // 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 == 505)
            {
                ShokoService.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 = string.Empty;
                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");
                ShokoService.AnidbProcessor.ExtendPause(300, errormsg);
            }
        }