예제 #1
0
        private void enterAllMUCs(XMPPClient client)
        {
            Task.Run(async() =>
            {
                // Delay joining MUCs for a couple of seconds to prevent a message overload:
                if (!await delayAsync(client.getXMPPAccount().getBareJid()))
                {
                    // Delay has been canceled:
                    return;
                }

                foreach (ChatTable muc in ChatDBManager.INSTANCE.getAllMUCs(client.getXMPPAccount().getBareJid()))
                {
                    MUCChatInfoTable info = MUCDBManager.INSTANCE.getMUCInfo(muc.id);
                    if (info is null)
                    {
                        info = new MUCChatInfoTable()
                        {
                            chatId        = muc.id,
                            state         = MUCState.DISCONNECTED,
                            nickname      = muc.userAccountId,
                            autoEnterRoom = true
                        };
                        MUCDBManager.INSTANCE.setMUCChatInfo(info, false, true);
                    }
                    if (info.autoEnterRoom)
                    {
                        await enterMUCAsync(client, muc, info);
                    }
                }
            });
        }
예제 #2
0
        /// <summary>
        /// Sends all chat messages passed to it.
        /// </summary>
        /// <param name="client">The XMPPClient that should be used to send the messages.</param>
        /// <param name="messages">A list of chat messages to send. They SHOULD be sorted by their chatId for optimal performance.</param>
        private async Task sendOutsandingChatMessagesAsync(XMPPClient client, IList <ChatMessageTable> messages)
        {
            ChatTable chat = null;

            foreach (ChatMessageTable msgDb in messages)
            {
                if (chat is null || !string.Equals(chat.id, msgDb.chatId))
                {
                    chat = ChatDBManager.INSTANCE.getChat(msgDb.chatId);

                    if (chat is null)
                    {
                        Logger.Warn("Unable to send outstanding chat message for: " + msgDb.chatId + " - no such chat.");
                        continue;
                    }
                }
                MessageMessage msg = msgDb.toXmppMessage(client.getXMPPAccount().getFullJid(), chat);

                if (msg is OmemoMessageMessage omemoMsg)
                {
                    await client.sendOmemoMessageAsync(omemoMsg, chat.chatJabberId, client.getXMPPAccount().getBareJid());
                }
                else
                {
                    await client.sendAsync(msg);
                }
            }
        }
        public bool PublishGeoInfo(geoloc item)
        {
            string strGeoInfo = Utility.GetXMLStringFromObject(item);

            PubSubIQ iq = new PubSubIQ();

            iq.Type           = IQType.set.ToString();
            iq.To             = null; /// null for personal eventing pub sub
            iq.From           = XMPPClient.JID;
            iq.PubSub.Publish = new Publish()
            {
                Node = "http://jabber.org/protocol/geoloc", Item = new PubSubItem()
            };
            iq.PubSub.Publish.Item.SetNodeFromObject(item);
            iq.PubSub.Publish.Item.Id = "lastlocation";

            ListSentIQs.Add(iq.ID);
            try
            {
                XMPPClient.SendObject(iq);
            }
            catch (Exception ex)
            {
                return(false);
            }
            return(true);
        }
예제 #4
0
 /// <summary>
 /// The XMPP connection was disconnected.
 /// </summary>
 private void XMPPDisconnected()
 {
     StatusMessage("The Google Voice XMPP client connection was unexpectedly disconnected.");
     m_xmppClient = null;
     _isBound     = false;
     CallFinished();
 }
예제 #5
0
 private void addItems(List <DiscoItem> items, string from, XMPPClient client, bool requestInfo)
 {
     if (items != null)
     {
         dB.Execute("DELETE FROM " + DBTableConsts.DISCO_ITEM_TABLE + " WHERE fromServer = ?;", from);
         foreach (DiscoItem i in items)
         {
             if (from != null && i.JID != null)
             {
                 dB.InsertOrReplace(new DiscoItemTable()
                 {
                     id         = DiscoItemTable.generateId(from, i.JID),
                     fromServer = from,
                     jid        = i.JID,
                     name       = i.NAME
                 });
                 if (requestInfo)
                 {
                     MessageResponseHelper <IQMessage> helper = client.GENERAL_COMMAND_HELPER.createDisco(i.JID, DiscoType.INFO, onDiscoMsg, onDiscoTimeout);
                     RESPONSE_HELPERS.Add(helper);
                 }
             }
         }
     }
 }
 private async void Client_NewChatMessage(XMPPClient client, NewChatMessageEventArgs args)
 {
     if (await VIEW_MODEL.OnNewChatMessage(args.getMessage(), btDeviceInfo_btdic.VIEW_MODEL.MODEL.Jid, ConnectionHandler.INSTANCE.GetClient(client.getXMPPAccount().getBareJid()).client))
     {
         await SharedUtils.CallDispatcherAsync(() => UpdateViewState(State_6.Name));
     }
 }
