예제 #1
0
        public static async Task <ResultsItem> DeleteBBThread(int threadId, LocalAccount.PegaUser user)
        {
            try
            {
                using (PegasunDBContext db = new PegasunDBContext())
                {
                    BBThreads serviceThread = db.BBThreads.FirstOrDefault(x => x.ThreadId == threadId);
                    if (serviceThread == null)
                    {
                        return(ResultsItem.Error("This thread was not found or has already been deleted."));
                    }
                    if (serviceThread.UserId != user.UserId)
                    {
                        return(ResultsItem.Error("This thread belongs to another user."));
                    }

                    db.Remove(serviceThread);
                    await db.SaveChangesAsync();

                    return(ResultsItem.Success("Successfully deleted this thread. Please refresh the page to see changes."));
                }
            }
            catch (Exception ex)
            {
                Utilities.LogException(new[] { $"User:{user.Username}" }, ex);
                return(ResultsItem.Error($"Unable to delete this thread. {ex.Message}"));
            }
        }
예제 #2
0
        public static ResultsPair <LocalAccount.PegaUser> ViewUserProfile(string username)
        {
            using (PegasunDBContext db = new PegasunDBContext())
            {
                var user = db.Users.FirstOrDefault(x => x.Username == username);
                if (user == null)
                {
                    return(ResultsPair.CreateError <LocalAccount.PegaUser>($"Could not find the user {username}."));
                }

                var portfolios = db.Portfolios.Where(x => x.UserId == user.UserId && x.DisplayType == 3).ToList();

                LocalAccount.PegaUser localUser = user.Adapt <LocalAccount.PegaUser>();
                localUser.Portfolios           = portfolios.Adapt <List <LocalCoins.Portfolio> >();
                localUser.TotalCreatedThreads  = db.BBThreads.Count(x => x.UserId == user.UserId);
                localUser.TotalCreatedComments = db.BBComments.Count(x => x.UserId == user.UserId);

                return(ResultsPair.CreateSuccess(localUser));
            }
        }
예제 #3
0
        public static async Task <ResultsItem> CreateBBThread(LocalCommunity.BBThread thread, LocalAccount.PegaUser user)
        {
            try
            {
                using (PegasunDBContext db = new PegasunDBContext())
                {
                    thread.Message = thread.Message.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM });
                    thread.UserId  = user.UserId;

                    BBThreads serviceMessageThread = thread.Adapt <BBThreads>();
                    serviceMessageThread.CreateDate = DateTime.Now;
                    serviceMessageThread.UserId     = user.UserId;
                    serviceMessageThread.Message    = serviceMessageThread.Message.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM });
                    serviceMessageThread.Title      = serviceMessageThread.Title.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM });

                    db.BBThreads.Add(serviceMessageThread);
                    await db.SaveChangesAsync();

                    return(ResultsItem.Success("Successfully created a new thread"));
                }
            }
            catch (Exception ex)
            {
                Utilities.LogException(new[] { $"User:{user.Username}" }, ex);
                return(ResultsItem.Error($"Unable to create a new thread. {ex.Message}"));
            }
        }
예제 #4
0
        public static async Task <LocalCommunity.BBThread> GetBBThreadWithComments(int threadId, LocalAccount.PegaUser currentUser)
        {
            try
            {
                using (PegasunDBContext db = new PegasunDBContext())
                {
                    var getThreadTask   = GetBBThreadsFromDB(db, currentUser, threadId: threadId);
                    var getCommentsTask = GetBBThreadCommentsFromDB(db, threadId, currentUser);

                    LocalCommunity.BBThread         thread   = (await getThreadTask).FirstOrDefault();
                    List <LocalCommunity.BBComment> comments = await getCommentsTask;

                    if (thread == null)
                    {
                        return(null);
                    }

                    thread.ThreadComments = comments;
                    thread.ThreadName     = "thread_" + thread.ThreadId;

                    return(thread);
                }
            }
            catch (Exception ex)
            {
                Utilities.LogException(new[] { $"ThreadId:{threadId}" }, ex);
                return(new LocalCommunity.BBThread());
            }
        }
