Exemple #1
0
        public async Task <IActionResult> AddProviderBatch([FromBody] List <WebCache_CrossRef_AniDB_Provider> crosses, string token, bool?approve)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                if (approve.HasValue && approve.Value && (s.Role & WebCache_RoleType.Admin) == 0)
                {
                    return(StatusCode(403, "Admin Only"));
                }
                //Exists already?
                foreach (WebCache_CrossRef_AniDB_Provider cross in crosses)
                {
                    await AddProviderInternal(s, cross, approve);
                }
                await _db.SaveChangesAsync();

                return(Ok());
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"ADDPROVIDERBATCH with Token={token} Count={crosses.Count}");
                return(StatusCode(500));
            }
        }
        public async Task <IActionResult> SetRole(string token, int anidbuserid, int role)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                if ((s.Role & WebCache_RoleType.Admin) == 0)
                {
                    return(StatusCode(403, "Admin Only"));
                }
                WebCache_User us = await _db.Users.FirstOrDefaultAsync(a => a.AniDBUserId == anidbuserid);

                if (us == null)
                {
                    return(StatusCode(404, "User not found"));
                }
                WebCache_RoleType rt = (WebCache_RoleType)role;
                SetRole(anidbuserid, rt);
                return(Ok());
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"SETROLE with Token={token} Userid={anidbuserid} Role={(WebCache_RoleType)role}");
                return(StatusCode(500));
            }
        }
Exemple #3
0
        public async Task <IActionResult> DeleteFileEpisodes(string token, string hash)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                List <WebCache_CrossRef_File_Episode> eps = await _db.CrossRef_File_Episodes.Where(a => a.Hash == hash && a.AniDBUserId == s.AniDBUserId).ToListAsync();

                if (eps.Count == 0)
                {
                    return(StatusCode(404, "CrossRef Not Found"));
                }
                _db.RemoveRange(eps);
                await _db.SaveChangesAsync();

                return(Ok());
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"DELETEFILEEPISODES with Token={token} Hash={hash}");
                return(StatusCode(500));
            }
        }
Exemple #4
0
        public async Task <IActionResult> DeleteProvider(string token, int animeId, int crossRefType)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                Models.Database.WebCache_CrossRef_AniDB_Provider r = await _db.CrossRef_AniDB_Providers.FirstOrDefaultAsync(a => a.AniDBUserId == s.AniDBUserId && a.AnimeID == animeId && a.CrossRefType == (CrossRefType)crossRefType);

                if (r == null)
                {
                    return(StatusCode(404, "CrossRef Not Found"));
                }
                _db.Remove(r);
                await _db.SaveChangesAsync();

                return(Ok());
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"DELETEPROVIDER with Token={token} AnimeId={animeId} CrossRefType={(CrossRefType)crossRefType}");

                return(StatusCode(500));
            }
        }
Exemple #5
0
        public async Task <IActionResult> GetRandomProvider(string token, int crossRefType)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                if ((s.Role & WebCache_RoleType.Admin) == 0)
                {
                    return(StatusCode(403, "Admin Only"));
                }
                int animeid = await _db.CrossRef_AniDB_Providers.Where(a => a.CrossRefType == (CrossRefType)crossRefType).GroupBy(a => a.AnimeID).Where(a => !a.Any(b => b.Approved == WebCache_RoleType.Admin)).Select(a => a.Key).FirstOrDefaultAsync();

                if (animeid == 0)
                {
                    return(StatusCode(404, "CrossRef Not Found, All Approved :)"));
                }
                return(await GetProviderInternal(s, animeid, (CrossRefType)crossRefType));
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"GETRANDOMPROVIDER with Token={token} CrossRefType={(CrossRefType)crossRefType}");
                return(StatusCode(500));
            }
        }
Exemple #6
0
        public async Task <IActionResult> AddFileEpisode(string token, [FromBody] CrossRef_File_Episode episode)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                WebCache_CrossRef_File_Episode ep = await _db.CrossRef_File_Episodes.FirstOrDefaultAsync(a => a.CrossRef_File_EpisodeID == episode.CrossRef_File_EpisodeID && a.AniDBUserId == s.AniDBUserId);

                if (ep == null)
                {
                    ep = new WebCache_CrossRef_File_Episode();
                    _db.Add(ep);
                }

                ep.FillWith(episode);
                ep.AniDBUserId = s.AniDBUserId;
                await _db.SaveChangesAsync();

                return(Ok());
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"ADDFILEEPISODE with Token={token}");
                return(StatusCode(500));
            }
        }
