Exemple #1
0
        public ServerDialog(Gtk.Window parent, ServerModel server,
                            IList<string> supportedProtocols,
                            IList<string> networks)
            : base(null, parent, Gtk.DialogFlags.DestroyWithParent)
        {
            Trace.Call(parent, server, supportedProtocols, networks);

            if (parent == null) {
                throw new ArgumentNullException("parent");
            }
            if (supportedProtocols == null) {
                throw new ArgumentNullException("supportedProtocols");
            }
            if (networks == null) {
                throw new ArgumentNullException("networks");
            }

            Build();
            TransientFor = parent;

            f_Widget.InitProtocols(supportedProtocols);
            f_Widget.InitNetworks(networks);
            if (server != null) {
                try {
                    f_Widget.Load(server);
                } catch (Exception) {
                    Destroy();
                    throw;
                }
            }
        }
Exemple #2
0
        public override void Connect(FrontendManager fm, ServerModel server)
        {
            Trace.Call(fm, server);

            if (fm == null)
            {
                throw new ArgumentNullException("fm");
            }
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }

            _FrontendManager = fm;
            Host             = server.Hostname;
            Port             = server.Port;

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

            ApplyConfig(Session.UserConfig, server);

            _JabberClient.Connect();
        }
Exemple #3
0
        public override void Connect(FrontendManager fm, ServerModel server)
        {
            Trace.Call(fm, server);

            if (fm == null)
            {
                throw new ArgumentNullException("fm");
            }
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }

            _FrontendManager = fm;
            _UsersAddress    = server.Username;
            Host             = server.Hostname;
            Port             = server.Port;

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

            _MsnClient.Credentials.Account  = server.Username;
            _MsnClient.Credentials.Password = server.Password;
            _MsnClient.Connect();
        }
Exemple #4
0
        public void CommandConnect(CommandModel cd)
        {
            FrontendManager fm = cd.FrontendManager;

            var server = new ServerModel();

            if (cd.DataArray.Length >= 3)
            {
                server.Username = cd.DataArray[2];
            }
            else
            {
                NotEnoughParameters(cd);
                return;
            }

            if (cd.DataArray.Length >= 4)
            {
                server.Password = cd.DataArray[3];
            }
            else
            {
                NotEnoughParameters(cd);
                return;
            }

            Connect(fm, server);
        }
Exemple #5
0
        public IList <ServerModel> GetServerList()
        {
            // load user servers
            string[]            servers    = (string[])_UserConfig["Servers/Servers"];
            IList <ServerModel> serverList = new List <ServerModel>();

            if (servers == null)
            {
                return(serverList);
            }
            foreach (string server in servers)
            {
                string[]    serverParts = server.Split(new char[] { '/' });
                string      protocol    = serverParts[0];
                string      serverId    = serverParts[1];
                ServerModel ser         = GetServer(protocol, serverId);
                if (ser == null)
                {
#if LOG4NET
                    _Logger.Error("GetServerList(): GetServer(" + protocol + ", " + serverId + ") returned null! ignoring...");
#endif
                    continue;
                }
                serverList.Add(ser);
            }
            return(serverList);
        }
Exemple #6
0
        public override void Connect(FrontendManager fm, ServerModel server)
        {
            Trace.Call(fm, server);

            if (fm == null)
            {
                throw new ArgumentNullException("fm");
            }
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }

            _FrontendManager = fm;
            Host             = "login.oscar.aol.com";
            Port             = 5190;

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

            _OscarSession = new OscarSession(server.Username, server.Password);
            _OscarSession.ClientCapabilities        = Capabilities.Chat | Capabilities.OscarLib;
            _OscarSession.LoginCompleted           += new LoginCompletedHandler(_OnLoginCompleted);
            _OscarSession.LoginFailed              += new LoginFailedHandler(_OnLoginFailed);
            _OscarSession.LoginStatusUpdate        += new LoginStatusUpdateHandler(_OnLoginStatusUpdate);
            _OscarSession.ErrorMessage             += new ErrorMessageHandler(_OnErrorMessage);
            _OscarSession.WarningMessage           += new WarningMessageHandler(_OnWarningMessage);
            _OscarSession.StatusUpdate             += new InformationMessageHandler(_OnStatusUpdate);
            _OscarSession.ContactListFinished      += new ContactListFinishedHandler(_OnContactListFinished);
            _OscarSession.Messages.MessageReceived += new MessageReceivedHandler(_OnMessageReceived);
            _OscarSession.Logon(Host, Port);
        }
        public void AddServer(ServerModel server)
        {
            Trace.Call(server);

            if (server == null) {
                throw new ArgumentNullException("server");
            }
            if (GetServer(server.Protocol, server.Hostname) != null) {
                throw new InvalidOperationException("Server '" + server.Hostname + "' already exists.");
            }

            string prefix = "Servers/" + server.Protocol + "/" + server.Hostname + "/";
            _UserConfig[prefix + "Hostname"] = server.Hostname;
            _UserConfig[prefix + "Port"]     = server.Port;
            _UserConfig[prefix + "Network"]  = server.Network;
            _UserConfig[prefix + "Username"] = server.Username;
            _UserConfig[prefix + "Password"] = server.Password;
            _UserConfig[prefix + "OnStartupConnect"] = server.OnStartupConnect;
            _UserConfig[prefix + "OnConnectCommands"] = server.OnConnectCommands;

            string[] servers = (string[]) _UserConfig["Servers/Servers"];
            if (servers == null) {
                servers = new string[] {};
            }
            List<string> serverList = new List<string>(servers);
            serverList.Add(server.Protocol + "/" + server.Hostname);
            _UserConfig["Servers/Servers"] = serverList.ToArray();
        }
