Esempio n. 1
0
    private void OnUserOnline(MessageRouter router, Message message, object tag)
    {
        Regex.Regex regex = new Regex.Regex(@"(?<status>\S+)\s+(?<email>\S+)\s+(?<screenName>\S+)");
        Regex.Match match = regex.Match(message.Arguments);

        if (match.Success)
        {
            string status     = match.Groups["status"].Value;
            string username   = match.Groups["email"].Value;
            string screenName = this.UriUnquote(match.Groups["screenName"].Value);

            if (control.ContainsFriend(username))
            {
                Friend f = control.GetFriend(username);

                f.DisplayName = screenName;
                f.Status      = this.ConvertStringToStatus(status);
            }
            else
            {
                Friend friend = new Friend(username, this.ConvertStringToStatus(status), 0);
                friend.DisplayName  = screenName;
                friend.EmailAddress = username;
                control.AddFriend(friend);
            }
        }
    }
Esempio n. 2
0
    public static string GetLoginAddress(string nexusUri)
    {
        Net.WebClient webClient = new Net.WebClient();

        // open connection to Nexus URL, then grab the headers (it has an empty body)
        IO.Stream strm         = webClient.OpenRead(nexusUri);
        string    passportUrls = webClient.ResponseHeaders["PassportURLs"];

        strm.Close();

        // get log in part of the http header we are looking at
        Regex.Regex regex = new Regex.Regex(@"DALogin=(?<loginURL>[^\,]+)", Regex.RegexOptions.Compiled);
        Regex.Match match = regex.Match(passportUrls);

        if (!match.Success)
        {
            throw new Exception();
        }

        // put https on front if it isnt there
        string loginUrl = match.Groups["loginURL"].Value.ToLower();

        if (!loginUrl.StartsWith("https://"))
        {
            loginUrl = "https://" + loginUrl;
        }

        // add port number after the host name
        int index = loginUrl.IndexOf("/", 9);

        loginUrl = loginUrl.Substring(0, index) + ":443" + loginUrl.Substring(index);

        return(loginUrl);
    }
Esempio n. 3
0
    private void OnUserAdd(MessageRouter router, Message message, object tag)
    {
        Regex.Regex regex = new Regex.Regex(@"(?<status>\w+)\s+(?<emailAddress>\S+)\s+(?<screenName>\S+)\s+(?<version>\d+)");
        Regex.Match match = regex.Match(message.Arguments);

        if (match.Success)
        {
            string status       = match.Groups["status"].Value;
            string emailAddress = match.Groups["emailAddress"].Value;
            string screenName   = this.UriUnquote(match.Groups["screenName"].Value);

            OnlineStatus s = this.ConvertStringToStatus(status);

            Friend friend = control.GetFriend(emailAddress);

            if (friend == null)
            {
                friend              = new Friend(emailAddress, s, 0);
                friend.DisplayName  = screenName;
                friend.EmailAddress = emailAddress;
                control.AddFriend(friend);
            }
            else
            {
                friend.Status      = s;
                friend.DisplayName = screenName;
            }
        }
    }
Esempio n. 4
0
    private void OnInvite(MessageRouter router, Message message, object tag)
    {
        Regex.Regex regex = new Regex.Regex(@"RNG\s+(?<sessionID>\d+)\s+(?<sbIP>\d+\.\d+\.\d+\.\d+):(?<sbPort>\d+)\s+CKI\s+(?<hash>\S+)\s+(?<emailAddress>\S+)\s+(?<screenName>[^\r$]*)");
        Regex.Match match = regex.Match(message.RawMessage);

        if (match.Success)
        {
            string sbIP       = match.Groups["sbIP"].Value;
            int    sbPort     = int.Parse(match.Groups["sbPort"].Value);
            string sessionID  = match.Groups["sessionID"].Value;
            string hash       = match.Groups["hash"].Value;
            string email      = match.Groups["emailAddress"].Value;
            string screenName = this.UriUnquote(match.Groups["screenName"].Value);

            Friend friend;

            if (this.control.ContainsFriend(email))
            {
                friend = control.GetFriend(email);
            }
            else
            {
                friend              = new Friend(email, OnlineStatus.Online, 0);
                friend.DisplayName  = this.UriUnquote(screenName);
                friend.EmailAddress = email;
            }

            // connect to switchboard
            control.StartInvitedConversation(friend, new OperationCompleteEvent(), new object[] { sbIP, sbPort, hash, sessionID });
        }
    }