예제 #7
0
 //--------------------------------------------------------Constructor:----------------------------------------------------------------\\
 #region --Constructors--
 /// <summary>
 /// Basic Constructor
 /// </summary>
 /// <history>
 /// 15/07/2018 Created [Fabian Sauter]
 /// </history>
 public AddBookmarkDialog(XMPPClient client)
 {
     this.CLIENT  = client;
     this.success = false;
     this.messageResponseHelper = null;
     this.InitializeComponent();
 }
예제 #8
0
        public void SendChatMessage(string strMessage, MessageSendOption option)
        {
            if (option == MessageSendOption.SendToAll)
            {
                SendChatMessageToAllAvailableInstances(strMessage);
                return;
            }

            TextMessage txtmsg = new TextMessage();

            txtmsg.Received = DateTime.Now;
            txtmsg.From     = XMPPClient.JID;

            if (option == MessageSendOption.SendPriority)
            {
                txtmsg.To = this.JID.BareJID;
            }
            else
            {
                txtmsg.To = LastFullJIDToGetMessageFrom;
            }

            txtmsg.Message = strMessage;
            XMPPClient.SendChatMessage(txtmsg);
        }
 //--------------------------------------------------------Constructor:----------------------------------------------------------------\\
 #region --Constructors--
 /// <summary>
 /// Basic Constructor
 /// </summary>
 /// <history>
 /// 15/07/2018 Created [Fabian Sauter]
 /// </history>
 public AddBookmarkDialog(XMPPClient client)
 {
     CLIENT  = client;
     success = false;
     messageResponseHelper = null;
     InitializeComponent();
 }
예제 #10
0
        //--------------------------------------------------------Events:---------------------------------------------------------------------\\
        #region --Events--
        private void OnOmemoSessionBuildError(XMPPClient xmppClient, OmemoSessionBuildErrorEventArgs args)
        {
            Task.Run(() =>
            {
                ChatModel chat;
                using (SemaLock semaLock = DataCache.INSTANCE.NewChatSemaLock())
                {
                    chat = DataCache.INSTANCE.GetChat(xmppClient.getXMPPAccount().getBareJid(), args.CHAT_JID, semaLock);
                }
                if (!(chat is null))
                {
                    // Add an error chat message:
                    ChatMessageModel msg = new ChatMessageModel()
                    {
                        chatId         = chat.id,
                        date           = DateTime.Now,
                        fromBareJid    = args.CHAT_JID,
                        isCC           = false,
                        isDummyMessage = false,
                        isEncrypted    = false,
                        isFavorite     = false,
                        isImage        = false,
                        message        = "Failed to encrypt and send " + args.MESSAGES.Count + " OMEMO message(s) with:\n" + args.ERROR,
                        stableId       = AbstractMessage.getRandomId(),
                        state          = MessageState.UNREAD,
                        type           = MessageMessage.TYPE_ERROR
                    };
                    DataCache.INSTANCE.AddChatMessage(msg, chat);

                    // Set chat messages to encrypted failed:
                    SetOmemoChatMessagesSendFailed(args.MESSAGES, chat);
                }
            });
        }
예제 #11
0
 private async void Client_NewChatMessage(XMPPClient client, NewChatMessageEventArgs args)
 {
     if (await VIEW_MODEL.OnNewChatMessage(args.getMessage(), btDeviceInfo_btdic.VIEW_MODEL.MODEL.Jid, client))
     {
         await SharedUtils.CallDispatcherAsync(() => UpdateViewState(State_6.Name));
     }
 }
