Example #1
0
        public async Task <int> ClaimReward(ulong userId)
        {
            await claimLockJustInCase.WaitAsync();

            var now = DateTime.UtcNow;

            try
            {
                var data = Pledges?.FirstOrDefault(x => x.User.attributes?.social_connections?.discord?.user_id == userId.ToString());

                if (data == null)
                {
                    return(0);
                }

                var amount = data.Reward.attributes.amount_cents;

                using (var uow = _db.UnitOfWork)
                {
                    var users = uow._context.Set <RewardedUser>();
                    var usr   = users.FirstOrDefault(x => x.PatreonUserId == data.User.id);

                    if (usr == null)
                    {
                        users.Add(new RewardedUser()
                        {
                            UserId                  = userId,
                            PatreonUserId           = data.User.id,
                            LastReward              = now,
                            AmountRewardedThisMonth = amount,
                        });

                        await _currency.AddAsync(userId, "Patreon reward - new", amount, uow).ConfigureAwait(false);

                        await uow.CompleteAsync().ConfigureAwait(false);

                        return(amount);
                    }

                    if (usr.LastReward.Month != now.Month)
                    {
                        usr.LastReward = now;
                        usr.AmountRewardedThisMonth = amount;
                        usr.PatreonUserId           = data.User.id;

                        await _currency.AddAsync(userId, "Patreon reward - recurring", amount, uow).ConfigureAwait(false);

                        await uow.CompleteAsync().ConfigureAwait(false);

                        return(amount);
                    }

                    if (usr.AmountRewardedThisMonth < amount)
                    {
                        var toAward = amount - usr.AmountRewardedThisMonth;

                        usr.LastReward = now;
                        usr.AmountRewardedThisMonth = amount;
                        usr.PatreonUserId           = data.User.id;

                        await _currency.AddAsync(usr.UserId, "Patreon reward - update", toAward, uow).ConfigureAwait(false);

                        await uow.CompleteAsync().ConfigureAwait(false);

                        return(toAward);
                    }
                }
                return(0);
            }
            finally
            {
                claimLockJustInCase.Release();
            }
        }