Exemple #8
0
        public void SetServer(ServerModel server)
        {
            Trace.Call(server);

            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            server.Save(_UserConfig);
        }
Exemple #9
0
        public void AddServer(ServerModel server)
        {
            Trace.Call(server);

            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (String.IsNullOrEmpty(server.Hostname))
            {
                throw new InvalidOperationException(_("Server hostname must not be empty."));
            }
            if (server.Hostname.Contains("\n"))
            {
                throw new InvalidOperationException(_("Server hostname contains invalid characters (newline)."));
            }
            foreach (var s in GetServerList())
            {
                if (s.Protocol == server.Protocol &&
                    s.Hostname == server.Hostname)
                {
                    throw new InvalidOperationException(
                              String.Format(_("Server '{0}' already exists."),
                                            server.Hostname)
                              );
                }
            }

            string prefix = "Servers/" + server.Protocol + "/" + server.Hostname + "/";

            _UserConfig[prefix + "Hostname"]                  = server.Hostname;
            _UserConfig[prefix + "Port"]                      = server.Port;
            _UserConfig[prefix + "Network"]                   = server.Network;
            _UserConfig[prefix + "Username"]                  = server.Username;
            _UserConfig[prefix + "Password"]                  = server.Password;
            _UserConfig[prefix + "UseEncryption"]             = server.UseEncryption;
            _UserConfig[prefix + "ValidateServerCertificate"] =
                server.ValidateServerCertificate;
            _UserConfig[prefix + "OnStartupConnect"]  = server.OnStartupConnect;
            _UserConfig[prefix + "OnConnectCommands"] = server.OnConnectCommands;

            string[] servers = (string[])_UserConfig["Servers/Servers"];
            if (servers == null)
            {
                servers = new string[] {};
            }
            List <string> serverList = new List <string>(servers);

            serverList.Add(server.Protocol + "/" + server.Hostname);
            _UserConfig["Servers/Servers"] = serverList.ToArray();
        }
Exemple #10
0
        public void AddServer(ServerModel server)
        {
            Trace.Call(server);

            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (String.IsNullOrEmpty(server.Hostname))
            {
                throw new InvalidOperationException(_("Server hostname must not be empty."));
            }
            if (server.Hostname.Contains("\n"))
            {
                throw new InvalidOperationException(_("Server hostname contains invalid characters (newline)."));
            }
            var highestServerId = -1;

            foreach (var s in GetServerList())
            {
                if (s.Protocol == server.Protocol &&
                    s.ServerID == server.ServerID)
                {
                    throw new InvalidOperationException(
                              String.Format(_("Server ID '{0}' already exists."),
                                            server.ServerID)
                              );
                }
                int id;
                if (Int32.TryParse(s.ServerID, out id) && id > highestServerId)
                {
                    highestServerId = id;
                }
            }
            if (String.IsNullOrEmpty(server.ServerID))
            {
                server.ServerID = (++highestServerId).ToString();
            }
            server.Save(_UserConfig);

            string[] servers = (string[])_UserConfig["Servers/Servers"];
            if (servers == null)
            {
                servers = new string[] {};
            }
            List <string> serverList = new List <string>(servers);

            serverList.Add(server.Protocol + "/" + server.ServerID);
            _UserConfig["Servers/Servers"] = serverList.ToArray();
        }
Exemple #11
0
        public void AddServer(ServerModel server)
        {
            Trace.Call(server);

            if (server == null) {
                throw new ArgumentNullException("server");
            }
            if (String.IsNullOrEmpty(server.Hostname)) {
                throw new InvalidOperationException(_("Server hostname must not be empty."));
            }
            if (server.Hostname.Contains("\n")) {
                throw new InvalidOperationException(_("Server hostname contains invalid characters (newline)."));
            }
            foreach (var s in GetServerList()) {
                if (s.Protocol == server.Protocol &&
                    s.Hostname == server.Hostname) {
                    throw new InvalidOperationException(
                        String.Format(_("Server '{0}' already exists."),
                                      server.Hostname)
                    );
                }
            }

            string prefix = "Servers/" + server.Protocol + "/" + server.Hostname + "/";
            _UserConfig[prefix + "Hostname"] = server.Hostname;
            _UserConfig[prefix + "Port"]     = server.Port;
            _UserConfig[prefix + "Network"]  = server.Network;
            _UserConfig[prefix + "Username"] = server.Username;
            _UserConfig[prefix + "Password"] = server.Password;
            _UserConfig[prefix + "UseEncryption"] = server.UseEncryption;
            _UserConfig[prefix + "ValidateServerCertificate"] =
                server.ValidateServerCertificate;
            _UserConfig[prefix + "OnStartupConnect"] = server.OnStartupConnect;
            _UserConfig[prefix + "OnConnectCommands"] = server.OnConnectCommands;

            string[] servers = (string[]) _UserConfig["Servers/Servers"];
            if (servers == null) {
                servers = new string[] {};
            }
            List<string> serverList = new List<string>(servers);
            serverList.Add(server.Protocol + "/" + server.Hostname);
            _UserConfig["Servers/Servers"] = serverList.ToArray();
        }
        public void AddServer(ServerModel server)
        {
            Trace.Call(server);

            if (server == null) {
                throw new ArgumentNullException("server");
            }
            if (String.IsNullOrEmpty(server.Hostname)) {
                throw new InvalidOperationException(_("Server hostname must not be empty."));
            }
            if (server.Hostname.Contains("\n")) {
                throw new InvalidOperationException(_("Server hostname contains invalid characters (newline)."));
            }
            var highestServerId = -1;
            foreach (var s in GetServerList()) {
                if (s.Protocol == server.Protocol &&
                    s.ServerID == server.ServerID) {
                    throw new InvalidOperationException(
                        String.Format(_("Server ID '{0}' already exists."),
                                      server.ServerID)
                    );
                }
                int id;
                if (Int32.TryParse(s.ServerID, out id) && id > highestServerId) {
                    highestServerId = id;
                }
            }
            if (String.IsNullOrEmpty(server.ServerID)) {
                server.ServerID = (++highestServerId).ToString();
            }
            server.Save(_UserConfig);

            string[] servers = (string[]) _UserConfig["Servers/Servers"];
            if (servers == null) {
                servers = new string[] {};
            }
            List<string> serverList = new List<string>(servers);
            serverList.Add(server.Protocol + "/" + server.ServerID);
            _UserConfig["Servers/Servers"] = serverList.ToArray();
        }