예제 #12
0
        public static void CreateNode(XMPPClient connection, string strNode, string strParentNode, PubSubConfigForm nodeform)
        {
            IQ pubsub = new IQ();

            pubsub.Type = IQType.set.ToString();
            pubsub.From = connection.JID;
            pubsub.To   = new JID(string.Format("pubsub.{0}", connection.Domain));


            string strXML = CreateNodeXML.Replace("#NODE#", strNode);

            /// Get inner xml
            ///
            string strForm = nodeform.BuildAskingForm(nodeform);

            strXML          = strXML.Replace("#x#", strForm);
            pubsub.InnerXML = strXML;

            IQ IQResponse = connection.SendRecieveIQ(pubsub, 10000);

            if (IQResponse == null)
            {
                return;
            }
            if (IQResponse.Type == IQType.error.ToString())
            {
                return;
            }
        }
예제 #13
0
        /// <summary>
        /// 在此页将要在 Frame 中显示时进行调用。
        /// </summary>
        /// <param name="e">描述如何访问此页的事件数据。
        /// 此参数通常用于配置页。</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // TODO: 准备此处显示的页面。

            // TODO: 如果您的应用程序包含多个页面,请确保
            // 通过注册以下事件来处理硬件“后退”按钮:
            // Windows.Phone.UI.Input.HardwareButtons.BackPressed 事件。
            // 如果使用由某些模板提供的 NavigationHelper,
            // 则系统会为您处理该事件。
            if (e.Parameter != null)
            {
                var datadir    = e.Parameter as Dictionary <string, string>;
                var XmppClient = new XMPPClient
                {
                    UserName      = datadir["UserName"],
                    Password      = datadir["Password"],
                    Server        = "chat-ej.myfriday.cn",
                    Domain        = "chat-ej.myfriday.cn",
                    Resource      = "Smack",
                    Port          = 5222,
                    UseTLS        = true,
                    AutoReconnect = true,
                    AutoAcceptPresenceSubscribe = false
                };
                XmppClient.OnStateChanged += XmppClient_OnStateChanged;
                XmppClient.MessageReceive += XmppClient_MessageReceive;
            }
            else
            {
                textblock.Text = "没有信息";
            }
        }
예제 #14
0
        private void showAccount()
        {
            if (Account != null)
            {
                IsEnabled = false;
                if (client != null)
                {
                    client.ConnectionStateChanged -= Client_ConnectionStateChanged;
                }
                string accountId = Account.getIdAndDomain();
                disableAccount_tggls.IsOn = !Account.disabled;
                Task.Run(() =>
                {
                    client = ConnectionHandler.INSTANCE.getClient(accountId);

                    if (client != null)
                    {
                        client.ConnectionStateChanged -= Client_ConnectionStateChanged;
                        client.ConnectionStateChanged += Client_ConnectionStateChanged;
                        client.getXMPPAccount().CONNECTION_INFO.PropertyChanged -= CONNECTION_INFO_PropertyChanged;
                        client.getXMPPAccount().CONNECTION_INFO.PropertyChanged += CONNECTION_INFO_PropertyChanged;
                        Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => showConnectionState(client, client.getConnetionState(), client.getLastConnectionError())).AsTask();
                    }
                    Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => IsEnabled = true).AsTask();
                });
            }
        }
예제 #15
0
        /// <summary>
        /// Purges the items in a node
        /// </summary>
        /// <param name="strNode"></param>
        /// <returns></returns>
        public static bool UnsubscribeNode(XMPPClient connection, string strNode, string strJID, string strSID, bool bWaitForResponse)
        {
            IQ pubsub = new IQ();

            pubsub.Type = IQType.set.ToString();
            pubsub.From = connection.JID;
            pubsub.To   = new JID(string.Format("pubsub.{0}", connection.Domain));

            pubsub.InnerXML = UnsubscribeNodeXML.Replace("#NODE#", strNode).Replace("#JID#", strJID).Replace("#SID#", strSID);

            if (bWaitForResponse == false)
            {
                connection.SendXMPP(pubsub);
                return(true);
            }

            IQ IQResponse = connection.SendRecieveIQ(pubsub, 10000);

            if (IQResponse.Type == IQType.error.ToString())
            {
                return(false);
            }

            return(true);
        }
