示例#1
0
        public override void Connect(FrontendManager fm, ServerModel server)
        {
            Trace.Call(fm, server);

            Network = server.Hostname.Substring(0, server.Hostname.IndexOf('.'));
            Host = server.Hostname;
            BaseUri = new Uri(String.Format("https://{0}", Host));

            NetworkChat = new ProtocolChatModel(Network, "Campfire " + Network, this);
            NetworkChat.InitMessageBuffer(MessageBufferPersistencyType.Volatile);
            NetworkChat.ApplyConfig(Session.UserConfig);
            Session.AddChat(NetworkChat);
            Session.SyncChat(NetworkChat);
            var msg = _("Connecting to campfire... ");
            if (fm != null) {
                fm.SetStatus(msg);
            }
            var bld = CreateMessageBuilder().AppendEventPrefix().AppendText(msg);
            Session.AddMessageToChat(NetworkChat, bld.ToMessage());

            if (!server.ValidateServerCertificate) {
                var whitelist = Session.CertificateValidator.HostnameWhitelist;
                lock (whitelist) {
                    // needed for favicon
                    if (!whitelist.Contains("campfirenow.com")) {
                        whitelist.Add("campfirenow.com");
                    }
                    // needed for receiving messages
                    if (!whitelist.Contains("streaming.campfirenow.com")) {
                        whitelist.Add("streaming.campfirenow.com");
                    }
                    if (!whitelist.Contains(Host)) {
                        whitelist.Add(Host);
                    }
                }
            }

            Client = new JsonServiceClient(BaseUri.AbsoluteUri);
            var creds = new NetworkCredential(server.Username, server.Password);
            Client.Credentials = creds;

            try {
                var me = Client.Get<UserResponse>("/users/me.json").User;
                Key = me.Api_Auth_Token;
                Me = CreatePerson(me);
                // The blue color is hardcoded for now
                Me.IdentityNameColored.ForegroundColor = new TextColor(0x0000FF);
                Me.IdentityNameColored.BackgroundColor = TextColor.None;
                Me.IdentityNameColored.Bold = true;

            } catch (Exception e) {
                FailedToConnect("Failed to connect to Campfire", e);
                return;
            }

            Client.Credentials = new NetworkCredential(Key, "X");
            msg = _("Connected to campfire");
            if (fm != null) {
                fm.SetStatus(msg);
            }
            bld = CreateMessageBuilder().AppendEventPrefix().AppendText(msg);
            Session.AddMessageToChat(NetworkChat, bld.ToMessage());

            // Campfire lets us know what channels the user is currently in, so
            // connect to those rooms automatically
            Rooms = Client.Get<RoomsResponse>("/rooms.json").Rooms;
            RoomsUpdated = DateTime.Now;

            var myrooms = Client.Get<RoomsResponse>("/presence.json").Rooms;
            if (myrooms.Length > 0) {
                bld = CreateMessageBuilder().
                    AppendEventPrefix().
                    AppendText("Present in {0}",
                        String.Join(", ", myrooms.Select(r => r.Name).ToArray())
                    );
                Session.AddMessageToChat(NetworkChat, bld.ToMessage());
            }

            foreach (var room in myrooms) {
                var chat = new GroupChatModel(room.Id.ToString(), room.Name, null);
                OpenChat(fm, chat);
            }
        }
        public override void Connect(FrontendManager fm, ServerModel server)
        {
            Trace.Call(fm, server);

            Server = server;
            Username = server.Username;
            var chatName = String.Format("{0} {1}", Protocol, NetworkID);
            ProtocolChat = new ProtocolChatModel(NetworkID, chatName, this);
            ProtocolChat.InitMessageBuffer(MessageBufferPersistencyType.Volatile);
            Session.AddChat(Chat);
            Session.SyncChat(Chat);

            try {
                string url;
                if (server.Hostname.StartsWith("http://") ||
                    server.Hostname.StartsWith("https://")) {
                    url = server.Hostname;
                } else {
                    if (server.UseEncryption && server.Port == 443) {
                        url = String.Format("https://{0}", server.Hostname);
                    } else if (server.UseEncryption) {
                        url = String.Format("https://{0}:{1}",
                                            server.Hostname, server.Port);
                    } else if (!server.UseEncryption && server.Port == 80) {
                        url = String.Format("http://{0}", server.Hostname);
                    } else {
                        url = String.Format("http://{0}:{1}",
                                            server.Hostname, server.Port);
                    }
                }
                // HACK: SignalR's ServerSentEventsTransport times out on Mono
                // for some reason and then fallbacks to LongPollingTransport
                // this takes 10 seconds though, so let's go LP directly
                Func<IClientTransport> transport = null;
                if (Type.GetType("Mono.Runtime") == null) {
                    transport = () => new AutoTransport(new DefaultHttpClient());
                } else {
                    transport = () => new LongPollingTransport();
                }
                var authProvider = new DefaultAuthenticationProvider(url);
                Client = new JabbRClient(url, authProvider, transport);
                Client.AutoReconnect = true;
                Client.MessageReceived += OnMessageReceived;
                Client.MeMessageReceived += OnMeMessageReceived;
                Client.UserLeft += OnUserLeft;
                Client.UserJoined += OnUserJoined;
                Client.JoinedRoom += OnJoinedRoom;
                Client.PrivateMessage += OnPrivateMessage;

                Me = CreatePerson(Username);
                Me.IdentityNameColored.ForegroundColor = new TextColor(0, 0, 255);
                Me.IdentityNameColored.BackgroundColor = TextColor.None;
                Me.IdentityNameColored.Bold = true;

                Connect();
            } catch (Exception ex) {
            #if LOG4NET
                Logger.Error(ex);
            #endif
                var msg = CreateMessageBuilder().
                    AppendEventPrefix().
                    AppendErrorText(_("Connection failed! Reason: {0}"),
                                    ex.Message).
                    ToMessage();
                Session.AddMessageToChat(ProtocolChat, msg);
            }
        }