Exemple #13
0
        public ServerModel(ServerModel server)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }

            UseEncryption             = server.UseEncryption;
            ValidateServerCertificate = server.ValidateServerCertificate;
            ClientCertificateFilename = server.ClientCertificateFilename;
            Protocol          = server.Protocol;
            Hostname          = server.Hostname;
            Port              = server.Port;
            Network           = server.Network;
            Nickname          = server.Nickname;
            Realname          = server.Realname;
            Username          = server.Username;
            Password          = server.Password;
            OnStartupConnect  = server.OnStartupConnect;
            OnConnectCommands = new List <string>(server.OnConnectCommands);
            ServerID          = server.ServerID;
        }
Exemple #14
0
        public void SetServer(ServerModel server)
        {
            Trace.Call(server);

            if (server == null)
            {
                throw new ArgumentNullException("server");
            }

            string prefix = "Servers/" + server.Protocol + "/" + server.Hostname + "/";

            _UserConfig[prefix + "Hostname"]                  = server.Hostname;
            _UserConfig[prefix + "Port"]                      = server.Port;
            _UserConfig[prefix + "Network"]                   = server.Network;
            _UserConfig[prefix + "Username"]                  = server.Username;
            _UserConfig[prefix + "Password"]                  = server.Password;
            _UserConfig[prefix + "UseEncryption"]             = server.UseEncryption;
            _UserConfig[prefix + "ValidateServerCertificate"] =
                server.ValidateServerCertificate;
            _UserConfig[prefix + "OnStartupConnect"]  = server.OnStartupConnect;
            _UserConfig[prefix + "OnConnectCommands"] = server.OnConnectCommands;
        }
Exemple #15
0
        public ServerModel GetServer(string protocol, string servername)
        {
            Trace.Call(protocol, servername);

            if (protocol == null)
            {
                throw new ArgumentNullException("protocol");
            }
            if (servername == null)
            {
                throw new ArgumentNullException("servername");
            }

            ServerModel server = new ServerModel();

            try {
                server.Load(_UserConfig, protocol, servername);
            } catch (ArgumentException) {
                return(null);
            }
            return(server);
        }
Exemple #16
0
        private void ApplyConfig(UserConfig config, ServerModel server)
        {
            if (server.Username.Contains("@"))
            {
                var jid_user = server.Username.Split('@')[0];
                var jid_host = server.Username.Split('@')[1];
                _JabberClient.NetworkHost = server.Hostname;
                _JabberClient.User        = jid_user;
                _JabberClient.Server      = jid_host;
            }
            else
            {
                _JabberClient.Server = server.Hostname;
                _JabberClient.User   = server.Username;
            }
            _JabberClient.Port     = server.Port;
            _JabberClient.Password = server.Password;

            // XMPP specific settings
            if (server is XmppServerModel)
            {
                var xmppServer = (XmppServerModel)server;
                _JabberClient.Resource = xmppServer.Resource;
            }

            // fallback
            if (String.IsNullOrEmpty(_JabberClient.Resource))
            {
                _JabberClient.Resource = "smuxi";
            }

            _JabberClient.OnInvalidCertificate -= ValidateCertificate;

            _JabberClient.AutoStartTLS = server.UseEncryption;
            if (!server.ValidateServerCertificate)
            {
                _JabberClient.OnInvalidCertificate += ValidateCertificate;
            }
        }
Exemple #17
0
        public ServerModel GetServer(string protocol, string servername)
        {
            Trace.Call(protocol, servername);

            if (protocol == null)
            {
                throw new ArgumentNullException("protocol");
            }
            if (servername == null)
            {
                throw new ArgumentNullException("servername");
            }

            string      prefix = "Servers/" + protocol + "/" + servername + "/";
            ServerModel server = new ServerModel();

            if (_UserConfig[prefix + "Hostname"] == null)
            {
                // server does not exist
                return(null);
            }
            server.Protocol                  = protocol;
            server.Hostname                  = (string)_UserConfig[prefix + "Hostname"];
            server.Port                      = (int)_UserConfig[prefix + "Port"];
            server.Network                   = (string)_UserConfig[prefix + "Network"];
            server.Username                  = (string)_UserConfig[prefix + "Username"];
            server.Password                  = (string)_UserConfig[prefix + "Password"];
            server.UseEncryption             = (bool)_UserConfig[prefix + "UseEncryption"];
            server.ValidateServerCertificate =
                (bool)_UserConfig[prefix + "ValidateServerCertificate"];
            if (_UserConfig[prefix + "OnStartupConnect"] != null)
            {
                server.OnStartupConnect = (bool)_UserConfig[prefix + "OnStartupConnect"];
            }
            server.OnConnectCommands = _UserConfig[prefix + "OnConnectCommands"] as IList <string>;
            return(server);
        }
 public override void Connect(FrontendManager fm, ServerModel server)
 {
     throw new System.NotImplementedException();
 }