예제 #16
0
        private void showConnectionState(XMPPClient client, ConnectionState state, object param)
        {
            updateSecurityButton(client, state);

            error_tblck.Visibility = Visibility.Collapsed;
            lastConnectionError    = null;

            switch (state)
            {
            case ConnectionState.DISCONNECTED:
                image_aciwp.Presence = Presence.Unavailable;
                break;

            case ConnectionState.CONNECTING:
                image_aciwp.Presence = Presence.Chat;
                break;

            case ConnectionState.CONNECTED:
                image_aciwp.Presence = Presence.Online;
                break;

            case ConnectionState.DISCONNECTING:
                image_aciwp.Presence = Presence.Chat;
                break;

            case ConnectionState.ERROR:
                image_aciwp.Presence = Presence.Dnd;
                showError(param);
                break;

            default:
                break;
            }
        }
예제 #17
0
 private void OnClientConnectionStateChanged(XMPPClient client, ConnectionStateChangedEventArgs args)
 {
     if (args.oldState == ConnectionState.CONNECTED)
     {
         discoDone = false;
     }
 }
예제 #18
0
        //--------------------------------------------------------Events:---------------------------------------------------------------------\\
        #region --Events--
        private void CLIENT_NewMUCMemberPresenceMessage(XMPPClient client, XMPP_API.Classes.Network.Events.NewMUCMemberPresenceMessageEventArgs args)
        {
            string roomJId = Utils.getBareJidFromFullJid(args.mucMemberPresenceMessage.getFrom());

            if (!Equals(roomJId, MUC.chatJabberId))
            {
                return;
            }

            switch (INFO.state)
            {
            case MUCState.ENTERING:
                // Evaluate status codes:
                foreach (MUCPresenceStatusCode statusCode in args.mucMemberPresenceMessage.STATUS_CODES)
                {
                    switch (statusCode)
                    {
                    case MUCPresenceStatusCode.PRESENCE_SELFE_REFERENCE:
                        // Remove event subscription:
                        CLIENT.NewMUCMemberPresenceMessage -= CLIENT_NewMUCMemberPresenceMessage;

                        // Update MUC info:
                        INFO.state = MUCState.ENTERD;
                        saveMUCEnterState();
                        Logger.Info("Entered MUC room '" + roomJId + "' as '" + INFO.nickname + '\'');
                        break;

                    default:
                        break;
                    }
                }
                break;
            }
        }
예제 #19
0
        /// <summary>
        /// Leaves the current party of the provided <see cref="XMPPClient"/>.
        /// </summary>
        /// <param name="xmppClient">The <see cref="XMPPClient"/> to leave the party from.</param>
        internal static async Task LeaveParty(XMPPClient xmppClient)
        {
            // Leave the party chat.
            await xmppClient.LeavePartyChat();

            // We're using a using statement so that the initialised client is disposed of when the code block is exited.
            using var client = new WebClient
                  {
                      Headers =
                      {
                          // Set the Authorization header to the access token from the provided OAuthSession.
                          [HttpRequestHeader.Authorization] = $"bearer {xmppClient.AuthSession.AccessToken}"
                      }
                  };

            try
            {
                // Use our request helper to make a DELETE request.
                await client.DeleteDataAsync(Endpoints.Party.Member(xmppClient.CurrentParty.Id, xmppClient.AuthSession.AccountId)).ConfigureAwait(false);

                xmppClient.CurrentParty = null;
            }
            catch (EpicException ex)
            {
                // If the error code DOESN'T indicate there was no party found, throw the exception.
                if (ex.ErrorCode != "errors.com.epicgames.social.party.party_not_found")
                {
                    throw;
                }
            }

            await InitParty(xmppClient);
        }