Esempio n. 5
0
    private void OnAnswerResponse(MessageRouter router, Message message, object tag)
    {
        if (message.Arguments == "OK")
        {
            ((OperationCompleteEvent)tag).Execute(new OperationCompleteArgs());
            router.RemoveMessageEvent(message);
        }
        else
        {
            if (message.Code == "IRO")
            {
                Regex.Regex regex = new Regex.Regex(
                    @"(?<userNumber>\d+)\s+(?<totalUsers>\d+)\s+(?<username>\S+)\s+(?<screenName>.*$)"
                    );

                Regex.Match match = regex.Match(message.Arguments);

                if (match.Success)
                {
                    string username = match.Groups["username"].Value;
                    control.FriendJoin(username);
                }
            }
        }
    }
Esempio n. 6
0
    private void OnPasswordSentResponse(MessageRouter router, Message message, object tag)
    {
        router.RemoveMessageEvent(message);

        OperationCompleteEvent op = (OperationCompleteEvent)tag;

        switch (message.Code)
        {
        case "USR":
        {
            // find our screen name
            Regex.Regex regex = new Regex.Regex(@"OK (?<email>\S+)\s+(?<screenName>\S+)");
            Regex.Match match = regex.Match(message.Header);

            if (!match.Success)
            {
                op.Execute(new ConnectionCompleteArgs(ConnectionFailedReport.InvalidProtocol));
            }
            else
            {
                settings.DisplayName = this.UriUnquote(match.Groups["screenName"].Value);

                // now we have to set our initial status.
                this.ChangeStatus(this.settings.Status, new ResponseReceivedHandler(OnInitialStatusSet), tag);
            }
        }
        break;

        case "911":
            // authentication failed
            op.Execute(new ConnectionCompleteArgs(ConnectionFailedReport.AuthFailed));
            break;
        }
    }
Esempio n. 7
0
    public Message(string message)
    {
        this.message = message;

        Regex.Regex regex = new Regex.Regex(@"(?<code>[\w\d]+)\s*(?<transID>\d*)\s*(?<arguments>[^\r\n]*)([\r\n]*)(?<body>.*$)", Regex.RegexOptions.Singleline);
        Regex.Match match = regex.Match(message);

        if (match.Success)
        {
            this.code          = match.Groups["code"].Value;
            this.transactionID = (match.Groups["transID"].Success && match.Groups["transID"].Value != "") ? int.Parse(match.Groups["transID"].Value) : -1;

            this.arguments = match.Groups["arguments"].Success ? match.Groups["arguments"].Value : string.Empty;
            this.body      = match.Groups["body"].Success ? match.Groups["body"].Value : string.Empty;

            if (transactionID != -1)
            {
                this.header = code + " " + transactionID + " " + arguments;
            }
            else
            {
                this.header = code + " " + arguments;
            }
        }
    }
Esempio n. 8
0
    private void OnByeReceived(MessageRouter router, Message message, object tag)
    {
        Regex.Regex regex = new Regex.Regex(@"(?<username>\S*)\s*\d*");
        Regex.Match match = regex.Match(message.Arguments);

        if (match.Success)
        {
            string username = match.Groups["username"].Value;

            control.FriendLeave(username);
        }
    }
Esempio n. 9
0
    private void OnJoinReceived(MessageRouter router, Message message, object tag)
    {
        Regex.Regex regex = new Regex.Regex(@"(?<username>\S+)\s+(?<screenName>\S+)");
        Regex.Match match = regex.Match(message.Arguments);

        if (match.Success)
        {
            string email      = match.Groups["username"].Value;
            string screenName = match.Groups["screenName"].Value;

            control.FriendJoin(email);
        }
    }
