示例#1
0
        public async Task <IMessageWriterResult> SendMessage(string optionsJson, ILogger logger)
        {
            logger.LogTrace("Starting SendMessage");
            IMessageWriterOptions options = null;
            IMessageWriterResult  Result  = null;

            try
            {
                options = performOptionsCast(optionsJson, logger);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Failed to cast message options json into an object!");
                Result = new WriterResult()
                {
                    MessageIdentifier = null,
                    MessageSent       = false,
                    ReasonFailed      = ex
                };
            }
            if (options != null)
            {
                try
                {
                    if (string.IsNullOrEmpty(options.MessageIdentifier))
                    {
                        var messageIdentifier = Guid.NewGuid().ToString();
                        logger.LogDebug($"The options object was missing a message identifier... Using generated identifier: {messageIdentifier}");
                        options.MessageIdentifier = messageIdentifier;
                    }

                    if (!options.IsValid())
                    {
                        throw new ArgumentException("Ohe value is not valid", "options");
                    }
                    logger.LogDebug($"About to attempt sending a message. type = {options.MessageType} : id = {options.MessageIdentifier}");
                    Result = await PerformSend(options, logger);

                    logger.LogDebug($"Finished sending, success = {Result.MessageSent}");
                    Result = new WriterResult()
                    {
                        MessageIdentifier = options.MessageIdentifier,
                        MessageSent       = true,
                        ReasonFailed      = null
                    };
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "SendMessage threw an error!");
                    Result = new WriterResult()
                    {
                        MessageIdentifier = options.MessageIdentifier,
                        MessageSent       = false,
                        ReasonFailed      = ex
                    };
                }
            }
            logger.LogTrace("Ending SendMessage");
            return(Result);
        }
示例#2
0
        public async Task <IWriterResult <bool> > AdminUpdateVoteItem(string userId, UpdateVoteItemModel model)
        {
            using (var context = DataContextFactory.CreateContext())
            {
                var voteItem = await context.VoteItem.FirstOrDefaultNoLockAsync(x => x.Id == model.Id);

                if (voteItem == null)
                {
                    return(WriterResult <bool> .ErrorResult("VoteItem {0} not found.", model.Id));
                }

                if (model.Status == VoteItemStatus.Deleted)
                {
                    context.VoteItem.Remove(voteItem);
                }
                else
                {
                    voteItem.AdminNote   = model.Note;
                    voteItem.Name        = model.Name;
                    voteItem.Source      = model.Source;
                    voteItem.Status      = model.Status;
                    voteItem.Symbol      = model.Symbol;
                    voteItem.Website     = model.Website;
                    voteItem.AlgoType    = model.AlgoType;
                    voteItem.Description = model.Description;
                }

                var contextResults = await context.SaveChangesWithLoggingAsync();

                return(WriterResult <bool> .ContextResult(contextResults));
            }
        }
示例#3
0
    public static Writer <W, V> SelectMany <W, T, U, V>(
        this Writer <W, T> self,
        Func <T, Writer <W, U> > bind,
        Func <T, U, V> project
        )
    {
        if (bind == null)
        {
            throw new ArgumentNullException(nameof(bind));
        }
        if (project == null)
        {
            throw new ArgumentNullException(nameof(project));
        }

        return(() =>
        {
            var resT = self.Valid()();
            if (resT.IsBottom)
            {
                return WriterResult.Bottom <W, V>(resT.Output);
            }
            var resU = bind(resT.Value).Valid().Invoke();
            if (resT.IsBottom)
            {
                return WriterResult.Bottom <W, V>(resU.Output);
            }
            var resV = project(resT.Value, resU.Value);
            return WriterResult.Return(resV, resT.Output.Concat(resU.Output));
        });
    }