예제 #20
0
        //--------------------------------------------------------Events:---------------------------------------------------------------------\\
        #region --Events--
        private void OnOmemoSessionBuildError(XMPPClient client, OmemoSessionBuildErrorEventArgs args)
        {
            Task.Run(async() =>
            {
                ChatTable chat = ChatDBManager.INSTANCE.getChat(ChatTable.generateId(args.CHAT_JID, GetBareJid()));
                if (!(chat is null))
                {
                    // Add an error chat message:
                    ChatMessageTable msg = new ChatMessageTable()
                    {
                        id       = ChatMessageTable.generateErrorMessageId(AbstractMessage.getRandomId(), chat.id),
                        chatId   = chat.id,
                        date     = DateTime.Now,
                        fromUser = args.CHAT_JID,
                        isImage  = false,
                        message  = "Failed to encrypt and send " + args.MESSAGES.Count + " OMEMO message(s) with:\n" + args.ERROR,
                        state    = MessageState.UNREAD,
                        type     = MessageMessage.TYPE_ERROR
                    };
                    await ChatDBManager.INSTANCE.setChatMessageAsync(msg, true, false);

                    // Set chat messages to encrypted failed:
                    SetOmemoChatMessagesSendFailed(args.MESSAGES, chat);
                }
            });
        }
예제 #21
0
 private async Task sendMUCLeaveMessageAsync(XMPPClient client, ChatTable muc, MUCChatInfoTable info)
 {
     string           from = client.getXMPPAccount().getIdDomainAndResource();
     string           to   = muc.chatJabberId + '/' + info.nickname;
     LeaveRoomMessage msg  = new LeaveRoomMessage(from, to);
     await client.sendAsync(msg, false);
 }
예제 #22
0
        /// <summary>
        /// Loads one specific XMPPAccount and subscribes to all its events.
        /// </summary>
        /// <param name="account">The account which should get loaded.</param>
        /// <returns>Returns a new XMPPClient instance.</returns>
        private XMPPClient LoadAccount(XMPPAccount account)
        {
            XMPPClient client = new XMPPClient(account);

            client.connection.TCP_CONNECTION.disableConnectionTimeout = Settings.getSettingBoolean(SettingsConsts.DEBUG_DISABLE_TCP_TIMEOUT);
            client.connection.TCP_CONNECTION.disableTlsUpgradeTimeout = Settings.getSettingBoolean(SettingsConsts.DEBUG_DISABLE_TLS_TIMEOUT);

            // Enable OMEMO:
            OmemoStore signalProtocolStore = new OmemoStore(account);

            // Generate OMEMO keys if necessary:
            if (!account.omemoKeysGenerated)
            {
                account.generateOmemoKeys();
                AccountDBManager.INSTANCE.setAccount(account, true, false);
            }
            client.enableOmemo(signalProtocolStore);

            // Sometimes the DB fails and only stores less than 100 OMEMO pre keys.
            // So if we detect an issue with that generate a new batch of OMEMO pre keys and announce the new ones.
            if (account.OMEMO_PRE_KEYS.Count < 100)
            {
                Logger.Warn("Only " + account.OMEMO_PRE_KEYS.Count + " found. Generating a new set.");
                account.OMEMO_PRE_KEYS.Clear();
                account.OMEMO_PRE_KEYS.AddRange(CryptoUtils.generateOmemoPreKeys());
                account.omemoBundleInfoAnnounced = false;
                AccountDBManager.INSTANCE.setAccount(account, true, false);
            }
            return(client);
        }
예제 #23
0
        public async Task RefreshOmemoDevicesAsync(XMPPClient client)
        {
            MODEL.RefreshingDevices = true;
            MessageResponseHelperResult <IQMessage> result = await client.OMEMO_COMMAND_HELPER.requestDeviceListAsync(client.getXMPPAccount().getBareJid());

            if (result.STATE == MessageResponseHelperResultState.SUCCESS)
            {
                if (result.RESULT is OmemoDeviceListResultMessage deviceListResultMessage)
                {
                    MODEL.DEVICES.Clear();
                    MODEL.DEVICES.AddRange(deviceListResultMessage.DEVICES.IDS.Select(x => new UintDataTemplate {
                        Value = x
                    }));
                }
                else
                {
                    Logger.Warn("Failed to request device list (" + result.RESULT.ToString() + ").");
                }
            }
            else
            {
                Logger.Warn("Failed to request device list (" + result.STATE.ToString() + ").");
            }
            MODEL.RefreshingDevices = false;
        }