示例#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 override void Connect(FrontendManager fm, ServerModel server)
        {
            Trace.Call(fm, server);

            Server   = server;
            Username = server.Username;
            var chatName = String.Format("{0} {1}", Protocol, NetworkID);

            ProtocolChat = new ProtocolChatModel(NetworkID, chatName, this);
            ProtocolChat.InitMessageBuffer(MessageBufferPersistencyType.Volatile);
            Session.AddChat(Chat);
            Session.SyncChat(Chat);

            try {
                string url;
                if (server.Hostname.StartsWith("http://") ||
                    server.Hostname.StartsWith("https://"))
                {
                    url = server.Hostname;
                }
                else
                {
                    if (server.UseEncryption && server.Port == 443)
                    {
                        url = String.Format("https://{0}", server.Hostname);
                    }
                    else if (server.UseEncryption)
                    {
                        url = String.Format("https://{0}:{1}",
                                            server.Hostname, server.Port);
                    }
                    else if (!server.UseEncryption && server.Port == 80)
                    {
                        url = String.Format("http://{0}", server.Hostname);
                    }
                    else
                    {
                        url = String.Format("http://{0}:{1}",
                                            server.Hostname, server.Port);
                    }
                }
                // HACK: SignalR's ServerSentEventsTransport times out on Mono
                // for some reason and then fallbacks to LongPollingTransport
                // this takes 10 seconds though, so let's go LP directly
                Func <IClientTransport> transport = null;
                if (Type.GetType("Mono.Runtime") == null)
                {
                    transport = () => new AutoTransport(new DefaultHttpClient());
                }
                else
                {
                    transport = () => new LongPollingTransport();
                }
                var authProvider = new DefaultAuthenticationProvider(url);
                Client = new JabbRClient(url, authProvider, transport);
                Client.AutoReconnect      = true;
                Client.MessageReceived   += OnMessageReceived;
                Client.MeMessageReceived += OnMeMessageReceived;
                Client.UserLeft          += OnUserLeft;
                Client.UserJoined        += OnUserJoined;
                Client.JoinedRoom        += OnJoinedRoom;
                Client.PrivateMessage    += OnPrivateMessage;

                Me = CreatePerson(Username);
                Me.IdentityNameColored.ForegroundColor = new TextColor(0, 0, 255);
                Me.IdentityNameColored.BackgroundColor = TextColor.None;
                Me.IdentityNameColored.Bold            = true;

                Connect();
            } catch (Exception ex) {
#if LOG4NET
                Logger.Error(ex);
#endif
                var msg = CreateMessageBuilder().
                          AppendEventPrefix().
                          AppendErrorText(_("Connection failed! Reason: {0}"),
                                          ex.Message).
                          ToMessage();
                Session.AddMessageToChat(ProtocolChat, msg);
            }
        }