Exemple #7
0
        public async Task <IActionResult> DeleteFileEpisode(string token, string hash, int episodeid)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                WebCache_CrossRef_File_Episode ep = await _db.CrossRef_File_Episodes.FirstOrDefaultAsync(a => a.CrossRef_File_EpisodeID == episodeid && a.Hash == hash && a.AniDBUserId == s.AniDBUserId);

                if (ep == null)
                {
                    return(StatusCode(404, "CrossRef Not Found"));
                }
                _db.Remove(ep);
                await _db.SaveChangesAsync();

                return(Ok());
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"DELETEFILEEPISODE with Token={token} Hash={hash} EpisodeId={episodeid}");
                return(StatusCode(500));
            }
        }
        private async Task <bool> AddMediaInfoInternal(SessionInfoWithError s, WebCache_Media media)
        {
            try
            {
                Models.Database.WebCache_Media m = await _db.WebCache_Medias.FirstOrDefaultAsync(a => a.ED2K == media.ED2K);

                if (m == null)
                {
                    m = new Models.Database.WebCache_Media();
                    _db.Add(m);
                }
                else if (m.Version >= media.Version)
                {
                    return(false);
                }

                m.Version      = media.Version;
                m.MediaInfo    = media.MediaInfo;
                m.ED2K         = media.ED2K;
                m.CreationDate = DateTime.UtcNow;
                m.AniDBUserId  = s.AniDBUserId;
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Exemple #9
0
        public async Task <IActionResult> AddHashes(string token, [FromBody] List <WebCache_FileHash> hashes)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                bool update = false;
                foreach (WebCache_FileHash hash in hashes)
                {
                    if (await InternalAddHash(s, hash))
                    {
                        update = true;
                    }
                }

                if (update)
                {
                    await _db.SaveChangesAsync();
                }
                return(Ok());
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"ADDHASHES with Token={token} Hashes={hashes.Count}");
                return(StatusCode(500));
            }
        }
        public async Task <IActionResult> GetMediaInfo(string token, string ed2k)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                ed2k = ed2k.ToUpperInvariant();
                Models.Database.WebCache_Media m = await _db.WebCache_Medias.FirstOrDefaultAsync(a => a.ED2K == ed2k);

                if (m == null)
                {
                    return(StatusCode(404, "Media Not Found"));
                }
                return(new JsonResult(m));
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"GETMEDIAINFO with Token={token} ED2K={ed2k}");
                return(StatusCode(500));
            }
        }
        public async Task <IActionResult> AddMediaInfoBatch(string token, [FromBody] List <WebCache_Media> medias)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                bool persist = false;
                foreach (WebCache_Media media in medias)
                {
                    media.ED2K = media.ED2K.ToUpperInvariant();
                    if (await AddMediaInfoInternal(s, media))
                    {
                        persist = true;
                    }
                }
                if (persist)
                {
                    await _db.SaveChangesAsync();
                }
                return(Ok());
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"ADDMEDIAINFOBATCH with Token={token} Medias={medias.Count}");
                return(StatusCode(500));
            }
        }
