Commit 4e0bc775 authored by Clint.Network's avatar Clint.Network

Implement some stuffs

parent f92d8edf
...@@ -9,16 +9,20 @@ using System.IO; ...@@ -9,16 +9,20 @@ using System.IO;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using NBitcoin; using NBitcoin;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using PaulMiami.AspNetCore.Mvc.Recaptcha; using PaulMiami.AspNetCore.Mvc.Recaptcha;
using QRCoder; using QRCoder;
using RestSharp;
using Stratis.Guru.Models; using Stratis.Guru.Models;
using Stratis.Guru.Modules; using Stratis.Guru.Modules;
using Stratis.Guru.Settings;
namespace Stratis.Guru.Controllers namespace Stratis.Guru.Controllers
{ {
...@@ -26,11 +30,19 @@ namespace Stratis.Guru.Controllers ...@@ -26,11 +30,19 @@ namespace Stratis.Guru.Controllers
{ {
private readonly IMemoryCache _memoryCache; private readonly IMemoryCache _memoryCache;
private readonly IAsk _ask; private readonly IAsk _ask;
private readonly ISettings _settings;
private readonly IParticipation _participation;
private readonly IDraws _draws;
private readonly DrawSettings _drawSettings;
public HomeController(IMemoryCache memoryCache, IAsk ask) public HomeController(IMemoryCache memoryCache, IAsk ask, ISettings settings, IParticipation participation, IDraws draws, IOptions<DrawSettings> drawSettings)
{ {
_memoryCache = memoryCache; _memoryCache = memoryCache;
_ask = ask; _ask = ask;
_settings = settings;
_participation = participation;
_draws = draws;
_drawSettings = drawSettings.Value;
} }
public IActionResult Index() public IActionResult Index()
...@@ -71,6 +83,7 @@ namespace Stratis.Guru.Controllers ...@@ -71,6 +83,7 @@ namespace Stratis.Guru.Controllers
public IActionResult Lottery() public IActionResult Lottery()
{ {
ViewBag.NextDraw = long.Parse(_memoryCache.Get("NextDraw").ToString()); ViewBag.NextDraw = long.Parse(_memoryCache.Get("NextDraw").ToString());
ViewBag.Jackpot = _memoryCache.Get("Jackpot");
return View(); return View();
} }
...@@ -81,7 +94,8 @@ namespace Stratis.Guru.Controllers ...@@ -81,7 +94,8 @@ namespace Stratis.Guru.Controllers
{ {
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
return RedirectToAction("Participate", new{id="5c1ef60f09f5754c34ba3010"}); var lastDraw = _draws.GetLastDraw();
return RedirectToAction("Participate", new{id=lastDraw});
} }
ViewBag.NextDraw = long.Parse(_memoryCache.Get("NextDraw").ToString()); ViewBag.NextDraw = long.Parse(_memoryCache.Get("NextDraw").ToString());
ViewBag.Participate = true; ViewBag.Participate = true;
...@@ -94,17 +108,49 @@ namespace Stratis.Guru.Controllers ...@@ -94,17 +108,49 @@ namespace Stratis.Guru.Controllers
{ {
ViewBag.NextDraw = long.Parse(_memoryCache.Get("NextDraw").ToString()); ViewBag.NextDraw = long.Parse(_memoryCache.Get("NextDraw").ToString());
ViewBag.Participate = true; ViewBag.Participate = true;
var pubkey = ExtPubKey.Parse(_drawSettings.PublicKey);
ViewBag.DepositAddress = pubkey.Derive(0).Derive(_settings.GetIterator()).PubKey.GetAddress(Network.StratisMain);
return View("Lottery"); return View("Lottery");
} }
[HttpPost] [HttpPost]
[Route("lottery/check-payment/{address}")] [Route("lottery/check-payment")]
public IActionResult CheckPayment(string address) public IActionResult CheckPayment()
{
var pubkey = ExtPubKey.Parse(_drawSettings.PublicKey);
var depositAddress = pubkey.Derive(0).Derive(_settings.GetIterator()).PubKey.GetAddress(Network.StratisMain).ToString();
ViewBag.DepositAddress = depositAddress;
var rc = new RestClient($"https://stratis.guru/api/address/{depositAddress}");
var rq = new RestRequest(Method.GET);
var response = rc.Execute(rq);
dynamic stratisAdressRequest = JsonConvert.DeserializeObject(response.Content);
if(stratisAdressRequest.unconfirmedBalance + stratisAdressRequest.balance > 0)
{
HttpContext.Session.SetString("Deposited", depositAddress);
return Json(true);
}
return BadRequest();
}
[Route("lottery/new-participation")]
public IActionResult NewParticipation()
{
var ticket = Guid.NewGuid().ToString();
HttpContext.Session.SetString("Ticket", ticket);
ViewBag.Ticket = ticket;
return PartialView();
}
[Route("lottery/save-participation")]
public IActionResult SaveParticipation(string nickname, string address)
{ {
var pubkey = ExtPubKey.Parse("xpub6Bfq1wKQ64UUzW2HzQ6aZmoxkMYVq6DNifiTU1A1d9UEe16qSGnyqSAbFr42XAMXSXi3kcMXQJseXcgyTGQeDpBvHYt5m1HCH74Q52C4kkZ"); _settings.IncrementIterator();
var newAddress = pubkey.Derive(0).Derive(0).PubKey.GetAddress(Network.StratisMain); _participation.StoreParticipation(HttpContext.Session.GetString("Ticket"), nickname, address);
Console.WriteLine(newAddress);
return Json(true); return RedirectToAction("Lottery");
} }
[Route("about")] [Route("about")]
......
...@@ -3,64 +3,70 @@ using System.Threading; ...@@ -3,64 +3,70 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using MongoDB.Bson; using MongoDB.Bson;
using MongoDB.Driver; using MongoDB.Driver;
using NBitcoin;
using Newtonsoft.Json;
using RestSharp;
using Stratis.Guru.Models; using Stratis.Guru.Models;
using Stratis.Guru.Settings;
namespace Stratis.Guru.Services namespace Stratis.Guru.Services
{ {
public class LotteryService : IHostedService, IDisposable public class LotteryService : IHostedService, IDisposable
{ {
private readonly IMemoryCache _memoryCache; private readonly IMemoryCache _memoryCache;
private readonly ISettings _settings;
private readonly IDraws _draws;
private readonly DrawSettings _drawSettings;
private DateTime _nextDraw; private DateTime _nextDraw;
public LotteryService(IMemoryCache memoryCache) public LotteryService(IMemoryCache memoryCache, ISettings settings, IDraws draws, IOptions<DrawSettings> drawSettings)
{ {
_memoryCache = memoryCache; _memoryCache = memoryCache;
_settings = settings;
_draws = draws;
_drawSettings = drawSettings.Value;
} }
public async Task StartAsync(CancellationToken cancellationToken) public async Task StartAsync(CancellationToken cancellationToken)
{ {
await InitLottery(); JackpotCounter();
await InitLotteryAsync();
await CalculateNextDrawAsync(); await CalculateNextDrawAsync();
} }
private async Task InitLottery() private void JackpotCounter()
{ {
#region use DI Task.Run(() =>
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("stratis-guru");
var collection = database.GetCollection<LotterySetting>("lottery");
if(!collection.Find(x => true).Any())
{ {
await collection.InsertOneAsync(new LotterySetting() var totalJackpot = 0.0;
var pubkey = ExtPubKey.Parse(_drawSettings.PublicKey);
for(int i=0; i<=_settings.GetIterator(); i++)
{ {
PublicKeyIterator = 0 var depositAddress = pubkey.Derive(0).Derive((uint)i).PubKey.GetAddress(Network.StratisMain).ToString();
}); var rc = new RestClient($"https://stratis.guru/api/address/{depositAddress}");
} var rq = new RestRequest(Method.GET);
#endregion var response = rc.Execute(rq);
dynamic stratisAdressRequest = JsonConvert.DeserializeObject(response.Content);
totalJackpot += (double)stratisAdressRequest.balance;
}
_memoryCache.Set("Jackpot", totalJackpot);
});
} }
private async Task InitLotteryAsync() => await _settings.InitAsync();
private async Task CalculateNextDrawAsync() private async Task CalculateNextDrawAsync()
{ {
DateTime today = DateTime.Today; DateTime today = DateTime.Today;
int daysUntilFriday = ((int)DayOfWeek.Friday - (int)today.DayOfWeek + 7) % 7; int daysUntilFriday = ((int)DayOfWeek.Friday - (int)today.DayOfWeek + 7) % 7;
_nextDraw = today.AddDays(daysUntilFriday); _nextDraw = today.AddDays(daysUntilFriday);
var nextDrawTimestamp = ((DateTimeOffset)_nextDraw).ToUnixTimeSeconds(); var nextDrawTimestamp = ((DateTimeOffset)_nextDraw).ToUnixTimeSeconds();
//TODO: set to 8pm
#region use DI await _draws.InitDrawAsync(nextDrawTimestamp);
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("stratis-guru");
var collection = database.GetCollection<LotteryDraw>("draws");
if(!collection.Find(x => x.DrawDate.Equals(nextDrawTimestamp)).Any())
{
await collection.InsertOneAsync(new LotteryDraw()
{
DrawDate = nextDrawTimestamp,
Passed = false
});
}
#endregion
_memoryCache.Set("NextDraw", nextDrawTimestamp); _memoryCache.Set("NextDraw", nextDrawTimestamp);
} }
......
...@@ -51,15 +51,34 @@ ...@@ -51,15 +51,34 @@
<div class="modal-body text-center py-4"> <div class="modal-body text-center py-4">
<h2 class="text-dark mb-1">Send Some $STRAT</h2> <h2 class="text-dark mb-1">Send Some $STRAT</h2>
<p>Your participation will be considered after 1 confirmation.</p> <p>Your participation will be considered after 1 confirmation.</p>
<img class="my-4" src="@Url.Action("Qr", "Home", new {value="SfXZxGJWnq3aP8hDmGKWJxJbtbEXYtba86"})" style="width: 250px;" /> <img class="my-4" src="@Url.Action("Qr", "Home", new {value=ViewBag.DepositAddress})" style="width: 250px;" />
<h4>Send to this address: <code>SfXZxGJWnq3aP8hDmGKWJxJbtbEXYtba86</code></h4> <h4>Send to this address: <code>@ViewBag.DepositAddress</code></h4>
<p class="d-none mt-3 text-danger" id="not-received">We don't have received $STRAT.</p>
</div> </div>
<div class="modal-footer"> <div class="modal-footer">
<a asp-controller="Home" asp-action="CheckPayment" data-ajax-method="POST" asp-route-address="SfXZxGJWnq3aP8hDmGKWJxJbtbEXYtba86" data-ajax-success="alert('yeah');" data-ajax-failure="alert('failure');" data-ajax="true" class="btn btn-info btn-lg btn-block"><i class="fa fa-check-circle"></i> Check Payment</a> <a asp-controller="Home" asp-action="CheckPayment" data-ajax-method="POST" data-ajax-success="PaymentSuccess" data-ajax-failure="PaymentFailed" data-ajax="true" class="btn btn-info btn-lg btn-block"><i class="fa fa-check-circle"></i> Check Payment</a>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<div class="modal fade" id="ticket-modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<form method="post" asp-controller="Home" asp-action="SaveParticipation" class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><i class="fa fa-ticket"></i> Lottery Participation</h5>
<a asp-controller="Home" asp-action="Lottery" type="button" class="close">
<span aria-hidden="true">&times;</span>
</a>
</div>
<div class="modal-body content text-center py-4"></div>
<div class="modal-footer">
<button type="submit" class="btn btn-info btn-lg btn-block"><i class="fa fa-check-circle"></i> Submit Participation</button>
</div>
</form>
</div>
</div>
</div>
<div class="shadow-inset"></div> <div class="shadow-inset"></div>
<section class="welcome-area pb-4" id="welcome-1"> <section class="welcome-area pb-4" id="welcome-1">
<div class="header-token"> <div class="header-token">
...@@ -72,7 +91,7 @@ ...@@ -72,7 +91,7 @@
<span id="clock"></span> <span id="clock"></span>
</span> </span>
</h1> </h1>
<h2 class="mb-5">Actual Jackpot: @(257.89.ToString("C"))</h2> <h2 class="mb-5">Actual Jackpot: @((ViewBag.Jackpot ?? 0).ToString("N0")) STRAT</h2>
<button data-toggle="modal" data-target="#participate-modal" class="btn-secondary-box"><i class="fa fa-ticket"></i> Buy a lottery ticket</button> <button data-toggle="modal" data-target="#participate-modal" class="btn-secondary-box"><i class="fa fa-ticket"></i> Buy a lottery ticket</button>
<button data-toggle="modal" data-target="#players-modal" class="btn-secondary-box"><i class="fa fa-user-o"></i> See Players</button> <button data-toggle="modal" data-target="#players-modal" class="btn-secondary-box"><i class="fa fa-user-o"></i> See Players</button>
</div> </div>
...@@ -86,15 +105,30 @@ ...@@ -86,15 +105,30 @@
<script src="~/lib/jquery-countdown/dist/jquery.countdown.min.js"></script> <script src="~/lib/jquery-countdown/dist/jquery.countdown.min.js"></script>
<script src="~/lib/jquery-ajax-unobtrusive/dist/jquery.unobtrusive-ajax.min.js"></script> <script src="~/lib/jquery-ajax-unobtrusive/dist/jquery.unobtrusive-ajax.min.js"></script>
<script type="text/javascript"> <script type="text/javascript">
$(document).ready(function() { function PaymentSuccess()
@if(ViewBag.Participate == true) {
{ $("#deposit-modal").modal("hide");
<text>$("#deposit-modal").modal({backdrop: 'static', keyboard: false});</text> $.get("/lottery/new-participation", function(data)
} {
$("#ticket-modal").find(".content").html(data);
$("#ticket-modal").modal("show");
});
}
function PaymentFailed()
{
$("#not-received").removeClass("d-none");
}
$(document).ready(function() {
@if(ViewBag.Participate == true)
{
<text>$("#deposit-modal").modal({backdrop: 'static', keyboard: false});</text>
}
$('#clock').countdown('@((DateTimeOffset.FromUnixTimeSeconds((long)ViewBag.NextDraw)).ToString("yyyy/MM/dd HH:mm:ss"))', function(event) { $('#clock').countdown('@((DateTimeOffset.FromUnixTimeSeconds((long)ViewBag.NextDraw)).ToString("yyyy/MM/dd HH:mm:ss"))', function(event) {
$(this).html(event.strftime('%D days %Hh %Mm %Ss')); $(this).html(event.strftime('%D days %Hh %Mm %Ss'));
}); });
}) })
</script> </script>
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment