예제 #1
0
        public void Connect(FrontendManager fm, string server, int port, string[] nicks, string user, string pass)
        {
            Trace.Call(fm, server, port, nicks, user, pass);

            _FrontendManager = fm;
            _Host = server;
            _Port = port;
            _Nicknames = nicks;
            _Username = user;
            _Password = pass;

            // add fallbacks if only one nick was specified, else we get random
            // number nicks when nick collisions happen
            if (_Nicknames.Length == 1) {
                _Nicknames = new string[] { _Nicknames[0], _Nicknames[0] + "_", _Nicknames[0] + "__" };
            }

            // TODO: use config for single network chat or once per network manager
            var servers = new ServerListController(Session.UserConfig);
            var serverModel = servers.GetServer(Protocol, server);
            _ServerModel = serverModel;
            ApplyConfig(Session.UserConfig, serverModel);

            string network;
            if (serverModel != null && !String.IsNullOrEmpty(serverModel.Network)) {
                network = serverModel.Network;
            } else {
                network = server;
            }

            _Network = network;
            _NetworkChat = new ProtocolChatModel(network, "IRC " + network, this);

            // BUG: race condition when we use Session.AddChat() as it pushes this already
            // to the connected frontend and the frontend will sync and get the page 2 times!
            //Session.Chats.Add(_NetworkChat);
            // NOTABUG: the frontend manager needs to take care for that
            Session.AddChat(_NetworkChat);
            Session.SyncChat(_NetworkChat);

            _RunThread = new Thread(new ThreadStart(_Run));
            _RunThread.IsBackground = true;
            _RunThread.Name = "IrcProtocolManager ("+server+":"+port+") listener";
            _RunThread.Start();

            _LagWatcherThread = new Thread(new ThreadStart(_LagWatcher));
            _LagWatcherThread.Name = "IrcProtocolManager ("+server+":"+port+") lag watcher";
            _LagWatcherThread.Start();
        }
예제 #2
0
        public void CommandPin(CommandModel cd)
        {
            if (String.IsNullOrEmpty(cd.Parameter)) {
                NotEnoughParameters(cd);
                return;
            }
            var pin = cd.Parameter.Trim();

            MessageBuilder builder;
            if (String.IsNullOrEmpty(f_RequestToken)) {
                builder = CreateMessageBuilder();
                builder.AppendEventPrefix();
                builder.AppendText(_("No pending authorization request!"));
                Session.AddMessageToChat(f_ProtocolChat, builder.ToMessage());
                return;
            }
            var reqToken = f_RequestToken;
            f_RequestToken = null;

            var key = GetApiKey();
            OAuthTokenResponse response;
            try {
                response = OAuthUtility.GetAccessToken(key[0], key[1],
                                                       reqToken, pin,
                                                       f_WebProxy);
            } catch (Exception ex) {
            #if LOG4NET
                f_Logger.Error("CommandPin(): GetAccessToken() threw Exception!", ex);
            #endif
                builder = CreateMessageBuilder();
                builder.AppendEventPrefix();
                // TRANSLATOR: {0} contains the reason of the failure
                builder.AppendText(
                    _("Failed to authorize with Twitter: {0}"),
                    ex.Message
                );
                Session.AddMessageToChat(f_ProtocolChat, builder.ToMessage());

                builder = CreateMessageBuilder();
                builder.AppendEventPrefix();
                builder.AppendText(
                    _("Twitter did not accept your PIN.  "  +
                      "Did you enter it correctly?")
                );
                Session.AddMessageToChat(f_ProtocolChat, builder.ToMessage());

                builder = CreateMessageBuilder();
                builder.AppendEventPrefix();
                builder.AppendText(
                    _("Please retry by closing this tab and reconnecting to " +
                      "the Twitter \"{0}\" account."),
                    f_Username
                );

                // allow the user to re-enter the pin
                // LAME: An incorrect PIN invalidates the request token!
                //f_RequestToken = reqToken;
                return;
            }
            #if LOG4NET
            f_Logger.Debug("CommandPin(): retrieved " +
                           " AccessToken: " + response.Token +
                           " AccessTokenSecret: " + response.TokenSecret +
                           " ScreenName: " + response.ScreenName +
                           " UserId: " + response.UserId);
            #endif
            var servers = new ServerListController(Session.UserConfig);
            var server = servers.GetServer(Protocol, response.ScreenName);
            if (server == null) {
                server = new ServerModel() {
                    Protocol = Protocol,
                    Network  = String.Empty,
                    Hostname = response.ScreenName,
                    Username = response.ScreenName,
                    Password = String.Format("{0}|{1}", response.Token,
                                             response.TokenSecret),
                    OnStartupConnect = true
                };
                servers.AddServer(server);

                var obsoleteServer = servers.GetServer(Protocol, String.Empty);
                if (obsoleteServer != null &&
                    obsoleteServer.Username.ToLower() == response.ScreenName.ToLower()) {
                    // found an old server entry for this user using basic auth
                    servers.RemoveServer(Protocol, String.Empty);

                    builder = CreateMessageBuilder();
                    builder.AppendEventPrefix();
                    builder.AppendText(
                        _("Migrated Twitter account from basic auth to OAuth.")
                    );
                    Session.AddMessageToChat(f_ProtocolChat, builder.ToMessage());
                }
            } else {
                // update token
                server.Password = String.Format("{0}|{1}", response.Token,
                                                response.TokenSecret);
                servers.SetServer(server);
            }
            servers.Save();

            builder = CreateMessageBuilder();
            builder.AppendEventPrefix();
            builder.AppendText(_("Successfully authorized Twitter account " +
                                 "\"{0}\" for Smuxi"), response.ScreenName);
            Session.AddMessageToChat(f_ProtocolChat, builder.ToMessage());

            f_OAuthTokens.AccessToken = response.Token;
            f_OAuthTokens.AccessTokenSecret = response.TokenSecret;
            f_Username = response.ScreenName;
        }
