async void IMSession_UserJoined(object sender, UserEventArgs e) { var imSession = (IMSession)sender; using (ConsoleExt.WithColor(eventColor)) Console.WriteLine("{0} joined an IM session", e.User.Nickname ?? e.User.LoginName); Message message = new Message(); MessageFormatter mf = new MessageFormatter(); mf.Color = Color.Purple; mf.Bold = true; mf.ApplyFormat(message); message.Body = UTF8Encoding.UTF8.GetBytes(String.Format("Hey, you joined {0}", e.User.LoginName ?? e.User.Nickname)); await imSession.SendMessageAsync(message); }
public async void TakeInput(object state) { string line = await Console.In.ReadLineAsync(); string cmd = line.Split(new char[] { ' ' }, 2)[0]; try { if (cmd != "login" && Msgr == null) throw new ArgumentException("First you must login..."); switch (cmd) { case "login": { var args = line.Split(' ').Skip(1).ToArray(); if (Msgr == null) { if (args.Length != 2) throw new ArgumentException("Login name and password required"); Credentials credentials = new Credentials(args[0], args[1]); Msgr = new MessengerClient(credentials); AddHandlers(); } try { await Msgr.LoginAsync(); } catch (AuthenticationErrorException ex) { using (ConsoleExt.WithColor(errorColor)) Console.WriteLine(ex.Message); } catch (ProtocolNotAcceptedException ex) { using (ConsoleExt.WithColor(errorColor)) Console.WriteLine(ex.Message); } } break; case "logout": await Msgr.LogoutAsync(); break; case "user": { string[] args = line.Split(new char[] { ' ' }).Skip(1).ToArray(); if (args.Length != 1) throw new ArgumentException("An email address is required"); string loginName = args[0]; if (loginName == "me") loginName = Msgr.LocalUser.LoginName; User user = Msgr.GetUser(loginName); var lists = Msgr.UserLists.Where(l => l.Users.Contains(user)); var groups = Msgr.Groups.Where(g => g.Users.Contains(user)); using (ConsoleExt.WithColor(infoColor)) { using (ConsoleExt.WithColor(titleColor)) Console.WriteLine("{0}:", user.LoginName); Console.WriteLine("Login name: {0}", user.LoginName); Console.WriteLine("Nickname: {0}", user.Nickname ?? "(n/a)"); Console.WriteLine("Status: {0}", user.Status); Console.WriteLine("Capabilities: {0}", user.Capabilities); using (ConsoleExt.WithColor(titleColor)) Console.WriteLine("Properties:"); Console.WriteLine("AuthorizedMobile: {0}", user.GetProperty(UserProperty.AuthorizedMobile)); Console.WriteLine("HasBlog: {0}", user.GetProperty(UserProperty.HasBlog)); Console.WriteLine("HasMobileDevice: {0}", user.GetProperty(UserProperty.MobileDevice)); Console.WriteLine("HomePhone: {0}", user.GetProperty(UserProperty.HomePhone)); Console.WriteLine("MobilePhone: {0}", user.GetProperty(UserProperty.MobilePhone)); Console.WriteLine("MSNDirectDevice: {0}", user.GetProperty(UserProperty.MSNDirectDevice)); Console.WriteLine("WorkPhone: {0}", user.GetProperty(UserProperty.WorkPhone)); if (lists.Count() > 0) { using (ConsoleExt.WithColor(titleColor)) Console.WriteLine("Member of lists:"); foreach (var l in lists) Console.WriteLine(l.ToString()); } if (groups.Count() > 0) { using (ConsoleExt.WithColor(titleColor)) Console.WriteLine("Member of groups:"); foreach (var g in groups) Console.WriteLine(g.Name); } } } break; case "name": { string[] args = line.Split(new char[] { ' ' }, 2).Skip(1).ToArray(); if (args.Length == 0) using (ConsoleExt.WithColor(infoColor)) Console.WriteLine("Your name is '{0}'", Msgr.LocalUser.Nickname ?? "(none)"); else { string newName = args[0]; await Msgr.LocalUser.ChangeNicknameAsync(newName); } } break; case "status": { string[] args = line.Split(new char[] { ' ' }, 2).Skip(1).ToArray(); if (args.Length == 0) using (ConsoleExt.WithColor(infoColor)) Console.WriteLine("Your status is '{0}'", Msgr.LocalUser.Status); else { UserStatus newStatus = StrToStatus(args[0]); await Msgr.LocalUser.ChangeStatusAsync(newStatus); } } break; case "caps": { string[] args = line.Split(new char[] { ' ' }, 2).Skip(1).ToArray(); if (args.Length == 0) using (ConsoleExt.WithColor(infoColor)) Console.WriteLine("Your capabilities are '{0}'", Msgr.LocalUser.Capabilities); else { await Msgr.LocalUser.ChangeCapabilitiesAsync(UserCapabilities.RendersGif | UserCapabilities.Version10); } } break; case "props": { var ranNum = new Random().Next(500, 100000).ToString(); await Msgr.LocalUser.SetPropertyAsync(UserProperty.HomePhone, ranNum); await Msgr.LocalUser.SetPropertyAsync(UserProperty.WorkPhone, ranNum); await Msgr.LocalUser.SetPropertyAsync(UserProperty.MobilePhone, ranNum); await Msgr.LocalUser.SetPropertyAsync(UserProperty.MSNDirectDevice, Msgr.LocalUser.GetProperty(UserProperty.MSNDirectDevice) == User.MSNDirectDeviceEnabled ? User.MSNDirectDeviceDisabled : User.MSNDirectDeviceEnabled); } break; case "groups": foreach (Group group in Msgr.Groups) using (ConsoleExt.WithColor(infoColor)) { using (ConsoleExt.WithColor(titleColor)) Console.WriteLine("{0}:", group.Name); foreach (User u in group.Users) Console.WriteLine("{0} ({1})", u.Nickname ?? u.LoginName, u.Status); } break; case "ims": int index = 0; foreach (IMSession im in Msgr.IMSessions.ToList()) using (ConsoleExt.WithColor(infoColor)) { index++; using (ConsoleExt.WithColor(titleColor)) Console.WriteLine("IM session #{0} ({1} users):", index, im.Users.Count()); foreach (User u in im.Users) Console.WriteLine("{0} ({1})", u.Nickname ?? u.LoginName, u.Status); } break; case "privs": await Msgr.SetPrivacySettingAsync(PrivacySetting.AddUsers, Msgr.GetPrivacySetting(PrivacySetting.AddUsers) == MessengerClient.AddUsersWithPrompt ? MessengerClient.AddUsersAutomatically : MessengerClient.AddUsersWithPrompt); await Msgr.SetPrivacySettingAsync(PrivacySetting.AcceptInvitations, Msgr.GetPrivacySetting(PrivacySetting.AcceptInvitations) == MessengerClient.AcceptInvitationsFromAllUsers ? MessengerClient.AcceptInvitationsFromAllowedUsersOnly : MessengerClient.AcceptInvitationsFromAllUsers); break; case "ingroups": using (ConsoleExt.WithColor(infoColor)) foreach (Group group in Msgr.Groups) Console.WriteLine("{0} has {1} users", group.Name, group.Users.Count); break; case "inlists": using (ConsoleExt.WithColor(infoColor)) foreach (UserList list in Msgr.UserLists) Console.WriteLine("{0} has {1} users", list, list.Users.Count); break; case "users": using (ConsoleExt.WithColor(infoColor)) foreach (UserList list in Msgr.UserLists) { using (ConsoleExt.WithColor(titleColor)) Console.WriteLine("{0} ({1} users):", list, list.Users.Count); foreach (User u in list.Users) Console.WriteLine("{0} ({1})", u.Nickname ?? u.LoginName, u.Status); } break; case "online": using (ConsoleExt.WithColor(infoColor)) { using (ConsoleExt.WithColor(titleColor)) Console.WriteLine("Online:"); foreach (User u in Msgr.UserLists.ForwardList.Users.Where(u => u.Status != UserStatus.Offline)) Console.WriteLine("{0} ({1})", u.Nickname ?? u.LoginName, u.Status); using (ConsoleExt.WithColor(titleColor)) Console.WriteLine("Offline:"); foreach (User u in Msgr.UserLists.ForwardList.Users.Where(u => u.Status == UserStatus.Offline)) Console.WriteLine("{0} ({1})", u.Nickname ?? u.LoginName, u.Status); } break; case "groupname": { string[] args = line.Split(new char[] { ' ' }, 2).Skip(1).ToArray(); if (args.Length == 0) throw new ArgumentException("Enter a name"); string name = args[0]; await Msgr.Groups.FirstOrDefault().ChangeNameAsync(name); } break; case "remgroups": foreach (Group group in Msgr.Groups.Where(g => g.Users.Count == 0)) await Msgr.RemoveGroupAsync(group); break; case "pmsg": { string[] args = line.Split(new char[] { ' ' }, 2).Skip(1).ToArray(); if (args.Length == 0) throw new ArgumentException("Enter a message"); string msg = args[0]; await Msgr.LocalUser.BroadcastAsync(String.Format("<Data><PSM>{0}</PSM><CurrentMedia></CurrentMedia></Data>", msg)); } break; case "remblock": foreach (User u in Msgr.UserLists.BlockList.Users.ToArray()) await Msgr.UserLists.BlockList.RemoveUserAsync(u); break; case "addall": { var rev = Msgr.UserLists.ReverseList.Users.Concat(Msgr.UserLists.PendingList.Users).Distinct(); foreach (var o in rev) { if (!Msgr.UserLists.ReverseList.Users.Contains(o)) { await Task.Delay(TimeSpan.FromSeconds(8)); await Msgr.UserLists.ReverseList.AddUserAsync(o); } if (!Msgr.UserLists.AllowList.Users.Contains(o)) { await Task.Delay(TimeSpan.FromSeconds(8)); await Msgr.UserLists.AllowList.AddUserAsync(o); } if (!Msgr.UserLists.ForwardList.Users.Contains(o)) { await Task.Delay(TimeSpan.FromSeconds(8)); await Msgr.UserLists.ForwardList.AddUserAsync(o); } } } break; case "allow": { foreach (User u in Msgr.UserLists.PendingList.Users.ToList()) { if (!Msgr.UserLists.ReverseList.Users.Contains(u)) await Msgr.UserLists.ReverseList.AddUserAsync(u); if (!Msgr.UserLists.AllowList.Users.Contains(u)) await Msgr.UserLists.AllowList.AddUserAsync(u); await Msgr.UserLists.PendingList.RemoveUserAsync(u); } } break; case "copydpic": { var args = line.Split(' ').Skip(1).ToArray(); if (args.Length == 0) throw new ArgumentException("Specify the user whose dpic you wish to copy"); string usr = args[0]; await Msgr.LocalUser.ChangeDisplayPictureAsync(Msgr.GetUser(usr).DisplayPicture); } break; case "addgroup": { string[] args = line.Split(new char[] { ' ' }, 2).Skip(1).ToArray(); if (args.Length == 0) throw new ArgumentException("Enter a name"); string name = args[0]; await Msgr.CreateGroupAsync(name); } break; case "remgroup": await Msgr.RemoveGroupAsync(Msgr.Groups.FirstOrDefault()); break; case "addtogroup": { var args = line.Split(' ').Skip(1).ToArray(); if (args.Length == 0) throw new ArgumentException("Specify the user you wish to add"); string usr = args[0]; await Msgr.Groups.FirstOrDefault().AddUserAsync(Msgr.GetUser(usr)); } break; case "remfromgroup": { Group group = Msgr.Groups.Where(g => g.Users.Count > 0).FirstOrDefault(); if (group == null) { using (ConsoleExt.WithColor(errorColor)) Console.WriteLine("No groups with users in them"); break; } User user = group.Users.FirstOrDefault(); await group.RemoveUserAsync(user); } break; case "add": { var args = line.Split(' ').Skip(1).ToArray(); if (args.Length != 2) throw new ArgumentException("Wrong number of args"); string lst = args[0]; string usr = args[1]; UserList list = StrToList(lst); if (list == null) throw new ArgumentException("Invalid list argument"); await list.AddUserAsync(Msgr.GetUser(usr)); } break; case "rem": { var args = line.Split(' ').Skip(1).ToArray(); if (args.Length != 2) throw new ArgumentException("Wrong number of args"); string lst = args[0]; string usr = args[1]; UserList list = StrToList(lst); if (list == null) throw new ArgumentException("Invalid list argument"); await list.RemoveUserAsync(Msgr.GetUser(usr)); } break; case "im": { var args = line.Split(' ').Skip(1).ToArray(); if (args.Length == 0) throw new ArgumentException("Specify the user who you wish to talk to"); string usr = args[0]; var imSession = await Msgr.CreateIMSession(); await imSession.InviteUserAsync(Msgr.GetUser(usr)); } break; case "msg": { string[] args = line.Split(new char[] { ' ' }, 2).Skip(1).ToArray(); if (args.Length == 0) throw new ArgumentException("Enter a message"); string msg = args[0]; Message message = new Message(); if (RandomColor) { MessageFormatter mf = new MessageFormatter(); mf.SetRandomColor(); mf.ApplyFormat(message); } message.Body = UTF8Encoding.UTF8.GetBytes(msg); foreach (IMSession im in Msgr.IMSessions) await im.SendMessageAsync(message, MessageOption.NoAcknoweldgement); } break; case "msg2": { string[] args = line.Split(new char[] { ' ' }, 2).Skip(1).ToArray(); if (args.Length == 0) throw new ArgumentException("Enter a message"); string msg = args[0]; Message message = new Message(); message.Body = UTF8Encoding.UTF8.GetBytes(msg); await Msgr.IMSessions.FirstOrDefault().SendMessageAsync(message, MessageOption.NegativeAcknowledgementOnly); } break; case "disim": foreach (IMSession im in Msgr.IMSessions) await im.DisconnectAsync(); break; case "parrot": ParrotMode = !ParrotMode; using (ConsoleExt.WithColor(infoColor)) Console.WriteLine("Parrot mode now " + ParrotMode); break; case "color": RandomColor = !RandomColor; using (ConsoleExt.WithColor(infoColor)) Console.WriteLine("Random color mode now " + RandomColor); break; case "closeim": foreach (IMSession im in Msgr.IMSessions.ToList()) im.Close(); break; case "inviteall": foreach (User user in Msgr.UserLists.ForwardList.Users.Where(u => u.Status != UserStatus.Offline)) foreach (IMSession im in Msgr.IMSessions.Where(im => !im.Users.Contains(user))) await im.InviteUserAsync(user); break; case "ping": await Msgr.PingAsync(); break; case "exit": endEvent.Set(); break; default: throw new ArgumentException("Command not recognized"); } } catch (TimeoutException ex) { using (ConsoleExt.WithColor(errorColor)) Console.WriteLine(ex.Message); } catch (NotLoggedInException ex) { using (ConsoleExt.WithColor(errorColor)) Console.WriteLine(ex.Message); } catch (ObjectDisposedException ex) { using (ConsoleExt.WithColor(errorColor)) Console.WriteLine(ex.Message); } catch (ConnectionErrorException ex) { using (ConsoleExt.WithColor(errorColor)) Console.WriteLine(ex.Message); } catch (ArgumentException ex) { using (ConsoleExt.WithColor(errorColor)) Console.WriteLine(ex.Message); } ThreadPool.QueueUserWorkItem(TakeInput); }
async void Msgr_InvitedToIMSession(object sender, InvitationEventArgs e) { using (ConsoleExt.WithColor(eventColor)) Console.WriteLine("Accepting IM Session invitation from {0}", e.Invitation.InvitingUser.Nickname ?? e.Invitation.InvitingUser.LoginName); IMSession imSession = null; try { imSession = await Msgr.AcceptInvitationAsync(e.Invitation); } catch (ConnectionErrorException ex) { using (ConsoleExt.WithColor(errorColor)) Console.WriteLine("Connection error while esablishing IM session: " + ex.Message); return; } Message message = new Message(); MessageFormatter mf = new MessageFormatter(); mf.Italic = true; mf.Color = Color.Tomato; mf.ApplyFormat(message); message.Body = UTF8Encoding.UTF8.GetBytes(String.Format("Gee, thanks for inviting me {0}", e.Invitation.InvitingUser.Nickname ?? e.Invitation.InvitingUser.LoginName)); await imSession.SendMessageAsync(message); }
SyncEvents ProcessSyncCommands(List<Command> syncCommands) { SyncEvents events = new SyncEvents(); List<User> referencedUsers = new List<User>(); List<Group> referencedGroups = new List<Group>(); User lastUser = null; foreach (Command cmd in syncCommands) { if (cmd is UserCommand) { UserCommand listCmd = cmd as UserCommand; User user = null; if (GetUserInner(listCmd.LoginName, out user)) { user.guid = listCmd.Guid; user.Nickname = listCmd.Nickname; } else { user.guid = listCmd.Guid; if (user.Nickname != listCmd.Nickname) { string prevName = user.Nickname; user.Nickname = listCmd.Nickname; events.userNickNameChangedEvents.Add(new UserNicknameEventArgs(user, user.Nickname, prevName, false)); } } //user added to lists foreach (UserList list in UserLists.Where(x => listCmd.Lists.Contains(x.listCode) && !x.Users.Contains(user))) { list.Users.AddUserInner(user); events.userAddedToListEvents.Add(new UserListUserEventArgs(user, list, true)); } //user removed from lists foreach (UserList list in UserLists.Where(x => !listCmd.Lists.Contains(x.listCode) && x.Users.Contains(user))) { list.Users.RemoveUserInner(user); events.userRemovedFromListEvents.Add(new UserListUserEventArgs(user, list, true)); } //user added to groups foreach (Group group in Groups.Where(x => listCmd.Groups.Contains(x.Guid) && !x.Users.Contains(user))) { group.Users.AddUserInner(user); events.userAddedToGroupEvents.Add(new GroupUserEventArgs(user, group, true)); } //user removed from groups foreach (Group group in Groups.Where(x => !listCmd.Groups.Contains(x.Guid) && x.Users.Contains(user))) { group.Users.RemoveUserInner(user); events.userRemovedFromGroupEvents.Add(new GroupUserEventArgs(user, group, true)); } referencedUsers.Add(user); lastUser = user; } else if (cmd is GroupCommand) { GroupCommand groupCmd = cmd as GroupCommand; Group group = Groups.Where(gx => gx.Guid == groupCmd.Guid).SingleOrDefault(); if (group == null) { group = new Group(this, groupCmd.Guid, groupCmd.Name); Groups.AddGroup(group); events.groupAddedEvents.Add(new GroupEventArgs(group, true)); } else { if (group.Name != groupCmd.Name) { string prevName = group.Name; group.Name = groupCmd.Name; events.groupNameChangedEvents.Add(new GroupNameEventArgs(group, groupCmd.Name, prevName, true)); } } referencedGroups.Add(group); } else if (cmd is UserPropertyCommand) { UserPropertyCommand propCmd = cmd as UserPropertyCommand; UserProperty property = User.StringToProperty(propCmd.Key); if (lastUser.GetPropertyInner(property) != propCmd.Value) { lastUser.SetPropertyInner(property, propCmd.Value); events.userPropertyChangedEvents.Add(new UserPropertyEventArgs(lastUser, property, propCmd.Value, true)); } } else if (cmd is LocalPropertyCommand && ((LocalPropertyCommand)cmd).Key == "MFN") { LocalPropertyCommand nameCmd = cmd as LocalPropertyCommand; if (LocalUser.Nickname != nameCmd.Value) { string prevName = LocalUser.Nickname; LocalUser.Nickname = nameCmd.Value; events.userNickNameChangedEvents.Add(new UserNicknameEventArgs(LocalUser, nameCmd.Value, prevName, true)); } } else if (cmd is LocalPropertyCommand) { LocalPropertyCommand propCmd = cmd as LocalPropertyCommand; UserProperty property = User.StringToProperty(propCmd.Key); if (LocalUser.GetPropertyInner(property) != propCmd.Value) { LocalUser.SetPropertyInner(property, propCmd.Value); events.userPropertyChangedEvents.Add(new UserPropertyEventArgs(LocalUser, property, propCmd.Value, true)); } } else if (cmd is PrivacySettingCommand) { PrivacySettingCommand privCmd = cmd as PrivacySettingCommand; PrivacySetting setting = MessengerClient.StringToPrivacySetting(privCmd.Key); if (GetPrivacySettingInner(setting) != privCmd.Value) { SetPrivacySettingInner(setting, privCmd.Value); events.privacySettingChangedEvents.Add(new PrivacySettingEventArgs(setting, privCmd.Value, true)); } } else if (cmd is MessageCommand) { MessageCommand message = cmd as MessageCommand; Message msg = new Message(message.Payload); events.messageEvents.Add(new MessageEventArgs(message.Sender, message.SenderNickname, msg, true)); } else if (cmd is SbsCommand) { //todo: do something with this command } } // remove groups that no longer exist foreach (Group group in Groups.Except(referencedGroups)) { Groups.RemoveGroup(group); events.groupRemovedEvents.Add(new GroupEventArgs(group, true)); } //remove users that no longer exist from lists and groups which currently contain them foreach (UserList list in UserLists) foreach (User user in list.Users.Except(referencedUsers)) { list.Users.RemoveUserInner(user); events.userRemovedFromListEvents.Add(new UserListUserEventArgs(user, list, true)); } foreach (Group group in Groups) foreach (User user in group.Users.Except(referencedUsers)) { group.Users.RemoveUserInner(user); events.userRemovedFromGroupEvents.Add(new GroupUserEventArgs(user, group, true)); } return events; }
void HandleMessages(MessageCommand messageCommand, IConnection connection) { Message message = new Message(messageCommand.Payload); OnMessageReceived(new MessageEventArgs(messageCommand.Sender, messageCommand.SenderNickname, message, false)); }
internal MessageEventArgs(string senderLoginName, string senderNickname, Message message, bool loginEvent) { SenderLoginName = senderLoginName; SenderNickname = senderNickname; Message = message; LoginEvent = loginEvent; }
internal MessageEventArgs(User user, Message message) { Sender = user; Message = message; }
public void CopyFormat(Message message) { if (message.ContentType != "text/plain; charset=UTF-8") throw new InvalidOperationException(); if (!message.Headers.ContainsKey("X-MMS-IM-Format")) return; string fHeader = message.Headers["X-MMS-IM-Format"]; var fArgs = fHeader.Split("; ") .Select(s => s.Split('=')) .ToDictionary(s => s[0], s => s[1]); if (fArgs.ContainsKey("FN")) Font = Uri.UnescapeDataString(fArgs["FN"]); if (fArgs.ContainsKey("EF")) { Bold = fArgs["EF"].Contains("B"); Italic = fArgs["EF"].Contains("I"); Strikethrough = fArgs["EF"].Contains("S"); Underline = fArgs["EF"].Contains("U"); } if (fArgs.ContainsKey("CO") && fArgs["CO"] != "0") { string[] rgb = (from Match m in Regex.Matches(fArgs["CO"], @"[\d\w]{2}") select m.Value) .Reverse() .ToArray(); Color = ColorTranslator.FromHtml("#" + String.Concat(rgb)); } }
public void ApplyFormat(Message message) { if (message.ContentType != "text/plain; charset=UTF-8") throw new InvalidOperationException(); Dictionary<string, string> args = new Dictionary<string, string>(); args.Add("FN", Uri.EscapeDataString(Font)); args.Add("EF", (Bold ? "B" : null) + (Italic ? "I" : null) + (Underline ? "U" : null) + (Strikethrough ? "S" : null)); args.Add("CO", Color.B.ToString("X2") + Color.G.ToString("X2") + Color.R.ToString("X2")); args.Add("CS", "0"); args.Add("PF", "22"); message.Headers["X-MMS-IM-Format"] = String.Join("; ", args.Select(m => String.Format("{0}={1}", m.Key, m.Value)).ToArray()); }
public static void CopyFormat(Message source, Message dest) { if (source.ContentType != "text/plain; charset=UTF-8" || (dest.ContentType != "text/plain; charset=UTF-8")) throw new InvalidOperationException(); if (!source.Headers.ContainsKey("X-MMS-IM-Format")) return; dest.Headers["X-MMS-IM-Format"] = source.Headers["X-MMS-IM-Format"]; }