예제 #24
0
        private void CLIENT_NewDiscoResponseMessage(XMPPClient client, XMPP_API.Classes.Network.Events.NewDiscoResponseMessageEventArgs args)
        {
            Task.Run(async() =>
            {
                string from = args.DISCO.getFrom();
                // Only store direct server results:
                if (from != null && !from.Contains("@") && messageIdCache.getTimed(args.DISCO.ID) != null)
                {
                    switch (args.DISCO.DISCO_TYPE)
                    {
                    case DiscoType.ITEMS:
                        await addItemsAsync(args.DISCO.ITEMS, from, client, true);
                        break;

                    case DiscoType.INFO:
                        addFeatures(args.DISCO.FEATURES, from);
                        addIdentities(args.DISCO.IDENTITIES, from);
                        break;

                    default:
                        throw new InvalidOperationException("Unexpected value for DISCO_TYPE: " + args.DISCO.DISCO_TYPE);
                    }
                }
            });
        }
예제 #25
0
        //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\
        #region --Set-, Get- Methods--


        #endregion
        //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\
        #region --Misc Methods (Public)--


        #endregion

        #region --Misc Methods (Private)--
        private bool checkUserInput()
        {
            client = accountSelection_asc.getSelectedAccount();
            if (client is null)
            {
                accountSelection_asc.showErrorMessage("No account selected!");
                return(false);
            }
            if (client.getXMPPAccount().getBareJid().Equals(jabberId_tbx.Text))
            {
                accountSelection_asc.showErrorMessage("You can't start a chat with your self!");
                return(false);
            }
            if (!Utils.isBareJid(jabberId_tbx.Text))
            {
                accountSelection_asc.showErrorMessage("Invalid JabberID!");
                return(false);
            }
            jabberId = jabberId_tbx.Text;
            if (ChatDBManager.INSTANCE.doesChatExist(ChatTable.generateId(jabberId, client.getXMPPAccount().getBareJid())))
            {
                accountSelection_asc.showErrorMessage("Chat does already exist!");
                return(false);
            }
            return(true);
        }
예제 #26
0
        /// <summary>
        /// Updates the nickname in the local DB.
        /// Also updates bookmarks if any exist.
        /// </summary>
        /// <returns>Returns true on success.</returns>
        public async Task <bool> SaveAsync(ChatTable chat, MUCChatInfoTable mucInfo, XMPPClient client)
        {
            MODEL.IsSaving = true;
            bool success = await Task.Run(async() =>
            {
                mucInfo.nickname = MODEL.Nickname;

                // Try to update the nickname at the chat room:
                bool result = await UpdateNicknameAsync(chat, mucInfo, client);
                if (!result)
                {
                    return(false);
                }

                // Update the DB entry since the server could respond with a different nickname:
                MUCDBManager.INSTANCE.setMUCChatInfo(mucInfo, false, true);

                // Update bookmarks:
                return(chat.inRoster ? await UpdateBookmarksAsync(chat, client) : true);
            });

            MODEL.IsSaving = false;
            MODEL.Error    = !success;
            if (success)
            {
                Logger.Info("Updating nickname to \"" + MODEL.Nickname + "\" in chat \"" + MODEL.MucName + "\" was successful!");
            }
            else
            {
                Logger.Info("Updating nickname to \"" + MODEL.Nickname + "\" in chat \"" + MODEL.MucName + "\" failed!");
            }
            return(success);
        }
예제 #27
0
        public void TestGroupChat()
        {
            XMPPClient ObjXmppClient = new XMPPClient();

            //initializing the xmpp client with credentials
            ObjXmppClient.JID            = "*****@*****.**";
            ObjXmppClient.Password       = "******";
            ObjXmppClient.Server         = "54.173.99.54";
            ObjXmppClient.AutoReconnect  = true;
            ObjXmppClient.RetrieveRoster = true;
            ObjXmppClient.PresenceStatus = new PresenceStatus()
            {
                PresenceType = PresenceType.available, IsOnline = true
            };
            ObjXmppClient.AutoAcceptPresenceSubscribe = true;
            ObjXmppClient.AttemptReconnectOnBadPing   = true;
            //
            XMPPConnection ObjXmppCon = new XMPPConnection(ObjXmppClient);

            ObjXmppCon = new XMPPConnection(ObjXmppClient);
            ObjXmppCon.Connect();
            ObjXmppClient.Connect();
            //muc manager test
            MucManager mucManager = new MucManager(ObjXmppClient);
            JID        roomJID    = "*****@*****.**";

            mucManager.EnterRoom(roomJID, "XMPPTestNickName");

            mucManager.SendGroupChat(roomJID, "test Chat");
        }