Exemple #12
0
        public async Task <IActionResult> ApproveCollision(string token, int id)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                if ((s.Role & WebCache_RoleType.Admin) == 0)
                {
                    return(StatusCode(403, "Admin Only"));
                }
                WebCache_FileHash_Collision approved = await _db.WebCache_FileHash_Collisions.FirstOrDefaultAsync(a => a.WebCache_FileHash_Collision_Id == id);

                if (approved == null)
                {
                    return(StatusCode(404, "Collision Not Found"));
                }
                List <WebCache_FileHash_Collision> notapproved = await _db.WebCache_FileHash_Collisions.Where(a => a.WebCache_FileHash_Collision_Unique == approved.WebCache_FileHash_Collision_Unique && a.WebCache_FileHash_Collision_Id != id).ToListAsync();

                foreach (WebCache_FileHash_Collision n in notapproved)
                {
                    WebCache_FileHash_Info fc = await _db.WebCache_FileHashes.FirstOrDefaultAsync(a => a.CRC32 == n.CRC32 && a.ED2K == n.ED2K && a.MD5 == n.MD5 && a.SHA1 == n.SHA1 && a.FileSize == n.FileSize);

                    if (fc != null)
                    {
                        _db.Remove(fc);
                        await _db.SaveChangesAsync();
                    }
                }

                WebCache_FileHash_Info ap = await _db.WebCache_FileHashes.FirstOrDefaultAsync(a => a.CRC32 == approved.CRC32 && a.ED2K == approved.ED2K && a.MD5 == approved.MD5 && a.SHA1 == approved.SHA1 && a.FileSize == approved.FileSize);

                if (ap == null)
                {
                    ap = new WebCache_FileHash_Info();
                    ap.FillWith(approved);
                    _db.Add(ap);
                }

                ap.AniDBUserId       = s.AniDBUserId;
                ap.CollisionApproved = true;
                await _db.SaveChangesAsync();

                return(Ok());
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"APPROVECOLLISION with Token={token} Id={id}");
                return(StatusCode(500));
            }
        }
        public async Task <IActionResult> Token(string code, string state, string error, string encoded)
        {
            WebCache_OAuthData enc;

            try
            {
                string normalbase64 = encoded.Replace("-", "+").Replace("_", "/"); //Convert BASE64URL to normal Base64
                int    mod          = normalbase64.Length % 4;
                if (mod == 2)
                {
                    normalbase64 += "==";
                }
                else if (mod == 3)
                {
                    normalbase64 += "=";
                }
                enc = JsonConvert.DeserializeObject <WebCache_OAuthData>(Encoding.UTF8.GetString(Convert.FromBase64String(normalbase64)));
                if (enc == null) //Bad encoded data, no way to redirect the error
                {
                    return(StatusCode(400, "Bad Request"));
                }
            }
            catch (Exception e) //Bad encoded data, no way to redirect the error
            {
                _logger.LogError(e, "OAuth Token Error: Bad encoded data.");
                return(StatusCode(400, "Bad Request"));
            }
            WebCache_OAuthAccessTokenWithState errtoken = new WebCache_OAuthAccessTokenWithState();
            SessionInfoWithError s = await VerifyTokenAsync(enc.Token);

            if (s.Error != null)
            {
                errtoken.error = s.Error.StatusCode + ": " + s.Error;
                return(ReturnResult(enc, errtoken));
            }
            Dictionary <string, Credentials> providers = GetOAuthProviders();

            if (!providers.ContainsKey(enc.Provider))
            {
                errtoken.error = $"404: Provider {enc.Provider} Not Found";
                _logger.LogError($"Provider {enc.Provider} Not Found");
                return(ReturnResult(enc, errtoken));
            }
            Credentials credentials = providers[enc.Provider];
            var         token       = await GetTokenAsync(code, state, credentials, enc.OriginalRedirectUri);

            if (token == null)
            {
                errtoken.error = "400: Bad Request";
                return(ReturnResult(enc, errtoken));
            }
            return(ReturnResult(enc, token));
        }
Exemple #14
0
        public async Task <IActionResult> GetHash(string token, int type, string hash, long?size)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                hash = hash.ToUpperInvariant();
                WebCache_FileHash h = null;
                switch ((WebCache_HashType)type)
                {
                case WebCache_HashType.ED2K:
                    h = await _db.WebCache_FileHashes.FirstOrDefaultAsync(a => a.ED2K == hash);

                    break;

                case WebCache_HashType.CRC:
                    if (size == null)
                    {
                        return(StatusCode(400, "You must include size when asking for CRC"));
                    }
                    h = await _db.WebCache_FileHashes.FirstOrDefaultAsync(a => a.CRC32 == hash && a.FileSize == size.Value);

                    break;

                case WebCache_HashType.MD5:
                    h = await _db.WebCache_FileHashes.FirstOrDefaultAsync(a => a.MD5 == hash);

                    break;

                case WebCache_HashType.SHA1:
                    h = await _db.WebCache_FileHashes.FirstOrDefaultAsync(a => a.SHA1 == hash);

                    break;
                }

                if (h == null)
                {
                    return(StatusCode(404, "Hash not found"));
                }
                return(new JsonResult(h));
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"GETHASH with Token={token} Hash={hash} Type={(WebCache_HashType) type} Size={size ?? 0}");
                return(StatusCode(500));
            }
        }