Esempio n. 10
0
        public static void Main(string[] args)
        {
            //Collections to work with
            List <Artist> Artists = JsonToFile <Artist> .ReadJson();

            List <Group> Groups = JsonToFile <Group> .ReadJson();

            //========================================================
            //Solve all of the prompts below using various LINQ queries
            //========================================================

            //There is only one artist in this collection from Mount Vernon, what is their name and age?

            Artist artistFromVernon = Artists.Where(artist => artist.Hometown == "Mount Vernon").First();

            System.Console.WriteLine(artistFromVernon.RealName + " " + artistFromVernon.Age);


            //Who is the youngest artist in our collection of artists?

            Artist youngest = Artists.OrderBy(artist => artist.Age).First();

            System.Console.WriteLine(youngest.Age);

            //Display all artists with 'William' somewhere in their real name
            string pattern = @"William";

            Regex.Regex   r        = new Regex.Regex(pattern);
            List <Artist> williams = Artists.Where(artist => r.IsMatch(artist.RealName)).ToList();

            //Display the 3 oldest artist from Atlanta

            List <Artist> oldest = Artists.OrderByDescending(artist => artist.Age).Where(artist => artist.Hometown == "Atlanta").Take(3).ToList();

            //(Optional) Display the Group Name of all groups that have members that are not from New York City

            var query = Groups.Join(Artists, group => group.Id, artist => artist.GroupId, (group, artist) => { return(new { Group = group, Artist = artist }); }).Where(groupAndArtist => groupAndArtist.Artist.Hometown != "New York City").Select(groupAndArtist => groupAndArtist.Group.GroupName).Distinct();

            //(Optional) Display the artist names of all members of the group 'Wu-Tang Clan'

            var query2 =
                from a in Artists
                join g in Groups on a.GroupId equals g.Id
                where g.GroupName == "Wu-Tang Clan"
                select new { a.RealName };

            var query3 =
                from g in Groups
                where g.GroupName.Length < 8
                select new { g.GroupName };
        }
Esempio n. 11
0
    private void OnMsgReceived(MessageRouter router, Message message, object tag)
    {
        // seperate message from all the crap
        string actualMessage = message.Body.Substring(message.Body.IndexOf("\r\n\r\n") + 4);

        actualMessage.TrimEnd('\r', '\n');

        // locate content type in mime headers
        Regex.Regex contentTypeRegex = new Regex.Regex(@"\r\nContent-Type:\s+(?<contentType>[^\;\s]+)");
        Regex.Match contentTypeMatch = contentTypeRegex.Match(message.Body);

        if (contentTypeMatch.Success)
        {
            string contentType = contentTypeMatch.Groups["contentType"].Value;

            switch (contentType)
            {
            case "text/x-msmsgscontrol":                     // user typing notification
            {
                // get username of typing user
                Regex.Regex notifyRegex = new Regex.Regex(@"TypingUser: (?<username>[^\r]+)");
                Regex.Match notifyMatch = notifyRegex.Match(message.Body);

                if (notifyMatch.Success)
                {
                    this.control.TypingNotification(notifyMatch.Groups["username"].Value);
                }
            }
                return;

            case "text/x-msmsgsinvite":                     // file transfer, netmeeting invitation
                return;
            }
        }

        // find user's name
        Regex.Regex regex = new Regex.Regex(@"(?<username>\S+)\s+(?<displayName>\S+)\s+\d+");
        Regex.Match match = regex.Match(message.Header);

        if (match.Success)
        {
            string username    = match.Groups["username"].Value;
            string displayName = match.Groups["displayName"].Value;

            control.FriendSay(username, actualMessage);
        }
    }
Esempio n. 12
0
    public static string Login(string loginUri, string challenge, string username, string password)
    {
        // url-encode username and password
        string urlUsername = uriQuote(username);
        string urlPassword = uriQuote(password);

        Net.WebClient webClient = new Net.WebClient();

        webClient.Headers.Add("Authorization",
                              @"Passport1.4 OrgVerb=GET,OrgURL=http%3A%2F%2Fmessenger%2Emsn%2Ecom," +
                              @"sign-in=" + urlUsername + @",pwd=" + urlPassword + @"," + challenge);

        IO.Stream strm = webClient.OpenRead(loginUri);
        strm.Close();

        string authInfo = webClient.ResponseHeaders["Authentication-Info"];

        if (authInfo == null || authInfo == string.Empty || authInfo == "")
        {
            throw new Exception();             // authorization failed
        }
        else
        {
            Regex.Regex regex = new Regex.Regex(@"from-PP='(?<ticket>t=[^\']+)", Regex.RegexOptions.Compiled);
            Regex.Match match = regex.Match(authInfo);

            if (match.Success)
            {
                return(match.Groups["ticket"].Value);                // success
            }
            else
            {
                // ok, need to redirect then.
                string newUri = webClient.ResponseHeaders["Location"];
                if (newUri == null || authInfo == string.Empty || authInfo == "")
                {
                    throw new Exception();                     // shouldn't happen
                }
                // start login procedure with new URI.
                return(Login(newUri, challenge, username, password));
            }
        }
    }
