Exemple #1
0
        // ログ変換
        private void logConvert(string inputName, string outputName, string key)
        {
            ChatFile cf = new ChatFile(inputName, key);
            cf.Read();
            if (!cf.Authenticated || cf.Text.Length <= 0)
            {
                return;
            }

            if ( Directory.Exists(outputName) )
            {
                return;
            }

            try
            {
                using (FileStream fs = new FileStream(outputName, FileMode.Create, FileAccess.Write, FileShare.Read))
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.Write(cf.Text);
                }
            }
            catch (IOException)
            {
            }
        }
Exemple #2
0
        public static int Execute(List <string> args)
        {
            String Filename;
            String Database;
            String NewFilename;

            if (args.Count != 3)
            {
                Console.WriteLine("Usage: GraceNote_TO8CHTX ChatFilename DBFilename NewChatFilename");
                return(-1);
            }
            else
            {
                Filename    = args[0];
                Database    = args[1];
                NewFilename = args[2];
            }

            ChatFile c = new ChatFile(System.IO.File.ReadAllBytes(Filename));

            c.GetSQL("Data Source=" + Database);

            c.RecalculatePointers();
            System.IO.File.WriteAllBytes(NewFilename, c.Serialize());

            return(0);
        }
Exemple #3
0
        public static int Execute(List <string> args)
        {
            String Filename;
            String Database;
            String NewFilename;

            if (args.Count != 3)
            {
                Console.WriteLine("Usage: GraceNote_TO8CHTX ChatFilename DBFilename NewChatFilename");
                return(-1);
            }
            else
            {
                Filename    = args[0];
                Database    = args[1];
                NewFilename = args[2];
            }

            ChatFile c = new ChatFile(Filename, EndianUtils.Endianness.BigEndian, TextUtils.GameTextEncoding.ShiftJIS, BitUtils.Bitness.B32, 2);

            c.GetSQL("Data Source=" + Database);

            c.RecalculatePointers();
            System.IO.File.WriteAllBytes(NewFilename, c.Serialize());

            return(0);
        }
Exemple #4
0
        public static void UploadFile(string key, ChatFile file, Action onSuccess, Action onFail)
        {
            FindChat(key, (ChatRoom room) => {
                room.AddFile(file);

                UniChatModule.mainInstance.database.GetCollection <Chat>("chats").Update(room.Chat);

                onSuccess?.Invoke();
            }, onFail);
        }
Exemple #5
0
        public int UploadFile(ChatFile chatFile)
        {
            try
            {
                using (UserContext userContext = new UserContext())
                {
                    userContext.ChatFiles.Add(chatFile);
                    userContext.SaveChanges();
                    int id = userContext.ChatFiles.Max(ch => ch.Id);

                    return(id);
                }
            }
            catch (Exception)
            {
                return(-1);
            }
        }
        /// <summary>
        /// Manage the selection of the file to be uploaded
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Upload(object sender, RoutedEventArgs e)
        {
            var            fileContent    = string.Empty;
            var            filePath       = string.Empty;
            OpenFileDialog openFileDialog = new OpenFileDialog();
            {
                try
                {
                    openFileDialog.InitialDirectory = Environment.CurrentDirectory;
                    openFileDialog.Filter           = "All files (*.*)|*.*";
                    openFileDialog.FilterIndex      = 1;
                    openFileDialog.RestoreDirectory = true;
                    if (openFileDialog.ShowDialog() == true)
                    {
                        //Get the path of specified file
                        filePath = openFileDialog.FileName;

                        //Read the contents of the file into a stream
                        var fileStream = openFileDialog.OpenFile();

                        Uploaded      = new ChatFile();
                        Uploaded.Name = Path.GetFileName(openFileDialog.FileName);
                        Uploaded.Kind = MessageKindType.FILE;
                        UploadName    = Uploaded.Name;
                        //Uploaded.Description updated on send
                        Uploaded.FileContent = new ChatFileContent()
                        {
                            Content = File.ReadAllBytes(openFileDialog.FileName)
                        };
                    }
                    UploadReady = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Unable to load file");
                    Uploaded    = null;
                    UploadReady = false;
                    UploadName  = string.Empty;
                }
            }
        }