Exemple #15
0
        public async Task <IActionResult> GetCollisions(string token)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                if ((s.Role & WebCache_RoleType.Admin) == 0)
                {
                    return(StatusCode(403, "Admin Only"));
                }
                Dictionary <int, string>                users      = new Dictionary <int, string>();
                List <WebCache_FileHash_Collision>      collisions = _db.WebCache_FileHash_Collisions.OrderBy(a => a.WebCache_FileHash_Collision_Unique).ToList();
                List <WebCache_FileHash_Collision_Info> rets       = new List <WebCache_FileHash_Collision_Info>();
                foreach (WebCache_FileHash_Collision c in collisions)
                {
                    string uname = null;
                    if (users.ContainsKey(c.AniDBUserId))
                    {
                        uname = users[c.AniDBUserId];
                    }
                    else
                    {
                        WebCache_User k = await _db.Users.FirstOrDefaultAsync(a => a.AniDBUserId == c.AniDBUserId);

                        if (k != null)
                        {
                            users.Add(c.AniDBUserId, k.AniDBUserName);
                            uname = k.AniDBUserName;
                        }
                    }

                    if (uname != null)
                    {
                        rets.Add(c.ToCollisionInfo(uname));
                    }
                }

                return(new JsonResult(rets));
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"GETCOLLISIONS with Token={token}");
                return(StatusCode(500));
            }
        }
Exemple #16
0
        public async Task <IActionResult> ProviderManage(string token, int id, bool approve)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                if ((s.Role & WebCache_RoleType.Admin) == 0)
                {
                    return(StatusCode(403, "Admin Only"));
                }
                //Exists already?
                Models.Database.WebCache_CrossRef_AniDB_Provider r = await _db.CrossRef_AniDB_Providers.FirstOrDefaultAsync(a => a.WebCache_AniDB_ProviderID == id);

                if (r == null)
                {
                    return(StatusCode(404, "CrossRef Not Found"));
                }
                if (approve)
                {
                    r.Approved = WebCache_RoleType.Admin;
                    List <Models.Database.WebCache_CrossRef_AniDB_Provider> reset_admins = await _db.CrossRef_AniDB_Providers.Where(a => a.AnimeID == r.AnimeID && a.CrossRefType == r.CrossRefType && a.AniDBUserId != s.AniDBUserId && a.Approved == WebCache_RoleType.Admin && a.WebCache_AniDB_ProviderID != r.WebCache_AniDB_ProviderID).ToListAsync();

                    foreach (Models.Database.WebCache_CrossRef_AniDB_Provider w in reset_admins)
                    {
                        w.Approved = WebCache_RoleType.None;
                    }
                }
                else
                {
                    r.Approved = WebCache_RoleType.None;
                }

                r.AniDBUserId = s.AniDBUserId;
                await _db.SaveChangesAsync();

                return(Ok());
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"PROVIDERMANAGE with Token={token} Id={id} Approval:{approve}");
                return(StatusCode(500));
            }
        }
        internal async Task <SessionInfoWithError> VerifyTokenAsync(string token, bool force = false)
        {
            WebCache_Session s = await _db.Sessions.FirstOrDefaultAsync(a => a.Token == token);

            if (s == null)
            {
                return new SessionInfoWithError {
                           Error = StatusCode(403, "Invalid Token")
                }
            }
            ;
            if (s.Expiration < DateTime.UtcNow)
            {
                //Lets reuse this call to kill em all, and do some database cleaning.
                _db.RemoveRange(_db.Sessions.Where(a => a.Expiration < DateTime.UtcNow));

                await _db.SaveChangesAsync();

                return(new SessionInfoWithError {
                    Error = StatusCode(403, "Invalid Token")
                });
            }

            if (s.Expiration.AddHours(-8) < DateTime.UtcNow || force) //Refresh Expiration if we have less than 8 hours left
            {
                s.Expiration = DateTime.UtcNow.AddHours(GetTokenExpirationInHours());
                await _db.SaveChangesAsync();
            }

            WebCache_Ban b = GetBan(s.AniDBUserId);

            if (b != null)
            {
                return new SessionInfoWithError {
                           Error = StatusCode(403, "Banned: " + b.Reason + " Expiration:" + b.ExpirationUTC.ToLongDateString())
                }
            }
            ;
            SessionInfoWithError si = new SessionInfoWithError {
                AniDBUserId = s.AniDBUserId, AniDBUserName = s.AniDBUserName, Expiration = s.Expiration, Token = s.Token
            };

            si.Role  = GetRole(s.AniDBUserId);
            si.Error = null;
            return(si);
        }