예제 #28
0
        void DeviceNetworkInformation_NetworkAvailabilityChanged(object sender, NetworkNotificationEventArgs e)
        {
            switch (e.NotificationType)
            {
            case NetworkNotificationType.InterfaceConnected:
                LogMessage("Network", SocketServer.MessageImportance.Medium, "Network was Connected at {0}\r\n", DateTime.Now);

                if ((XMPPClient != null) && (XMPPClient.XMPPState == XMPPState.Unknown) && (XMPPClient.XMPPAccount != null) && (XMPPClient.XMPPAccount.HaveSuccessfullyConnectedAndAuthenticated == true))
                {
                    XMPPClient.Connect(this);
                }
                break;

            case NetworkNotificationType.InterfaceDisconnected:
                LogMessage("Network", SocketServer.MessageImportance.Medium, "Network was Disconnected at {0}\r\n", DateTime.Now);
                if ((XMPPClient != null) && (XMPPClient.XMPPState != XMPPState.Unknown))
                {
                    XMPPClient.Disconnect();
                    XMPPClient.Connect(this);
                    //MessageBox.Show("Network connection lost");
                }
                break;

            case NetworkNotificationType.CharacteristicUpdate:

                break;

            default:

                break;
            }
        }
예제 #29
0
 private void enterAllMUCs(XMPPClient client)
 {
     Task.Run(async() =>
     {
         foreach (ChatTable muc in ChatDBManager.INSTANCE.getAllMUCs(client.getXMPPAccount().getIdAndDomain()))
         {
             MUCChatInfoTable info = MUCDBManager.INSTANCE.getMUCInfo(muc.id);
             if (info == null)
             {
                 info = new MUCChatInfoTable()
                 {
                     chatId        = muc.id,
                     state         = MUCState.DISCONNECTED,
                     nickname      = muc.userAccountId,
                     autoEnterRoom = true
                 };
                 MUCDBManager.INSTANCE.setMUCChatInfo(info, false, true);
             }
             if (info.autoEnterRoom)
             {
                 await enterMUCAsync(client, muc, info);
             }
         }
     });
 }
예제 #30
0
        private void C_NewBookmarksResultMessage(XMPPClient client, NewBookmarksResultMessageEventArgs args)
        {
            foreach (ConferenceItem c in args.BOOKMARKS_MESSAGE.STORAGE.CONFERENCES)
            {
                bool   newMUC = false;
                string to     = client.getXMPPAccount().getIdAndDomain();
                string from   = c.jid;
                string id     = ChatTable.generateId(from, to);

                // Create / update chat:
                ChatTable chat = ChatDBManager.INSTANCE.getChat(id);
                if (chat == null)
                {
                    chat = new ChatTable()
                    {
                        id            = id,
                        chatJabberId  = from,
                        userAccountId = to,
                        ask           = null,
                        lastActive    = DateTime.Now,
                        muted         = false,
                        status        = null,
                        subscription  = null
                    };
                    newMUC = true;
                }
                chat.chatType = ChatType.MUC;
                chat.inRoster = true;
                chat.presence = Presence.Unavailable;

                ChatDBManager.INSTANCE.setChat(chat, false, true);

                // Create / update MUC info:
                MUCChatInfoTable info = MUCDBManager.INSTANCE.getMUCInfo(chat.id);
                if (info == null)
                {
                    info = new MUCChatInfoTable
                    {
                        chatId  = chat.id,
                        subject = null
                    };
                    newMUC = true;
                }

                info.autoEnterRoom = c.autoJoin;
                info.name          = c.name;
                info.nickname      = c.nick;
                info.password      = c.password;

                MUCDBManager.INSTANCE.setMUCChatInfo(info, false, true);


                // Enter MUC manually if the MUC is new for this client:
                if (newMUC && info.autoEnterRoom && !Settings.getSettingBoolean(SettingsConsts.DISABLE_AUTO_JOIN_MUC))
                {
                    Task.Run(() => MUCHandler.INSTANCE.enterMUCAsync(client, chat, info));
                }
            }
        }
