public async Task <byte[]> Handle(GetScriptContentBytesQuery request, CancellationToken cancellationToken) { if (request.CheckAccess) { var access = await _mediator.Send(new HasAccessToScriptQuery { ScriptId = request.ScriptId, UserId = request.User?.Id }, cancellationToken); if (!access) { throw new AuthorizationException("You are not allowed to run additional instances of this script currently."); } } var bytes = await _redis.GetDatabase().StringGetAsync($"{request.ScriptId}_content_bytes"); if (bytes.HasValue) { return((byte[])bytes); } var fromDb = await _db.ScriptContents.Where(w => w.ScriptId == request.ScriptId).Select(w => w.Content) .FirstOrDefaultAsync(cancellationToken); await _redis.GetDatabase().StringSetAsync($"{request.ScriptId}_content_bytes", fromDb); return(fromDb); }
private async Task ClearScriptCache(DiscordMessageEvent notification, string value) { if (value != "meta" && value != "content") { await SendMessage(notification, "Invalid value, must be meta or content. Meta being the script information, content being the actual script jar itself."); return; } var ids = await _db.Scripts.Select(w => w.Id).ToListAsync(); if (value == "meta") { var keys = ids.Select(w => (RedisKey)$"script_{w}_details").ToArray(); await _redis.GetDatabase().KeyDeleteAsync(keys); await SendMessage(notification, $"Successfully cleared script meta cache for {ids.Count} scripts."); } else if (value == "content") { var keys = ids.Select(w => (RedisKey)$"{w}_content_bytes").ToArray(); await _redis.GetDatabase().KeyDeleteAsync(keys); await SendMessage(notification, $"Successfully cleared script content cache for {ids.Count} scripts."); } }
internal async Task <IEnumerable <dynamic> > GetReminders(ulong id) { using var conn = (NpgsqlConnection)_database.GetDbConnection(); var result = await conn.QueryAsync(GetReminderPerUser, new { id = (long)id }); return(result.Select(async(x) => { var v = (await _redis.GetDatabase().StringGetWithExpiryAsync($"reminder:remove:{x.Id}")).Expiry; return new { x, r = v }; }).Select((x) => { x.Wait(); return x.Result; }).Select(x => { if (!x.r.HasValue) { return new { x.x, x.r, anulated = true }; } return new { x.x, x.r, anulated = false }; })); }
public async Task <byte[]> Handle(GetFileQuery request, CancellationToken cancellationToken) { var key = !request.Version.HasValue ? $"file_{request.Name}_latest" : $"file_{request.Name}_version_{request.Version.Value}"; var value = await _redis.GetDatabase().StringGetAsync(key); if (value.HasValue) { return((byte[])value); } var query = _db.Files.AsQueryable(); if (request.Version.HasValue) { query = query.Where(w => w.Version == request.Version.Value); } var file = await query .Where(w => w.Name == request.Name) .OrderByDescending(w => w.Version) .Select(w => w.File) .FirstOrDefaultAsync(cancellationToken); await _redis.GetDatabase().StringSetAsync(key, file, TimeSpan.FromDays(30)); return(file); }
public async Task <IEnumerable <Launcher> > Handle(GetRegisteredLaunchersQuery request, CancellationToken cancellationToken) { var launcherIds = await _redis.GetSet($"{request.UserId}_connected_launchers"); if (!launcherIds.Any()) { return(new List <Launcher>()); } var keys = launcherIds.Select(w => (RedisKey)$"{request.UserId}_{w}_launcher").ToArray(); var launchers = await _redis.GetDatabase().StringGetAsync(keys); var currentLaunchers = launchers.Where(w => w.HasValue).Select(w => JsonSerializer.Deserialize <Launcher>(w)); var currentLauncherIds = currentLaunchers.Select(w => w.Tag).ToHashSet(); var toRemove = launcherIds.Where(w => !currentLauncherIds.Contains(Guid.Parse(w.ToString()))); if (toRemove.Any()) { var transaction = _redis.GetDatabase().CreateTransaction(); foreach (var value in toRemove) { transaction.SetRemoveAsync($"{request.UserId}_connected_launchers", value); } await transaction.ExecuteAsync(CommandFlags.FireAndForget); } return(currentLaunchers); }
public RedisController(IRedisService redisService, AplicationContext context) { _redisService = redisService; _redisStringDb = _redisService.GetDatabase(RedisDbType.String); _redisListDb = _redisService.GetDatabase(RedisDbType.List); _redisSetDb = _redisService.GetDatabase(RedisDbType.Set); _redisHashDb = _redisService.GetDatabase(RedisDbType.Hash); _context = context; }
public async Task <bool> CreatetempMute(TempMute reminder) { if (!await _redis.GetDatabase().KeyExistsAsync($"tempmute:remove:{reminder.UserId}:{reminder.GuildId}")) { await _redis.GetDatabase().StringSetAsync($"tempmute:remove:{reminder.UserId}:{reminder.GuildId}", String.Empty, reminder.TimeSpan); return(true); } else { return(false); } }
public async Task <Unit> Handle(SaveUserJsonDataCommand request, CancellationToken cancellationToken) { var exists = await _db.UserJsonData.FirstOrDefaultAsync(w => w.Key == request.Key && w.UserId == request.UserId, cancellationToken); var value = JsonSerializer.Serialize(request.Value); if (exists != null) { exists.Value = value; _db.UserJsonData.Update(exists); } else { exists = new UserJsonData { Key = request.Key, Value = value, UserId = request.UserId }; await _db.UserJsonData.AddAsync(exists, cancellationToken); } await _db.SaveChangesAsync(cancellationToken); await _redis.GetDatabase().StringSetAsync($"user_json_data_{request.Key}_{request.UserId}", JsonSerializer.Serialize(exists)); return(Unit.Value); }
private async Task CheckInstances(int userId) { var allowed = await _mediator.Send(new GetAllowedInstancesQuery { UserId = userId }); var running = await _mediator.Send(new GetRunningClientsQuery { UserId = userId }); var tags = running .Where(w => w.Game == Game.Osrs).Select(w => w.Tag) .OrderByDescending(w => w) .Distinct().ToList(); var allowedTags = tags.Take(allowed).ToHashSet(); var overLimit = tags.Where(w => !allowedTags.Contains(w)).ToArray(); var transaction = _redis.GetDatabase().CreateTransaction(); foreach (var allowedTag in allowedTags) { transaction.StringSetAsync($"clients_over_limit_{allowedTag}", false, TimeSpan.FromMinutes(15)); } foreach (var tag in overLimit) { count++; users.Add(userId); transaction.StringSetAsync($"clients_over_limit_{tag}", true, TimeSpan.FromMinutes(15)); } await transaction.ExecuteAsync(CommandFlags.FireAndForget); }
public async Task <Unit> Handle(UpdateUserCacheCommand request, CancellationToken cancellationToken) { var user = await _db.Users .Include(w => w.UserGroups).ThenInclude(w => w.Group) .FirstOrDefaultAsync(w => w.Username.ToLower() == request.UsernameOrEmail.ToLower() || w.Email.ToLower() == request.UsernameOrEmail.ToLower(), cancellationToken); if (user == null) { throw new ArgumentException("User was not found by value: " + request.UsernameOrEmail); } var transaction = _redis.GetDatabase().CreateTransaction(); var serialized = JsonSerializer.Serialize(user); transaction.StringSetAsync($"user_{user.Id}", serialized); if (user.LinkKey != null) { transaction.StringSetAsync($"{user.LinkKey}_user_id", user.Id); } transaction.StringSetAsync($"user_{user.Username}", serialized); await transaction.ExecuteAsync(CommandFlags.FireAndForget); return(Unit.Value); }
public async Task CreateGiveaway(IGuildChannel channel, IMessage message, TimeSpan time, string price, int winners) { var connection = _sqlDatabase.GetDbConnection(); var id = (long)await connection.ExecuteScalarAsync(Creategiveaway, new { winners, price, message = (long)message.Id, channel = (long)channel.Id }); await _redisDatabase.GetDatabase().StringSetAsync($"giveaway:{id}", String.Empty, time); }
public async Task <bool> Handle(IsClientOverLimitQuery request, CancellationToken cancellationToken) { var key = $"clients_over_limit_{request.Tag}"; try { var over = await _redis.GetDatabase().StringGetAsync(key); if (over.HasValue) { if (int.TryParse(over.ToString(), out var parsed)) { return(parsed != 0); } return(bool.Parse(over.ToString())); } } catch (Exception e) { _logger.Log(LogLevel.Error, e, "Failed to check instance limit for " + request.UserId + " " + request.Tag); return(false); } return(false); }
public async Task <Unit> Handle(SetClientClosedCommand request, CancellationToken cancellationToken) { var transaction = _redis.GetDatabase().CreateTransaction(); transaction.KeyDeleteAsync($"{request.Tag}_client_details"); await transaction.ExecuteAsync(); return(Unit.Value); }
public async Task <long> Handle(GetRunningClientsCountQuery request, CancellationToken cancellationToken) { var tags = await _redis.GetSet($"{request.UserId}_running_client"); if (tags.Count == 0) { return(0); } var keys = tags.Select(w => (RedisKey)$"{w}_client_details").ToArray(); return(await _redis.GetDatabase().KeyExistsAsync(keys)); }
public async Task <Unit> Handle(UnregisterLauncherCommand request, CancellationToken cancellationToken) { var key = $"{request.UserId}_{request.Tag}_launcher"; var connected = $"{request.UserId}_connected_launchers"; var transaction = _redis.GetDatabase().CreateTransaction(); transaction.KeyDeleteAsync(key); transaction.SetRemoveAsync(connected, request.Tag.ToString()); await transaction.ExecuteAsync(CommandFlags.FireAndForget); return(Unit.Value); }
public async Task <IActionResult> Close() { var id = GetConnectionId(); var userId = await GetUserId(); var transaction = _redis.GetDatabase().CreateTransaction(); transaction.SetRemoveAsync($"{userId}_running_client", id.ToString()); transaction.KeyDeleteAsync($"{id.ToString()}_client_details"); await transaction.ExecuteAsync(StackExchange.Redis.CommandFlags.FireAndForget); return(Ok()); }
public async Task <IEnumerable <ScriptDto> > Handle(GetScriptsByIdsQuery request, CancellationToken cancellationToken) { var keys = request.ScriptIds.Select(w => (RedisKey)$"script_{w}_details").ToArray(); var scripts = await _redis.GetDatabase().StringGetAsync(keys); var toSet = new HashSet <int>(request.ScriptIds); var results = new List <ScriptDto>(); foreach (var value in scripts) { if (!value.HasValue) { continue; } var script = JsonSerializer.Deserialize <ScriptDto>(value.ToString()); toSet.Remove(script.Id); results.Add(script); } if (toSet.Count > 0) { var list = toSet.ToList(); var toSetScripts = await _db.Scripts.Where(w => list.Contains(w.Id)) .Include(w => w.User) .ToListAsync(cancellationToken); results.AddRange(toSetScripts.Select(w => new ScriptDto(w))); var transaction = _redis.GetDatabase().CreateTransaction(); foreach (var script in toSetScripts) { transaction.StringSetAsync($"script_{script.Id}_details", JsonSerializer.Serialize(new ScriptDto(script))); } await transaction.ExecuteAsync(CommandFlags.FireAndForget); } return(results); }
public async Task <IEnumerable <RunescapeClient> > Handle(GetRunningClientsQuery request, CancellationToken cancellationToken) { var tags = await _redis.GetSet($"{request.UserId}_running_client"); if (tags.Count == 0) { return(new List <RunescapeClient>()); } var keys = tags.Select(w => (RedisKey)$"{w}_client_details").ToArray(); var clients = await _redis.GetDatabase().StringGetAsync(keys); return(clients.Where(w => w.HasValue).Select(w => JsonSerializer.Deserialize <RunescapeClient>(w))); }
public async Task <decimal> Handle(GetFileLatestVersionQuery request, CancellationToken cancellationToken) { var version = await _redis.GetDatabase().StringGetAsync($"file_{request.Name}_latest_version"); if (version.HasValue && decimal.TryParse(version, out var parsed)) { if (parsed > 0) { return(parsed); } } var ver = await _db.Files.Where(w => w.Name == request.Name) .OrderByDescending(w => w.Version) .Select(w => w.Version) .FirstOrDefaultAsync(cancellationToken); if (ver > 0) { await _redis.GetDatabase().StringSetAsync($"file_{request.Name}_latest_version", ver.ToString()); } return(ver); }
public async Task <Unit> Handle(SaveClientInfoBulkCommand request, CancellationToken cancellationToken) { var transaction = _redis.GetDatabase().CreateTransaction(); foreach (var client in request.Clients) { transaction.SetAddAsync($"users_running_clients_{client.Game.ToString()}", client.UserId); transaction.SetAddAsync($"{client.UserId}_running_client", client.Tag.ToString()); transaction.StringSetAsync($"{client.Tag}_client_details", JsonSerializer.Serialize(client), TimeSpan.FromMinutes(5)); } await transaction.ExecuteAsync(CommandFlags.FireAndForget); return(Unit.Value); }
public async Task <IEnumerable <RemoteMessage> > Handle(GetRemoteMessagesQuery request, CancellationToken cancellationToken) { var key = $"messages_{request.UserId}"; var messageIds = await _redis.GetSet(key); if (!messageIds.Any()) { return(new List <RemoteMessage>()); } var keys = messageIds.Select(w => (RedisKey)$"messages_{request.UserId}_{w}").ToArray(); var values = await _redis.GetDatabase().StringGetAsync(keys); var messages = values.Where(w => w.HasValue).Select(w => JsonSerializer.Deserialize <RemoteMessage>(w)); return(messages.Where(w => w.Consumer == request.Consumer)); }
public async Task <BinaryFile> Handle(PutFileCommand request, CancellationToken cancellationToken) { var exists = await _db.Files.AsQueryable().Where(w => w.Name == request.Name) .Select(w => w.Version).OrderByDescending(w => w).FirstOrDefaultAsync(cancellationToken); var file = new BinaryFile { Name = request.Name, LastUpdate = DateTimeOffset.UtcNow, Version = request.Version == default ? exists != default ? exists + (decimal)0.01 : (decimal)0.01 : request.Version }; if (request.Contents == null && request.Stream != null) { file.File = request.Stream.ToByteArray(); } else { file.File = request.Contents; } if (file.File != null && file.File.Length <= 0) { throw new Exception("Can not put an empty file by name: " + request.Name); } await _db.Files.AddAsync(file, cancellationToken); await _db.SaveChangesAsync(cancellationToken); var transaction = _redis.GetDatabase().CreateTransaction(); transaction.StringSetAsync($"file_{request.Name}_latest_version", file.Version.ToString()); transaction.StringSetAsync($"file_{request.Name}_version_{file.Version}", file.File); transaction.StringSetAsync($"file_{request.Name}_latest", file.File); await transaction.ExecuteAsync(); return(file); } }
public async Task <Unit> Handle(ConsumeRemoteMessageCommand request, CancellationToken cancellationToken) { var key = $"messages_{request.UserId}"; var messageIds = await _redis.GetSet(key); var filtered = messageIds.FirstOrDefault(w => w == request.MessageId.ToString()); if (filtered == null) { return(Unit.Value); } var transaction = _redis.GetDatabase().CreateTransaction(); transaction.SetRemoveAsync(key, filtered); transaction.KeyDeleteAsync($"messages_{request.UserId}_{filtered}"); await transaction.ExecuteAsync(CommandFlags.FireAndForget); return(Unit.Value); }
public async Task <Unit> Handle(RegisterLauncherCommand request, CancellationToken cancellationToken) { if (!request.UserId.HasValue && request.LinkKey.HasValue) { var userId = await _mediator.Send(new GetUserIdByLinkKeyQuery { LinkKey = request.LinkKey.Value }, cancellationToken); request.UserId = userId; } if (!request.UserId.HasValue) { throw new Exception("Failed to get user by link key or user id, cannot register launcher."); } var transaction = _redis.GetDatabase().CreateTransaction(); var key = $"{request.UserId}_{request.Tag}_launcher"; var launcher = new Domain.Entities.Launcher { Ip = request.Ip, UserId = request.UserId.Value, Tag = request.Tag, Host = request.Host, MachineUsername = request.MachineUsername, Platform = request.Platform, LastUpdate = DateTimeOffset.Now }; transaction.StringSetAsync(key, JsonSerializer.Serialize(launcher), TimeSpan.FromMinutes(3)); transaction.SetAddAsync($"{request.UserId}_connected_launchers", request.Tag.ToString()); await transaction.ExecuteAsync(CommandFlags.FireAndForget); return(Unit.Value); }
public async Task <Unit> Handle(SendRemoteMessageCommand request, CancellationToken cancellationToken) { var message = new RemoteMessage { UserId = request.UserId, Consumer = request.Consumer, Timestamp = DateTimeOffset.Now, Message = request.Message, Source = request.Source, Id = RandomExtensions.RandomNumber() }; var transaction = _redis.GetDatabase().CreateTransaction(); var key = $"messages_{request.UserId}"; transaction.SetAddAsync(key, message.Id); transaction.StringSetAsync($"messages_{request.UserId}_{message.Id}", JsonSerializer.Serialize(message), TimeSpan.FromMinutes(10)); await transaction.ExecuteAsync(CommandFlags.FireAndForget); return(Unit.Value); }
public SimpleCacheImplementation(IRedisService redisService) { _redis = redisService.GetDatabase(); }
public async Task <TimeSpan?> IsCommandCooldowned(ulong userid, string commandName) { return((await _redis.GetDatabase().StringGetWithExpiryAsync($"{userid}-c-{commandName}")).Expiry); }
public RedisExampleDataController( IRedisService redis ) { _database = redis.GetDatabase("testdb"); }
public RedisDataController( IRedisService redisService) { _database = redisService.GetDatabase("testdb"); }
public async Task <Unit> Handle(CreatePrivateScriptCommand request, CancellationToken cancellationToken) { if (!request.Script.Name.StartsWith($"{request.User.Username}'s")) { request.Script.Name = $"{request.User.Username}'s {request.Script.Name}".Trim(); } var exists = await _db.Scripts.FirstOrDefaultAsync(w => w.Name.ToLower() == request.Script.Name.ToLower() || w.Id == request.Script.Id, cancellationToken); if (exists != null && request.Script.Id != exists.Id) { throw new Exception("A script by that name already exists."); } if (exists != null && exists.UserId != request.User.Id) { throw new Exception("A script by that name already exists."); } if (exists != null && exists.Type != ScriptType.Private) { throw new Exception("Existing non private scripts may not be converted to private."); } if (request.File.Length > 5e+7) { throw new Exception("Max file size is 50mb."); } request.Script.Type = ScriptType.Private; request.Script.Price = null; request.Script.Instances = null; request.Script.Status = ScriptStatus.Live; request.Script.ForumThread = "https://rspeer.org"; request.Script.UserId = request.User.Id; var bytes = request.File.OpenReadStream().ToByteArray(); using (var transaction = await _db.Database.BeginTransactionAsync(cancellationToken)) { if (exists != null) { exists = TinyMapper.Map(request.Script, exists); var content = await _db.ScriptContents.FirstOrDefaultAsync(w => w.ScriptId == exists.Id, cancellationToken); if (content == null) { await _db.ScriptContents.AddAsync(new ScriptContent { Content = bytes, ScriptId = exists.Id }, cancellationToken); } else { content.Content = bytes; _db.ScriptContents.Update(content); } _db.Scripts.Update(exists); await _db.SaveChangesAsync(cancellationToken); } else { request.Script.Id = 0; await _db.Scripts.AddAsync(request.Script, cancellationToken); await _db.SaveChangesAsync(cancellationToken); await _db.ScriptContents.AddAsync(new ScriptContent { ScriptId = request.Script.Id, Content = bytes }, cancellationToken); await _db.SaveChangesAsync(cancellationToken); } await _mediator.Send(new AddPrivateScriptAccessCommand { ScriptId = request.Script.Id, UserId = request.User.Id, RequestingUserId = request.User.Id }, cancellationToken); transaction.Commit(); var trans = _redis.GetDatabase().CreateTransaction(); trans.KeyDeleteAsync($"{request.Script.Id}_content_bytes", StackExchange.Redis.CommandFlags.FireAndForget); trans.StringSetAsync($"script_{request.Script.Id}_details", JsonConvert.SerializeObject(new ScriptDto(request.Script))); await trans.ExecuteAsync(CommandFlags.FireAndForget); } return(Unit.Value); }