示例#4
0
        public async Task <IWriterResult <bool> > AddUserRole(UserRoleModel model)
        {
            using (var context = DataContextFactory.CreateContext())
            {
                var user = await context.Users.FirstOrDefaultNoLockAsync(x => x.UserName == model.UserName);

                if (user == null)
                {
                    return(WriterResult <bool> .ErrorResult("User {0} not found.", model.UserName));
                }

                var role = await context.Roles.FirstOrDefaultNoLockAsync(x => x.Name == model.SecurityRole.ToString());

                if (role == null)
                {
                    return(WriterResult <bool> .ErrorResult("{0} role does not exist", model.SecurityRole));
                }

                var exists = await context.UserRoles.FirstOrDefaultNoLockAsync(x => x.User.UserName == model.UserName && x.Role.Name == model.SecurityRole.ToString());

                if (exists != null)
                {
                    return(WriterResult <bool> .ErrorResult("{0} is already assigned to {1} role.", model.UserName, model.SecurityRole));
                }

                context.UserRoles.Add(new UserRole {
                    UserId = user.Id, RoleId = role.Id
                });
                await context.SaveChangesAsync();

                return(WriterResult <bool> .SuccessResult());
            }
        }
示例#5
0
        public async Task <IWriterResult <bool> > AdminCreateSupportFaq(string userId, CreateSupportFaqModel model)
        {
            using (var context = DataContextFactory.CreateContext())
            {
                var faq = await context.SupportFaq.FirstOrDefaultNoLockAsync(x => x.Question == model.Question);

                if (faq != null)
                {
                    return(WriterResult <bool> .ErrorResult("FAQ with question '{0}' already exists.", model.Question));
                }

                int order = context.SupportFaq.Count() + 1;
                context.SupportFaq.Add(new SupportFaq
                {
                    Question  = model.Question,
                    Answer    = model.Answer,
                    Order     = order,
                    IsEnabled = true
                });

                await context.SaveChangesAsync();

                return(WriterResult <bool> .SuccessResult());
            }
        }
示例#6
0
 public static Reader <E, Writer <Out, V> > SelectMany <E, Out, T, U, V>(
     this Reader <E, T> self,
     Func <T, Writer <Out, U> > bind,
     Func <T, U, V> project
     )
 {
     if (bind == null)
     {
         throw new ArgumentNullException(nameof(bind));
     }
     if (project == null)
     {
         throw new ArgumentNullException(nameof(project));
     }
     return((E env) =>
     {
         var resT = self.Valid()(env);
         if (resT.IsBottom)
         {
             return Bottom <Writer <Out, V> >();
         }
         return Return <Writer <Out, V> >(() =>
         {
             var resU = bind(resT.Value).Valid()();
             if (resU.IsBottom)
             {
                 return WriterResult.Bottom <Out, V>(resU.Output);
             }
             return WriterResult.Return(project(resT.Value, resU.Value), resU.Output);
         });
     });
 }
示例#7
0
 public static State <S, Writer <Out, V> > SelectMany <S, Out, T, U, V>(
     this State <S, T> self,
     Func <T, Writer <Out, U> > bind,
     Func <T, U, V> project
     )
 {
     if (bind == null)
     {
         throw new ArgumentNullException(nameof(bind));
     }
     if (project == null)
     {
         throw new ArgumentNullException(nameof(project));
     }
     return((S s) =>
     {
         var resT = self.Valid()(s);
         if (resT.IsBottom)
         {
             return StateResult.Bottom <S, Writer <Out, V> >(s);
         }
         return StateResult.Return <S, Writer <Out, V> >(resT.State, () =>
         {
             var resU = bind(resT.Value).Valid()();
             if (resU.IsBottom)
             {
                 return new WriterResult <Out, V>(default(V), resU.Output, true);
             }
             return WriterResult.Return(project(resT.Value, resU.Value), resU.Output);
         });
     });
 }
示例#8
0
        public async Task <IWriterResult <bool> > AdminUpdateSupportFaq(string userId, UpdateSupportFaqModel model)
        {
            using (var context = DataContextFactory.CreateContext())
            {
                var faq = await context.SupportFaq.FirstOrDefaultNoLockAsync(x => x.Id == model.Id);

                if (faq == null)
                {
                    return(WriterResult <bool> .ErrorResult("FAQ with id '{0}' not found.", model.Id));
                }

                if (faq.Order != model.Order)
                {
                    var order = Math.Max(Math.Min(context.SupportFaq.Count() - 1, model.Order), 0);
                    foreach (var item in context.SupportFaq.Where(x => x.Order >= order).ToList())
                    {
                        item.Order++;
                    }
                    faq.Order = order;
                }

                faq.Question  = model.Question;
                faq.Answer    = model.Answer;
                faq.IsEnabled = model.IsEnabled;

                await context.SaveChangesAsync();

                return(WriterResult <bool> .SuccessResult());
            }
        }
示例#9
0
        public async Task <IWriterResult <int> > CreateSupportTicketReply(string userId, CreateSupportTicketReplyModel model)
        {
            using (var context = DataContextFactory.CreateContext())
            {
                var ticket = await context.SupportTicket.Include(x => x.Replies).FirstOrDefaultNoLockAsync(x => x.Id == model.TicketId);

                if (ticket == null)
                {
                    return(WriterResult <int> .ErrorResult("Support ticket #{0} not found", model.TicketId));
                }

                var reply = new SupportTicketReply
                {
                    Message  = model.Message,
                    UserId   = userId,
                    TicketId = ticket.Id,
                    IsPublic = true,
                    IsAdmin  = false,
                    Created  = DateTime.UtcNow
                };
                ticket.Replies.Add(reply);
                ticket.Status     = SupportTicketStatus.UserReply;
                ticket.LastUpdate = DateTime.UtcNow;
                await context.SaveChangesAsync();

                return(WriterResult <int> .SuccessResult(reply.Id));
            }
        }
示例#10
0
        public async Task <IWriterResult <bool> > CancelWithdraw(string userId, int withdrawId)
        {
            using (var context = DataContextFactory.CreateContext())
            {
                var withdraw = await context.Withdraw
                               .Include(x => x.User)
                               .Include(x => x.Currency)
                               .FirstOrDefaultAsync(x => x.Id == withdrawId && x.UserId == userId && x.WithdrawStatus == WithdrawStatus.Unconfirmed);

                if (withdraw == null || withdraw.WithdrawStatus != WithdrawStatus.Unconfirmed)
                {
                    return(WriterResult <bool> .ErrorResult("Withdraw #{0} not found or is already canceled.", withdrawId));
                }
                if (!withdraw.User.IsWithdrawEnabled)
                {
                    return(WriterResult <bool> .ErrorResult("Your withdrawals are currently disabled."));
                }


                withdraw.WithdrawStatus = WithdrawStatus.Canceled;
                await context.SaveChangesAsync();

                await AuditService.AuditUserCurrency(context, userId, withdraw.CurrencyId);

                return(WriterResult <bool> .SuccessResult());
            }
        }
示例#11
0
        public async Task <IWriterResult <int> > CreateApiWithdraw(string userId, string currency, string address, decimal amount)
        {
            int currencyId = 0;

            using (var context = DataContextFactory.CreateContext())
            {
                var currencyEntity = await context.Currency.Where(w => w.Symbol == currency).FirstOrDefaultNoLockAsync();

                if (currencyEntity == null)
                {
                    return(WriterResult <int> .ErrorResult("Currency not found."));
                }

                currencyId = currencyEntity.Id;
            }

            return(await WithdrawService.QueueWithdraw(new CreateWithdraw
            {
                IsApi = true,
                UserId = userId,
                Address = address,
                Amount = amount,
                ConfirmationToken = "",
                CurrencyId = currencyId
            }));
        }
示例#12
0
        public async Task <IWriterResult <bool> > CreateVoteItem(string userId, CreateVoteItemModel model)
        {
            using (var context = DataContextFactory.CreateContext())
            {
                var voteItem = await context.VoteItem.FirstOrDefaultNoLockAsync(x => x.Name == model.Name);

                if (voteItem != null)
                {
                    return(WriterResult <bool> .ErrorResult("VoteItem {0} already exists.", model.Name));
                }

                voteItem = new VoteItem
                {
                    Name        = model.Name,
                    Symbol      = model.Symbol,
                    Website     = model.Website,
                    Source      = model.Source,
                    AlgoType    = model.AlgoType,
                    Created     = DateTime.UtcNow,
                    UserId      = userId,
                    Status      = VoteItemStatus.Pending,
                    Description = model.Description
                };

                context.VoteItem.Add(voteItem);

                var contextResults = await context.SaveChangesWithLoggingAsync();

                return(WriterResult <bool> .ContextResult(contextResults, "Successfully submitted coin for review"));
            }
        }