예제 #5
0
        private static async Task <List <LocalCommunity.BBComment> > GetBBThreadCommentsFromDB(PegasunDBContext db, int threadId, LocalAccount.PegaUser currentUser)
        {
            var query = db.BBComments.Select(x => new
            {
                BBComment  = x,
                User       = new { x.User.UserId, x.User.Username, x.User.Email },
                VoteResult = new { TotalVotes = x.BBCommentVotes.Count, TotalUpvotes = x.BBCommentVotes.Count(v => v.IsUpvote) }
            });

            var result = await query.Where(x => x.BBComment.ThreadId == threadId).ToListAsync();

            List <LocalCommunity.BBComment> comments = new List <LocalCommunity.BBComment>();

            result.ForEach(r =>
            {
                LocalCommunity.BBComment comment = r.BBComment.Adapt <LocalCommunity.BBComment>();
                comment.User                  = r.User.Adapt <LocalAccount.PegaUser>();
                comment.VoteResult            = r.VoteResult.Adapt <LocalCommunity.VoteResult>();
                comment.CurrentLoggedInUserID = (currentUser?.UserId).GetValueOrDefault();

                comments.Add(comment);
            });

            return(comments);
        }
예제 #6
0
        private static async Task <List <LocalCommunity.BBThread> > GetBBThreadsFromDB(PegasunDBContext db, LocalAccount.PegaUser currentUser, int?take = null, int?threadId = null,
                                                                                       List <Types.ConvThreadCategory> categories = null, int officialCoindId = 0)
        {
            if ((take == null || categories.IsNullOrEmpty()) && threadId == null)
            {
                throw new Exception("GetMessageThread: Not all parameters were passed in correctly.");
            }

            var query = db.BBThreads.OrderByDescending(x => x.CreateDate).Select(x => new
            {
                BBThread      = x,
                User          = new { x.User.UserId, x.User.Username, x.User.Email },
                VoteResult    = new { TotalVotes = x.BBThreadVotes.Count, TotalUpvotes = x.BBThreadVotes.Count(v => v.IsUpvote) },
                TotalComments = x.BBComments.Count
            });

            var result = threadId.GetValueOrDefault() > 0 ? await query.Where(x => x.BBThread.ThreadId == threadId).ToListAsync()
                                                          : officialCoindId > 0
                                                               ? await query.Where(x => x.BBThread.OfficialCoinId == officialCoindId).Take(take.GetValueOrDefault()).ToListAsync()
                                                               : await query.Where(x => categories.Any(c => (short)c == x.BBThread.CategoryCode)).Take(take.GetValueOrDefault()).ToListAsync();

            List <LocalCommunity.BBThread> threads = new List <LocalCommunity.BBThread>();

            result.ForEach(r =>
            {
                LocalCommunity.BBThread thread = r.BBThread.Adapt <LocalCommunity.BBThread>();
                thread.User                  = r.User.Adapt <LocalAccount.PegaUser>();
                thread.VoteResult            = r.VoteResult.Adapt <LocalCommunity.VoteResult>();
                thread.TotalComments         = r.TotalComments;
                thread.CurrentLoggedInUserID = (currentUser?.UserId).GetValueOrDefault();

                threads.Add(thread);
            });

            return(threads);
        }
예제 #7
0
        public static async Task <ResultsItem> VoteBBComment(long commentId, bool isUpvote, LocalAccount.PegaUser user)
        {
            try
            {
                string message = "Successfully updated your vote. It will be reflected shortly.";
                using (PegasunDBContext db = new PegasunDBContext())
                {
                    var getServiceCommentTask = db.BBComments.FirstOrDefaultAsync(x => x.CommentId == commentId);
                    var getExistingVoteTask   = db.BBCommentVotes.FirstOrDefaultAsync(x => x.CommentId == commentId && x.UserId == user.UserId);

                    var serviceComment = await getServiceCommentTask;
                    var existingVote   = await getExistingVoteTask;

                    if (serviceComment == null)
                    {
                        return(ResultsItem.Error("This comment does not exist."));
                    }
                    if (existingVote != null)
                    {
                        if (existingVote.IsUpvote == isUpvote)
                        {
                            db.Remove(existingVote); message = "Successfully removed your vote. It will be reflected shortly.";
                        }                                                                                                                                              // Same vote (e.g. clicked on upvote twice), which means they are re-tracing their vote.
                        else
                        {
                            existingVote.IsUpvote = isUpvote;
                        }
                    }
                    else
                    {
                        var newServiceVote = new BBCommentVotes
                        {
                            CommentId = commentId,
                            IsUpvote  = isUpvote,
                            UserId    = user.UserId
                        };
                        db.BBCommentVotes.Add(newServiceVote);
                    }

                    db.SaveChanges();
                    return(ResultsItem.Success(message));
                }
            }
            catch (Exception ex)
            {
                Utilities.LogException(new[] { $"User:{user.Username}", $"CommentId:{commentId}" }, ex);
                return(ResultsItem.Error($"Unable to submit your vote. {ex.Message}"));
            }
        }