Exemple #18
0
        private async Task <IActionResult> GetProviderInternal(SessionInfoWithError s, int animeId, CrossRefType crossRefType)
        {
            List <WebCache_CrossRef_AniDB_Provider> results = new List <WebCache_CrossRef_AniDB_Provider>();

            //First check for admin approved link
            Models.Database.WebCache_CrossRef_AniDB_Provider r = await _db.CrossRef_AniDB_Providers.FirstOrDefaultAsync(a => a.Approved == WebCache_RoleType.Admin && a.AnimeID == animeId && a.CrossRefType == crossRefType);

            if (r != null)
            {
                results.Add(r.ToWebCache(WebCache_ReliabilityType.AdminVerified, 0));
                if ((s.Role & WebCache_RoleType.Admin) == 0)
                {
                    return(new JsonResult(results));
                }
                //If not Admin, early exit, otherwise other admin might want to evaluate
            }

            //Second Check for Moderator Approved Link
            List <Models.Database.WebCache_CrossRef_AniDB_Provider> rl = await _db.CrossRef_AniDB_Providers.Where(a => a.Approved == WebCache_RoleType.Moderator && a.AnimeID == animeId && a.CrossRefType == crossRefType).ToListAsync();

            if (rl.Count > 0)
            {
                results.AddRange(rl.Select(a => a.ToWebCache(WebCache_ReliabilityType.ModeratorVerified, 0)));
            }
            //Then The user link
            r = await _db.CrossRef_AniDB_Providers.FirstOrDefaultAsync(a => a.AniDBUserId == s.AniDBUserId && a.AnimeID == animeId && a.CrossRefType == crossRefType);

            if (r != null)
            {
                results.Add(r.ToWebCache(WebCache_ReliabilityType.User, 0));
            }
            //And Now, the popular ones.
            var res = await _db.CrossRef_AniDB_Providers.Where(a => a.AnimeID == animeId && a.CrossRefType == crossRefType && a.Approved == WebCache_RoleType.None).GroupBy(a => new { a.CrossRefID, a.EpisodesOverrideData }).Select(a => new { Count = a.Count(), Result = a.First() }).OrderByDescending(a => a.Count).Take(5).ToListAsync();

            foreach (var n in res)
            {
                results.Add(n.Result.ToWebCache(WebCache_ReliabilityType.Popular, n.Count));
            }

            if (results.Count > 0)
            {
                return(new JsonResult(results));
            }
            return(StatusCode(404, "CrossRef Not Found"));
        }
Exemple #19
0
        public async Task <IActionResult> GetProvider(string token, int animeId, int crossRefType)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                return(await GetProviderInternal(s, animeId, (CrossRefType)crossRefType));
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"GETPROVIDER with Token={token} AnimeId={animeId} CrossRefType={(CrossRefType)crossRefType}");
                return(StatusCode(500));
            }
        }
        public async Task <IActionResult> RefreshSession(string token)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token, true);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                return(new JsonResult(s));
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"REFRESHSESSION with Token={token}");
                return(StatusCode(500));
            }
        }
Exemple #21
0
        public async Task <IActionResult> AddHash(string token, [FromBody] WebCache_FileHash hash)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                if (await InternalAddHash(s, hash))
                {
                    await _db.SaveChangesAsync();
                }
                return(Ok());
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"ADDHASH with Token={token} ED2K={hash.ED2K}");
                return(StatusCode(500));
            }
        }
        public async Task <IActionResult> AddMediaInfo(string token, [FromBody] WebCache_Media media)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                media.ED2K = media.ED2K.ToUpperInvariant();
                if (await AddMediaInfoInternal(s, media))
                {
                    await _db.SaveChangesAsync();
                }
                return(Ok());
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"ADDMEDIAINFO with Token={token} ED2K={media.ED2K} Version={media.Version}");
                return(StatusCode(500));
            }
        }
        public async Task <IActionResult> Ban(string token, WebCache_Ban ban)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                if ((s.Role & WebCache_RoleType.Admin) == 0)
                {
                    return(StatusCode(403, "Admin Only"));
                }
                SetBan(ban.AniDBUserId, ban.Reason, ban.Hours);
                return(Ok());
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"BAN with Token={token} Userid={ban.AniDBUserId} Reason={ban.Reason ?? "null"} Hours: {ban.Hours}");
                return(StatusCode(500));
            }
        }