示例#13
0
 public static Writer <Out, State <S, V> > SelectMany <Out, S, T, U, V>(
     this Writer <Out, T> self,
     Func <T, State <S, U> > bind,
     Func <T, U, V> project
     )
 {
     if (bind == null)
     {
         throw new ArgumentNullException(nameof(bind));
     }
     if (project == null)
     {
         throw new ArgumentNullException(nameof(project));
     }
     return(() =>
     {
         var resT = self.Valid()();
         if (resT.IsBottom)
         {
             return WriterResult.Bottom <Out, State <S, V> >(resT.Output);
         }
         return WriterResult.Return <Out, State <S, V> >(state =>
         {
             var resU = bind(resT.Value).Valid()(state);
             if (resU.IsBottom)
             {
                 return StateResult.Bottom <S, V>(state);
             }
             return StateResult.Return(resU.State, project(resT.Value, resU.Value));
         }, resT.Output);
     });
 }
示例#14
0
        public async Task <IWriterResult <bool> > CreatePaidVote(string userId, CreatePaidVoteModel model)
        {
            if (!await VoteService.CheckVoteItems())
            {
                return(WriterResult <bool> .ErrorResult("The current vote round has ended."));
            }

            using (var context = DataContextFactory.CreateContext())
            {
                var settings = await context.VoteSetting.FirstOrDefaultNoLockAsync();

                if (settings == null)
                {
                    return(WriterResult <bool> .ErrorResult("VoteItem not found."));
                }

                if (model.VoteCount <= 0 || (settings.Price * model.VoteCount) <= 0)
                {
                    return(WriterResult <bool> .ErrorResult("Invalid vote amount."));
                }

                var voteItem = await context.VoteItem.FirstOrDefaultNoLockAsync(x => x.Id == model.VoteItemId);

                if (voteItem == null)
                {
                    return(WriterResult <bool> .ErrorResult("VoteItem not found."));
                }

                var transferResult = await TradeService.QueueTransfer(new CreateTransferModel
                {
                    UserId       = userId,
                    ToUser       = Constants.SystemVoteUserId,
                    CurrencyId   = settings.CurrencyId,
                    Amount       = model.VoteCount *settings.Price,
                    TransferType = TransferType.Vote
                });

                if (transferResult.HasError)
                {
                    return(WriterResult <bool> .ErrorResult(transferResult.Error));
                }

                var vote = new Entity.Vote
                {
                    Created    = DateTime.UtcNow,
                    Count      = model.VoteCount,
                    Type       = VoteType.Paid,
                    Status     = VoteStatus.Live,
                    UserId     = userId,
                    VoteItemId = model.VoteItemId
                };

                context.Vote.Add(vote);

                var contextResults = await context.SaveChangesWithLoggingAsync();

                return(WriterResult <bool> .ContextResult(contextResults, "Successfully added {0} vote(s) for {1}", model.VoteCount, voteItem.Name));
            }
        }
示例#15
0
        public async Task <WriterResult <bool> > CreateCurrency(string userId, CreateCurrencyModel model)
        {
            using (var context = DataContextFactory.CreateContext())
            {
                var existing = await context.Currency.FirstOrDefaultNoLockAsync(c => c.Name == model.Name || c.Symbol == model.Symbol);

                if (existing != null)
                {
                    return(WriterResult <bool> .ErrorResult("Currency with {0} already exists.", existing.Name == model.Name?$"Name '{model.Name}'" : $"Symbol '{model.Symbol}'"));
                }

                existing = await context.Currency.FirstOrDefaultNoLockAsync(c => c.WalletPort == model.WalletPort && c.WalletHost == model.WalletHost);

                if (existing != null)
                {
                    return(WriterResult <bool> .ErrorResult("Wallet with RPC settings {0}:{1} already exists.", model.WalletHost, model.WalletPort));
                }

                var entity = new Entity.Currency
                {
                    IsEnabled        = model.IsEnabled,
                    MaxTrade         = model.MaxTrade,
                    MaxWithdraw      = model.MaxWithdraw,
                    MinBaseTrade     = model.MinBaseTrade,
                    MinConfirmations = model.MinConfirmations,
                    MinTrade         = model.MinTrade,
                    MinWithdraw      = model.MinWithdraw,
                    Name             = model.Name,
                    Status           = model.Status,
                    StatusMessage    = model.StatusMessage,
                    Symbol           = model.Symbol,
                    TradeFee         = model.TradeFee,
                    TransferFee      = model.TransferFee,
                    WithdrawFee      = model.WithdrawFee,
                    WithdrawFeeType  = model.WithdrawFeeType,
                    WalletHost       = model.WalletHost,
                    WalletPass       = model.WalletPass,
                    WalletPort       = model.WalletPort,
                    WalletUser       = model.WalletUser,
                    ColdBalance      = 0m,

                    MarketSortOrder = model.MarketSortOrder,
                    Algo            = model.Algo,
                    InterfaceType   = model.InterfaceType,
                    Type            = model.Type,
                    IsFaucetEnabled = model.IsFaucetEnabled,
                    FaucetMax       = model.FaucetMax,
                    FaucetPayment   = model.FaucetPayment
                };

                context.Currency.Add(entity);
                await context.SaveChangesAsync();

                return(WriterResult <bool> .SuccessResult());
            }
        }