Esempio n. 13
0
        public JsonResult SearchGroupsByName(string name, bool displayArtists = true)
        {
            Regex.Regex  r      = new Regex.Regex($"(?i){name}");
            List <Group> groups = allGroups.Where(group => r.IsMatch(group.GroupName)).ToList();

            if (displayArtists)
            {
                List <Artist> allArtists = JsonToFile <Artist> .ReadJson();

                var artists = from Group in groups
                              join Artist in allArtists on Group.Id equals Artist.GroupId
                              where Artist.GroupId == Group.Id
                              select Artist;
                return(Json(new { groups, artists }));
            }
            else
            {
                return(Json(groups));
            }
        }
Esempio n. 14
0
    private void OnSwitchBoardRequestResponse(MessageRouter router, Message message, object tag)
    {
        object[] o = (object[])tag;

        Friend friend             = (Friend)o[0];
        OperationCompleteEvent op = (OperationCompleteEvent)o[1];

        Regex.Regex regex = new Regex.Regex(@"SB (?<sbServerIP>\d+\.\d+\.\d+\.\d+):(?<sbServerPort>\d+) CKI (?<hash>.*$)");
        Regex.Match match = regex.Match(message.Arguments);

        if (match.Success)
        {
            string sbIP           = match.Groups["sbServerIP"].Value;
            int    sbPort         = int.Parse(match.Groups["sbServerPort"].Value);
            string conversationID = match.Groups["hash"].Value;

            // connect
            try
            {
                Proxy.IConnection conn = this.control.CreateConnection();
                conn.Connect("", 0, sbIP, sbPort, Proxy.ConnectionType.Tcp);
                sbRouter = new MessageRouter(this.protocol, conn, null, new ResponseReceivedHandler(OnForcedDisconnect));
            }
            catch
            {
                op.Execute(new OperationCompleteArgs("Could not connect", true));
                return;
            }

            RegisterCodeEvents();

            sbRouter.SendMessage(Message.ConstructMessage("USR", this.settings.Username + " " + conversationID),
                                 new ResponseReceivedHandler(OnSwitchBoardUsrResponse), tag);
        }
        else
        {
            op.Execute(new OperationCompleteArgs("Could not connect", true));
        }

        router.RemoveMessageEvent(message);
    }
Esempio n. 15
0
    public Message(string message)
    {
        this.message = message;

        Regex.Regex regex = new Regex.Regex(@"(?<code>[\w\d]+)\s*(?<transID>\d*)\s*(?<arguments>[^\r\n]*)([\r\n]*)(?<body>.*$)", Regex.RegexOptions.Singleline);
          Regex.Match match = regex.Match(message);

        if (match.Success)
        {
            this.code = match.Groups["code"].Value;
            this.transactionID = (match.Groups["transID"].Success && match.Groups["transID"].Value != "") ? int.Parse(match.Groups["transID"].Value) : -1;

            this.arguments = match.Groups["arguments"].Success ? match.Groups["arguments"].Value : string.Empty;
            this.body = match.Groups["body"].Success ? match.Groups["body"].Value : string.Empty;

            if (transactionID != -1)
                this.header = code + " " + transactionID + " " + arguments;
            else
                this.header = code + " " + arguments;
        }
    }
Esempio n. 16
0
    private static string uriQuote(string str)
    {
        string newStr = string.Empty;

        for (int i = 0; i < str.Length; ++i)
        {
            char c = str[i];

            Regex.Regex regex = new Regex.Regex(@"\w{1}", Regex.RegexOptions.Compiled);
            Regex.Match match = regex.Match(new String(c, 1));

            if (!match.Success)
            {
                newStr += Uri.HexEscape(c);
            }
            else
            {
                newStr += c;
            }
        }

        return(newStr);
    }
Esempio n. 17
0
    private void OnByeReceived(MessageRouter router, Message message, object tag)
    {
        Regex.Regex regex = new Regex.Regex(@"(?<username>\S*)\s*\d*");
        Regex.Match match = regex.Match(message.Arguments);

        if (match.Success)
        {
            string username = match.Groups["username"].Value;

            control.FriendLeave(username);
        }
    }
Esempio n. 18
0
    private void OnJoinReceived(MessageRouter router, Message message, object tag)
    {
        Regex.Regex regex = new Regex.Regex(@"(?<username>\S+)\s+(?<screenName>\S+)");
        Regex.Match match = regex.Match(message.Arguments);

        if (match.Success)
        {
            string email = match.Groups["username"].Value;
            string screenName = match.Groups["screenName"].Value;

            control.FriendJoin(email);
        }
    }
Esempio n. 19
0
 get => this.ConvertDuration(this.DurationStr);
