public async Task <IHttpActionResult> PostIdentity([FromBody] string contacts) { DataClassesManager.ControllerLog("info", _User.Id, this.Request.RequestUri.PathAndQuery, string.Format("{0}#{1}:{2}", "", _User.Username, string.IsNullOrEmpty(contacts) ? "NULL" : (contacts.Length > 20 ? contacts.Substring(0, 20) + "..." : contacts))); DateTimeOffset?ack; string countryCode; DataClassesManager.GetUserSyncInfo(_User.UserId.Value, out countryCode, out ack); string error = string.Empty; var script = Helper.SynchronizeUtils.GenerateSynchronizeIdentityTSQL(_User.UserId.Value, countryCode, contacts, out error); if (!string.IsNullOrEmpty(error)) { DataClassesManager.ControllerLog("error", _User.Id, this.Request.RequestUri.PathAndQuery, string.Format("{0}#{1}:{2}", "", _User.Username, error)); return(BadRequest(error)); } DataClassesManager.ExecuteSynchronizeScript(_User.UserId.Value, script, "Identity", ack, out error); if (string.IsNullOrEmpty(error)) { DataClassesManager.ControllerLog("info", _User.Id, this.Request.RequestUri.PathAndQuery, string.Format("{0}#{1}:{2}:{3}", "", _User.Username, ack, "Done")); } else { DataClassesManager.ControllerLog("error", _User.Id, this.Request.RequestUri.PathAndQuery, string.Format("{0}#{1}:{2}", "", _User.Username, error)); } DataClassesManager.ControllerLog("info", _User.Id, this.Request.RequestUri.PathAndQuery, string.Format("{0}#{1}:{2}", "", _User.Username, ack)); return(Ok(new { ack = ack })); }
public async Task <IHttpActionResult> Validate(string token, string code) { _SessionInfo.Details = Request.UserAgentInfo(); LogManager.WriteLog("info", token, this.Request.RequestUri.PathAndQuery, "", "", JsonConvert.SerializeObject(_SessionInfo)).Forget(); var error = string.Empty; long? userId = 0; string user_Id = string.Empty; var content = string.Empty; var updates = DataClassesManager.Validate(token, code, out userId, out user_Id, out content, out error); if (!string.IsNullOrEmpty(error)) { LogManager.WriteLog("error", token, this.Request.RequestUri.PathAndQuery, error).Forget(); return(BadRequest(error)); } LogManager.WriteLog("info", token, this.Request.RequestUri.PathAndQuery, "success").Forget(); return(Ok()); //foreach (var update in updates) //{ // if (update.Recipients != null && update.Recipients.Count > 0) // Task.Factory.StartNew(() => ChatUtils.BroadcastUpdate((ChatUtils.NotificationTypeEnum)update.TypeId, update.Id, user_Id, update.Recipients.Select(x => x.Id).ToList(), "")); //} }
public async Task <IHttpActionResult> Get() { var deviceSerial = _SessionInfo.DeviceSerial; if (string.IsNullOrEmpty(deviceSerial)) { DataClassesManager.ControllerLog("error", _User.Id, this.Request.RequestUri.PathAndQuery, string.Format("{0}:{1}", _User.Username, "SerialHeaderRequired")); return(BadRequest("SerialHeaderRequired")); } //var activeSession = context.UserSession.Where(x => x.UserId == user.UserId).OrderByDescending(x => x.LoggedAt).Take(1).SingleOrDefault(); //if (activeSession.DeviceSerial != deviceSerial) //{ // var ac = activeSession.DeviceSerial; // DataClassesManager.ControllerLog("error", id, this.Request.RequestUri.PathAndQuery, string.Format("{0}:{1}-current:{2}-active:{3}", user.Username, "Conflict", activeSession.DeviceSerial, deviceSerial)); // return Conflict(); //} var errorMessage = ""; var result = DataClassesManager.GetPendingChat(_User.UserId.Value, out errorMessage); if (!string.IsNullOrEmpty(errorMessage)) { DataClassesManager.ControllerLog("error", _User.Id, this.Request.RequestUri.PathAndQuery, string.Format("{0}:{1}", _User.Username, errorMessage)); return(BadRequest(errorMessage)); } var chatGroupedBySender = result.GroupBy(x => new { x.Group, x.Sender }, x => new { Id = x.Id, Type = x.Type, Content = x.Content, IssuedAt = x.IssuedAt.ToString(ChatUtils.DATE_TIME_FORMAT), ExpiresAt = x.ExpiresAt, SizeInBytes = x.SizeInBytes, Duration = x.Duration, IsScrambled = x.IsScrambled }) .Select(grp => new { sender = grp.Key.Sender, group = grp.Key.Group, chat = grp.ToList().OrderBy(x => x.IssuedAt) }).ToList(); DataClassesManager.ControllerLog("info", _User.Id, this.Request.RequestUri.PathAndQuery, string.Format("{0}:count={1}", _User.Username, result.Count)); return(Ok(chatGroupedBySender)); }
public async Task <IHttpActionResult> GetFavorites(DateTimeOffset?ack = null) { var inProcess = false; List <UserDTO> favorites = DataClassesManager.GetFavorites(_User.UserId.Value, ref ack, out inProcess); return(Ok(new { ack = ack, inProcess = inProcess, favorite = favorites })); }
public async Task <IHttpActionResult> CheckAvailability(int type, string value) { value = value.ToLower(); bool available = DataClassesManager.CheckIdentityAvailability(type, value); DataClassesManager.ControllerLog("info", value, this.Request.RequestUri.PathAndQuery, string.Format("{0}:{1}:available={2}", type, value, available)); return(Ok(new { Available = available })); }
internal static MessageServerFeedback SP_SaveNotification(long senderId, string recipientPublicId, ref long recipientInternalId, string localMessageId, int messageTypeId, string message, bool isScrambled, string expiresAt, int delay = 0, long?fileSizeInBytes = 0, int?duration = 0) { bool?alreadyReceived; string messageId; DateTimeOffset?issuedAt; bool?senderHasPendingNotifications; long?_recipientInternalId = recipientInternalId; DataClassesManager.SaveNotification(senderId, recipientPublicId, ref _recipientInternalId, localMessageId, messageTypeId, message, expiresAt, fileSizeInBytes, duration, isScrambled, delay, out alreadyReceived, out messageId, out issuedAt, out senderHasPendingNotifications); recipientInternalId = _recipientInternalId.Value; return(new MessageServerFeedback { AlreadyReceived = alreadyReceived.Value, Id = messageId, IssuedAt = issuedAt.Value, FormattedIssuedAt = issuedAt.Value.ToString(DATE_TIME_FORMAT), ReInitSessionRequired = senderHasPendingNotifications.Value }); }
public override Task OnConnected() { Models.User user; if (AuthorizedUser(out user, Context.ConnectionId)) { _connections.Add(user.Id, user.ConnectionInfo); DataClassesManager.InsertLog(string.Empty, "SignalR", "OnConnected", Context.ConnectionId, user.Id); } return(base.OnConnected()); }
protected override void OnIncomingError(ExceptionContext exceptionContext, IHubIncomingInvokerContext invokerContext) { var connectionId = invokerContext.Hub.Context.ConnectionId; DataClassesManager.InsertLog("=> Exception " + exceptionContext.Error.Message, "SignalR", "OnIncomingError", connectionId); if (exceptionContext.Error.InnerException != null) { DataClassesManager.InsertLog("=> Inner Exception " + exceptionContext.Error.InnerException.Message, "SignalR", "OnIncomingError", connectionId); } base.OnIncomingError(exceptionContext, invokerContext); }
public async Task <IHttpActionResult> Post(RegistrationDTO item) { var userId = string.Empty; if (!ModelState.IsValid) { LogManager.WriteLog("error", userId, this.Request.RequestUri.PathAndQuery, string.Format("{0}:{1}", JsonConvert.SerializeObject(item), JsonConvert.SerializeObject(ModelState))).Forget(); return(BadRequest(ModelState)); } var error = string.Empty; if (string.IsNullOrEmpty(item.Mobile) && string.IsNullOrEmpty(item.Email)) { error = "Mobile or email are required"; DataClassesManager.ControllerLog("error", userId, this.Request.RequestUri.PathAndQuery, error); return(BadRequest(error)); } long?preUserId = 0; var password = AuthorizationUtils.HashPassword(item.Password); var validation = DataClassesManager.Register(item.Username.ToLower(), password.Hash, password.Salt, item.CountryId, IdentityUtils.GetIdentitiesXML(item.Mobile, item.Email), out preUserId, out error); if (!string.IsNullOrEmpty(error)) { LogManager.WriteLog("error", userId, this.Request.RequestUri.PathAndQuery, error).Forget(); return(BadRequest(error)); } foreach (var v in validation) { IdentityUtils.ValidateIdentity(v); } LogManager.WriteLog("info", userId, this.Request.RequestUri.PathAndQuery, string.Format("{0}:{1}:{2}", preUserId, JsonConvert.SerializeObject(item), JsonConvert.SerializeObject(validation))).Forget(); return(Ok(new { RefId = preUserId, Identity = from x in validation where x.Immediate select new IdentityDTO { TypeId = x.TypeId, Value = x.Identity, Token = x.Token } } )); }
public async Task <IHttpActionResult> ValidateMobile(string id, string mobile) { DataClassesManager.ControllerLog("info", "", this.Request.RequestUri.PathAndQuery, string.Empty); var error = string.Empty; var regExp = DataClassesManager.GetRegExpByCountry(id); var result = IdentityUtils.ExactMatch(mobile, regExp); if (result) { return(Ok()); } return(BadRequest()); }
//[Authorize] public async Task <IHttpActionResult> Get(int offset = 0, int limit = 100) { var error = string.Empty; LogManager.WriteLog("info", _User.Username, this.Request.RequestUri.PathAndQuery, JsonConvert.SerializeObject(_SessionInfo)).Forget(); var users = DataClassesManager.GetUsers(_User.Id, offset, limit, out error); if (!string.IsNullOrEmpty(error)) { LogManager.WriteLog("error", "", this.Request.RequestUri.PathAndQuery, error).Forget(); return(BadRequest()); } return(Ok(users)); }
public void RecallNotification(IList <string> recalledIds) { Models.User user; if (AuthorizedUser(out user)) { string _recalledIds = string.Join(",", recalledIds); var updates = DataClassesManager.NotificationRecalled(user.UserId, _recalledIds); foreach (var update in updates) { var recipientConnectionId = _connections.GetConnectionId(update.Recipient_Id); if (!string.IsNullOrEmpty(recipientConnectionId)) { Clients.Client(recipientConnectionId).MessageRecalled(update.Id, update.Content); } } } }
public void ConfirmDelivery(IList <string> receivedIds) { Models.User user; if (AuthorizedUser(out user)) { DataClassesManager.InsertLog(string.Join(",", receivedIds), "SignalR", "ConfirmDelivery", Context.ConnectionId, string.Format("{0}-{1}", user.UserId, user.Username)); var updates = DataClassesManager.NotificationDelivered(user.UserId, string.Join(",", receivedIds)); foreach (var update in updates) { var recipientConnectionId = _connections.GetConnectionId(update.Recipient_Id); if (!string.IsNullOrEmpty(recipientConnectionId)) { Clients.Client(recipientConnectionId).MyMessageDelivered(update.Id, update.Content); } } } }
public void ConfirmRead(string notificationId, bool applyOnPreviouslyReceived) { Models.User user; if (AuthorizedUser(out user)) { DataClassesManager.InsertLog(string.Format("{0}-{1}", notificationId, applyOnPreviouslyReceived.ToString()), "SignalR", "ConfirmRead", Context.ConnectionId, string.Format("{0}-{1}", user.UserId, user.Username)); string recipientId = string.Empty; var update = DataClassesManager.NotificationRead(user.UserId, notificationId, applyOnPreviouslyReceived); if (update != null) { var recipientConnectionId = _connections.GetConnectionId(update.Recipient_Id); if (!string.IsNullOrEmpty(recipientConnectionId)) { Clients.Client(recipientConnectionId).MyMessageRead(update.Id, update.Content, applyOnPreviouslyReceived); } } } }
public override Task OnDisconnected(bool stopCalled) { if (!stopCalled) { var id = _connections.GetUserIdByConnectionId(Context.ConnectionId); _connections.Remove(id); DataClassesManager.InsertLog(string.Empty, "SignalR", "OnDisconnected", Context.ConnectionId, id); } else { Models.User user; if (AuthorizedUser(out user)) { _connections.Remove(user.Id); DataClassesManager.InsertLog(string.Empty, "SignalR", "OnDisconnected", Context.ConnectionId, string.Format("{0}-{1}", user.UserId, user.Username)); } } return(base.OnDisconnected(stopCalled)); }
public AuthSessionInfo ValidateSession(string username) { var id = string.Empty; long?internalId = -1; var password = new byte[] { }; var salt = new byte[] { }; try { DataClassesManager.preAuthorizationTokenGeneration(username, out id, out internalId, out password, out salt); return(new AuthSessionInfo { Id = id, UserId = internalId.Value, Password = password, Salt = salt }); } catch (Exception) { return(new AuthSessionInfo { Id = "", UserId = -1 }); } }
private static void SaveLog(string level, string userId, string request, string message, string category = "", string header = "") { StringBuilder builder = new StringBuilder(); builder.AppendLine(""); builder.AppendLine(string.Format("[Category:{0}]", category)); builder.AppendLine(string.Format("[UserId:{0}]", userId)); builder.AppendLine(header.Replace("\r\n", "")); builder.AppendLine(request); builder.AppendLine(message); builder.AppendLine(new string('-', 200)); if (level == "error") { log.Error(builder.ToString()); DataClassesManager.ControllerLog(level, userId, request, message, category); } else { log.Info(builder.ToString()); } }
public async Task <IHttpActionResult> ValidateIdentity(string token, string code) { DataClassesManager.ControllerLog("info", token, this.Request.RequestUri.PathAndQuery, string.Empty); var error = string.Empty; long? userId; string user_Id; var content = string.Empty; var updates = DataClassesManager.Validate(token, code, out userId, out user_Id, out content, out error); if (!string.IsNullOrEmpty(error)) { DataClassesManager.ControllerLog("error", token, this.Request.RequestUri.PathAndQuery, error); return(BadRequest(error)); } //Broadcast user joining //foreach (var update in updates) //{ // if (update.Recipients != null && update.Recipients.Count > 0) // Task.Factory.StartNew(() => ChatUtils.BroadcastUpdate((ChatUtils.NotificationTypeEnum)update.TypeId, update.Id, user_Id, update.Recipients.Select(x => x.Id).ToList(), "")); //} return(Ok()); }
private string SendMessage(string recipientId, string localMessageId, int messageTypeId, string message, string expiresAt, bool isScrambled) { Models.User sender; var messageId = string.Empty; var issuedAt = string.Empty; var reInitSessionRequired = false; if (AuthorizedUser(out sender)) { //if (!ChatHelper.FormatMessage(messageTypeId, ref message)) // return string.Empty; var recipientConnection = _connections.GetConnection(recipientId); long recipientInternalId = recipientConnection.PushMode ? -1 : recipientConnection.UserId; var feedback = ChatUtils.SP_SaveNotification(sender.UserId, recipientId, ref recipientInternalId, localMessageId, messageTypeId, message, isScrambled, expiresAt); DataClassesManager.InsertLog(string.Format("From {0}:{1}", sender.Username, message), "ChatHub", "SendMessage", string.Format("{0}-{1}", recipientConnection.PushMode, recipientConnection.ConnectionId), recipientId); messageId = feedback.Id; issuedAt = feedback.FormattedIssuedAt; reInitSessionRequired = feedback.ReInitSessionRequired; if (string.IsNullOrEmpty(messageId)) { return(string.Empty); } if (feedback.AlreadyReceived) { goto AlreadyReceived; } if (!recipientConnection.PushMode) { if (!string.IsNullOrEmpty(expiresAt))//.HasValue { Clients.Client(recipientConnection.ConnectionId).TemporaryMessageReceived(messageTypeId, messageId, message, sender.Id, expiresAt, isScrambled, issuedAt); } else { Clients.Client(recipientConnection.ConnectionId).MessageReceived(messageTypeId, messageId, message, sender.Id, isScrambled, issuedAt); } } else { bool requirePush; string pushPreview; //requirePush = Settings.PushNotificationTypes.TryGetValue(messageTypeId, out pushPreview); //if (string.IsNullOrEmpty(pushPreview)) // pushPreview = message; //Task.Factory.StartNew(() => { // PushManager.Send(pushPreview, recipientInternalId, recipientId, sender.Name, sender.Id); //}); } AlreadyReceived: if (messageId == "AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA") { Clients.Client(sender.ConnectionInfo.ConnectionId).RemoveContact(Guid.NewGuid().ToString(), recipientId); messageId = Guid.NewGuid().ToString(); } var callBack = string.Empty; callBack = string.Format("{0}#{1}#{2}#{3}", localMessageId, messageId, issuedAt, reInitSessionRequired.ToString()); return(callBack); } throw new HubException("Reconnect required"); }
public static void Remove(string id) { _connections.Remove(id); DataClassesManager.InsertLog(string.Empty, "SignalR", "#OnDisconnected", "", id); }