示例#16
0
 public static Writer <W, T> Where <W, T>(this Writer <W, T> self, Func <T, bool> pred)
 {
     return(() =>
     {
         var res = self.Valid()();
         return pred(res.Value)
             ? WriterResult.Return(res.Value, res.Output)
             : WriterResult.Bottom <W, T>(res.Output);
     });
 }
示例#17
0
        public async Task <IWriterResult <bool> > CreateTransfer(CreateTransferModel model)
        {
            var result = await TradeService.QueueTransfer(model);

            if (result.HasError)
            {
                return(WriterResult <bool> .ErrorResult(result.Error));
            }

            return(WriterResult <bool> .SuccessResult());
        }
示例#18
0
 public static Writer <Out, Unit> Iter <Out, T>(this Writer <Out, T> self, Action <T> action)
 {
     return(() =>
     {
         var res = self.Valid()();
         if (!res.IsBottom)
         {
             action(res.Value);
         }
         return WriterResult.Return(unit, res.Output);
     });
 }
示例#19
0
        public async Task <IWriterResult <bool> > CancelTrade(string userId, CancelTradeModel model)
        {
            model.UserId = userId;
            var result = await TradeService.QueueCancel(model);

            if (result.HasError)
            {
                return(WriterResult <bool> .ErrorResult(result.Error));
            }

            return(WriterResult <bool> .SuccessResult());
        }
示例#20
0
 private static WriterResult <W, Unit> bmap <W, T>(WriterResult <W, T> r, Action <T> f)
 {
     if (r.IsBottom)
     {
         return(WriterResult.Bottom <W, Unit>(r.Output));
     }
     else
     {
         f(r.Value);
         return(WriterResult.Return(unit, r.Output));
     }
 }
示例#21
0
 public static Writer <Out, R> Bind <Out, T, R>(this Writer <Out, T> self, Func <T, Writer <Out, R> > binder)
 {
     return(() =>
     {
         var t = self.Valid()();
         if (t.IsBottom)
         {
             return WriterResult.Bottom <Out, R>(t.Output);
         }
         var u = binder(t.Value).Valid()();
         return WriterResult.Return(u.Value, t.Output.Concat(u.Output));
     });
 }
示例#22
0
 public static Writer <Out, V> FoldT <Out, T, V>(this Writer <Out, Writer <Out, T> > self, V state, Func <V, T, V> fold)
 {
     return(() =>
     {
         var inner = self.Valid()();
         if (inner.IsBottom)
         {
             return WriterResult.Bottom <Out, V>(inner.Output);
         }
         var res = inner.Value.Fold(state, fold)();
         return WriterResult.Return <Out, V>(res.Value, inner.Output.Concat(res.Output));
     });
 }
示例#23
0
    public static Writer <Out, State <S, V> > FoldT <Out, S, T, V>(this Writer <Out, State <S, T> > self, V state, Func <V, T, V> fold)
    {
        return(() =>
        {
            var inner = self.Valid()();
            if (inner.IsBottom)
            {
                return WriterResult.Bottom <Out, State <S, V> >(inner.Output);
            }

            return WriterResult.Return <Out, State <S, V> >(s =>
                                                            inner.Value.Fold(state, fold)(s),
                                                            inner.Output
                                                            );
        });
    }