Esempio n. 20
0
    private void OnAnswerResponse(MessageRouter router, Message message, object tag)
    {
        if (message.Arguments == "OK")
        {
            ((OperationCompleteEvent)tag).Execute(new OperationCompleteArgs());
            router.RemoveMessageEvent(message);
        }
        else
        {
            if (message.Code == "IRO")
            {
                Regex.Regex regex = new Regex.Regex(
                    @"(?<userNumber>\d+)\s+(?<totalUsers>\d+)\s+(?<username>\S+)\s+(?<screenName>.*$)"
                    );

                Regex.Match match = regex.Match(message.Arguments);

                if (match.Success)
                {
                    string username = match.Groups["username"].Value;
                    control.FriendJoin(username);
                }
            }
        }
    }
Esempio n. 21
0
    private void OnUsrResponse(MessageRouter router, Message message, object tag)
    {
        router.RemoveMessageEvent(message);
        OperationCompleteEvent op = (OperationCompleteEvent)tag;

        // see if its an XFR or a USR code.
        switch (message.Code)
        {
        case "XFR":                 // we need to connect to a notification server
        {
            // get ip and port of notification server from response string
            Regex.Regex regex = new Regex.Regex(
                @"NS (?<notifyServerIP>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(?<notifyServerPort>\d{1,5})" +
                @"\s+\d+\s+" +
                @"(?<currentNotifyIP>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(?<currentNotifyPort>\d{1,5})");
            Regex.Match match = regex.Match(message.Arguments);

            if (!match.Success)
            {
                op.Execute(new ConnectionCompleteArgs(ConnectionFailedReport.InvalidProtocol));
            }
            else
            {
                string notifyIP   = match.Groups["notifyServerIP"].Value;
                int    notifyPort = int.Parse(match.Groups["notifyServerPort"].Value);

                // connect to notification server
                if (this.notifyRouter != null)
                {
                    this.notifyRouter.Close();
                }

                try
                {
                    Proxy.IConnection con = control.CreateConnection();
                    con.Connect("", 0, notifyIP, notifyPort, Proxy.ConnectionType.Tcp);
                    this.notifyRouter = new MessageRouter(this, con,
                                                          new ResponseReceivedHandler(OnDefaultNotifyMessage),
                                                          new ResponseReceivedHandler(OnForcedDisconnect));
                }
                catch
                {
                    op.Execute(new ConnectionCompleteArgs(ConnectionFailedReport.ConnectionFailed));
                    return;
                }

                RegisterEvents();

                // go through authentication again, this time with the new notification server
                DoAuthentication(this.notifyRouter, (OperationCompleteEvent)tag);
            }
        }
        break;

        case "USR":                 // we need to do encrypt and send password
        {
            string challenge = message.Arguments.Substring(6);

            // we need to authenticate with passport server
            string url = this.settings.PassportURL;
            string ticket;

            if (url != string.Empty || url != null || url != "")
            {
                try
                {
                    ticket = Passport.Login(url, challenge, settings.Username, settings.Password);
                }
                catch
                {
                    // passport url is out of date
                    url    = Passport.GetLoginAddress(this.nexusUri);
                    ticket = Passport.Login(url, challenge, settings.Username, settings.Password);
                }
            }
            else
            {
                url    = Passport.GetLoginAddress(this.nexusUri);
                ticket = Passport.Login(url, challenge, settings.Username, settings.Password);
            }

            if (ticket == null || ticket == string.Empty || ticket == "")
            {
                // wrong username / password
                op.Execute(new ConnectionCompleteArgs(ConnectionFailedReport.AuthFailed));
                return;
            }

            // send ticket command
            router.SendMessage(Message.ConstructMessage("USR", "TWN S " + ticket), new ResponseReceivedHandler(OnPasswordSentResponse), tag);
        }
        break;
        }
    }