Exemple #24
0
        public async Task <IActionResult> GetFileEpisodes(string token, string hash)
        {
            try
            {
                SessionInfoWithError s = await VerifyTokenAsync(token);

                if (s.Error != null)
                {
                    return(s.Error);
                }
                List <CrossRef_File_Episode> ep = await _db.CrossRef_File_Episodes.Where(a => a.Hash == hash && a.AniDBUserId == s.AniDBUserId).Cast <CrossRef_File_Episode>().ToListAsync();

                if (ep.Count == 0)
                {
                    return(StatusCode(404, "CrossRef Not Found"));
                }
                return(new JsonResult(ep));
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"GETFILEEPISODES with Token={token} Hash={hash}");
                return(StatusCode(500));
            }
        }
Exemple #25
0
        private async Task AddProviderInternal(SessionInfoWithError s, WebCache_CrossRef_AniDB_Provider cross, bool?approve)
        {
            Models.Database.WebCache_CrossRef_AniDB_Provider r = await _db.CrossRef_AniDB_Providers.FirstOrDefaultAsync(a => a.AniDBUserId == s.AniDBUserId && a.AnimeID == cross.AnimeID && a.CrossRefType == cross.CrossRefType);

            if (r == null)
            {
                r = new Models.Database.WebCache_CrossRef_AniDB_Provider();
                _db.Add(r);
            }

            WebCache_RoleType rt = GetRole(s.AniDBUserId);

            r.FillWith(cross);
            //If user is Admin, and this come with approve flag, let approve it, and clean any other approval from the db
            if ((rt & WebCache_RoleType.Admin) > 0 && approve.HasValue && approve.Value)
            {
                r.Approved = WebCache_RoleType.Admin;
                List <Models.Database.WebCache_CrossRef_AniDB_Provider> reset_admins = await _db.CrossRef_AniDB_Providers.Where(a => a.AnimeID == cross.AnimeID && a.CrossRefType == cross.CrossRefType && a.AniDBUserId != s.AniDBUserId && a.Approved == WebCache_RoleType.Admin).ToListAsync();

                foreach (Models.Database.WebCache_CrossRef_AniDB_Provider w in reset_admins)
                {
                    w.Approved = WebCache_RoleType.None;
                }
            }
            //If moderator, simple tag it.
            else if ((rt & WebCache_RoleType.Moderator) > 0)
            {
                r.Approved = WebCache_RoleType.Moderator;
            }
            else
            {
                r.Approved = WebCache_RoleType.None;
            }

            r.AniDBUserId = s.AniDBUserId;
        }
        public async Task <IActionResult> Verify(WebCache_AniDBLoggedInfo data)
        {
            try
            {
                CookieContainer cookieContainer = new CookieContainer();
                using (var handler = new HttpClientHandler {
                    CookieContainer = cookieContainer
                })
                    using (var client = new HttpClient(handler))
                    {
                        string curi  = GetAniDBUserVerificationUri();
                        string regex = GetAniDBUserVerificationRegEx();
                        client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", User_Agent);
                        Uri   uri = new Uri(curi);
                        Regex rn  = new Regex(regex, RegexOptions.Singleline);
                        foreach (string k in data.Cookies.Keys)
                        {
                            cookieContainer.Add(new Cookie(k, data.Cookies[k], "/", uri.Host));
                        }
                        HttpRequestMessage  request  = new HttpRequestMessage(HttpMethod.Get, uri);
                        HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead);

                        if (response.IsSuccessStatusCode)
                        {
                            string str = await response.Content.ReadAsStringAsync();

                            response.Dispose();
                            Match m = rn.Match(str);
                            if (m.Success)
                            {
                                if (m.Groups.Count > 1)
                                {
                                    string val = m.Groups["username"]?.Value;
                                    string id  = m.Groups["id"]?.Value;
                                    int    aniid;
                                    if (val != null && id != null && int.TryParse(id, out aniid))
                                    {
                                        if (string.Compare(val, data.UserName, StringComparison.InvariantCultureIgnoreCase) == 0)
                                        {
                                            uri = new Uri(GetAniDBLogoutUri());
                                            try
                                            {
                                                request  = new HttpRequestMessage(HttpMethod.Get, uri);
                                                response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

                                                response.Dispose();
                                            }
                                            catch (Exception)
                                            {
                                                //ignore
                                            }
                                            WebCache_User u = await _db.Users.FirstOrDefaultAsync(a => a.AniDBUserId == aniid);

                                            if (u == null)
                                            {
                                                u               = new WebCache_User();
                                                u.AniDBUserId   = aniid;
                                                u.AniDBUserName = val;
                                                _db.Add(u);
                                            }
                                            else if (u.AniDBUserName != val)
                                            {
                                                u.AniDBUserName = val;
                                            }
                                            WebCache_Session s = new WebCache_Session();
                                            s.Token         = Guid.NewGuid().ToString().Replace("-", string.Empty);
                                            s.Expiration    = DateTime.UtcNow.AddHours(GetTokenExpirationInHours());
                                            s.AniDBUserName = val;
                                            s.AniDBUserId   = aniid;
                                            _db.Add(s);
                                            await _db.SaveChangesAsync();

                                            SessionInfoWithError si = new SessionInfoWithError {
                                                AniDBUserId = s.AniDBUserId, AniDBUserName = s.AniDBUserName, Expiration = s.Expiration, Token = s.Token
                                            };
                                            si.Role  = GetRole(s.AniDBUserId);
                                            si.Error = null;
                                            return(new JsonResult(s));
                                        }
                                    }
                                }
                            }
                        }
                    }

                return(StatusCode(403, "Invalid credentials"));
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"VERIFY with UserName={data.UserName}");
                return(StatusCode(500));
            }
        }