Exemple #7
0
        public static int Execute(List <string> args)
        {
            if (args.Count != 3)
            {
                Console.WriteLine("Usage: TO8CHTX_GraceNote ChatFilename NewDBFilename GracesJapanese");
                return(-1);
            }

            String Filename = args[0];
            String NewDB    = args[1];
            String GracesDB = args[2];

            ChatFile c = new ChatFile(System.IO.File.ReadAllBytes(Filename));

            GraceNoteUtil.GenerateEmptyDatabase(NewDB);

            List <GraceNoteDatabaseEntry> Entries = new List <GraceNoteDatabaseEntry>(c.Lines.Length * 2);

            foreach (ChatFileLine Line in c.Lines)
            {
                String EnglishText;
                int    EnglishStatus;
                if (Line.SENG == "Dummy" || Line.SENG == "")
                {
                    EnglishText   = Line.SJPN;
                    EnglishStatus = 0;
                }
                else
                {
                    EnglishText   = Line.SENG;
                    EnglishStatus = 1;
                }

                Entries.Add(new GraceNoteDatabaseEntry(Line.SName, Line.SName, "", 1, Line.Location, "", 0));
                Entries.Add(new GraceNoteDatabaseEntry(Line.SJPN, EnglishText, "", EnglishStatus, Line.Location + 4, "", 0));
            }

            GraceNoteDatabaseEntry.InsertSQL(Entries.ToArray(), "Data Source=" + NewDB, "Data Source=" + GracesDB);
            return(0);
        }
        protected override void Begin()
        {
            CommandListener listener = new UniChatListener();

            servant.Listen?.Invoke(listener);
            servant.CatchUp?.Invoke();

            server.Start(socket => {
                string ip = socket.ConnectionInfo.ClientIpAddress;

                socket.OnOpen = () => {
                    if (onlineUsers.Find((user) => user.IP.Equals(ip)) != null)
                    {
                        socket.Close();

                        socket = null;

                        servant.Log($"Connection attempt denied (Duplicate IP {ip})", foreground: Servant.LogColors.RED);
                    }

                    else
                    {
                        servant.Log($"New client connected ({ip})", foreground: Servant.LogColors.GREEN, group: (newClientGroup) => {
                            logContexts[ip] = newClientGroup;
                        });
                    }
                };

                if (socket != null)
                {
                    socket.OnClose = () => {
                        servant.Log($"Client disconnected ({ip})", foreground: Servant.LogColors.RED, context: logContexts[ip]);

                        User disconnectedUser = onlineUsers.Find(user => user.IP.Equals(ip));

                        if (disconnectedUser != null)
                        {
                            ChatRoomsController.LeaveAllChats(disconnectedUser);

                            onlineUsers.Remove(disconnectedUser);
                        }
                    };

                    socket.OnMessage = json => {
                        servant.Log($"Received new message: {json}", context: logContexts[ip], group: (newDataGroup) => {
                            Message message = null;

                            try {
                                message = JsonConvert.DeserializeObject <Message>(json);
                            }

                            catch (Exception e) {
                                servant.Log($"Failed to parse message ({e.Message})", context: newDataGroup);
                            }

                            if (message != null)
                            {
                                if (message.core?.action != null)
                                {
                                    switch (message.core.action)
                                    {
                                    case Actions.PING:

                                        Send(new Message()
                                        {
                                            core = new Message.Core()
                                            {
                                                action = Actions.PONG
                                            }
                                        }, socket);

                                        break;

                                    case Actions.LOGIN_ANONYMOUS:

                                        if (message.auth != null && !string.IsNullOrWhiteSpace(message.auth.username))
                                        {
                                            string key = GenerateKey(User.USER_KEY_LENGTH);

                                            onlineUsers.Add(new User(User.UserTypes.ANONYMOUS, message.auth.username, key, ip, (string type, dynamic update) => {
                                                switch (type)
                                                {
                                                case Actions.ADD_CHAT_MESSAGE:

                                                    Send(new Message()
                                                    {
                                                        core = new Message.Core()
                                                        {
                                                            action = Actions.ADD_CHAT_MESSAGE
                                                        },

                                                        query = new Message.Query()
                                                        {
                                                            chatMesage = update.message,
                                                            chat       = new Chat(update.key)
                                                        }
                                                    }, socket);

                                                    break;

                                                case Actions.ADD_CHAT_FILE:

                                                    Send(new Message()
                                                    {
                                                        core = new Message.Core()
                                                        {
                                                            action = Actions.ADD_CHAT_FILE
                                                        },

                                                        query = new Message.Query()
                                                        {
                                                            file = new ChatFile()
                                                            {
                                                                key  = update.file.key,
                                                                name = update.file.name
                                                            },
                                                            chat = new Chat(update.key)
                                                        }
                                                    }, socket);

                                                    break;
                                                }
                                            }));

                                            Send(new Message()
                                            {
                                                core = new Message.Core()
                                                {
                                                    action = Actions.LOGIN_ANONYMOUS,
                                                    key    = key
                                                }
                                            }, socket);
                                        }

                                        else
                                        {
                                            SendError(true, "Specified name is invalid", socket);
                                        }

                                        break;

                                    default:

                                        if (message.core.key != null)
                                        {
                                            User user = onlineUsers.Find(entry => entry.Key.Equals(message.core.key));

                                            if (user != null)
                                            {
                                                switch (message.core.action)
                                                {
                                                case Actions.LIST_CHAT_ROOMS:

                                                    Send(new Message()
                                                    {
                                                        core = new Message.Core()
                                                        {
                                                            action = Actions.LIST_CHAT_ROOMS
                                                        },

                                                        query = new Message.Query()
                                                        {
                                                            chatList = ChatRoomsController.GetChats(user)
                                                        }
                                                    }, socket);

                                                    break;

                                                case Actions.LIST_ACCESSIBLE_CHAT_ROOMS:

                                                    Send(new Message()
                                                    {
                                                        core = new Message.Core()
                                                        {
                                                            action = Actions.LIST_ACCESSIBLE_CHAT_ROOMS
                                                        },

                                                        query = new Message.Query()
                                                        {
                                                            chatList = ChatRoomsController.GetAccessibleChats(user)
                                                        }
                                                    }, socket);

                                                    break;

                                                case Actions.LOGOUT:

                                                    onlineUsers.Remove(user);

                                                    Send(new Message()
                                                    {
                                                        core = new Message.Core()
                                                        {
                                                            action = Actions.LOGOUT
                                                        }
                                                    }, socket);

                                                    break;

                                                case Actions.CHANGE_ANONYMOUS_NAME:

                                                    ChatRoomsController.IsUserInAnyChat(user, () => SendError(true, "The user needs to leave all chats before they can change their name", socket), () => {
                                                        user.Name = message.auth.username;

                                                        Send(new Message()
                                                        {
                                                            core = new Message.Core()
                                                            {
                                                                action = Actions.CHANGE_ANONYMOUS_NAME
                                                            },

                                                            auth = new Message.Auth()
                                                            {
                                                                username = message.auth.username
                                                            }
                                                        }, socket);
                                                    });

                                                    break;

                                                default:

                                                    if (message.query != null)
                                                    {
                                                        switch (message.core.action)
                                                        {
                                                        case Actions.GET_FILE_META: {
                                                            string key = message.query.file.key,
                                                            chatKey    = message.query.file.chatKey;

                                                            ChatFile result = database.GetCollection <Chat>("chats").FindOne(chat => chat.key.Equals(chatKey))?.files?.Find(file => file.key.Equals(key));

                                                            if (result != null)
                                                            {
                                                                Send(new Message()
                                                                    {
                                                                        core = new Message.Core()
                                                                        {
                                                                            action = Actions.GET_FILE_META
                                                                        },

                                                                        query = new Message.Query()
                                                                        {
                                                                            file = new ChatFile()
                                                                            {
                                                                                name        = result.name,
                                                                                key         = result.key,
                                                                                chatKey     = chatKey,
                                                                                extension   = result.extension,
                                                                                destination = message.query.file.destination
                                                                            },
                                                                        }
                                                                    }, socket);
                                                            }

                                                            else
                                                            {
                                                                SendError(false, "File couldn't be found", socket);
                                                            }

                                                            break;
                                                        }

                                                        case Actions.GET_FILE: {
                                                            string key = message.query.file.key,
                                                            chatKey    = message.query.file.chatKey;

                                                            ChatFile result = database.GetCollection <Chat>("chats").FindOne(chat => chat.key.Equals(chatKey)).files.Find(file => file.key.Equals(key));

                                                            if (result != null)
                                                            {
                                                                result.destination = message.query.file.destination;
                                                                result.chatKey     = chatKey;

                                                                Send(new Message()
                                                                    {
                                                                        core = new Message.Core()
                                                                        {
                                                                            action = Actions.GET_FILE
                                                                        },

                                                                        query = new Message.Query()
                                                                        {
                                                                            file = result,
                                                                        }
                                                                    }, socket);
                                                            }

                                                            else
                                                            {
                                                                SendError(false, "File couldn't be found", socket);
                                                            }

                                                            break;
                                                        }

                                                        case Actions.CREATE_CHAT_ROOM:

                                                            ChatRoomsController.CreateChatRoom(message.query.chat, (Chat chat) => {
                                                                onlineUsers.ForEach((onlineUser) => {
                                                                    if (onlineUser.Type.Equals(User.UserTypes.ANONYMOUS))
                                                                    {
                                                                        Send(new Message()
                                                                        {
                                                                            core = new Message.Core()
                                                                            {
                                                                                action = Actions.ADD_CHAT_ROOM
                                                                            },

                                                                            query = new Message.Query()
                                                                            {
                                                                                chat = new Chat(chat.key)
                                                                                {
                                                                                    name        = chat.name,
                                                                                    description = chat.description,
                                                                                    messages    = chat.messages,
                                                                                    password    = string.IsNullOrEmpty(chat.password) ? ChatRoomsController.ChatRoomProtectoionStatus.UNLOCKED : ChatRoomsController.ChatRoomProtectoionStatus.LOCKED
                                                                                }
                                                                            }
                                                                        }, socket);
                                                                    }
                                                                });
                                                            }, () => SendError(true, "Failed to create chat", socket));

                                                            break;

                                                        case Actions.UPLOAD_FILE: {
                                                            string uploadKey = message.query.file?.key;

                                                            if (uploadKey != null && uploadingFiles.TryGetValue(uploadKey, out string chatKey))
                                                            {
                                                                string key = GenerateKey(FILE_KEY_LENGTH);

                                                                message.query.file.key = key;

                                                                uploadingFiles.Remove(uploadKey);

                                                                ChatRoomsController.UploadFile(chatKey, message.query.file, () => {
                                                                    }, () => {
                                                                        SendError(false, "Error uploading file", socket);
                                                                    });
                                                            }

                                                            else
                                                            {
                                                                SendError(true, "Error uploading file - wrong key", socket);
                                                            }

                                                            break;
                                                        }

                                                        default:

                                                            if (message.query.chat?.key != null)
                                                            {
                                                                switch (message.core.action)
                                                                {
                                                                case Actions.START_FILE_UPLOAD:

                                                                    ChatRoomsController.IsUserInChat(message.query.chat.key, user, () => {
                                                                        string key = GenerateKey(FILE_UPLOAD_KEY_LENGTH);

                                                                        uploadingFiles.Add(key, message.query.chat?.key, 1 * 60 * 1000);

                                                                        Send(new Message()
                                                                        {
                                                                            core = new Message.Core()
                                                                            {
                                                                                action = Actions.START_FILE_UPLOAD
                                                                            },

                                                                            query = new Message.Query()
                                                                            {
                                                                                file = new ChatFile()
                                                                                {
                                                                                    key  = key,
                                                                                    name = message.query.file.name
                                                                                }
                                                                            }
                                                                        }, socket);
                                                                    }, () => {
                                                                        SendError(true, "User can't upload files to this chat", socket);
                                                                    });

                                                                    break;

                                                                case Actions.LEAVE_CHAT_ROOM:

                                                                    ChatRoomsController.LeaveChat(message.query.chat.key, user, () => {
                                                                        Send(new Message()
                                                                        {
                                                                            core = new Message.Core()
                                                                            {
                                                                                action = Actions.LEAVE_CHAT_ROOM
                                                                            },

                                                                            query = new Message.Query()
                                                                            {
                                                                                chat = new Chat(message.query.chat.key)
                                                                            }
                                                                        }, socket);

                                                                        ChatRoomsController.ChatExists(message.query.chat.key, null, () => {
                                                                            Send(new Message()
                                                                            {
                                                                                core = new Message.Core()
                                                                                {
                                                                                    action = Actions.REMOVE_CHAT_ROOM
                                                                                },

                                                                                query = new Message.Query()
                                                                                {
                                                                                    chat = new Chat(message.query.chat.key)
                                                                                }
                                                                            }, socket);
                                                                        });
                                                                    }, () => SendError(true, "This user is not connected to a chat", socket));

                                                                    break;

                                                                case Actions.ADD_CHAT_MESSAGE:

                                                                    if (message.query.chatMesage?.text != null)
                                                                    {
                                                                        ChatRoomsController.SendMessage(message.query.chat.key, message.query.chatMesage, ChatMessage.ChatMessageTypes.BASIC, user, () => {
                                                                        }, () => SendError(true, "Chat doesn't exist or user have not joined it", socket));
                                                                    }

                                                                    else
                                                                    {
                                                                        SendError(true, "Message can't be empty", socket);
                                                                    }

                                                                    break;

                                                                case Actions.GET_CHAT_MESSAGES:

                                                                    ChatRoomsController.GetChatMessages(message.query.chat.key, (List <ChatMessage> chatMessages) => Send(new Message()
                                                                    {
                                                                        core = new Message.Core()
                                                                        {
                                                                            action = Actions.GET_CHAT_MESSAGES
                                                                        },

                                                                        query = new Message.Query()
                                                                        {
                                                                            chat = new Chat(message.query.chat.key)
                                                                            {
                                                                                messages = chatMessages
                                                                            }
                                                                        }
                                                                    }, socket), () => SendError(true, "Chat with specified key was not found", socket));

                                                                    break;

                                                                case Actions.GET_CHAT_FILES:

                                                                    ChatRoomsController.GetChatFiles(message.query.chat.key, (List <ChatFile> chatFiles) => Send(new Message()
                                                                    {
                                                                        core = new Message.Core()
                                                                        {
                                                                            action = Actions.GET_CHAT_FILES
                                                                        },

                                                                        query = new Message.Query()
                                                                        {
                                                                            chat = new Chat(message.query.chat.key)
                                                                            {
                                                                                files = chatFiles
                                                                            }
                                                                        }
                                                                    }, socket), () => SendError(true, "Chat with specified key was not found", socket));

                                                                    break;

                                                                case Actions.UNLOCK_CHAT_ROOM:

                                                                    ChatRoomsController.UnlockChat(message.query.chat?.key, user, message.query.chat?.password, () => {
                                                                        Send(new Message()
                                                                        {
                                                                            core = new Message.Core()
                                                                            {
                                                                                action = Actions.UNLOCK_CHAT_ROOM
                                                                            },

                                                                            query = new Message.Query()
                                                                            {
                                                                                chat = new Chat(message.query.chat?.key)
                                                                            }
                                                                        }, socket);
                                                                    }, () => SendError(true, "Failed to unlock chat", socket));

                                                                    break;

                                                                case Actions.JOIN_CHAT_ROOM:

                                                                    ChatRoomsController.JoinChat(message.query.chat?.key, user, (Chat chat) => {
                                                                        Send(new Message()
                                                                        {
                                                                            core = new Message.Core()
                                                                            {
                                                                                action = Actions.JOIN_CHAT_ROOM
                                                                            },

                                                                            query = new Message.Query()
                                                                            {
                                                                                chat = chat
                                                                            }
                                                                        }, socket);
                                                                    }, () => SendError(true, "Failed to join chat", socket));

                                                                    break;
                                                                }
                                                            }

                                                            else
                                                            {
                                                                SendError(true, "No chat key specified", socket);
                                                            }

                                                            break;
                                                        }
                                                    }

                                                    else
                                                    {
                                                        SendError(true, "No query specified", socket);
                                                    }

                                                    break;
                                                }
                                            }

                                            else
                                            {
                                                SendError(true, "This user is no longer online", socket);
                                            }
                                        }

                                        else
                                        {
                                            SendError(true, "No key specified", socket);
                                        }

                                        break;
                                    }
                                }

                                else
                                {
                                    SendError(true, "No action specified", socket);
                                }
                            }
                            else
                            {
                                SendError(true, "Unable to parse message", socket);
                            }
                        });
                    };
                }
            });

            servant.Log("Server started", foreground: Servant.LogColors.MAGENTA);

            IsRunning = true;
        }