示例#5
0
        public override void Connect(FrontendManager fm, ServerModel server)
        {
            Trace.Call(fm, server);

            Network = server.Hostname.Substring(0, server.Hostname.IndexOf('.'));
            Host    = server.Hostname;
            BaseUri = new Uri(String.Format("https://{0}", Host));

            NetworkChat = new ProtocolChatModel(Network, "Campfire " + Network, this);
            NetworkChat.InitMessageBuffer(MessageBufferPersistencyType.Volatile);
            NetworkChat.ApplyConfig(Session.UserConfig);
            Session.AddChat(NetworkChat);
            Session.SyncChat(NetworkChat);
            var msg = _("Connecting to campfire... ");

            if (fm != null)
            {
                fm.SetStatus(msg);
            }
            var bld = CreateMessageBuilder().AppendEventPrefix().AppendText(msg);

            Session.AddMessageToChat(NetworkChat, bld.ToMessage());

            if (!server.ValidateServerCertificate)
            {
                var whitelist = Session.CertificateValidator.HostnameWhitelist;
                lock (whitelist) {
                    // needed for favicon
                    if (!whitelist.Contains("campfirenow.com"))
                    {
                        whitelist.Add("campfirenow.com");
                    }
                    // needed for receiving messages
                    if (!whitelist.Contains("streaming.campfirenow.com"))
                    {
                        whitelist.Add("streaming.campfirenow.com");
                    }
                    if (!whitelist.Contains(Host))
                    {
                        whitelist.Add(Host);
                    }
                }
            }

            Client = new JsonServiceClient(BaseUri.AbsoluteUri);
            var creds = new NetworkCredential(server.Username, server.Password);

            Client.Credentials = creds;

            try {
                var me = Client.Get <UserResponse>("/users/me.json").User;
                Key = me.Api_Auth_Token;
                Me  = CreatePerson(me);
                // The blue color is hardcoded for now
                Me.IdentityNameColored.ForegroundColor = new TextColor(0x0000FF);
                Me.IdentityNameColored.BackgroundColor = TextColor.None;
                Me.IdentityNameColored.Bold            = true;
            } catch (Exception e) {
                FailedToConnect("Failed to connect to Campfire", e);
                return;
            }

            Client.Credentials = new NetworkCredential(Key, "X");
            msg = _("Connected to campfire");
            if (fm != null)
            {
                fm.SetStatus(msg);
            }
            bld = CreateMessageBuilder().AppendEventPrefix().AppendText(msg);
            Session.AddMessageToChat(NetworkChat, bld.ToMessage());

            // Campfire lets us know what channels the user is currently in, so
            // connect to those rooms automatically
            Rooms        = Client.Get <RoomsResponse>("/rooms.json").Rooms;
            RoomsUpdated = DateTime.Now;

            var myrooms = Client.Get <RoomsResponse>("/presence.json").Rooms;

            if (myrooms.Length > 0)
            {
                bld = CreateMessageBuilder().
                      AppendEventPrefix().
                      AppendText("Present in {0}",
                                 String.Join(", ", myrooms.Select(r => r.Name).ToArray())
                                 );
                Session.AddMessageToChat(NetworkChat, bld.ToMessage());
            }

            foreach (var room in myrooms)
            {
                var chat = new GroupChatModel(room.Id.ToString(), room.Name, null);
                OpenChat(fm, chat);
            }
        }