예제 #3
0
        public override void Connect(FrontendManager fm, string host, int port,
                                     string username, string password)
        {
            Trace.Call(fm, host, port, username, "XXX");

            f_Username = username;

            var proxyType = (string) Session.UserConfig["Connection/ProxyType"];
            if (proxyType.ToLower() == "http") {
                var uriBuilder = new UriBuilder();
                uriBuilder.Scheme = "http";
                uriBuilder.Host = (string) Session.UserConfig["Connection/ProxyHostname"];
                uriBuilder.Port = (int) Session.UserConfig["Connection/ProxyPort"];
                uriBuilder.UserName = (string) Session.UserConfig["Connection/ProxyUsername"];
                uriBuilder.Password = (string) Session.UserConfig["Connection/ProxyPassword"];
                var proxyUri = uriBuilder.ToString();
                f_WebProxy = new WebProxy(proxyUri);
            }

            f_OptionalProperties = new OptionalProperties();
            if (f_WebProxy != null) {
                f_OptionalProperties.Proxy = f_WebProxy;
            }

            f_ProtocolChat = new ProtocolChatModel(NetworkID, "Twitter " + username, this);
            Session.AddChat(f_ProtocolChat);
            Session.SyncChat(f_ProtocolChat);

            string msg;
            msg = String.Format(_("Connecting to Twitter..."));
            fm.SetStatus(msg);
            Session.AddTextToChat(f_ProtocolChat, "-!- " + msg);
            try {
                var key = GetApiKey();
                f_OAuthTokens = new OAuthTokens();
                f_OAuthTokens.ConsumerKey = key[0];
                f_OAuthTokens.ConsumerSecret = key[1];

                MessageBuilder builder;
                var servers = new ServerListController(Session.UserConfig);
                var server = servers.GetServer(Protocol, username);
                if (server != null) {
                    if (password == null) {
                        // no password passed, use server password
                        password = server.Password;
                    }
                }

                password = password ?? String.Empty;
                var access = password.Split('|');
                if (password.Length == 0 || access.Length == 1) {
                    // new account or basic auth user that needs to be migrated
                    var reqToken = OAuthUtility.GetRequestToken(key[0], key[1],
                                                            "oob", f_WebProxy);
                    f_RequestToken = reqToken.Token;
                    var authUri = OAuthUtility.BuildAuthorizationUri(f_RequestToken);
                    builder = CreateMessageBuilder();
                    builder.AppendEventPrefix();
                    builder.AppendText(_("Twitter authorization required."));
                    Session.AddMessageToChat(f_ProtocolChat, builder.ToMessage());

                    /*
                        _("Twitter authorization required, please open the " +
                          "following URL and enter the returned PIN using the " +
                          "/pin command: {0}"),
                        String.Empty
                    );
                    */

                    builder = CreateMessageBuilder();
                    builder.AppendEventPrefix();
                    // TRANSLATOR: do NOT change the position of {0}!
                    builder.AppendText(
                        _("Please open the following URL and click " +
                          "\"Allow\" to allow Smuxi to connect to your " +
                          "Twitter account: {0}"),
                        String.Empty
                    );
                    Session.AddMessageToChat(f_ProtocolChat, builder.ToMessage());

                    builder = CreateMessageBuilder();
                    builder.AppendEventPrefix();
                    builder.AppendText(" ");
                    builder.AppendUrl(authUri.AbsoluteUri);
                    Session.AddMessageToChat(f_ProtocolChat, builder.ToMessage());

                    builder = CreateMessageBuilder();
                    builder.AppendEventPrefix();
                    builder.AppendText(
                        _("Once you have allowed Smuxi to access your " +
                          "Twitter account, Twitter will provide a PIN.")
                    );
                    Session.AddMessageToChat(f_ProtocolChat, builder.ToMessage());

                    builder = CreateMessageBuilder();
                    builder.AppendEventPrefix();
                    builder.AppendText(_("Please type: /pin PIN_FROM_TWITTER"));
                    Session.AddMessageToChat(f_ProtocolChat, builder.ToMessage());
                } else {
                    f_OAuthTokens.AccessToken = access[0];
                    f_OAuthTokens.AccessTokenSecret = access[1];
                }
            } catch (Exception ex) {
            #if LOG4NET
                f_Logger.Error("Connect(): Exception", ex);
            #endif
                fm.SetStatus(_("Connection failed!"));
                Session.AddTextToChat(f_ProtocolChat,
                    "-!- " + _("Connection failed! Reason: ") + ex.Message
                );
                return;
            }

            // twitter is sometimes pretty slow, so fetch this in the background
            ThreadPool.QueueUserWorkItem(delegate {
                try {
                    // FIXME: replace with AutoResetEvent
                    while (!HasTokens) {
                        Thread.Sleep(1000);
                    }

                    var message = _("Fetching user details from Twitter, please wait...");
                    Session.AddTextToChat(f_ProtocolChat, "-!- " + message);

                    UpdateUser();

                    message = _("Finished fetching user details.");
                    Session.AddTextToChat(f_ProtocolChat, "-!- " + message);

                    f_IsConnected = true;
                    fm.UpdateNetworkStatus();
                    msg =_("Successfully connected to Twitter.");
                    fm.SetStatus(msg);
                    Session.AddTextToChat(f_ProtocolChat, "-!- " + msg);
                    f_Listening = true;

                    f_FriendsTimelineChat.PersonCount =
                    f_RepliesChat.PersonCount =
                    f_DirectMessagesChat.PersonCount = (int) f_TwitterUser.NumberOfFriends;
                } catch (Exception ex) {
                    var message = _("Failed to fetch user details from Twitter. Reason: ");
            #if LOG4NET
                    f_Logger.Error("Connect(): " + message, ex);
            #endif
                    Session.AddTextToChat(f_ProtocolChat, "-!- " + message + ex.Message);

                    fm.SetStatus(_("Connection failed!"));
                    Session.AddTextToChat(f_ProtocolChat,
                        "-!- " + _("Connection failed! Reason: ") + ex.Message
                    );
                }
            });
            ThreadPool.QueueUserWorkItem(delegate {
                try {
                    // FIXME: replace with AutoResetEvent
                    // f_TwitterUser needed for proper self detection in the
                    // CreatePerson() method
                    while (!HasTokens || f_TwitterUser == null) {
                        Thread.Sleep(1000);
                    }

                    var message = _("Fetching friends from Twitter, please wait...");
                    Session.AddTextToChat(f_ProtocolChat, "-!- " + message);

                    UpdateFriends();

                    message = _("Finished fetching friends.");
                    Session.AddTextToChat(f_ProtocolChat, "-!- " + message);
                } catch (Exception ex) {
                    var message = _("Failed to fetch friends from Twitter. Reason: ");
            #if LOG4NET
                    f_Logger.Error("Connect(): " + message, ex);
            #endif
                    Session.AddTextToChat(f_ProtocolChat, "-!- " + message + ex.Message);
                }
            });

            OpenFriendsTimelineChat();
            OpenRepliesChat();
            OpenDirectMessagesChat();
        }
예제 #4
0
        public void Connect(FrontendManager fm, string host, int port, string username, string password, string resource)
        {
            Trace.Call(fm, host, port, username, "XXX");

            _FrontendManager = fm;
            Host = host;
            Port = port;

            // TODO: use config for single network chat or once per network manager
            _NetworkChat = new ProtocolChatModel(NetworkID, "Jabber " + host, this);
            Session.AddChat(_NetworkChat);
            Session.SyncChat(_NetworkChat);

            // HACK: try to lookup settings via config
            var servers = new ServerListController(Session.UserConfig);
            var serverModel = servers.GetServer(Protocol, host);
            if (serverModel != null) {
                ApplyConfig(Session.UserConfig, serverModel);
            }

            if (username.Contains("@")) {
                var user = username.Split('@')[0];
                var server = username.Split('@')[1];
                _JabberClient.NetworkHost = host;
                _JabberClient.Server = server;
                _JabberClient.User = user;
            } else {
                _JabberClient.Server = host;
                _JabberClient.User = username;
            }
            _JabberClient.Port = port;
            _JabberClient.Password = password;
            _JabberClient.Resource = resource;

            _JabberClient.Connect();
        }