예제 #8
0
        // CurrentUser can be null
        public static async Task <List <LocalCommunity.BBThread> > GetBBThreads(int take, List <Types.ConvThreadCategory> categories, LocalAccount.PegaUser currentUser, int officialCoinId = 0)
        {
            try
            {
                using (PegasunDBContext db = new PegasunDBContext())
                {
                    List <LocalCommunity.BBThread> threads = await GetBBThreadsFromDB(db, currentUser, take : take, categories : categories, officialCoindId : officialCoinId);

                    return(threads);
                }
            }
            catch (Exception ex)
            {
                Utilities.LogException(new[] { $"Category:{string.Join(",", categories)}" }, ex);
                return(new List <LocalCommunity.BBThread>());
            }
        }
예제 #9
0
        public static async Task <ResultsItem> CreateBBComment(LocalCommunity.BBComment comment, LocalAccount.PegaUser user)
        {
            try
            {
                using (PegasunDBContext db = new PegasunDBContext())
                {
                    comment.Message.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM });

                    BBComments serviceComment = comment.Adapt <BBComments>();
                    serviceComment.CreateDate = DateTime.Now;
                    serviceComment.UserId     = user.UserId;
                    serviceComment.Message    = serviceComment.Message.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM });

                    db.BBComments.Add(serviceComment);
                    await db.SaveChangesAsync();

                    return(ResultsItem.Success("Successfully posted a new comment."));
                }
            }
            catch (Exception ex)
            {
                Utilities.LogException(new[] { $"User:{user.Username}" }, ex);
                return(ResultsItem.Error($"Unable to create a comment. {ex.Message}"));
            }
        }
예제 #10
0
        public static async Task <List <ImportedCoin> > ApiImport_GDax(string encryptedApiPublic, string encryptedApiSecret, string passphrase, LocalAccount.PegaUser user)
        {
            string apiKey    = Cryptography.Decrypt(encryptedApiPublic, Types.EncryptionType.ApiKey_Public, user);  //"c6b8915e430a662b1ee2563e710d8a51";
            string apiSecret = Cryptography.Decrypt(encryptedApiSecret, Types.EncryptionType.ApiKey_Private, user); // "4cIDR3rTUJtQvCnrrr5wGQvcvbeBef0Cy/JTmTmfr4C38rdL1+wEDuTG8jztU1ZXlu6Z2Pti7nWCwUouG463tQ==";

            string url           = "https://api.gdax.com/fills";
            int    timeStamp     = Utilities.GetCurrentEpochTime();
            string toSignMessage = timeStamp + "GET" + "/fills";

            string signKey;

            using (var hmac = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(apiSecret)))
            {
                signKey = Convert.ToBase64String(hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(toSignMessage)));
            }

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("User-Agent", "PegaTrade_APICaller");
                client.DefaultRequestHeaders.Add("CB-ACCESS-KEY", apiKey);
                client.DefaultRequestHeaders.Add("CB-ACCESS-SIGN", signKey);
                client.DefaultRequestHeaders.Add("CB-ACCESS-TIMESTAMP", timeStamp.ToString());
                client.DefaultRequestHeaders.Add("CB-ACCESS-PASSPHRASE", passphrase);

                string jsonResult = await client.GetStringAsync(url);

                List <API_GDaxImportResult> result = Deserialize <List <API_GDaxImportResult> >(jsonResult);

                if (!result.IsNullOrEmpty())
                {
                    return(result.Where(x => x.settled).Select(x => new ImportedCoin
                    {
                        Symbol = "USD-" + x.product_id.Replace("-USD", string.Empty),
                        Shares = Convert.ToDecimal(x.size),
                        OrderDate = x.created_at,
                        OrderType = x.side,
                        TotalPricePaidInCurrency = (Convert.ToDecimal(x.price) * Convert.ToDecimal(x.size)),
                        Exchange = Types.Exchanges.GDax
                    }).ToList());
                }
                return(new List <ImportedCoin>());
            }
        }