Exemple #19
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();
        }
Exemple #20
0
        public ServerModel GetServer()
        {
            ServerModel server = new ServerModel();
            server.Protocol = f_ProtocolComboBox.ActiveText;
            server.ServerID = ServerID;
            server.Hostname = f_HostnameEntry.Text.Trim();
            server.Network  = f_NetworkComboBoxEntry.Entry.Text.Trim();
            server.Port     = f_PortSpinButton.ValueAsInt;
            server.Username = f_UsernameEntry.Text.Trim();
            // HACK: use Twitter username as hostname for multi-account support
            if (f_ProtocolComboBox.ActiveText == "Twitter") {
                server.Hostname = server.Username;
            }
            server.Password = f_PasswordEntry.Text;
            server.UseEncryption = f_UseEncryptionCheckButton.Active;
            server.ValidateServerCertificate =
                f_ValidateServerCertificateCheckButton.Active;
            server.OnStartupConnect = f_OnStartupConnectCheckButton.Active;
            if (f_OnConnectCommandsTextView.Sensitive) {
                server.OnConnectCommands =
                    f_OnConnectCommandsTextView.Buffer.Text.Split('\n');
            }

            return server;
        }
        public void CommandConnect(CommandModel cd)
        {
            FrontendManager fm = cd.FrontendManager;

            var server = new ServerModel();
            if (cd.DataArray.Length >= 1) {
                server.Username = cd.DataArray[2];
            } else {
                NotEnoughParameters(cd);
                return;
            }

            if (cd.DataArray.Length >= 2) {
                server.Password = cd.DataArray[3];
            } else {
                NotEnoughParameters(cd);
                return;
            }

            Connect(fm, server);
        }
Exemple #22
0
        protected virtual void OnConnectButtonClicked(object sender, EventArgs e)
        {
            Trace.Call(sender, e);

            try {
                f_ServerModel = f_Widget.GetServer();
            } catch (Exception ex) {
                Frontend.ShowException(ex);
            }
        }
        public override void Connect(FrontendManager fm, ServerModel server)
        {
            Trace.Call(fm, server);

            if (fm == null) {
                throw new ArgumentNullException("fm");
            }
            if (server == null) {
                throw new ArgumentNullException("server");
            }

            _FrontendManager = fm;
            _UsersAddress = server.Username;
            Host = server.Hostname;
            Port = server.Port;

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

            _MsnClient.Credentials.Account = server.Username;
            _MsnClient.Credentials.Password = server.Password;
            _MsnClient.Connect();
        }
Exemple #24
0
        public static bool TryOpenChatLink(Uri link)
        {
            Trace.Call(link);

            if (Session == null) {
                return false;
            }

            // supported:
            // smuxi://freenode/#smuxi
            // smuxi://freenode/#%23csharp (##csharp)
            // irc://#smuxi
            // irc://irc.oftc.net/
            // irc://irc.oftc.net/#smuxi
            // irc://irc.oftc.net:6667/#smuxi
            // not supported (yet):
            // smuxi:///meebey

            IProtocolManager manager = null;
            var linkPort = link.Port;
            if (linkPort == -1) {
                switch (link.Scheme) {
                    case "irc":
                        linkPort = 6667;
                        break;
                    case "ircs":
                        linkPort = 6697;
                        break;
                }
            }
            // decode #%23csharp to ##csharp
            var linkChat = HttpUtility.UrlDecode(link.Fragment);
            if (String.IsNullOrEmpty(linkChat) && link.AbsolutePath.Length > 0) {
                linkChat = link.AbsolutePath.Substring(1);
            }

            var linkProtocol = link.Scheme;
            var linkHost = link.Host;
            string linkNetwork = null;
            if (!linkHost.Contains(".")) {
                // this seems to be a network name
                linkNetwork = linkHost;
            }

            // find existing protocol chat
            foreach (var chatView in MainWindow.ChatViewManager.Chats) {
                if (!(chatView is ProtocolChatView)) {
                    continue;
                }
                var protocolChat = (ProtocolChatView) chatView;
                var host = protocolChat.Host;
                var port = protocolChat.Port;
                var network = protocolChat.NetworkID;
                // Check first by network name with fallback to host+port.
                // The network name has to be checked against the NetworkID and
                // also ChatModel.ID as the user might have entered a different
                // network name in settings than the server does
                if (!String.IsNullOrEmpty(network) &&
                    (String.Compare(network, linkNetwork, true) == 0 ||
                     String.Compare(chatView.ID, linkNetwork, true) == 0)) {
                    manager = protocolChat.ProtocolManager;
                    break;
                }
                if (String.Compare(host, linkHost, true) == 0 &&
                    port == linkPort) {
                    manager = protocolChat.ProtocolManager;
                    break;
                }
            }

            if (manager == null) {
                // only irc may autoconnect to a server
                switch (linkProtocol) {
                    case "irc":
                    case "ircs":
                    case "smuxi":
                        break;
                    default:
                        return false;
                }
                ServerModel server = null;
                if (!String.IsNullOrEmpty(linkNetwork)) {
                    // try to find a server with this network name and connect to it
                    var serverSettings = new ServerListController(UserConfig);
                    server = serverSettings.GetServerByNetwork(linkNetwork);
                    if (server == null) {
                        // in case someone tried an unknown network
                        return false;
                    }
                    // ignore OnConnectCommands
                    server.OnConnectCommands = null;
                } else if (!String.IsNullOrEmpty(linkHost)) {
                    server = new ServerModel() {
                        Protocol = linkProtocol,
                        Hostname = linkHost,
                        Port = linkPort
                    };
                }
                if (server != null) {
                    manager = Session.Connect(server, FrontendManager);
                }
            }

            if (String.IsNullOrEmpty(linkChat)) {
                return true;
            }

            // switch to existing chat
            foreach (var chatView in MainWindow.ChatViewManager.Chats) {
                if (manager != null && chatView.ProtocolManager != manager) {
                    continue;
                }
                if (String.Compare(chatView.ID, linkChat, true) == 0) {
                    MainWindow.ChatViewManager.CurrentChatView = chatView;
                    return true;
                }
            }

            // join chat
            if (manager != null) {
                var chat = new GroupChatModel(linkChat, linkChat, null);
                ThreadPool.QueueUserWorkItem(delegate {
                    try {
                        manager.OpenChat(FrontendManager, chat);
                    } catch (Exception ex) {
                        Frontend.ShowException(ex);
                    }
                });
            }
            return true;
        }
