Exemplo n.º 1
0
        public override IQ HandleIQ(XmppStream stream, IQ iq, XmppHandlerContext context)
        {
            if (!iq.HasTo || !iq.To.HasUser)
            {
                return(XmppStanzaError.ToServiceUnavailable(iq));
            }

            var session = context.SessionManager.GetSession(iq.To);

            if (session != null)
            {
                context.Sender.SendTo(session, iq);
                return(null);
            }
            else
            {
                return(XmppStanzaError.ToRecipientUnavailable(iq));
            }
        }
Exemplo n.º 2
0
        public override void HandleMessage(XmppStream stream, Message message, XmppHandlerContext context)
        {
            if (!message.HasTo || message.To.IsServer)
            {
                context.Sender.SendTo(stream, XmppStanzaError.ToServiceUnavailable(message));
                return;
            }

            var session = context.SessionManager.GetSession(message.To);

            if (session != null)
            {
                context.Sender.SendTo(session, message);
            }
            else
            {
                StoreOffline(message, context.StorageManager.OfflineStorage);
            }
        }
Exemplo n.º 3
0
 public override IQ HandleIQ(XmppStream stream, IQ iq, XmppHandlerContext context)
 {
     if (iq.Query is PrivateLog && iq.Type == IqType.get)
     {
         return(GetPrivateLog(stream, iq, context));
     }
     if (iq.Query is PrivateLog && iq.Type == IqType.set)
     {
         return(SetPrivateLog(stream, iq, context));
     }
     if (iq.Query is PrivateLog && (iq.Type == IqType.result || iq.Type == IqType.error))
     {
         return(null);
     }
     if (iq.Query is History && iq.Type == IqType.get)
     {
         return(GetHistory(stream, iq, context));
     }
     return(XmppStanzaError.ToServiceUnavailable(iq));
 }
        private IQ GetHistory(XmppStream stream, IQ iq, XmppHandlerContext context)
        {
            if (!iq.HasTo)
            {
                return(XmppStanzaError.ToServiceUnavailable(iq));
            }

            FlushMessageBuffer();

            var history = (History)iq.Query;

            history.RemoveAllChildNodes();
            foreach (var m in archiveStore.GetMessages(iq.From, iq.To, history.From, history.To, history.Count))
            {
                history.AddChild(HistoryItem.FromMessage(m));
            }

            iq.Type = IqType.result;
            iq.SwitchDirection();
            return(iq);
        }
Exemplo n.º 5
0
        protected override IQ GetDiscoItems(XmppStream stream, IQ iq, XmppHandlerContext context)
        {
            if (((DiscoItems)iq.Query).Node != null)
            {
                return(XmppStanzaError.ToServiceUnavailable(iq));
            }

            var answer = new IQ(IqType.result);

            answer.Id   = iq.Id;
            answer.From = Jid;
            answer.To   = iq.From;
            var items = new DiscoItems();

            answer.Query = items;
            if (realJid != null)
            {
                items.AddDiscoItem().Jid = realJid;
            }
            return(answer);
        }
Exemplo n.º 6
0
        protected virtual IQ GetDiscoInfo(XmppStream stream, IQ iq, XmppHandlerContext context)
        {
            if (((DiscoInfo)iq.Query).Node != null)
            {
                return(XmppStanzaError.ToServiceUnavailable(iq));
            }

            var service = ServiceManager.GetService(Jid);

            if (service == null)
            {
                return(XmppStanzaError.ToItemNotFound(iq));
            }

            var answer = new IQ(IqType.result);

            answer.Id    = iq.Id;
            answer.From  = Jid;
            answer.To    = iq.From;
            answer.Query = service.DiscoInfo;
            return(answer);
        }
Exemplo n.º 7
0
        protected virtual IQ GetDiscoItems(XmppStream stream, IQ iq, XmppHandlerContext context)
        {
            if (((DiscoItems)iq.Query).Node != null)
            {
                return(XmppStanzaError.ToServiceUnavailable(iq));
            }

            var answer = new IQ(IqType.result);

            answer.Id   = iq.Id;
            answer.From = Jid;
            answer.To   = iq.From;
            var items = new DiscoItems();

            answer.Query = items;
            foreach (var service in ServiceManager.GetChildServices(Jid))
            {
                if (service.DiscoItem != null)
                {
                    items.AddDiscoItem(service.DiscoItem);
                }
            }
            return(answer);
        }