예제 #11
0
        public static async Task <List <ImportedCoin> > ApiImport_BitTrex(string encryptedApiPublic, string encryptedApiSecret, LocalAccount.PegaUser user)
        {
            string apiKey    = Cryptography.Decrypt(encryptedApiPublic, Types.EncryptionType.ApiKey_Public, user);  // 3df1e84424d2416a9284804f67ce21ca
            string apiSecret = Cryptography.Decrypt(encryptedApiSecret, Types.EncryptionType.ApiKey_Private, user); // 3fca8d88270f4bfeb56742bf5fd70841

            string url = "https://bittrex.com/api/v1.1/account/getorderhistory";

            int    nonce   = Utilities.GetCurrentEpochTime();
            string uri     = $"{url}?apikey={apiKey}&nonce={nonce}&count=100";
            string signKey = Utilities.GenerateHmacSHA512Hash(uri, apiSecret);

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("apisign", signKey);
                string jsonResult = await client.GetStringAsync(uri);

                API_BitTrexImportResult result = Newtonsoft.Json.JsonConvert.DeserializeObject <API_BitTrexImportResult>(jsonResult);

                if (result != null && result.success)
                {
                    return(result.result.Select(x => new ImportedCoin
                    {
                        Symbol = x.Exchange,
                        Shares = Convert.ToDecimal(x.Quantity),
                        OrderDate = DateTime.Parse(x.TimeStamp),
                        OrderType = x.OrderType,
                        TotalPricePaidInCurrency = Convert.ToDecimal(x.Price),
                        Exchange = Types.Exchanges.BitTrex
                    }).ToList());
                }
                return(new List <ImportedCoin>());
            }
        }
예제 #12
0
        public static async Task <ResultsPair <List <LocalCoins.CryptoCoin> > > ApiImport_EtherAddress(List <LocalCoins.MarketCoin> marketCoins, string etherAddress, int portfolioId, LocalAccount.PegaUser user)
        {
            ResultsPair <List <LocalCoins.CryptoCoin> > generateError(string errorMessage) => ResultsPair.CreateError <List <LocalCoins.CryptoCoin> >(errorMessage);

            LocalCoins.CryptoCoin generateCoin(string symbol, decimal shares, decimal pricePerUnit)
            {
                return(new LocalCoins.CryptoCoin
                {
                    CoinCurrency = Types.CoinCurrency.USD,
                    Exchange = Types.Exchanges.EtherAddressLookup,
                    OrderDate = DateTime.Now,
                    OrderType = Types.OrderType.Buy,
                    PortfolioId = portfolioId,
                    Shares = shares,
                    TotalPricePaidUSD = shares * pricePerUnit,
                    PricePerUnit = pricePerUnit,
                    Symbol = symbol
                });
            }

            if (etherAddress.Length != 42)
            {
                return(generateError("This ethereum address is not valid."));
            }

            string url = $"https://api.ethplorer.io/getAddressInfo/{etherAddress}?apiKey=freekey";

            using (HttpClient client = new HttpClient())
            {
                string jsonResult = await client.GetStringAsync(url);

                if (string.IsNullOrEmpty(jsonResult))
                {
                    return(generateError("An error has occured while calling the API endpoint"));
                }

                API_EthplorerAddressLookup result = Newtonsoft.Json.JsonConvert.DeserializeObject <API_EthplorerAddressLookup>(jsonResult);
                if (result != null)
                {
                    List <LocalCoins.CryptoCoin> coins = new List <LocalCoins.CryptoCoin>();
                    if (result.Eth.Balance > 0)
                    {
                        coins.Add(generateCoin("USD-ETH", (decimal)result.Eth.Balance, marketCoins.First(x => x.Symbol == "ETH").CurrentSymbolPriceUSD));

                        if (!result.Tokens.IsNullOrEmpty())
                        {
                            foreach (var x in result.Tokens.Where(x => x.TokenInfo != null && x.Balance > 0))
                            {
                                try
                                {
                                    LocalCoins.MarketCoin marketCoin = marketCoins.FirstOrDefault(m => m.Name.ToUpper() == x.TokenInfo.Name.ToUpper());
                                    if (marketCoin == null)
                                    {
                                        marketCoin = marketCoins.FirstOrDefault(m => m.Symbol.ToUpper() == x.TokenInfo.Symbol.ToUpper());
                                    }
                                    if (marketCoin == null)
                                    {
                                        continue;
                                    }

                                    double  tokenDecimals = x.TokenInfo.Decimals;
                                    decimal shares        = tokenDecimals <= 0 ? (decimal)x.Balance : (decimal)(x.Balance / Math.Pow(10, x.TokenInfo.Decimals));

                                    coins.Add(generateCoin($"USD-{x.TokenInfo.Symbol}", shares, marketCoin.CurrentSymbolPriceUSD));
                                }
                                catch { }
                            }
                            ;
                        }
                    }

                    return(ResultsPair.CreateSuccess(coins));
                }

                return(generateError("Something went wrong, or you may not have any coins to import"));
            }
        }