示例#24
0
 public static Writer <W, U> Select <W, T, U>(this Writer <W, T> self, Func <T, U> select)
 {
     if (select == null)
     {
         throw new ArgumentNullException(nameof(select));
     }
     return(() =>
     {
         var resT = self.Valid()();
         if (resT.IsBottom)
         {
             return WriterResult.Bottom <W, U>(resT.Output);
         }
         var resU = select(resT.Value);
         return WriterResult.Return(resU, resT.Output);
     });
 }
示例#25
0
 public static Writer <Out, T> LiftUnsafeT <Env, Out, T>(this Reader <Env, Writer <Out, T> > self, Env env) where T : class
 {
     return(() =>
     {
         var inner = self.Valid()(env);
         if (inner.IsBottom)
         {
             return WriterResult.Bottom <Out, T>();
         }
         var res = inner.Value();
         if (res.IsBottom)
         {
             return WriterResult.Bottom <Out, T>();
         }
         return WriterResult.Return(res.Value, res.Output);
     });
 }
示例#26
0
        public async Task <WriterResult <bool> > AdminUpdateChatMessage(string userId, UpdateChatMessageModel model)
        {
            using (var context = DataContextFactory.CreateContext())
            {
                var chatEntity = await context.ChatMessage.FirstOrDefaultNoLockAsync(x => x.Id == model.Id);

                if (chatEntity == null)
                {
                    return(WriterResult <bool> .ErrorResult());
                }

                chatEntity.IsEnabled = model.IsEnabled;
                await context.SaveChangesAsync();

                return(WriterResult <bool> .SuccessResult());
            }
        }
示例#27
0
        public async Task <WriterResult <int> > CreateChatMessage(string userId, ChatMessageModel model)
        {
            using (var context = DataContextFactory.CreateContext())
            {
                var chatEntity = new Entity.ChatMessage
                {
                    IsEnabled = true,
                    Message   = model.Message,
                    Timestamp = DateTime.UtcNow,
                    UserId    = userId
                };
                context.ChatMessage.Add(chatEntity);
                await context.SaveChangesAsync();

                return(WriterResult <int> .SuccessResult(chatEntity.Id));
            }
        }
示例#28
0
        public async Task <WriterResult <bool> > Claim(string userId, string ipaddress, int currencyId)
        {
            var result = await TradeService.QueueFaucetPayment(new CreateFaucetPaymentModel
            {
                UserId     = userId,
                IPAddress  = ipaddress,
                CurrencyId = currencyId,
                IsApi      = false
            });

            if (result.HasError)
            {
                return(WriterResult <bool> .ErrorResult(result.Error));
            }

            return(WriterResult <bool> .SuccessResult(result.Message));
        }
示例#29
0
        public async Task <IWriterResult <bool> > CreateSupportRequest(CreateSupportRequestModel model)
        {
            using (var context = DataContextFactory.CreateContext())
            {
                var request = new SupportRequest
                {
                    Title       = model.Title,
                    Sender      = model.Sender,
                    Description = model.Description,
                    Replied     = false,
                    Created     = DateTime.UtcNow
                };
                context.SupportRequest.Add(request);
                await context.SaveChangesAsync();

                return(WriterResult <bool> .SuccessResult());
            }
        }
示例#30
0
        public async Task <IWriterResult <bool> > UpdateSupportTicketStatus(string userId, UpdateSupportTicketStatusModel model)
        {
            using (var context = DataContextFactory.CreateContext())
            {
                var ticket = await context.SupportTicket.Include(x => x.Replies).FirstOrDefaultNoLockAsync(x => x.Id == model.TicketId);

                if (ticket == null)
                {
                    return(WriterResult <bool> .ErrorResult("Support ticket #{0} not found", model.TicketId));
                }

                ticket.Status     = model.Status;
                ticket.LastUpdate = DateTime.UtcNow;
                await context.SaveChangesAsync();

                return(WriterResult <bool> .SuccessResult());
            }
        }