Exemplo n.º 8
0
        public void ProcessStreamElement(Node node, XmppStream stream)
        {
            if (node == null)
            {
                throw new ArgumentNullException("node");
            }
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            try
            {
                var address = new Jid(stream.Domain);

                foreach (var handler in HandlerStorage.GetStreamHandlers(address, node.GetType()))
                {
                    handler.ElementHandle(stream, (Element)node.Clone(), context);
                }

                if (node is Stanza)
                {
                    var stanza = (Stanza)node;

                    if (!validator.ValidateStanza(stanza, stream, context))
                    {
                        return;
                    }

                    if (stanza.HasTo)
                    {
                        address = stanza.To;
                    }

                    var handlres = HandlerStorage.GetStanzaHandlers(address, GetStanzaType(stanza));
                    if (handlres.Count == 0)
                    {
                        if (stanza is IQ)
                        {
                            var iq = (IQ)stanza;
                            if ((iq.Type == IqType.error || iq.Type == IqType.result) && iq.HasTo && iq.To.HasUser)
                            {
                                //result and error retranslate to user
                                var session = context.SessionManager.GetSession(iq.To);
                                if (session != null)
                                {
                                    sender.SendTo(session, iq);
                                    return;
                                }
                            }
                            //result and error ignored by server
                        }
                        sender.SendTo(stream, XmppStanzaError.ToServiceUnavailable(stanza));
                        log.DebugFormat("Stanza handler not found for address '{0}'", address);
                        return;
                    }

                    bool      iqHandled = true;
                    Stopwatch stopwatch = null;

                    foreach (var handler in handlres)
                    {
                        if (log.IsDebugEnabled)
                        {
                            stopwatch = Stopwatch.StartNew();
                        }

                        if (stanza is IQ)
                        {
                            var answer = handler.HandleIQ(stream, (IQ)stanza.Clone(), context);
                            if (answer != null)
                            {
                                sender.SendTo(stream, answer);
                                iqHandled = answer.Id == stanza.Id;
                            }
                        }
                        else if (stanza is Message)
                        {
                            handler.HandleMessage(stream, (Message)stanza.Clone(), context);
                        }
                        else if (stanza is Presence)
                        {
                            handler.HandlePresence(stream, (Presence)stanza.Clone(), context);
                        }
                        else
                        {
                            sender.SendTo(stream, XmppStanzaError.ToNotAcceptable(stanza));
                            return;
                        }

                        if (log.IsDebugEnabled)
                        {
                            stopwatch.Stop();
                            log.DebugFormat("Process stanza handler '{1}' on address '{0}', time: {2}ms", address, handler.GetType().FullName, stopwatch.Elapsed.TotalMilliseconds);
                        }
                    }
                    if (!iqHandled)
                    {
                        sender.SendTo(stream, XmppStanzaError.ToServiceUnavailable(stanza));
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                ProcessException(ex, node, stream);
            }
        }
Exemplo n.º 9
0
        public override IQ HandleIQ(XmppStream stream, IQ iq, XmppHandlerContext context)
        {
            var answer = new IQ(IqType.result)
            {
                Id   = iq.Id,
                To   = iq.From,
                From = iq.To,
            };

            //iq sended to server
            if (iq.Type == IqType.get && (!iq.HasTo || iq.To.IsServer || iq.To == iq.From))
            {
                if (iq.Query is Version)
                {
                    answer.Query = new Version()
                    {
                        Name = "TeamLab Jabber Server",
                        Os   = System.Environment.OSVersion.ToString(),
                        Ver  = "1.0",
                    };
                    return(answer);
                }
                else if (iq.Query is Ping)
                {
                    return(answer);
                }
                return(XmppStanzaError.ToServiceUnavailable(iq));
            }

            if (iq.Type == IqType.get && iq.HasTo)
            {
                //resend iq
                var sessionTo   = context.SessionManager.GetSession(iq.To);
                var sessionFrom = context.SessionManager.GetSession(iq.From);
                if (sessionTo != null && sessionFrom != null)
                {
                    if (string.IsNullOrEmpty(iq.Id))
                    {
                        iq.Id = System.Guid.NewGuid().ToString("N");
                    }

                    IdleWatcher.StartWatch(
                        iq.Id + iq.From,
                        System.TimeSpan.FromSeconds(3),
                        (s, e) => { context.Sender.SendTo(sessionFrom, XmppStanzaError.ToServiceUnavailable(iq)); });
                    context.Sender.SendTo(sessionTo, iq);
                }
                else
                {
                    return(XmppStanzaError.ToRecipientUnavailable(iq));
                }
            }
            if (iq.Type == IqType.error || iq.Type == IqType.result)
            {
                if (!iq.HasTo)
                {
                    return(XmppStanzaError.ToBadRequest(iq));
                }

                IdleWatcher.StopWatch(iq.Id + iq.To);
                var session = context.SessionManager.GetSession(iq.To);
                if (session != null)
                {
                    context.Sender.SendTo(session, iq);
                }
            }
            return(null);
        }
        public override void HandleMessage(XmppStream stream, Message message, XmppHandlerContext context)
        {
            if (!message.HasTo || message.To.IsServer)
            {
                context.Sender.SendTo(stream, XmppStanzaError.ToServiceUnavailable(message));
                return;
            }

            var sessions = context.SessionManager.GetBareJidSessions(message.To);

            if (0 < sessions.Count)
            {
                foreach (var s in sessions)
                {
                    try
                    {
                        context.Sender.SendTo(s, message);
                    }
                    catch
                    {
                        context.Sender.SendToAndClose(s.Stream, message);
                    }
                }
            }
            else
            {
                pushStore = new DbPushStore();
                var properties = new Dictionary <string, string>(1);
                properties.Add("connectionStringName", "default");
                pushStore.Configure(properties);

                if (message.HasTag("active"))
                {
                    var fromFullName = message.HasAttribute("username") ?
                                       message.GetAttribute("username") : message.From.ToString();


                    var messageToDomain = message.To.ToString().Split(new char[] { '@' })[1];
                    var tenant          = CoreContext.TenantManager.GetTenant(messageToDomain);
                    var tenantId        = tenant != null ? tenant.TenantId : -1;

                    var userPushList = new List <UserPushInfo>();
                    userPushList = pushStore.GetUserEndpoint(message.To.ToString().Split(new char[] { '@' })[0]);

                    var firebaseAuthorization = "";
                    try
                    {
                        CallContext.SetData(TenantManager.CURRENT_TENANT, new Tenant(tenantId, ""));
                        firebaseAuthorization = FireBase.Instance.Authorization;
                    }
                    catch (Exception exp)
                    {
                        log.DebugFormat("firebaseAuthorizationERROR: {0}", exp);
                    }
                    foreach (var user in userPushList)
                    {
                        try
                        {
                            var           from = message.From.ToString().Split(new char[] { '@' })[0];
                            List <string> userId;
                            string        photoPath = "";
                            using (var db = new DbManager("core"))
                                using (var command = db.Connection.CreateCommand())
                                {
                                    var q = new SqlQuery("core_user").Select("id").Where(Exp.Like("username", from)).Where("tenant", tenantId);

                                    userId = command.ExecuteList(q, DbRegistry.GetSqlDialect(db.DatabaseId))
                                             .ConvertAll(r => Convert.ToString(r[0]))
                                             .ToList();
                                }
                            if (userId.Count != 0)
                            {
                                var guid = new Guid(userId[0]);
                                photoPath = UserPhotoManager.GetBigPhotoURL(guid);
                            }

                            var tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
                            tRequest.Method      = "post";
                            tRequest.ContentType = "application/json";
                            var data = new
                            {
                                to   = user.endpoint,
                                data = new
                                {
                                    msg          = message.Body,
                                    fromFullName = fromFullName,
                                    photoPath    = photoPath
                                }
                            };
                            var serializer = new JavaScriptSerializer();
                            var json       = serializer.Serialize(data);
                            var byteArray  = Encoding.UTF8.GetBytes(json);
                            tRequest.Headers.Add(string.Format("Authorization: key={0}", firebaseAuthorization));
                            tRequest.ContentLength = byteArray.Length;
                            using (var dataStream = tRequest.GetRequestStream())
                            {
                                dataStream.Write(byteArray, 0, byteArray.Length);
                                using (var tResponse = tRequest.GetResponse())
                                {
                                    using (var dataStreamResponse = tResponse.GetResponseStream())
                                    {
                                        using (var tReader = new StreamReader(dataStreamResponse))
                                        {
                                            var sResponseFromServer = tReader.ReadToEnd();
                                            var str = sResponseFromServer;
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            var str = ex.Message;
                            log.DebugFormat("PushRequestERROR: {0}", str);
                        }
                    }
                }
                StoreOffline(message, context.StorageManager.OfflineStorage);
            }
        }
        public override void HandleMessage(XmppStream stream, Message message, XmppHandlerContext context)
        {
            if (!message.HasTo || message.To.IsServer)
            {
                context.Sender.SendTo(stream, XmppStanzaError.ToServiceUnavailable(message));
                return;
            }

            var sessions = context.SessionManager.GetBareJidSessions(message.To);

            if (0 < sessions.Count)
            {
                foreach (var s in sessions)
                {
                    try
                    {
                        context.Sender.SendTo(s, message);
                    }
                    catch
                    {
                        context.Sender.SendToAndClose(s.Stream, message);
                    }
                }
            }
            else
            {
                pushStore = new DbPushStore();
                var properties = new Dictionary <string, string>(1);
                properties.Add("connectionStringName", "default");
                pushStore.Configure(properties);

                if (message.HasTag("active"))
                {
                    var fromFullName = message.HasAttribute("username") ?
                                       message.GetAttribute("username") : message.From.ToString();

                    var tenantId = message.HasAttribute("tenantid") ?
                                   Convert.ToInt32(message.GetAttribute("tenantid"), 16) : -1;

                    var userPushList = new List <UserPushInfo>();
                    userPushList = pushStore.GetUserEndpoint(message.To.ToString().Split(new char[] { '@' })[0]);

                    var firebaseAuthorization = "";
                    try
                    {
                        CallContext.SetData(TenantManager.CURRENT_TENANT, new Tenant(tenantId, ""));
                        firebaseAuthorization = KeyStorage.Get("firebase_authorization");
                    }
                    catch (Exception exp)
                    {
                        log.DebugFormat("firebaseAuthorizationERROR: {0}", exp);
                    }
                    foreach (var user in userPushList)
                    {
                        try{
                            var tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
                            tRequest.Method      = "post";
                            tRequest.ContentType = "application/json";
                            var data = new
                            {
                                to   = user.endpoint,
                                data = new
                                {
                                    msg          = message.Body,
                                    fromFullName = fromFullName
                                }
                            };
                            var serializer = new JavaScriptSerializer();
                            var json       = serializer.Serialize(data);
                            var byteArray  = Encoding.UTF8.GetBytes(json);
                            tRequest.Headers.Add(string.Format("Authorization: key={0}", firebaseAuthorization));
                            tRequest.ContentLength = byteArray.Length;
                            using (var dataStream = tRequest.GetRequestStream())
                            {
                                dataStream.Write(byteArray, 0, byteArray.Length);
                                using (var tResponse = tRequest.GetResponse())
                                {
                                    using (var dataStreamResponse = tResponse.GetResponseStream())
                                    {
                                        using (var tReader = new StreamReader(dataStreamResponse))
                                        {
                                            var sResponseFromServer = tReader.ReadToEnd();
                                            var str = sResponseFromServer;
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            var str = ex.Message;
                            log.DebugFormat("PushRequestERROR: {0}", str);
                        }
                    }
                }
                StoreOffline(message, context.StorageManager.OfflineStorage);
            }
        }