Esempio n. 22
0
    private void OnSynResponse(MessageRouter router, Message message, object tag)
    {
        router.RemoveMessageEvent(message);

        OperationCompleteEvent opCompleteEvent = (OperationCompleteEvent)tag;

        switch (message.Code)
        {
        case "SYN":
        {
            // check if our cached list is up-to-date
            Regex.Regex regex = new Regex.Regex(@"(?<serverVersion>\d+)\s*(?<numLST>\d*)\s*(?<numLSG>\d*)", Regex.RegexOptions.Compiled);
            Regex.Match match = regex.Match(message.Arguments);

            if (!match.Success)
            {
                opCompleteEvent.Execute(new ConnectionCompleteArgs(ConnectionFailedReport.InvalidProtocol));
                router.RemoveMessageEvent(message);
                return;
            }

            int serverVersion = int.Parse(match.Groups["serverVersion"].Value);

            if (serverVersion != this.settings.ContactListVersion)
            {
                int numLST = int.Parse(match.Groups["numLST"].Value);

                // it's different, so clear out the old friends list and await the new
                this.settings.ContactListVersion = serverVersion;
                this.settings.AllowList.Clear();
                this.settings.BlockList.Clear();
                this.settings.ForwardList.Clear();
                this.settings.ReverseList.Clear();

                // contact list sync commands
                this.notifyRouter.AddCodeEvent("GLP", new ResponseReceivedHandler(OnGLP));
                this.notifyRouter.AddCodeEvent("BLP", new ResponseReceivedHandler(OnBLP));

                this.notifyRouter.AddCodeEvent("LSG", new ResponseReceivedHandler(OnLSG));
                this.notifyRouter.AddCodeEvent("LST", new ResponseReceivedHandler(OnLST), new Pair(tag, numLST));
            }
            else
            {
                // otherwise we are up-to-date so connection is completed.

                // check if any of the friends in the reverse list are not in any of the others
                foreach (Friend friend in this.settings.ReverseList)
                {
                    if (!this.settings.AllowList.Contains(friend) &&
                        !this.settings.BlockList.Contains(friend))
                    {
                        this.HandleNewFriend(friend);
                    }
                }

                // then add each friend in the forward list to the control
                foreach (Friend friend in this.settings.ForwardList)
                {
                    if (!this.control.ContainsFriend(friend.Username))
                    {
                        this.control.AddFriend(friend);
                    }
                }

                opCompleteEvent.Execute(new OperationCompleteArgs());
            }
        }
        break;
        }
    }
Esempio n. 23
0
    private void OnLST(MessageRouter router, Message message, object tag)
    {
        Pair pair = (Pair)tag;
        OperationCompleteEvent op = (OperationCompleteEvent)pair.First;
        int numUsersLeft          = (int)pair.Second;

        Regex.Regex regex = new Regex.Regex(
            @"(?<username>\S+)\s+(?<screenName>\S+)\s+(?<listID>\d+)\s*(?<groupList>.*)");

        Regex.Match match = regex.Match(message.Arguments);

        if (match.Success)
        {
            string username   = match.Groups["username"].Value;
            string screenName = this.UriUnquote(match.Groups["screenName"].Value);
            int    listID     = int.Parse(match.Groups["listID"].Value);

            Friend friend = new Friend(username, OnlineStatus.Offline, 0);

            friend.DisplayName  = screenName;
            friend.EmailAddress = username;

            if ((listID & 1) == 1)             // forward list
            {
                if (!this.settings.ForwardList.Contains(friend))
                {
                    this.settings.ForwardList.Add(friend);
                }
            }

            if ((listID & 2) == 2)             // allow list
            {
                if (!this.settings.AllowList.Contains(friend))
                {
                    this.settings.AllowList.Add(friend);
                }
            }

            if ((listID & 4) == 4)             // block list
            {
                if (!this.settings.BlockList.Contains(friend))
                {
                    this.settings.BlockList.Add(friend);
                }
            }

            if ((listID & 8) == 8)             // reverse list
            {
                if (!this.settings.ReverseList.Contains(friend))
                {
                    this.settings.ReverseList.Add(friend);
                }

                // if this person isn't on the allow or blocking list, then they have added
                // me to their forward list. Inform the user
                if (!this.settings.AllowList.Contains(friend) &&
                    !this.settings.BlockList.Contains(friend))
                {
                    this.HandleNewFriend(friend);
                }
            }
        }

        // check if we have finished yet
        if (--numUsersLeft == 0)
        {
            foreach (Friend friend2 in this.settings.ForwardList)
            {
                friend2.Blocked = this.settings.BlockList.Contains(friend2);

                if (!this.control.ContainsFriend(friend2.Username))
                {
                    this.control.AddFriend(friend2);
                }
            }

            op.Execute(new ConnectionCompleteArgs());
        }
        else         // replace number of users left
        {
            router.AddCodeEvent("LST", new ResponseReceivedHandler(OnLST), new Pair(op, numUsersLeft));
        }
    }