Exemple #27
0
        private async Task <bool> InternalAddHash(SessionInfoWithError s, WebCache_FileHash hash)
        {
            bool update = false;

            if (string.IsNullOrEmpty(hash.ED2K) || string.IsNullOrEmpty(hash.CRC32) || string.IsNullOrEmpty(hash.MD5) || string.IsNullOrEmpty(hash.SHA1) || hash.FileSize == 0)
            {
                return(false);
            }
            hash.ED2K  = hash.ED2K.ToUpperInvariant();
            hash.CRC32 = hash.CRC32.ToUpperInvariant();
            hash.MD5   = hash.MD5.ToUpperInvariant();
            hash.SHA1  = hash.SHA1.ToUpperInvariant();
            WebCache_FileHash_Info ed2k = await _db.WebCache_FileHashes.FirstOrDefaultAsync(a => a.ED2K == hash.ED2K);

            WebCache_FileHash_Info md5 = await _db.WebCache_FileHashes.FirstOrDefaultAsync(a => a.MD5 == hash.MD5);

            WebCache_FileHash_Info sha1 = await _db.WebCache_FileHashes.FirstOrDefaultAsync(a => a.SHA1 == hash.SHA1);

            WebCache_FileHash_Info orig = new WebCache_FileHash_Info();

            orig.FillWith(hash);
            orig.AniDBUserId  = s.AniDBUserId;
            orig.CreationDate = DateTime.UtcNow;
            if (ed2k == null && md5 == null && sha1 == null) //Not CRC, we may get a normal collision in CRC
            {
                _db.Add(orig);
                update = true;
            }
            else
            {
                List <WebCache_FileHash_Info> collisions = new List <WebCache_FileHash_Info>();
                // ReSharper disable PossibleNullReferenceException
                if (ed2k.CRC32 != hash.CRC32 || ed2k.FileSize != hash.FileSize || ed2k.SHA1 != hash.SHA1 || ed2k.MD5 != hash.MD5)
                {
                    collisions.Add(ed2k);
                }

                if (md5.CRC32 != hash.CRC32 || md5.FileSize != hash.FileSize || md5.SHA1 != hash.SHA1 || md5.ED2K != hash.ED2K)
                {
                    if (!collisions.Contains(md5))
                    {
                        collisions.Add(md5);
                    }
                }

                if (sha1.CRC32 != hash.CRC32 || sha1.FileSize != hash.FileSize || sha1.MD5 != hash.MD5 || sha1.ED2K != hash.ED2K)
                {
                    if (!collisions.Contains(sha1))
                    {
                        collisions.Add(sha1);
                    }
                }
                // ReSharper restore PossibleNullReferenceException

                if (collisions.Count > 0)
                {
                    if (collisions.Any(b => b.CollisionApproved))
                    {
                        return(false); //We already have the approved one, so this new one is wrong
                    }
                    collisions.Add(orig);
                    string unique = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    _db.AddRange(collisions.Select(a => a.ToCollision(unique)));
                    update = true;
                }
            }

            return(update);
        }