Exemple #25
0
 public abstract void Connect(FrontendManager fm,
                              ServerModel server);
        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;
        }
Exemple #27
0
        public override void Connect(FrontendManager fm, ServerModel server)
        {
            Trace.Call(fm, server);

            if (fm == null) {
                throw new ArgumentNullException("fm");
            }
            if (server == null) {
                throw new ArgumentNullException("server");
            }

            _FrontendManager = fm;
            _ServerModel = server;

            ApplyConfig(Session.UserConfig, server);

            // 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
            _NetworkChat = Session.CreateChat<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 = String.Format(
                "IrcProtocolManager ({0}:{1}) listener",
                server.Hostname, server.Port
             );
            _RunThread.Start();

            _LagWatcherThread = new Thread(new ThreadStart(_LagWatcher));
            _LagWatcherThread.IsBackground = true;
            _LagWatcherThread.Name = String.Format(
                "IrcProtocolManager ({0}:{1}) lag watcher",
                server.Hostname, server.Port
             );
            _LagWatcherThread.Start();
        }
Exemple #28
0
        public override void Connect(FrontendManager fm, ServerModel server)
        {
            Trace.Call(fm, server);

            if (server == null) {
                throw new ArgumentNullException("server");
            }

            if (server is XmppServerModel) {
                Server = (XmppServerModel) server;
            } else {
                Server = new XmppServerModel();
                if (server.ServerID != null) {
                    Server.Load(Session.UserConfig, Protocol, server.ServerID);
                }
                // HACK: previous line overwrites any passed values with the values from config
                // thus we have to copy the original values:
                Server.Hostname = server.Hostname;
                Server.Network = server.Network;
                Server.OnConnectCommands = server.OnConnectCommands;
                Server.OnStartupConnect = server.OnStartupConnect;
                Server.Password = server.Password;
                Server.Port = server.Port;
                Server.Protocol = server.Protocol;
                Server.ServerID = server.ServerID;
                Server.UseEncryption = server.UseEncryption;
                Server.Username = server.Username;
                Server.ValidateServerCertificate = server.ValidateServerCertificate;
            }

            Host = Server.Hostname;
            Port = Server.Port;

            // TODO: use config for single network chat or once per network manager
            NetworkChat = Session.CreateChat<ProtocolChatModel>(
                NetworkID, String.Format("{0} {1}", Protocol, Host), this
            );
            Session.AddChat(NetworkChat);
            if (Host.EndsWith("facebook.com") && !(this is FacebookProtocolManager)) {
                var builder = CreateMessageBuilder();
                builder.AppendEventPrefix();
                builder.AppendMessage(_("This engine has native Facebook support, you should be using it instead of connecting to Facebook with XMPP"));
                // cannot use AddMessageToFrontend because NetworkChat is not yet synced, causing AddMessageToFrontend to drop it.
                // cannot sync NetworkChat before this, because then the sync would swallow the message
                Session.AddMessageToChat(NetworkChat, builder.ToMessage());
            }
            Session.SyncChat(NetworkChat);

            Connect();
        }
Exemple #29
0
        protected virtual void OnConnectButtonClicked(object sender, EventArgs e)
        {
            Trace.Call(sender, e);

            try {
                f_ServerModel = new ServerModel();
                f_ServerModel.Protocol = f_ProtocolComboBox.ActiveText;
                f_ServerModel.Hostname = f_HostnameEntry.Text;
                f_ServerModel.Port     = f_PortSpinButton.ValueAsInt;
                f_ServerModel.Username = f_UsernameEntry.Text;
                f_ServerModel.Password = f_PasswordEntry.Text;
            } catch (Exception ex) {
                Frontend.ShowException(ex);
            }
        }
Exemple #30
0
        public void Load(ServerModel server)
        {
            Trace.Call(server);

            // protocol is part of the PKEY, not allowed to change
            f_ProtocolComboBox.Sensitive = false;
            Gtk.ListStore store = (Gtk.ListStore) ProtocolComboBox.Model;

            int protocolPosition = -1;
            int j = 0;
            foreach (object[] row in store) {
                string protocolName = (string) row[0];
                if (protocolName == server.Protocol) {
                    protocolPosition = j;
                    break;
                }
                j++;
            }
            if (protocolPosition == -1) {
                throw new ApplicationException("Unsupported protocol: " + server.Protocol);
            }
            f_ProtocolComboBox.Active = protocolPosition;
            ServerID = server.ServerID;
            f_HostnameEntry.Text = server.Hostname;
            f_NetworkComboBoxEntry.Entry.Text = server.Network;
            f_UsernameEntry.Text = server.Username;
            // HACK: Twitter username is part of the PKEY, not allowed to change
            if (server.Protocol == "Twitter") {
                f_UsernameEntry.Sensitive = false;
            }
            f_PasswordEntry.Text = server.Password;
            f_UseEncryptionCheckButton.Active = server.UseEncryption;
            f_ValidateServerCertificateCheckButton.Active =
                server.ValidateServerCertificate;
            f_PortSpinButton.Value = server.Port;
            OnStartupConnectCheckButton.Active = server.OnStartupConnect;
            if (server.OnConnectCommands == null ||
                server.OnConnectCommands.Count == 0) {
                f_OnConnectCommandsTextView.Buffer.Text = String.Empty;
            } else {
                // LAME: replace me when we have .NET 3.0
                string[] commands = new string[server.OnConnectCommands.Count];
                server.OnConnectCommands.CopyTo(commands, 0);
                f_OnConnectCommandsTextView.Buffer.Text = String.Join(
                    "\n", commands
                );
            }
        }