예제 #31
0
        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
            var client = new XMPPClient("etienne.pierrot", "fakepass");
            client.Connect();
            ObjectFactory.Configure(init => init.For<XMPPClient>().Singleton().Use(client));
            TimerCallback timerDelegate = new TimerCallback(ChangeStatus);

            // create timer and attach our method delegate to it
            _serviceTimer =new Timer(timerDelegate, null, 1000, 5000);
        }
예제 #32
0
        static void Main(string[] args)
        {
            try
            {
                //if (args == null || args.Count() == 0)
                //{
                //    Console.WriteLine(USAGE_STRING);
                //}
                //else
                //{
                //    bool validArgs = ParseArgs(args);

                //    if (validArgs)
                //    {
                        Console.WriteLine("XMPP Test Client:");

                        m_xmppClient = new XMPPClient(XMPP_SERVER, XMPP_SERVER_PORT, XMPP_REALM, m_xmppUsername, m_xmppPassword);
                        m_xmppClient.Disconnected += XMPPDisconnected;
                        m_xmppClient.IsBound += () =>
                        {
                            Console.WriteLine("XMPP client is bound.");
                            //var rosterRequest = m_xmppClient.GetRosterRequest();
                            //rosterRequest.GetRoster();

                            var presenceRequest = m_xmppClient.GetPresenceRequest();
                            //presenceRequest.Subscribe();
                            presenceRequest.Notify();
                            presenceRequest.NotifySupportedFeatures();

                            //var discoveryRequest = m_xmppClient.GetServiceDiscoveryRequest("*****@*****.**");
                            //discoveryRequest.Send();
                            //discoveryRequest.SendServerDiscoveryQuery();
                            //discoveryRequest.SendJingleInfoQuery();

                            var jingleRequest = m_xmppClient.GetJingleRequest("[email protected]/TalkGadgetE90A6B3B");
                            //var jingleRequest = m_xmppClient.GetJingleRequest("*****@*****.**");
                            jingleRequest.Initiate();

                            //m_xmppClient.SendMessage("*****@*****.**", "hi");
                            //XMPPPhoneSession call = m_xmppClient.GetPhoneSession();
                            ////call.PlaceCall("*****@*****.**", new SDP()
                            //call.PlaceCall("*****@*****.**", new SDP()
                            //{
                            //    Address = "127.0.0.1",
                            //    Username = "******",
                            //    SessionId = Crypto.GetRandomString(5),
                            //    AnnouncementVersion = Crypto.GetRandomInt(5),
                            //    Connection = new SDPConnectionInformation("127.0.0.1"),
                            //    Timing = "0 0",
                            //    Media = new List<SDPMediaAnnouncement>()
                            //    {
                            //        new SDPMediaAnnouncement(0)
                            //        {
                            //            MediaFormats = new List<SDPMediaFormat>(){ new SDPMediaFormat((int)SDPMediaFormatsEnum.PCMU) }
                            //        }
                            //    }
                            //});
                        };
                        ThreadPool.QueueUserWorkItem(delegate { m_xmppClient.Connect(); });

                        ManualResetEvent mre = new ManualResetEvent(false);
                        mre.WaitOne();
                    //}
                //}
            }
            catch (Exception excp)
            {
                Console.WriteLine("Exception Main. " + excp.Message);
            }
            finally
            {
                Console.WriteLine("press any key to exit...");
                Console.Read();
            }
        }
예제 #33
0
 public JingleSessionManager(XMPPClient client)
     : base(client)
 {
 }
예제 #34
0
 public GoogleTalkLogic(XMPPClient client, string strSessionId, GoogleTalkSessionManager mgr)
     : base(client)
 {
     SessionId = strSessionId;
     GoogleTalkSessionManager = mgr;
 }
예제 #35
0
 public FileTransferManager(XMPPClient client)
 {
     XMPPClient = client;
 }
예제 #36
0
 public JingleSessionLogic(XMPPClient client, string strSessionId, JingleSessionManager mgr)
     : base(client)
 {
     SessionId = strSessionId;
     JingleSessionManager = mgr;
 }
예제 #37
0
 public GoogleTalkSessionManager(XMPPClient client)
     : base(client)
 {
 }
예제 #38
0
 private static void XMPPDisconnected()
 {
     Console.WriteLine("The XMPP client was disconnected.");
     m_xmppClient = null;
 }