コード例 #1
0
ファイル: Client.cs プロジェクト: Dids/SharpMUD
        private void Poll()
        {
            var jObject = new JObject();

            jObject["chat_token"] = Token;
            jObject["usernames"]  = JArray.FromObject(AccountData.Users.Where(x => x.Update).Select(x => x.Name).ToArray());
            jObject["after"]      = LastPollTime + 0.005;

            try
            {
                var response = Requester.PostRequest(Methods.ChatHistory, jObject);
                var obj      = JsonConvert.DeserializeObject(response) as JObject;

                var chatHistory = new ChatHistory();
                var chatObject  = obj["chats"] as JObject;
                foreach (var kvp in chatObject)
                {
                    foreach (JObject msgObject in kvp.Value as JArray)
                    {
                        var channel = string.Empty;
                        if (msgObject["channel"] != null)
                        {
                            channel = msgObject["channel"].ToString();
                        }

                        if (msgObject["is_join"] != null)
                        {
                            var presence = new Presence(
                                msgObject["id"].ToString(),
                                double.Parse(msgObject["t"].ToString()),
                                kvp.Key,
                                msgObject["from_user"].ToString(),
                                channel,
                                bool.Parse(msgObject["is_join"].ToString())
                                );
                            chatHistory.Push(presence);
                        }
                        else
                        {
                            var message = new Message(
                                msgObject["id"].ToString(),
                                double.Parse(msgObject["t"].ToString()),
                                kvp.Key,
                                msgObject["from_user"].ToString(),
                                channel,
                                msgObject["msg"].ToString()
                                );
                            chatHistory.Push(message);
                        }
                    }
                }

                if (!chatHistory.IsEmpty)
                {
                    LastPollTime = chatHistory.Last.Timestamp;
                }

                while (!chatHistory.IsEmpty)
                {
                    var element = chatHistory.Pop();

                    if (element is Presence)
                    {
                        var pres    = element as Presence;
                        var channel = AccountData.FindUser(pres.To).FindChannel(pres.Channel);

                        if (channel != null)
                        {
                            if (!pres.Joined)
                            {
                                if (channel.MemberExists(pres.From))
                                {
                                    channel.Members.Remove(pres.From);
                                }
                            }
                            else
                            {
                                if (!channel.MemberExists(pres.From))
                                {
                                    channel.Members.Add(pres.From);
                                }
                            }
                        }
                        PresenceReceived?.Invoke(this, new PresenceEventArgs(pres));
                        continue;
                    }
                    else if (element is Message)
                    {
                        if (element.From != element.To)
                        {
                            if (!RelayedIDs.Contains(element.ID))
                            {
                                RelayedIDs.Add(element.ID);
                                MessageReceived?.Invoke(this, new MessageEventArgs(element as Message));
                            }
                        }
                        else
                        {
                            if (!RelayedIDs.Contains(element.ID))
                            {
                                RelayedIDs.Add(element.ID);
                                MessageSent?.Invoke(this, new MessageEventArgs(element as Message));
                            }
                        }


                        if (RelayedIDs.Count > 100)
                        {
                            RelayedIDs.Clear();
                        }
                    }
                }
            }
            catch (RequestException e)
            {
                ErrorOccured?.Invoke(this, new ErrorEventArgs(e));
            }
        }
