yavsc/src/Yavsc/Hubs/ChatHub.cs

395 lines
15 KiB
C#
Raw Normal View History

2016-05-17 18:22:18 +02:00
//
2019-05-22 17:27:44 +01:00
// ChatHub.cs
2016-05-17 18:22:18 +02:00
//
// Author:
// Paul Schneider <paul@pschneider.fr>
//
2019-05-22 17:27:44 +01:00
// Copyright (c) 2016-2019 GNU GPL
2016-05-17 18:22:18 +02:00
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
2019-05-24 20:15:48 +01:00
2019-05-11 02:50:19 +01:00
using System;
using System.Collections.Concurrent;
2019-06-05 01:36:50 +01:00
using Microsoft.AspNet.SignalR;
2019-05-11 02:50:19 +01:00
using Microsoft.Data.Entity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
2019-06-05 01:36:50 +01:00
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Localization;
2016-05-17 18:22:18 +02:00
namespace Yavsc
{
2016-11-03 14:52:17 +01:00
using Models;
using Models.Chat;
2016-05-17 18:22:18 +02:00
2019-06-05 11:44:33 +01:00
public partial class ChatHub : Hub, IDisposable
2016-05-17 18:22:18 +02:00
{
2019-01-26 14:23:53 +00:00
ApplicationDbContext _dbContext;
2019-06-05 01:36:50 +01:00
private IStringLocalizer _localizer;
2019-01-26 14:23:53 +00:00
ILogger _logger;
2019-05-24 20:15:48 +01:00
public static ConcurrentDictionary<string, string> ChatUserNames = new ConcurrentDictionary<string, string>();
2019-06-05 01:36:50 +01:00
public static ConcurrentDictionary<string, ChatRoomInfo> Channels = new ConcurrentDictionary<string, ChatRoomInfo>();
2019-01-26 14:23:53 +00:00
2019-05-10 09:58:09 +01:00
public ChatHub()
2019-05-13 14:44:28 +01:00
{
2019-01-26 14:23:53 +00:00
var scope = Startup.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
2019-05-10 09:58:09 +01:00
2019-01-26 14:23:53 +00:00
_dbContext = scope.ServiceProvider.GetService<ApplicationDbContext>();
var loggerFactory = scope.ServiceProvider.GetService<ILoggerFactory>();
2019-06-05 01:36:50 +01:00
var stringLocFactory = scope.ServiceProvider.GetService<IStringLocalizerFactory>();
_localizer = stringLocFactory.Create(typeof(ChatHub));
2019-01-26 14:23:53 +00:00
_logger = loggerFactory.CreateLogger<ChatHub>();
}
2016-11-02 11:27:12 +01:00
2019-01-30 11:14:32 +00:00
public override async Task OnConnected()
2016-11-01 23:22:46 +01:00
{
bool isAuth = false;
2019-05-10 09:58:09 +01:00
string userName = setUserName();
2016-11-01 23:22:46 +01:00
if (Context.User != null)
{
isAuth = Context.User.Identity.IsAuthenticated;
2019-05-13 14:44:28 +01:00
2016-11-01 23:22:46 +01:00
var group = isAuth ?
2019-05-08 16:33:29 +01:00
Constants.HubGroupAuthenticated : Constants.HubGroupAnonymous;
2016-11-01 23:22:46 +01:00
// Log ("Cx: " + group);
2019-01-30 11:14:32 +00:00
await Groups.Add(Context.ConnectionId, group);
2016-11-02 11:27:12 +01:00
if (isAuth)
{
2019-06-05 01:36:50 +01:00
_logger.LogInformation(_localizer.GetString(Constants.LabAuthChatUser));
2019-05-10 09:58:09 +01:00
2019-05-13 14:44:28 +01:00
var userId = _dbContext.Users.First(u => u.UserName == userName).Id;
2019-05-08 16:33:29 +01:00
var userHadConnections = _dbContext.ChatConnection.Any(accx => accx.ConnectionId == Context.ConnectionId);
2019-05-13 14:44:28 +01:00
if (userHadConnections)
{
var ccx = _dbContext.ChatConnection.First(c => c.ConnectionId == Context.ConnectionId);
ccx.Connected = true;
2019-05-08 16:33:29 +01:00
}
else
_dbContext.ChatConnection.Add(new ChatConnection
2019-01-30 11:14:32 +00:00
{
2019-05-10 09:58:09 +01:00
ApplicationUserId = userId,
2019-01-30 11:14:32 +00:00
ConnectionId = Context.ConnectionId,
UserAgent = Context.Request.Headers["User-Agent"],
Connected = true
});
2019-05-13 14:44:28 +01:00
_dbContext.SaveChanges();
2019-06-05 01:36:50 +01:00
Clients.Group(Constants.HubGroupFollowingPrefix+userId).notifyuser(NotificationTypes.Connected, userName, null);
foreach (var uid in _dbContext.CircleMembers.Select(m => m.MemberId))
{
await Groups.Add(Context.ConnectionId, Constants.HubGroupFollowingPrefix+uid);
}
2016-11-02 11:27:12 +01:00
}
2019-05-08 16:33:29 +01:00
else
2019-05-10 09:58:09 +01:00
{
2019-05-29 21:41:19 +01:00
// this line isn't reached: Context.User != null <=> Context.User.Identity.IsAuthenticated
2019-06-06 09:02:33 +01:00
throw new NotSupportedException("Context.User != null && no auth");
2019-05-10 09:58:09 +01:00
}
}
2019-05-13 14:44:28 +01:00
else
{
2019-05-10 09:58:09 +01:00
await Groups.Add(Context.ConnectionId, Constants.HubGroupAnonymous);
2016-11-01 23:22:46 +01:00
}
2019-06-05 01:36:50 +01:00
await base.OnConnected();
2016-11-01 23:22:46 +01:00
}
2019-05-10 09:58:09 +01:00
string setUserName()
{
2019-05-13 14:44:28 +01:00
if (Context.User != null)
2019-05-10 09:58:09 +01:00
if (Context.User.Identity.IsAuthenticated)
{
2019-05-13 14:44:28 +01:00
ChatUserNames[Context.ConnectionId] = Context.User.Identity.Name;
2019-05-10 09:58:09 +01:00
return Context.User.Identity.Name;
}
anonymousSequence++;
2019-05-13 14:44:28 +01:00
var queryUname = Context.Request.QueryString[Constants.KeyParamChatUserName];
2019-05-11 02:50:19 +01:00
var aname = $"{Constants.AnonymousUserNamePrefix}{queryUname}{anonymousSequence}";
2019-05-13 14:44:28 +01:00
ChatUserNames[Context.ConnectionId] = aname;
return aname;
2019-05-10 09:58:09 +01:00
}
2019-05-13 14:44:28 +01:00
static long anonymousSequence = 0;
2016-11-02 11:27:12 +01:00
2016-11-01 23:22:46 +01:00
public override Task OnDisconnected(bool stopCalled)
{
2016-11-02 11:27:12 +01:00
string userName = Context.User?.Identity.Name;
if (userName != null)
{
2019-05-10 09:58:09 +01:00
var cx = _dbContext.ChatConnection.SingleOrDefault(c => c.ConnectionId == Context.ConnectionId);
if (cx != null)
{
if (stopCalled)
2016-11-02 11:27:12 +01:00
{
2019-05-10 09:58:09 +01:00
var user = _dbContext.Users.Single(u => u.UserName == userName);
user.Connections.Remove(cx);
2019-05-24 20:15:48 +01:00
ChatUserNames[Context.ConnectionId] = null;
2016-11-02 11:27:12 +01:00
}
2019-05-10 09:58:09 +01:00
else
{
cx.Connected = false;
}
_dbContext.SaveChanges();
2016-11-02 11:27:12 +01:00
}
}
2019-06-05 01:36:50 +01:00
Clients.Group("authenticated").notifyUser(NotificationTypes.DisConnected, userName, "disconnected");
2016-11-01 23:22:46 +01:00
return base.OnDisconnected(stopCalled);
}
public override Task OnReconnected()
{
2019-05-10 09:58:09 +01:00
if (Context.User != null) if (Context.User.Identity.IsAuthenticated)
2019-05-13 14:44:28 +01:00
{
var userName = Context.User.Identity.Name;
var user = _dbContext.Users.FirstOrDefault(u => u.UserName == userName);
var userId = user.Id;
var userHadConnections = _dbContext.ChatConnection.Any(accx => accx.ConnectionId == Context.ConnectionId);
if (userHadConnections)
2019-05-10 09:58:09 +01:00
{
2019-05-13 14:44:28 +01:00
var ccx = _dbContext.ChatConnection.First(c => c.ConnectionId == Context.ConnectionId);
ccx.Connected = true;
}
else
_dbContext.ChatConnection.Add(new ChatConnection
{
ApplicationUserId = userId,
ConnectionId = Context.ConnectionId,
UserAgent = Context.Request.Headers["User-Agent"],
Connected = true
});
_dbContext.SaveChanges();
2019-06-05 01:36:50 +01:00
Clients.Group("authenticated").notifyUser(NotificationTypes.Reconnected, userName, "reconnected");
2019-05-13 14:44:28 +01:00
}
2019-05-10 09:58:09 +01:00
return base.OnReconnected();
}
2016-11-03 14:52:17 +01:00
2019-05-20 18:48:03 +01:00
public void Nick(string nickName)
{
2019-05-24 20:15:48 +01:00
var candidate = "?" + nickName;
if (ChatUserNames.Any(u => u.Value == candidate))
2019-05-20 18:48:03 +01:00
{
2019-05-29 21:41:19 +01:00
Clients.Caller.notifyUser(NotificationTypes.ExistingUserName, nickName, "aborting");
2019-05-24 20:15:48 +01:00
return;
2019-05-20 18:48:03 +01:00
}
2019-05-24 20:15:48 +01:00
ChatUserNames[Context.ConnectionId] = "?" + nickName;
2019-05-20 18:48:03 +01:00
}
2019-05-18 09:42:50 +01:00
public void JoinAsync(string roomName)
{
2019-05-24 20:15:48 +01:00
var info = Join(roomName);
Clients.Caller.joint(info);
2019-05-18 09:42:50 +01:00
}
2019-05-14 21:22:44 +01:00
public ChatRoomInfo Join(string roomName)
2019-05-10 09:58:09 +01:00
{
var userName = ChatUserNames[Context.ConnectionId];
2019-06-05 01:36:50 +01:00
var roomGroupName = Constants.HubGroupRomsPrefix + roomName;
2019-05-10 09:58:09 +01:00
ChatRoomInfo chanInfo;
if (Channels.ContainsKey(roomName))
{
2019-05-13 14:44:28 +01:00
if (Channels.TryGetValue(roomName, out chanInfo))
{
2019-05-10 09:58:09 +01:00
if (chanInfo.Users.ContainsKey(Context.ConnectionId))
2019-05-13 14:44:28 +01:00
_logger.LogWarning("user already joint.");
else
{
chanInfo.Users.Add(Context.ConnectionId, userName);
Groups.Add(Context.ConnectionId, roomGroupName);
2019-05-29 21:41:19 +01:00
Clients.Caller.joint(chanInfo);
2019-06-05 01:36:50 +01:00
Clients.Group(Constants.HubGroupRomsPrefix + roomName).notifyRoom(NotificationTypes.UserJoin, roomName, userName);
2019-05-29 21:41:19 +01:00
return chanInfo;
2019-01-26 14:23:53 +00:00
}
2019-05-29 21:41:19 +01:00
return null;
2019-05-10 09:58:09 +01:00
}
2019-05-13 14:44:28 +01:00
else
{
2019-06-06 09:02:33 +01:00
_logger.LogError("room seemd to be avaible ... but we could get no info on it.");
2019-05-29 21:41:19 +01:00
Clients.Caller.notifyRoom(NotificationTypes.Error, roomName, "join get chan failed ...");
2019-05-14 21:22:44 +01:00
return null;
2019-05-10 09:58:09 +01:00
}
2016-11-02 11:27:12 +01:00
}
2019-05-10 09:58:09 +01:00
var room = _dbContext.ChatRoom.FirstOrDefault(r => r.Name == roomName);
chanInfo = new ChatRoomInfo();
chanInfo.Users.Add(Context.ConnectionId, userName);
2019-05-13 14:44:28 +01:00
if (room != null)
2019-05-10 09:58:09 +01:00
{
chanInfo.Topic = room.Topic;
chanInfo.Name = room.Name;
}
2019-05-13 14:44:28 +01:00
else
{ // a first join, we create it.
2019-05-10 09:58:09 +01:00
chanInfo.Name = roomName;
chanInfo.Topic = "<just created>";
}
if (Channels.TryAdd(roomName, chanInfo))
{
Groups.Add(Context.ConnectionId, roomGroupName);
2019-05-24 20:15:48 +01:00
return (chanInfo);
2019-05-10 09:58:09 +01:00
}
else _logger.LogError("Chan create failed unexpectly...");
2019-05-14 21:22:44 +01:00
return null;
2016-11-01 23:22:46 +01:00
}
2016-05-17 18:22:18 +02:00
2019-05-10 09:58:09 +01:00
[Authorize]
2019-05-13 14:44:28 +01:00
public void Register(string room)
2016-11-01 23:22:46 +01:00
{
2019-05-10 09:58:09 +01:00
var existent = _dbContext.ChatRoom.Any(r => r.Name == room);
2019-05-13 14:44:28 +01:00
if (existent)
{
2019-05-29 21:41:19 +01:00
Clients.Caller.notifyUser(NotificationTypes.Error, room, "already registered.");
2019-05-10 09:58:09 +01:00
return;
}
string userName = Context.User.Identity.Name;
2019-05-13 14:44:28 +01:00
var user = _dbContext.Users.FirstOrDefault(u => u.UserName == userName);
2019-05-10 09:58:09 +01:00
var newroom = new ChatRoom { Name = room, OwnerId = user.Id };
ChatRoomInfo chanInfo;
if (Channels.TryGetValue(room, out chanInfo))
{
// TODO get and require some admin status for current user on this chan
newroom.Topic = chanInfo.Topic;
}
newroom.LatestJoinPart = DateTime.Now;
_dbContext.ChatRoom.Add(newroom);
_dbContext.SaveChanges(user.Id);
2016-11-01 23:22:46 +01:00
}
2016-05-17 18:22:18 +02:00
2019-05-13 14:44:28 +01:00
/** TODO chan register on server command
room = new ChatRoom { Name = roomName, OwnerId = uid };
_dbContext.ChatRoom.Add(room);
_dbContext.SaveChanges(uid);
room.LatestJoinPart = DateTime.Now;
chanInfo.Topic = room.Topic;
*/
2016-11-01 23:22:46 +01:00
2019-01-26 14:23:53 +00:00
2019-05-13 14:44:28 +01:00
public void Part(string roomName, string reason)
2019-05-10 09:58:09 +01:00
{
ChatRoomInfo chanInfo;
if (Channels.TryGetValue(roomName, out chanInfo))
{
2019-06-05 01:36:50 +01:00
var roomGroupName = Constants.HubGroupRomsPrefix + roomName;
2019-05-29 21:41:19 +01:00
if (!chanInfo.Users.ContainsKey(Context.ConnectionId))
{
NotifyRoomError(roomName, "you didn't join.");
return;
}
2019-05-10 09:58:09 +01:00
Groups.Remove(Context.ConnectionId, roomGroupName);
var group = Clients.Group(roomGroupName);
var username = ChatUserNames[Context.ConnectionId];
2019-05-29 21:41:19 +01:00
group.notifyRoom(NotificationTypes.UserPart, roomName, $"{username}: {reason}");
2019-05-10 09:58:09 +01:00
chanInfo.Users.Remove(Context.ConnectionId);
ChatRoomInfo deadchanInfo;
2019-05-13 14:44:28 +01:00
if (chanInfo.Users.Count == 0)
2019-05-10 09:58:09 +01:00
if (Channels.TryRemove(roomName, out deadchanInfo))
{
var room = _dbContext.ChatRoom.FirstOrDefault(r => r.Name == roomName);
room.LatestJoinPart = DateTime.Now;
_dbContext.SaveChanges();
}
}
2019-05-13 14:44:28 +01:00
else
{
2019-05-29 21:41:19 +01:00
NotifyRoomError(roomName, $"could not join: no such room");
2019-05-10 09:58:09 +01:00
}
}
2019-05-29 21:41:19 +01:00
void NotifyRoomError(string room, string reason)
2019-05-22 17:27:44 +01:00
{
2019-05-29 21:41:19 +01:00
Clients.Caller.notifyUser(NotificationTypes.Error, room, reason);
2019-05-22 17:27:44 +01:00
}
2019-05-10 09:58:09 +01:00
public void Send(string roomName, string message)
{
2019-06-05 01:36:50 +01:00
var groupname = Constants.HubGroupRomsPrefix + roomName;
2019-05-10 09:58:09 +01:00
ChatRoomInfo chanInfo;
if (Channels.TryGetValue(roomName, out chanInfo))
{
2019-05-13 14:44:28 +01:00
if (!chanInfo.Users.ContainsKey(Context.ConnectionId))
{
2019-05-24 20:15:48 +01:00
var notSentMsg = $"could not send to channel ({roomName}) (not joint)";
2019-05-29 21:41:19 +01:00
Clients.Caller.notifyUser(NotificationTypes.Error, roomName, notSentMsg);
2019-05-10 09:58:09 +01:00
return;
}
2019-05-13 14:44:28 +01:00
string uname = ChatUserNames[Context.ConnectionId];
2019-05-10 09:58:09 +01:00
Clients.Group(groupname).addMessage(uname, roomName, message);
}
else
{
2019-05-22 17:27:44 +01:00
var noChanMsg = $"could not send to channel ({roomName}) (no such chan)";
2019-05-29 21:41:19 +01:00
Clients.Caller.notifyUser(NotificationTypes.Error, roomName, noChanMsg);
2019-05-10 09:58:09 +01:00
return;
}
2019-05-13 14:44:28 +01:00
2019-05-10 09:58:09 +01:00
}
2016-11-01 23:22:46 +01:00
[Authorize]
2019-05-22 17:27:44 +01:00
public void SendPV(string userName, string message)
2016-11-01 23:22:46 +01:00
{
2019-06-06 08:24:55 +01:00
if (string.IsNullOrWhiteSpace(userName)) return;
2019-05-24 20:15:48 +01:00
if (userName[0] != '?')
if (!Context.User.IsInRole(Constants.AdminGroupName))
{
var bl = _dbContext.BlackListed
.Include(r => r.User)
.Include(r => r.Owner)
.Where(r => r.User.UserName == Context.User.Identity.Name && r.Owner.UserName == userName)
.Select(r => r.OwnerId);
if (bl.Count() > 0)
{
2019-05-29 21:41:19 +01:00
Clients.Caller.notifyUser(NotificationTypes.PrivateMessageDenied, userName, "you are black listed.");
2019-05-24 20:15:48 +01:00
return;
}
}
var cxIds = ChatUserNames.Where(name => name.Value == userName).Select(name => name.Key);
foreach (var connectionId in cxIds)
{
var cli = Clients.Client(connectionId);
cli.addPV(Context.User.Identity.Name, message);
}
2016-11-01 23:22:46 +01:00
}
2019-01-26 14:23:53 +00:00
2019-05-10 09:58:09 +01:00
[Authorize]
2019-01-26 14:23:53 +00:00
public void SendStream(string connectionId, long streamId, string message)
{
var sender = Context.User.Identity.Name;
var cli = Clients.Client(connectionId);
cli.addStreamInfo(sender, streamId, message);
}
2016-11-03 14:52:17 +01:00
public void Abort()
2016-11-01 23:22:46 +01:00
{
2019-05-13 14:44:28 +01:00
var cx = _dbContext.ChatConnection.SingleOrDefault(c => c.ConnectionId == Context.ConnectionId);
if (cx != null)
{
2019-05-07 14:01:23 +01:00
_dbContext.ChatConnection.Remove(cx);
2019-05-13 14:44:28 +01:00
_dbContext.SaveChanges();
2016-11-03 14:52:17 +01:00
}
}
2016-11-01 23:22:46 +01:00
}
2016-05-17 18:22:18 +02:00
}