Esempio n. 24
0
    private void OnMsgReceived(MessageRouter router, Message message, object tag)
    {
        // seperate message from all the crap
        string actualMessage = message.Body.Substring( message.Body.IndexOf("\r\n\r\n") + 4 );
        actualMessage.TrimEnd('\r', '\n');

        // locate content type in mime headers
        Regex.Regex contentTypeRegex = new Regex.Regex(@"\r\nContent-Type:\s+(?<contentType>[^\;\s]+)");
        Regex.Match contentTypeMatch = contentTypeRegex.Match(message.Body);

        if (contentTypeMatch.Success)
        {
            string contentType = contentTypeMatch.Groups["contentType"].Value;

            switch (contentType)
            {
                case "text/x-msmsgscontrol": // user typing notification
                {
                    // get username of typing user
                    Regex.Regex notifyRegex = new Regex.Regex(@"TypingUser: (?<username>[^\r]+)");
                    Regex.Match notifyMatch = notifyRegex.Match(message.Body);

                    if (notifyMatch.Success)
                    {
                        this.control.TypingNotification(notifyMatch.Groups["username"].Value);
                    }
                }
                    return;

                case "text/x-msmsgsinvite": // file transfer, netmeeting invitation
                    return;
            }
        }

        // find user's name
        Regex.Regex regex = new Regex.Regex(@"(?<username>\S+)\s+(?<displayName>\S+)\s+\d+");
        Regex.Match match = regex.Match(message.Header);

        if (match.Success)
        {
            string username = match.Groups["username"].Value;
            string displayName = match.Groups["displayName"].Value;

            control.FriendSay(username, actualMessage);
        }
    }
Esempio n. 25
0
    private void OnDataReceive(IAsyncResult result)
    {
        lock (this)
        {
            int bytesRead = this.connection.EndReceive(result);

            if (bytesRead > 0)
            {
                // shove data into memory stream
                circStream.Write(this.receiveBuffer, 0, bytesRead);

                // get raw data from circular stream
                byte[] rawData = new byte[circStream.DataAvailable];
                circStream.Read(rawData, 0, rawData.Length);

                // split the message into composite messages
                string rawMessage = System.Text.Encoding.ASCII.GetString(rawData);
                string subMessage = string.Empty;
                int    position   = 0;

                while (position < rawMessage.Length)
                {
                    // see if we have enough to determine the message code
                    if (rawMessage.Length - position >= 3)
                    {
                        string messageCode = rawMessage.Substring(position, 3);

                        if (messageCode == "MSG")
                        {
                            // if its a MSG, then read until the length is satified
                            Regex.Regex regex = new Regex.Regex(@"MSG\s+\S+\s+\S+\s+(?<length>\d+)");
                            Regex.Match match = regex.Match(rawMessage.Substring(position));

                            if (match.Success)
                            {
                                int length      = int.Parse(match.Groups["length"].Value);
                                int endOfHeader = rawMessage.IndexOf("\r\n", position);

                                if (endOfHeader >= 0 && position + endOfHeader + length + 2 <= rawMessage.Length)
                                {
                                    subMessage = rawMessage.Substring(position, endOfHeader + length + 2 - position);
                                }
                                else
                                {
                                    this.SetToDataStream(rawMessage.Substring(position));
                                    break;
                                }
                            }
                            else
                            {
                                // we didnt get enough of the string to determine the message length -
                                // set it to the data stream and wait till the next rush of data
                                this.SetToDataStream(rawMessage.Substring(position));
                                break;
                            }
                        }
                        else
                        {
                            // otherwise it isnt a MSG, so read up until the first \r\n
                            int newPosition = rawMessage.IndexOf("\r\n", position);
                            if (newPosition < 0)
                            {
                                // we dont have the entire message - clear out the left over data stream
                                // and add the incomplete message to the stream
                                this.SetToDataStream(rawMessage.Substring(position));
                                break;
                            }
                            else
                            {
                                newPosition += 2;
                                subMessage   = rawMessage.Substring(position, newPosition - position);
                            }
                        }
                    }
                    else
                    {
                        // we dont even have enough to determine the message code - add it to the data stream
                        // and forget about it
                        this.SetToDataStream(rawMessage.Substring(position));
                        break;
                    }

                    position += subMessage.Length;

                    this.protocol.control.WriteDebug("-----------------------------------------");
                    this.protocol.control.WriteDebug("Received");
                    this.protocol.control.WriteDebug(subMessage);
                    this.protocol.control.WriteDebug("-----------------------------------------");

                    Message message = new Message(subMessage);

                    switch (message.Code)
                    {
                    case "CHL":
                    {
                        // we received a challenge. Respond to it appropriately.
                        string hash = message.Arguments;

                        // md5 encrypt hash
                        hash += md5MagicHash;

                        MD5Encryption encryption = new MD5Encryption();
                        string        md5hash    = encryption.Encrypt(hash);

                        Message responseMessage = Message.ConstructMessage("QRY", @"[email protected] 32" + "\r\n" + md5hash);
                        this.SendMessage(responseMessage, false);
                    }
                    break;
                    }

                    try
                    {
                        // see if theres a transaction ID registered with it
                        if (this.transactionEvents.Contains(message.TransactionID))
                        {
                            Pair pair = (Pair)this.transactionEvents[message.TransactionID];
                            ((ResponseReceivedHandler)pair.First)(this, message, pair.Second);
                        }
                        // else check if the code is registered
                        else if (this.codeEvents.Contains(message.Code))
                        {
                            Pair pair = (Pair)this.codeEvents[message.Code];
                            ((ResponseReceivedHandler)pair.First)(this, message, pair.Second);
                        }
                        // otherwise uses the default message sink
                        else
                        {
                            if (defaultMessageSink != null)
                            {
                                defaultMessageSink(this, message, null);
                            }
                        }
                    }
                    catch
                    {}
                }

                try
                {
                    // restart async call
                    this.connection.BeginReceive(receiveBuffer, new AsyncCallback(OnDataReceive), null);
                }
                catch
                {
                    this.onDisconnect(this, null, null);
                }
            }
            else if (!ExpectingDisconnection)
            {
                this.onDisconnect(this, null, null);
            }
        }
    }