Exemple #31
0
        private void ApplyConfig(UserConfig config, ServerModel server)
        {
            if (String.IsNullOrEmpty(_Username)) {
                _Username = (string) config["Connection/Username"];
            }

            string encodingName = (string) config["Connection/Encoding"];
            if (String.IsNullOrEmpty(encodingName)) {
                _IrcClient.Encoding = Encoding.Default;
            } else {
                try {
                    _IrcClient.Encoding = Encoding.GetEncoding(encodingName);
                } catch (Exception ex) {
            #if LOG4NET
                    _Logger.Warn("ApplyConfig(): Error getting encoding for: " +
                                 encodingName + " falling back to system encoding.", ex);
            #endif
                    _IrcClient.Encoding = Encoding.Default;
                }
            }

            string proxyTypeStr = (string) config["Connection/ProxyType"];
            if (!String.IsNullOrEmpty(proxyTypeStr)) {
                var proxyType = ProxyType.None;
                try {
                    proxyType = (ProxyType) Enum.Parse(typeof(ProxyType),
                                                       proxyTypeStr);
                } catch (ArgumentException ex) {
            #if LOG4NET
                    _Logger.Error("ApplyConfig(): Couldn't parse proxy type: " +
                                  proxyType, ex);
            #endif
                }

                // HACK: map our ProxyType to SmartIrc4net's ProxyType
                var ircProxyType =
                    (Meebey.SmartIrc4net.ProxyType) Enum.Parse(
                        typeof(ProxyType), proxyType.ToString(), true
                    );
                _IrcClient.ProxyType = ircProxyType;
                _IrcClient.ProxyHost = (string) config["Connection/ProxyHostname"];
                _IrcClient.ProxyPort = (int) config["Connection/ProxyPort"];
                _IrcClient.ProxyUsername = (string) config["Connection/ProxyUsername"];
                _IrcClient.ProxyPassword = (string) config["Connection/ProxyPassword"];
            }

            if (server != null) {
                _IrcClient.UseSsl = server.UseEncryption;
                _IrcClient.ValidateServerCertificate = server.ValidateServerCertificate;
            }
        }
Exemple #32
0
        public void Load(ServerModel server)
        {
            Trace.Call(server);

            // protocol is part of the PKEY, not allowed to change
            f_ProtocolComboBox.Sensitive = false;

            Protocol = server.Protocol;
            ServerID = server.ServerID;
            f_HostnameEntry.Text = server.Hostname;
            f_NetworkComboBoxEntry.Entry.Text = server.Network;
            f_UsernameEntry.Text = server.Username;
            // HACK: Twitter username is part of the PKEY, not allowed to change
            if (server.Protocol == "Twitter") {
                f_UsernameEntry.Sensitive = false;
            }
            f_PasswordEntry.Text = server.Password;
            f_UseEncryptionCheckButton.Active = server.UseEncryption;
            f_ValidateServerCertificateCheckButton.Active =
                server.ValidateServerCertificate;
            f_PortSpinButton.Value = server.Port;
            OnStartupConnectCheckButton.Active = server.OnStartupConnect;
            if (server.OnConnectCommands == null ||
                server.OnConnectCommands.Count == 0) {
                f_OnConnectCommandsTextView.Buffer.Text = String.Empty;
            } else {
                // LAME: replace me when we have .NET 3.0
                string[] commands = new string[server.OnConnectCommands.Count];
                server.OnConnectCommands.CopyTo(commands, 0);
                f_OnConnectCommandsTextView.Buffer.Text = String.Join(
                    "\n", commands
                );
            }
        }
Exemple #33
0
 public abstract void Connect(FrontendManager fm,
                              ServerModel server);
Exemple #34
0
 public void Connect(FrontendManager frontman, ServerModel srv)
 {
 }
        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);
            }
        }
Exemple #36
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);
            }
        }
Exemple #37
0
        protected virtual void OnTreeViewRowActivated(object sender, Gtk.RowActivatedArgs e)
        {
            Trace.Call(sender, e);

            try {
                ServerModel server = GetCurrentServer();
                if (server == null) {
                    return;
                }

                f_ServerModel = server;
                Respond(Gtk.ResponseType.Ok);
            } catch (Exception ex) {
                Frontend.ShowException(ex);
            }
        }
Exemple #38
0
        public void SetServer(ServerModel server)
        {
            Trace.Call(server);

            if (server == null) {
                throw new ArgumentNullException("server");
            }

            string prefix = "Servers/" + server.Protocol + "/" + server.Hostname + "/";
            _UserConfig[prefix + "Hostname"] = server.Hostname;
            _UserConfig[prefix + "Port"]     = server.Port;
            _UserConfig[prefix + "Network"]  = server.Network;
            _UserConfig[prefix + "Username"] = server.Username;
            _UserConfig[prefix + "Password"] = server.Password;
            _UserConfig[prefix + "OnStartupConnect"] = server.OnStartupConnect;
            _UserConfig[prefix + "OnConnectCommands"] = server.OnConnectCommands;
        }