Exemple #9
0
        // チャットファイル設定
        private DateTime setupTodayChatFile()
        {
            // ファイル名を作る
            DateTime dt = DateTime.Now;
            string baseName = dt.ToString("yyyyMMdd") + ".txt";
            string fileName = Path.Combine(this.ChannelPath, baseName);
            if (this.logPath.Length > 0)
            {
                this.logFileName = Path.Combine(this.logPath, baseName);
            }
            if (this.chatFile == null || fileName != this.chatFile.FileName)
            {
                this.chatFile = new ChatFile(fileName, this.key);
                this.chatFile.Authenticate(this.nickName);
            }

            return dt;
        }
Exemple #10
0
        public void SendChatMessage(string chatGroupId, string message, int chatSourceId, string receiverIds, int?fileId = null,
                                    int?taskId = null, int?taskMultilevelListId = null, int?userChatGroupId = null)
        {
            try
            {
                if (string.IsNullOrEmpty(receiverIds))
                {
                    ErrorLogBLL.Instance.SaveApplicationError("ChatHub", "ReceiverIds cannot be empty or null", "ReceiverIds cannot be empty or null", "");
                    Clients.Group(chatGroupId).sendChatMessageCallbackError(new ActionOutput <string>
                    {
                        Status  = ActionStatus.Successfull,
                        Object  = "ReceiverIds cannot be empty or null",
                        Message = chatGroupId
                    });
                }

                System.Web.HttpContextBase httpContext = Context.Request.GetHttpContext();

                //int? UserChatGroupId = ChatBLL.Instance.GetUserChatGroupId(chatGroupId);


                string baseurl = httpContext.Request.Url.Scheme + "://" +
                                 httpContext.Request.Url.Authority +
                                 httpContext.Request.ApplicationPath.TrimEnd('/') + "/";
                // Getting Logged In UserID from cookie.
                // FYI: Sessions are not allowed in SignalR, so have to user some other way to pass information
                int        SenderUserId = 0;
                HttpCookie auth_cookie  = httpContext.Request.Cookies[Cookies.UserId];
                if (auth_cookie != null)
                {
                    SenderUserId = Convert.ToInt32(auth_cookie.Value);
                }

                // Check for file attachment
                if (fileId.HasValue && fileId.Value > 0)
                {
                    ChatFile file = ChatBLL.Instance.GetChatFile(fileId.Value);
                    message = file.DisplayName + ":-:" + file.SavedName;
                }
                //add logger
                //ChatBLL.Instance.ChatLogger(chatGroupId, message, chatSourceId, SenderUserId, httpContext.Request.UserHostAddress);
                DataRow sender = InstallUserBLL.Instance.getuserdetails(SenderUserId).Tables[0].Rows[0];
                string  pic    = string.IsNullOrEmpty(sender["Picture"].ToString()) ? "default.jpg"
                                    : sender["Picture"].ToString().Replace("~/UploadeProfile/", "");
                pic = /*baseUrl +*/ "Employee/ProfilePictures/" + pic;

                // Create TaskGroup if taskId is not null and userChatGroupId is null/0
                if (taskId.HasValue && taskId.Value > 0 && userChatGroupId.Value <= 0)
                {
                    userChatGroupId = ChatBLL.Instance.CreateTaskChatGroup(taskId.Value, taskMultilevelListId);
                }

                // Instatiate ChatMessage
                ChatMessage chatMessage = new ChatMessage
                {
                    UserChatGroupId      = userChatGroupId,
                    TaskId               = taskId,
                    TaskMultilevelListId = taskMultilevelListId,
                    Message              = message,
                    FileId               = fileId,
                    ChatSourceId         = chatSourceId,
                    UserId               = SenderUserId,
                    UserProfilePic       = pic,
                    UserFullname         = sender["FristName"].ToString() + " " + sender["Lastname"].ToString(),
                    UserInstallId        = sender["UserInstallID"].ToString(),
                    MessageAt            = DateTime.UtcNow.ToEST(),
                    MessageAtFormatted   = DateTime.UtcNow.ToEST().ToString()
                };

                // Finding correct chat group in which message suppose to be posted.
                ChatGroup chatGroup = SingletonUserChatGroups.Instance.ChatGroups.Where(m => m.ChatGroupId == chatGroupId).FirstOrDefault();
                if (chatGroup != null && chatGroup.ChatMessages == null)
                {
                    chatGroup.ChatMessages = new List <ChatMessage>();
                }
                // Adding chat message into chatGroup
                // Remove old Messages from list and newly one.
                chatGroup.ChatMessages.RemoveRange(0, chatGroup.ChatMessages.Count()); // May require to comment in future.
                chatGroup.ChatMessages.Add(chatMessage);

                // Checking in database to fetch all connectionIds of browser of this chat group
                // FYI: Everytime, we reload a web page, SignalR brower connectionId gets changed, So
                // we have to always look database for correct connectionIds
                var        newConnections = ChatBLL.Instance.GetChatUsers(chatGroup.ChatUsers.Select(m => m.UserId.Value).ToList()).Results;
                List <int> onlineUserIds  = newConnections.Select(m => m.UserId.Value).ToList();
                // Modify existing connectionIds into particular ChatGroup and save into static "UserChatGroups" object
                foreach (var user in chatGroup.ChatUsers.Where(m => onlineUserIds.Contains(m.UserId.Value)))
                {
                    if (newConnections.Where(m => m.UserId == user.UserId).Any())
                    {
                        user.ConnectionIds     = newConnections.Where(m => m.UserId == user.UserId).Select(m => m.ConnectionIds).FirstOrDefault();
                        user.OnlineAt          = newConnections.Where(m => m.UserId == user.UserId).OrderByDescending(m => m.OnlineAt).Select(m => m.OnlineAt).FirstOrDefault();
                        user.OnlineAtFormatted = user.OnlineAt.HasValue ? user.OnlineAt.Value.ToEST().ToString() : null;
                    }
                }
                // Chat status to active of sender
                if (SingletonUserChatGroups.Instance.ActiveUsers.Where(m => m.UserId == SenderUserId).Any())
                {
                    SingletonUserChatGroups.Instance.ActiveUsers.Where(m => m.UserId == SenderUserId)
                    .First().Status = (int)ChatUserStatus.Active;
                    SingletonUserChatGroups.Instance.ActiveUsers.Where(m => m.UserId == SenderUserId)
                    .First().LastActivityAt = DateTime.UtcNow;
                }

                // Adding each connection into SignalR Group, so that we can send messages to all connected users.
                foreach (var item in chatGroup.ChatUsers.Where(m => m.OnlineAt.HasValue))
                {
                    foreach (string connectionId in item.ConnectionIds)
                    {
                        Groups.Add(connectionId, chatGroupId);
                    }
                }

                // merge logged in user id into ReceiverIds
                receiverIds += "," + SenderUserId;

                // Check if message has base64 string (images)
                List <ChatMessage> imageMessages = new List <ChatMessage>();
                if (message.Contains("img") && message.Contains("copy-paste-image"))
                {
                    int             imageFileId   = 0;
                    string          imageName     = "";
                    List <string>   images        = new List <string>();
                    string          regexImgSrc   = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
                    MatchCollection matchesImgSrc = Regex.Matches(message, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                    foreach (Match m in matchesImgSrc)
                    {
                        string base64 = m.Groups[1].Value;
                        base64 = base64.Substring(base64.IndexOf("base64,") + 7);
                        images.Add(base64);
                        byte[] bytes = Convert.FromBase64String(base64);
                        Image  image;
                        using (MemoryStream ms = new MemoryStream(bytes))
                        {
                            image = Image.FromStream(ms);
                        }
                        imageName = Guid.NewGuid().ToString().Replace("@", "-") + ".jpg";
                        string path = HostingEnvironment.MapPath(JGConstant.ChatFilePath + "/" + imageName);
                        image.Save(path);

                        imageFileId = ChatBLL.Instance.SaveChatFile(imageName, imageName, image.GetImageMime());

                        imageMessages.Add(new ChatMessage
                        {
                            UserChatGroupId      = chatMessage.UserChatGroupId,
                            TaskId               = chatMessage.TaskId,
                            TaskMultilevelListId = chatMessage.TaskMultilevelListId,
                            Message              = imageName + ":-:" + imageName,
                            FileId               = imageFileId,
                            ChatSourceId         = chatMessage.ChatSourceId,
                            UserId               = chatMessage.UserId,
                            UserProfilePic       = chatMessage.UserProfilePic,
                            UserFullname         = chatMessage.UserFullname,
                            UserInstallId        = chatMessage.UserInstallId,
                            MessageAt            = chatMessage.MessageAt,
                            MessageAtFormatted   = chatMessage.MessageAtFormatted
                        });
                        chatMessage.FileId  = imageFileId;
                        chatMessage.Message = imageName + ":-:" + imageName;
                        ChatBLL.Instance.SaveChatMessage(chatMessage, chatGroupId, receiverIds, SenderUserId);
                    }
                }

                // Send Email notification to all offline users
                foreach (var item in chatGroup.ChatUsers.Where(m => !m.OnlineAt.HasValue))
                {
                    // Send Chat Notification Email
                    ChatBLL.Instance.SendOfflineChatEmail(SenderUserId, item.UserId.Value, sender["UserInstallID"].ToString(),
                                                          chatMessage.Message, chatSourceId, baseurl, chatGroupId);
                }

                // Saving chat into database
                // Check if message does not have base64 string (images)
                if (!(message.Contains("img") && message.Contains("copy-paste-image")))
                {
                    ChatBLL.Instance.SaveChatMessage(chatMessage, chatGroupId, receiverIds, SenderUserId);
                    imageMessages.Add(chatMessage);
                }

                taskId = taskId.HasValue ? taskId.Value : 0;
                taskMultilevelListId = taskMultilevelListId.HasValue ? taskMultilevelListId.Value : 0;

                Clients.Group(chatGroupId).updateClient(new ActionOutput <ChatMessage>
                {
                    Status  = ActionStatus.Successfull,
                    Object  = chatMessage,
                    Results = imageMessages,
                    Message = chatGroupId + "`" + chatGroup.ChatGroupName + "`" + receiverIds + "`" + SenderUserId + "`" + taskId + "`" + taskMultilevelListId + "`" + userChatGroupId
                });
            }
            catch (Exception ex)
            {
                ErrorLogBLL.Instance.SaveApplicationError("ChatHub", ex.Message, ex.ToString(), "");
                Clients.Group(chatGroupId).sendChatMessageCallbackError(new ActionOutput <string>
                {
                    Status  = ActionStatus.Successfull,
                    Object  = ex.ToString(),
                    Message = chatGroupId
                });
            }
        }
Exemple #11
0
        public ActionResult AddToAdmin(ChatFormViewModel model)
        {
            if (!Init(User))
            {
                return(RedirectToAction("Index", "Home"));
            }

            if ((_isAdministrator && !_permission.Contains(PermissionEnum.CHAT)) && !_isStudent)
            {
                return(RedirectToAction("Menu", "Home"));
            }

            if (string.IsNullOrEmpty(model.Title))
            {
                ModelState.AddModelError("", "Należy podać tytuł wiadomości");
            }

            if (string.IsNullOrEmpty(model.Content))
            {
                ModelState.AddModelError("", "Należy podać treść wiadomości");
            }

            if (_userRepository.GetById(model.User) == null)
            {
                ModelState.AddModelError("", "Nalezy wybrać adresata wiadomości");
            }

            if (ModelState.IsValid)
            {
                Chat chatDb = new Chat()
                {
                    Title          = model.Title,
                    Content        = model.Content,
                    ReceiverUserId = model.User,
                };

                if (_isAdministrator)
                {
                    chatDb.SenderUserId = _administrator.Id;
                }
                else if (_isStudent)
                {
                    chatDb.SenderStudentId = _student.Id;
                }

                _chatRepository.Add(chatDb);

                if (model.File != null)
                {
                    string   guid       = Guid.NewGuid().ToString("N");
                    ChatFile chatFileDb = new ChatFile()
                    {
                        RealFileName  = model.File.FileName,
                        SavedFileName = guid + Path.GetExtension(model.File.FileName),
                        ChatId        = chatDb.Id
                    };
                    chatDb.File = chatFileDb;

                    string path = Request.PhysicalApplicationPath + "Uploads\\" + guid + Path.GetExtension(model.File.FileName);
                    model.File.SaveAs(path);
                }

                chatDb.ParentChatId = chatDb.Id;
                _chatRepository.AddParentId(chatDb);

                return(RedirectToAction("Details", new { id = chatDb.Id }));
            }

            model.Users    = GetUsers();
            model.HasError = true;
            return(View(model));
        }
Exemple #12
0
 public void NewFile(ChatFile file, string key)
 {
     updateListener?.Invoke(Actions.ADD_CHAT_FILE, new { file, key });
 }
Exemple #13
0
 /// <summary>
 /// Remove an uploaded file
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void CancelUpload(object sender, RoutedEventArgs e)
 {
     Uploaded    = null;
     UploadReady = false;
 }
Exemple #14
0
        /// <summary>
        /// Send message to the channel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Send(object sender, RoutedEventArgs e)
        {
            List <ChatUser> selectedToSend = new List <ChatUser>();

            foreach (ChatUser cu in Book.UserList)
            {
                if (cu.Selected)
                {
                    selectedToSend.Add(cu);
                }
            }

            this.Dispatcher.Invoke(() =>
            {
                Message MessageToSend = null;
                if (UploadReady)
                {
                    //send the uploaded file with the text message
                    MessageToSend               = Uploaded;
                    MessageToSend.Sender        = messageModule.Id;
                    MessageToSend.StringContent = MessageText.Text;
                }
                else
                {
                    //prepare a text message
                    MessageToSend = new Message()
                    {
                        Sender        = messageModule.Id,
                        Kind          = MessageKindType.STRING,
                        StringContent = MessageText.Text
                    };
                }
                if (selectedToSend.Count == 0)
                {
                    SignedMessage signedTextMessage = new SignedMessage(MessageToSend.ToJson());
                    messageModule.SendMessage <string>(signedTextMessage.ToJson());
                }
                else
                {
                    bool sentToMyself = false;
                    foreach (ChatUser cu in selectedToSend)
                    {
                        MessageToSend.Destination       = cu.Sender;
                        SignedMessage signedTextMessage = new SignedMessage(MessageToSend.ToJson());
                        messageModule.SendMessage <string>(signedTextMessage.ToJson());
                        if (cu.Sender == UserProfile.Sender)
                        {
                            sentToMyself = true;
                        }
                    }
                    if (!sentToMyself)
                    {
                        //send always a copy of the encrypted message to myself
                        MessageToSend.Destination       = UserProfile.Sender;
                        SignedMessage signedTextMessage = new SignedMessage(MessageToSend.ToJson());
                        messageModule.SendMessage <string>(signedTextMessage.ToJson());
                    }
                }
                MessageText.Text = string.Empty;
                Uploaded         = null;
                UploadReady      = false;
            });
        }
Exemple #15
0
        public void AddFile(ChatFile file)
        {
            Chat.files.Add(file);

            ConnectedUsers.ForEach(user => user.NewFile(file, Chat.key));
        }