Esempio n. 26
0
    private void OnSwitchBoardRequestResponse(MessageRouter router, Message message, object tag)
    {
        object[] o = (object[])tag;

        Friend friend = (Friend)o[0];
        OperationCompleteEvent op = (OperationCompleteEvent)o[1];

        Regex.Regex regex = new Regex.Regex(@"SB (?<sbServerIP>\d+\.\d+\.\d+\.\d+):(?<sbServerPort>\d+) CKI (?<hash>.*$)");
        Regex.Match match = regex.Match(message.Arguments);

        if (match.Success)
        {
            string sbIP = match.Groups["sbServerIP"].Value;
            int sbPort = int.Parse(match.Groups["sbServerPort"].Value);
            string conversationID = match.Groups["hash"].Value;

            // connect
            try
            {
                Proxy.IConnection conn = this.control.CreateConnection();
                conn.Connect("", 0, sbIP, sbPort, Proxy.ConnectionType.Tcp);
                sbRouter = new MessageRouter(this.protocol, conn, null, new ResponseReceivedHandler(OnForcedDisconnect));
            }
            catch
            {
                op.Execute(new OperationCompleteArgs("Could not connect", true));
                return;
            }

            RegisterCodeEvents();

            sbRouter.SendMessage(Message.ConstructMessage("USR", this.settings.Username + " " + conversationID),
                new ResponseReceivedHandler(OnSwitchBoardUsrResponse), tag);
        }
        else
            op.Execute(new OperationCompleteArgs("Could not connect", true));

        router.RemoveMessageEvent(message);
    }
Esempio n. 27
0
    private bool HandleListChangeMessage(Message message, Friend friend)
    {
        Regex.Regex regex = new Regex.Regex(@"(?<listType>\w{2})\s+(?<contactListVersion>\d+)\s+(?<username>\S+)\s*(?<groupNumber>\d*)");
        Regex.Match match = regex.Match(message.Arguments);

        if (match.Success)
        {
            // get new contact list version number and update local friends list
            this.settings.ContactListVersion = int.Parse(match.Groups["contactListVersion"].Value);

            if (friend == null)
            {
                friend = new Friend(match.Groups["username"].Value, OnlineStatus.Offline);
            }

            ListType listType = this.ConvertStringToListType(match.Groups["listType"].Value);

            if (message.Code == "ADD")
            {
                switch (listType)
                {
                case ListType.Allow:
                    this.settings.AllowList.Add(friend);
                    break;

                case ListType.Block:
                    this.settings.BlockList.Add(friend);
                    break;

                case ListType.Forward:
                    this.settings.ForwardList.Add(friend);
                    break;

                case ListType.Reverse:
                    this.settings.ReverseList.Add(friend);
                    break;
                }
            }
            else
            {
                switch (listType)
                {
                case ListType.Allow:
                    this.settings.AllowList.Remove(friend);
                    break;

                case ListType.Block:
                    this.settings.BlockList.Remove(friend);
                    break;

                case ListType.Forward:
                    this.settings.ForwardList.Remove(friend);
                    break;

                case ListType.Reverse:
                    this.settings.ReverseList.Remove(friend);
                    break;
                }
            }

            return(true);
        }
        else
        {
            return(false);
        }
    }