Exemple #39
0
        public virtual void Edit(ServerModel server)
        {
            Trace.Call(server);

            if (server == null) {
                throw new ArgumentNullException("server");
            }

            ServerView serverView = new ServerView(_Parent, server, Frontend.Session.GetSupportedProtocols(), _Controller.GetNetworks());
            int res = serverView.Run();
            serverView.Destroy();
            if (res != (int) Gtk.ResponseType.Ok) {
                return;
            }

            _Controller.SetServer(serverView.Server);
            _Controller.Save();

            // refresh the view
            Load();
        }
Exemple #40
0
        public static void Init()
        {
            if (_IsInitialized)
            {
                return;
            }
            _IsInitialized = true;

            var asm = Assembly.GetEntryAssembly();

            if (asm == null)
            {
                asm = Assembly.GetAssembly(typeof(Engine));
            }
            var asm_name = asm.GetName(false);

            var distVersion = Defines.DistVersion;

            if (!String.IsNullOrEmpty(distVersion))
            {
                distVersion = String.Format(" ({0})", distVersion);
            }
            _VersionString = String.Format(
                "{0} {1}{2} - running on {3} {4}",
                Path.GetFileNameWithoutExtension(asm_name.Name),
                AssemblyVersion,
                distVersion,
                Platform.OperatingSystem,
                Platform.Architecture
                );

            _Config = new Config();
            _Config.Load();

            // migration config settins from 1.0 or earlier to 1.1
            if (_Config.PreviousVersion == null ||
                _Config.PreviousVersion < new Version(1, 1))
            {
                // migrate all existing IRC connections for Slack to the
                // SlackProtocolManager
                var users = (string[])_Config["Engine/Users/Users"];
                if (users != null)
                {
                    foreach (var user in users)
                    {
                        var userConfig       = new UserConfig(_Config, user);
                        var serverController = new ServerListController(userConfig);
                        var servers          = serverController.GetServerList();
                        foreach (var server in servers)
                        {
                            if (server.Protocol != "IRC")
                            {
                                continue;
                            }
                            if (!server.Hostname.EndsWith(".irc.slack.com"))
                            {
                                continue;
                            }
#if LOG4NET
                            f_Logger.InfoFormat(
                                "Migrating Slack server '{0}' of user '{1}' " +
                                "from IRC to Slack protocol manager",
                                server,
                                user
                                );
#endif
                            // this is Slack IRC bridge connection
                            var migratedServer = new ServerModel(server);
                            migratedServer.ServerID = null;
                            migratedServer.Protocol = "Slack";
                            serverController.AddServer(migratedServer);
                            // remove old Slack server with IRC as protocol
                            serverController.RemoveServer(server.Protocol,
                                                          server.ServerID);
                        }
                    }
                }
                _Config["Engine/ConfigVersion"] = _Config.CurrentVersion.ToString();
            }

            _Config.Save();

            string location = Path.GetDirectoryName(asm.Location);
            if (String.IsNullOrEmpty(location) &&
                Environment.OSVersion.Platform == PlatformID.Unix)
            {
                // we are mkbundled
                var locationBuilder = new StringBuilder(8192);
                if (Mono.Unix.Native.Syscall.readlink("/proc/self/exe", locationBuilder) >= 0)
                {
                    location = Path.GetDirectoryName(locationBuilder.ToString());
                }
            }
            _ProtocolManagerFactory = new ProtocolManagerFactory();
            _ProtocolManagerFactory.LoadAllProtocolManagers(location);
        }
Exemple #41
0
        public override void Connect(FrontendManager fm, ServerModel server)
        {
            Trace.Call(fm, server);

            if (fm == null) {
                throw new ArgumentNullException("fm");
            }
            if (server == null) {
                throw new ArgumentNullException("server");
            }

            if (server is XmppServerModel) {
                Server = (XmppServerModel) server;
            } else {
                Server = new XmppServerModel();
                if (server.ServerID != null) {
                    Server.Load(Session.UserConfig, server.ServerID);
                }
                // HACK: previous line overwrites any passed values with the values from config
                // thus we have to copy the original values:
                Server.Hostname = server.Hostname;
                Server.Network = server.Network;
                Server.OnConnectCommands = server.OnConnectCommands;
                Server.OnStartupConnect = server.OnStartupConnect;
                Server.Password = server.Password;
                Server.Port = server.Port;
                Server.Protocol = server.Protocol;
                Server.ServerID = server.ServerID;
                Server.UseEncryption = server.UseEncryption;
                Server.Username = server.Username;
                Server.ValidateServerCertificate = server.ValidateServerCertificate;
            }

            Host = server.Hostname;
            Port = server.Port;

            ApplyConfig(Session.UserConfig, Server);

            // TODO: use config for single network chat or once per network manager
            NetworkChat = Session.CreateChat<ProtocolChatModel>(
                NetworkID, "Jabber " + Host, this
            );
            Session.AddChat(NetworkChat);
            Session.SyncChat(NetworkChat);

            OpenContactChat();

            if (!String.IsNullOrEmpty(JabberClient.ProxyHost)) {
                var builder = CreateMessageBuilder();
                builder.AppendEventPrefix();
                builder.AppendText(_("Using proxy: {0}:{1}"),
                                   JabberClient.ProxyHost,
                                   JabberClient.ProxyPort);
                Session.AddMessageToChat(Chat, builder.ToMessage());
            }
            JabberClient.Connect();
        }