コード例 #2
0
        /// <summary>
        /// Starts receiving presence events.
        /// </summary>
        /// <since_tizen> 3 </since_tizen>
        /// <remarks>
        /// <para>Sends request to receive presence to an interested server's resource with resourceType.
        /// If succeeded, <see cref="PresenceReceived"/> event handler will be triggered when the server sends presence.
        /// A server sends presence events when adds / removes / alters a resource or start / stop presence.</para>
        /// <para><paramref name="hostAddress" /> could be <see cref="MulticastAddress"/> for IPv4 multicast.
        /// The length of <paramref name="resourceType" /> should be less than or equal to 61.
        /// The <paramref name="resourceType" /> must start with a lowercase alphabetic character, followed by a sequence
        /// of lowercase alphabetic, numeric, ".", or "-" characters, and contains no white space.</para>
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/internet</privilege>
        /// <privlevel>public</privlevel>
        /// <param name="hostAddress">The address or addressable name of the server.</param>
        /// <param name="resourceType">A resource type that a client is interested in.</param>
        /// <returns>PresenceId - An identifier for this request.</returns>
        /// <feature>http://tizen.org/feature/iot.ocf</feature>
        /// <pre>Initialize() should be called to initialize.</pre>
        /// <post>
        /// When the resource receive presence, <see cref="PresenceReceived"/> event handler will be invoked.<br/>
        /// You must destroy presence by calling StopReceivingPresence() if presence event is no longer needed.
        /// </post>
        /// <seealso cref="IoTConnectivityServerManager.StartSendingPresence(uint)"/>
        /// <seealso cref="IoTConnectivityServerManager.StopSendingPresence()"/>
        /// <seealso cref="StopReceivingPresence(int)"/>
        /// <seealso cref="PresenceReceived"/>
        /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
        /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
        /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
        /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
        /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
        /// <example><code><![CDATA[
        /// EventHandler<PresenceReceivedEventArgs> handler = (sender, e) => {
        ///     Console.Log("PresenceReceived, presence id :" + e.PresenceId);
        /// }
        /// EventHandler<FindingErrorOccurredEventArgs> errorHandler = (sender, e) => {
        ///     Console.Log("Found error :" + e.Error.Message);
        /// }
        /// IoTConnectivityClientManager.PresenceReceived += handler;
        /// IoTConnectivityClientManager.FindingErrorOccurred += errorHandler;
        /// // Do not forget to remove these event handlers when they are not required any more.
        /// int id = IoTConnectivityClientManager.StartReceivingPresence(IoTConnectivityClientManager.MulticastAddress, "oic.iot.door");
        /// ]]></code></example>
        public static int StartReceivingPresence(string hostAddress, string resourceType)
        {
            Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType connectivityType = Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.Ip;

            if (resourceType != null && !ResourceTypes.IsValid(resourceType))
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Invalid type");
                throw new ArgumentException("Invalid type");
            }

            IntPtr id = IntPtr.Zero;

            lock (s_presenceCallbacksMap)
            {
                id = (IntPtr)s_presenceListenerId++;
            }
            s_presenceCallbacksMap[id] = (IntPtr presence, int result, IntPtr presenceResponseHandle, IntPtr userData) =>
            {
                int presenceId = (int)userData;
                if (result == (int)IoTConnectivityError.None)
                {
                    if (presenceResponseHandle != IntPtr.Zero)
                    {
                        PresenceReceivedEventArgs e = GetPresenceReceivedEventArgs(presenceId, presenceResponseHandle);
                        if (e == null)
                        {
                            Log.Error(IoTConnectivityErrorFactory.LogTag, "Can't get PresenceReceivedEventArgs");
                            return;
                        }
                        PresenceReceived?.Invoke(null, e);
                    }
                    else
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Handle is null");
                        return;
                    }
                }
                else
                {
                    FindingErrorOccurredEventArgs e = GetFindingErrorOccurredEventArgs(presenceId, result);
                    FindingErrorOccurred?.Invoke(null, e);
                }
            };

            IntPtr presenceHandle;
            int    errorCode = Interop.IoTConnectivity.Client.Presence.AddPresenceCb(hostAddress, (int)connectivityType, resourceType, s_presenceCallbacksMap[id], id, out presenceHandle);

            if (errorCode != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to register presence event handler");
                lock (s_presenceCallbacksMap)
                {
                    s_presenceCallbacksMap.Remove(id);
                }
                throw IoTConnectivityErrorFactory.GetException(errorCode);
            }

            lock (s_presenceHandlesMap)
            {
                s_presenceHandlesMap[id] = presenceHandle;
            }
            return((int)id);
        }