예제 #13
0
        // Creates a new user and then redirects them to the login page.
        public static async Task <ResultsPair <LocalAccount.PegaUser> > CreateNewUser(LocalAccount.PegaUser user)
        {
            using (HttpClient client = new HttpClient())
            {
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("Username", user.Username),
                    new KeyValuePair <string, string>("Password", user.Password),
                    new KeyValuePair <string, string>("Email", user.Email),
                    new KeyValuePair <string, string>("EmailSubscribePreferenceCode", ((int)EmailPreferences.Default).ToString()),
                    new KeyValuePair <string, string>("platform", ((int)Platform.PegaTrade).ToString())
                });

                HttpResponseMessage response = await client.PostAsync($"{baseUrl}/v1/Account/Create", content);

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

                    ResultsItem createUserResult = NetJSON.NetJSON.Deserialize <PegasunAPIResult>(jsonString).ConvertToResultsItem();
                    if (createUserResult.ResultType == ResultsType.Successful)
                    {
                        var getUserResult = await AuthorizeUser(user.Username, user.Password);

                        if (!getUserResult.Result.IsSuccess)
                        {
                            return(getUserResult);
                        }

                        return(ResultsPair.Create(createUserResult, getUserResult.Value));
                    }

                    return(ResultsPair.CreateError <LocalAccount.PegaUser>(createUserResult.Message));
                }
            }

            return(ResultsPair.CreateError <LocalAccount.PegaUser>(Lang.ServerConnectionError));
        }
예제 #14
0
        private static async Task <ResultsPair <LocalAccount.PTUserInfo> > CreateNewPTUserInfo(LocalAccount.PegaUser user)
        {
            try
            {
                using (PegasunDBContext db = new PegasunDBContext())
                {
                    PTUserInfo ptUserInfo = new PTUserInfo
                    {
                        UserId                 = user.UserId,
                        SubscriptionLevel      = (byte)SubscriptionLevel.Free,
                        SubscriptionExpireDate = null
                    };

                    db.PTUserInfo.Add(ptUserInfo);
                    await db.SaveChangesAsync();

                    LocalAccount.PTUserInfo localSubscription = ptUserInfo.Adapt <LocalAccount.PTUserInfo>();

                    return(ResultsPair.Create(ResultsItem.Success("Successfully created a new subscription."), localSubscription));
                }
            }
            catch (Exception ex)
            {
                return(ResultsPair.CreateError <LocalAccount.PTUserInfo>($"Unable to create a new PTUserInfo: {ex.Message}"));
            }
        }