Exemple #42
0
        public virtual void Remove(ServerModel server)
        {
            Trace.Call(server);

            if (server == null) {
                throw new ArgumentNullException("server");
            }

            Gtk.MessageDialog md = new Gtk.MessageDialog(null,
                                                         Gtk.DialogFlags.Modal,
                                                         Gtk.MessageType.Warning,
                                                         Gtk.ButtonsType.YesNo,
                _("Are you sure you want to delete the selected server?"));
            int result = md.Run();
            md.Destroy();
            if (result != (int) Gtk.ResponseType.Yes) {
                return;
            }

            _Controller.RemoveServer(server.Protocol, server.Hostname);
            _Controller.Save();

            // refresh the view
            Load();
        }
Exemple #43
0
        public ServerModel GetServer(string protocol, string servername)
        {
            Trace.Call(protocol, servername);

            if (protocol == null) {
                throw new ArgumentNullException("protocol");
            }
            if (servername == null) {
                throw new ArgumentNullException("servername");
            }

            string prefix = "Servers/" + protocol + "/" + servername + "/";
            ServerModel server = new ServerModel();
            if (_UserConfig[prefix + "Hostname"] == null) {
                // server does not exist
                return null;
            }
            server.Protocol    = protocol;
            server.Hostname    = (string) _UserConfig[prefix + "Hostname"];
            server.Port        = (int)    _UserConfig[prefix + "Port"];
            server.Network     = (string) _UserConfig[prefix + "Network"];
            server.Username    = (string) _UserConfig[prefix + "Username"];
            server.Password    = (string) _UserConfig[prefix + "Password"];
            server.OnStartupConnect = (bool) _UserConfig[prefix + "OnStartupConnect"];
            server.OnConnectCommands  = (IList<string>) _UserConfig[prefix + "OnConnectCommands"];
            return server;
        }
Exemple #44
0
 public override void Connect(FrontendManager fm, ServerModel server)
 {
     throw new System.NotImplementedException();
 }
        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);
            }
        }
Exemple #46
0
        private void ApplyConfig(UserConfig config, ServerModel server)
        {
            _JabberClient.OnInvalidCertificate -= ValidateCertificate;

            _JabberClient.AutoStartTLS = server.UseEncryption;
            if (!server.ValidateServerCertificate) {
                _JabberClient.OnInvalidCertificate += ValidateCertificate;
            }
        }
Exemple #47
0
        private void ApplyConfig(UserConfig config, ServerModel server)
        {
            _Host = server.Hostname;
            _Port = server.Port;
            if (String.IsNullOrEmpty(server.Network)) {
                _Network = server.Hostname;
            } else {
                _Network = server.Network;
            }
            if (String.IsNullOrEmpty(server.Username)) {
                _Username = (string) config["Connection/Username"];
            } else {
                _Username = server.Username;
            }
            _Password = server.Password;

            // internal fallbacks
            if (String.IsNullOrEmpty(_Username)) {
                _Username = "******";
            }

            // IRC specific settings
            if (server is IrcServerModel) {
                var ircServer = (IrcServerModel) server;
                if (ircServer.Nicknames != null && ircServer.Nicknames.Count > 0) {
                    _Nicknames = ircServer.Nicknames.ToArray();
                }
            }

            // global fallbacks
            if (_Nicknames == null) {
                _Nicknames = (string[]) config["Connection/Nicknames"];
            }

            string encodingName = (string) config["Connection/Encoding"];
            if (String.IsNullOrEmpty(encodingName)) {
                _IrcClient.Encoding = Encoding.Default;
            } else {
                try {
                    _IrcClient.Encoding = Encoding.GetEncoding(encodingName);
                } catch (Exception ex) {
            #if LOG4NET
                    _Logger.Warn("ApplyConfig(): Error getting encoding for: " +
                                 encodingName + " falling back to system encoding.", ex);
            #endif
                    _IrcClient.Encoding = Encoding.Default;
                }
            }

            var proxySettings = new ProxySettings();
            proxySettings.ApplyConfig(config);
            var protocol = server.UseEncryption ? "ircs" : "irc";
            var serverUri = String.Format("{0}://{1}:{2}", protocol,
                                          server.Hostname, server.Port);
            var proxy = proxySettings.GetWebProxy(serverUri);
            if (proxy == null) {
                _IrcClient.ProxyType = IrcProxyType.None;
            } else {
                var proxyScheme = proxy.Address.Scheme;
                var ircProxyType = IrcProxyType.None;
                try {
                    // HACK: map proxy scheme to SmartIrc4net's ProxyType
                    ircProxyType = (IrcProxyType) Enum.Parse(
                        typeof(IrcProxyType), proxyScheme, true
                    );
                } catch (ArgumentException ex) {
            #if LOG4NET
                    _Logger.Error("ApplyConfig(): Couldn't parse proxy type: " +
                                  proxyScheme, ex);
            #endif
                }
                _IrcClient.ProxyType = ircProxyType;
                _IrcClient.ProxyHost = proxy.Address.Host;
                _IrcClient.ProxyPort = proxy.Address.Port;
                if (!String.IsNullOrEmpty(proxySettings.ProxyUsername)) {
                    _IrcClient.ProxyUsername = proxySettings.ProxyUsername;
                }
                if (!String.IsNullOrEmpty(proxySettings.ProxyPassword)) {
                    _IrcClient.ProxyPassword = proxySettings.ProxyPassword;
                }
            }

            if (server != null) {
                _IrcClient.UseSsl = server.UseEncryption;
                _IrcClient.ValidateServerCertificate = server.ValidateServerCertificate;
            }
        }
Exemple #48
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);
            }
        }