示例#1
0
        public virtual void SetVCard(Jid jid, Vcard vcard)
        {
            if (jid == null)
            {
                throw new ArgumentNullException("jid");
            }
            if (vcard == null)
            {
                throw new ArgumentNullException("vcard");
            }

            try
            {
                lock (vcardsCache)
                {
                    ExecuteNonQuery(
                        new SqlInsert("jabber_vcard", true)
                        .InColumnValue("jid", jid.Bare.ToLowerInvariant())
                        .InColumnValue("vcard", ElementSerializer.SerializeElement(vcard)));
                    vcardsCache[jid.Bare.ToLowerInvariant()] = vcard;
                }
            }
            catch (Exception e)
            {
                throw new JabberException("Could not save VCard.", e);
            }
        }
示例#2
0
        public void AddMucMessages(Jid mucName, params Message[] messages)
        {
            if (mucName == null || messages == null || messages.Length == 0)
            {
                return;
            }

            var batch = new List <ISqlInstruction>(messages.Length);

            foreach (var m in messages)
            {
                if (m != null)
                {
                    if (m.XDelay == null)
                    {
                        m.XDelay = new Delay();
                    }
                    m.XDelay.Stamp = DateTime.UtcNow;

                    batch.Add(
                        new SqlInsert("jabber_room_history")
                        .InColumnValue("jid", mucName.Bare)
                        .InColumnValue("message", ElementSerializer.SerializeElement(m))
                        .InColumnValue("stamp", m.XDelay.Stamp));
                }
            }
            ExecuteBatch(batch);
        }
        public virtual Vcard GetVCard(Jid jid, string id = "")
        {
            if (jid == null)
            {
                throw new ArgumentNullException("jid");
            }

            try
            {
                lock (vcardsCache)
                {
                    var bareJid = jid.Bare.ToLowerInvariant();
                    if (!vcardsCache.ContainsKey(bareJid))
                    {
                        var vcardStr = ExecuteScalar <string>(new SqlQuery("jabber_vcard").Select("vcard").Where("jid", bareJid));
                        vcardsCache[bareJid] = !string.IsNullOrEmpty(vcardStr) ? ElementSerializer.DeSerializeElement <Vcard>(vcardStr) : null;
                    }
                    return(vcardsCache[bareJid]);
                }
            }
            catch (Exception e)
            {
                throw new JabberException("Could not get VCard.", e);
            }
        }
示例#4
0
        public void SaveMessages(params Message[] messages)
        {
            if (messages == null)
            {
                throw new ArgumentNullException("message");
            }
            if (messages.Length == 0)
            {
                return;
            }

            var batch = new List <ISqlInstruction>(messages.Length);

            foreach (var m in messages)
            {
                if (string.IsNullOrEmpty(m.Body) && string.IsNullOrEmpty(m.Subject) && string.IsNullOrEmpty(m.Thread) && m.Html == null)
                {
                    continue;
                }

                batch.Add(new SqlInsert("jabber_archive")
                          .InColumnValue("jid", GetKey(m.From, m.To))
                          .InColumnValue("stamp", DateTime.UtcNow)
                          .InColumnValue("message", ElementSerializer.SerializeElement(m)));
            }
            ExecuteBatch(batch);
        }
示例#5
0
 /// <inheritdoc />
 public override void Write(TObjectType[] value, IWireStreamWriterStrategy dest)
 {
     for (int i = 0; i < value.Length; i++)
     {
         ElementSerializer.Write(value[i], dest);
     }
 }
示例#6
0
        public Message[] GetMessages(Jid from, Jid to, DateTime start, DateTime end, int count)
        {
            if (from == null)
            {
                throw new ArgumentNullException("from");
            }
            if (to == null)
            {
                throw new ArgumentNullException("to");
            }

            var q = new SqlQuery("jabber_archive")
                    .Select("message")
                    .Where("jid", GetKey(from, to))
                    .Where(Exp.Between("stamp", start, end))
                    .OrderBy("id", false);

            if (0 < count && count < int.MaxValue)
            {
                q.SetMaxResults(count);
            }

            var messages = ExecuteList(q).ConvertAll(r => ElementSerializer.DeSerializeElement <Message>((string)r[0]));

            messages.Reverse();
            return(messages.ToArray());
        }
示例#7
0
        private void SerializeElements(XmlWriter writer, XmlNamespaceManager manager, Element element)
        {
            var elementSerializer = new ElementSerializer(this, writer, manager, element.GetType());

            elementSerializer.SerializeElements(element, element.GetType());
            elementSerializer.SerializeOrphans(element);
        }
示例#8
0
        public static Body ReadBodyFromRequest(HttpListenerContext ctx)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }

            try
            {
                if (!ctx.Request.HasEntityBody)
                {
                    return(null);
                }

                string body;
                using (var streamReader = new StreamReader(ctx.Request.InputStream))
                {
                    body = streamReader.ReadToEnd();
                }

                return(ElementSerializer.DeSerializeElement <Body>(body));
            }
            catch (Exception e)
            {
                if (e is HttpListenerException || e is ObjectDisposedException)
                {
                    // ignore
                }
                else
                {
                    log.ErrorFormat("Error read body from request: {0}", e);
                }
            }
            return(null);
        }
示例#9
0
        public Vcard GetVCard(string user)
        {
            try
            {
                if (string.IsNullOrEmpty(user))
                {
                    throw new ArgumentNullException("user");
                }
                if (CoreContext.UserManager.IsUserNameExists(user))
                {
                    var ui    = CoreContext.UserManager.GetUserByUserName(user);
                    var vcard = new Vcard();

                    vcard.Fullname = vcard.Nickname = string.Format("{0} {1}", ui.LastName, ui.FirstName);
                    if (ui.BirthDate != null)
                    {
                        vcard.Birthday = ui.BirthDate.Value;
                    }
                    vcard.JabberId = new Jid(ui.UserName);
                    vcard.AddTelephoneNumber(new Telephone(TelephoneLocation.WORK, TelephoneType.NUMBER, ui.PhoneOffice));
                    vcard.AddTelephoneNumber(new Telephone(TelephoneLocation.WORK, TelephoneType.FAX, ui.Fax));
                    vcard.AddTelephoneNumber(new Telephone(TelephoneLocation.HOME, TelephoneType.NUMBER, ui.PhoneHome));
                    vcard.AddTelephoneNumber(new Telephone(TelephoneLocation.HOME, TelephoneType.CELL, ui.PhoneMobile));
                    vcard.AddEmailAddress(new Email(EmailType.INTERNET, ui.Email, true));

                    vcard.Organization = new Organization(CoreContext.UserManager.GetCompanyName(), ui.Department);
                    vcard.Title        = ui.Title;

                    vcard.AddAddress(new Address(AddressLocation.HOME, null, ui.PrimaryAddress, ui.City, ui.State, ui.PostalCode, ui.Country, true));

                    vcard.Description = ui.Notes;

                    var image = PreparePhoto(CoreContext.UserManager.GetUserPhoto(ui.ID, Guid.Empty));
                    if (image != null)
                    {
                        vcard.Photo = new Photo(image, image.RawFormat);
                        //image.Dispose();
                    }

                    return(vcard);
                }
                else
                {
                    lock (vcardsCache)
                    {
                        if (!vcardsCache.ContainsKey(user))
                        {
                            var vcardStr = ExecuteScalar("select VCard from VCard where UserName = @userName", "userName", user) as string;
                            vcardsCache[user] = !string.IsNullOrEmpty(vcardStr) ? ElementSerializer.DeSerializeElement <Vcard>(vcardStr) : null;
                        }
                        return(vcardsCache[user]);
                    }
                }
            }
            catch (Exception e)
            {
                throw new JabberServiceUnavailableException("Could not get vcard", e);
            }
        }
示例#10
0
        public Element GetPrivate(Jid jid, Element element)
        {
            CheckArgs(jid, element);

            var elementStr = ExecuteScalar <string>(new SqlQuery("jabber_private").Select("element").Where("jid", jid.Bare).Where("tag", element.TagName).Where("namespace", element.Namespace));

            return(!string.IsNullOrEmpty(elementStr) ? ElementSerializer.DeSerializeElement <Element>(elementStr) : null);
        }
示例#11
0
 /// <inheritdoc />
 public override async Task WriteAsync(TObjectType[] value, IWireStreamWriterStrategyAsync dest)
 {
     for (int i = 0; i < value.Length; i++)
     {
         await ElementSerializer.WriteAsync(value[i], dest)
         .ConfigureAwait(false);
     }
 }
示例#12
0
 public RosterItem GetRosterItem(Jid user, Jid contact)
 {
     Args.NotNull(user, "user");
     Args.NotNull(contact, "contact");
     using (var db = GetDb())
     {
         var s = db.ExecScalar <string>(new SqlQuery("jabber_roster").Select("item").Where("user_jid", user.Bare).Where("contact_jid", contact.Bare));
         return(!string.IsNullOrEmpty(s) ? ElementSerializer.DeSerializeElement <RosterItem>(s) : null);
     }
 }
示例#13
0
 public IEnumerable <RosterItem> GetRosterItems(Jid user)
 {
     Args.NotNull(user, "user");
     using (var db = GetDb())
     {
         return(db.ExecList(new SqlQuery("jabber_roster").Select("item").Where("user_jid", user.Bare))
                .Select(r => ElementSerializer.DeSerializeElement <RosterItem>((string)r[0]))
                .ToArray());
     }
 }
示例#14
0
        public Message[] GetMessages(Jid from, Jid to, DateTime start, DateTime end, string text, int count, int startindex = 0)
        {
            if (from == null)
            {
                throw new ArgumentNullException("from");
            }
            if (to == null)
            {
                throw new ArgumentNullException("to");
            }

            var q = new SqlQuery("jabber_archive")
                    .Select("message")
                    .Where("jid", GetKey(from, to))
                    .OrderBy("id", false);

            if (start != DateTime.MinValue)
            {
                q.Where(Exp.Ge("stamp", start));
            }
            if (end != DateTime.MaxValue)
            {
                q.Where(Exp.Le("stamp", end));
            }
            if (startindex < int.MaxValue)
            {
                q.SetFirstResult(startindex);
            }
            if (0 < count && count < int.MaxValue)
            {
                q.SetMaxResults(count);
            }

            if (!string.IsNullOrEmpty(text))
            {
                try
                {
                    List <int> ids;
                    CallContext.SetData(TenantManager.CURRENT_TENANT, CoreContext.TenantManager.GetTenant(from.Server));
                    if (FactoryIndexer <Web.Talk.JabberWrapper> .TrySelectIds(r => r.MatchAll(HttpUtility.HtmlDecode(text)), out ids))
                    {
                        q.Where(Exp.In("id", ids));
                    }
                }
                finally
                {
                    CallContext.SetData(TenantManager.CURRENT_TENANT, null);
                }
            }

            var messages = ExecuteList(q).ConvertAll(r => ElementSerializer.DeSerializeElement <Message>((string)r[0]));

            messages.Reverse();
            return(messages.ToArray());
        }
示例#15
0
        public void SetPrivate(Jid jid, Element element)
        {
            CheckArgs(jid, element);

            ExecuteNonQuery(
                new SqlInsert("jabber_private", true)
                .InColumnValue("jid", jid.Bare)
                .InColumnValue("tag", element.TagName)
                .InColumnValue("namespace", element.Namespace)
                .InColumnValue("element", ElementSerializer.SerializeElement(element)));
        }
示例#16
0
        public List <Message> GetMucMessages(Jid mucName, DateTime after)
        {
            if (Jid.IsNullOrEmpty(mucName))
            {
                throw new ArgumentNullException("mucName");
            }

            var q        = new SqlQuery("jabber_room_history").Select("message").Where("jid", mucName.Bare).Where(Exp.Ge("stamp", after)).OrderBy("id", false);
            var messages = ExecuteList(q).ConvertAll(m => ElementSerializer.DeSerializeElement <Message>((string)m[0]));

            messages.Reverse();
            return(messages);
        }
示例#17
0
        public void SaveMessages(params Message[] messages)
        {
            if (messages == null)
            {
                throw new ArgumentNullException("message");
            }
            if (messages.Length == 0)
            {
                return;
            }

            foreach (var m in messages)
            {
                if (string.IsNullOrEmpty(m.Body) && string.IsNullOrEmpty(m.Subject) && string.IsNullOrEmpty(m.Thread) && m.Html == null)
                {
                    continue;
                }

                if (m.XDelay == null)
                {
                    m.XDelay = new Delay();
                }
                if (m.XDelay.Stamp == default(DateTime))
                {
                    m.XDelay.Stamp = DateTime.UtcNow;
                }

                var message = ElementSerializer.SerializeElement(m);
                var jid     = GetKey(m.From, m.To);
                var stamp   = DateTime.UtcNow;

                var id = ExecuteScalar <int>(
                    new SqlInsert("jabber_archive")
                    .InColumnValue("id", 0)
                    .InColumnValue("jid", jid)
                    .InColumnValue("stamp", stamp)
                    .InColumnValue("message", message)
                    .Identity(0, 0, true));

                FactoryIndexer <JabberWrapper> .IndexAsync(new JabberWrapper
                {
                    Id             = id,
                    Jid            = jid,
                    LastModifiedOn = stamp,
                    Message        = message
                });
            }
        }
示例#18
0
        /// <inheritdoc />
        public override TObjectType[] Read(IWireStreamReaderStrategy source)
        {
            byte[] bytes = source.ReadAllBytes();
            FixedBufferWireReaderStrategy fixedStrategy = new FixedBufferWireReaderStrategy(bytes, 0, bytes.Length);

            QuickList <TObjectType> objects = new QuickList <TObjectType>(4);

            //Read until the fixed buffer is empty. This iwll give us all objects without read exceptions when end is reached.
            while (!fixedStrategy.isFinished)
            {
                objects.Add(ElementSerializer.Read(fixedStrategy));
            }

            //We can avoid some copies like this
            return(objects.Count == objects._items.Length ? objects._items : objects.ToArray());
        }
        public IEnumerable <Element> GetElements(Jid jid, string key)
        {
            Args.NotNull(jid, "jid");
            Args.NotNull(key, "key");

            var q = new SqlQuery("jabber_element")
                    .Select("element_text")
                    .Where("jid", jid.Bare)
                    .Where(key.Contains('%') ? Exp.Like("element_key", key) : Exp.Eq("element_key", key));

            using (var db = GetDb())
            {
                return(db.ExecList(q)
                       .Select(r => ElementSerializer.DeSerializeElement <Element>((string)r[0]))
                       .ToList());
            }
        }
示例#20
0
        public void SaveOfflineMessages(params Message[] messages)
        {
            if (messages == null)
            {
                throw new ArgumentNullException("messages");
            }
            if (messages.Length == 0)
            {
                return;
            }

            var batch = new List <ISqlInstruction>(messages.Length);

            foreach (var m in messages)
            {
                if (m == null || !m.HasTo || string.IsNullOrEmpty(m.To.Bare))
                {
                    continue;
                }
                if (string.IsNullOrEmpty(m.Body) &&
                    string.IsNullOrEmpty(m.Subject) &&
                    string.IsNullOrEmpty(m.Thread) &&
                    m.Html == null)
                {
                    continue;
                }

                if (m.XDelay == null)
                {
                    m.XDelay = new Delay();
                }
                if (m.XDelay.Stamp == default(DateTime))
                {
                    m.XDelay.Stamp = DateTime.UtcNow;
                }

                batch.Add(
                    new SqlInsert("jabber_offmessage")
                    .InColumnValue("jid", GetBareJid(m.To))
                    .InColumnValue("message", ElementSerializer.SerializeElement(m)));

                lock (countCache) countCache.Remove(GetBareJid(m.To));
            }
            ExecuteBatch(batch);
        }
示例#21
0
        public Message[] GetMessages(Jid from, Jid to, int id, int count)
        {
            if (from == null)
            {
                throw new ArgumentNullException("from");
            }
            if (to == null)
            {
                throw new ArgumentNullException("to");
            }

            var q = new SqlQuery("jabber_archive")
                    .UseIndex("jabber_archive_jid")
                    .Select("id", "stamp", "message")
                    .Where("jid", GetKey(from, to))
                    .Where(Exp.Lt("id", id))
                    .OrderBy("id", false);

            if (0 < count && count < int.MaxValue)
            {
                q.SetMaxResults(count);
            }

            var messages = ExecuteList(q).ConvertAll(r =>
            {
                Message m;
                try
                {
                    var internalId = Convert.ToInt32(r[0]);
                    var dbStamp    = Convert.ToDateTime(r[1]);
                    m            = ElementSerializer.DeSerializeElement <Message>((string)r[2]);
                    m.InternalId = internalId;
                    m.DbStamp    = dbStamp;
                }
                catch
                {
                    throw new Exception(string.Format("Wrong message: {0} {1} {2}", r[0], r[1], r[2]));
                }
                return(m);
            });

            messages.Reverse();
            return(messages.ToArray());
        }
示例#22
0
        public static Body ReadBodyFromRequest(HttpListenerContext ctx)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }

            try
            {
                if (!ctx.Request.HasEntityBody)
                {
                    return(null);
                }

                byte[] data   = new byte[ctx.Request.ContentLength64];
                int    offset = 0;
                int    count  = data.Length;
                // Read may return anything from 0 to ContentLength64.
                while (0 < count)
                {
                    int readed = ctx.Request.InputStream.Read(data, offset, count);
                    if (readed == 0)
                    {
                        break;
                    }
                    offset += readed;
                    count  -= readed;
                }
                NetStatistics.ReadBytes(count);
                return(ElementSerializer.DeSerializeElement <Body>(Encoding.UTF8.GetString(data)));
            }
            catch (Exception e)
            {
                if (e is HttpListenerException || e is ObjectDisposedException)
                {
                    // ignore
                }
                else
                {
                    log.ErrorFormat("Error read body from request: {0}", e);
                }
            }
            return(null);
        }
示例#23
0
        public List <Message> GetMucMessages(Jid mucName, int count)
        {
            if (Jid.IsNullOrEmpty(mucName))
            {
                throw new ArgumentNullException("mucName");
            }

            var q = new SqlQuery("jabber_room_history").Select("message").Where("jid", mucName.Bare).OrderBy("id", false);

            if (0 < count && count < int.MaxValue)
            {
                q.SetMaxResults(count);
            }

            var messages = ExecuteList(q).ConvertAll(m => ElementSerializer.DeSerializeElement <Message>((string)m[0]));

            messages.Reverse();
            return(messages);
        }
示例#24
0
        public BoshXmppRequest(string id, Body bodyElement, HttpListenerContext context)
        {
            this.context = context;

            body = ElementSerializer.DeSerializeElement <Body>(ElementSerializer.SerializeElement(bodyElement)); // clone

            if (string.IsNullOrEmpty(body.Sid))
            {
                body.Sid    = id;
                body.Secure = false;
            }
            body.Ack = body.Rid;
            body.RemoveAttribute("rid");
            body.To = null;
            if (body.HasAttribute("xmpp:version") || body.HasAttribute("xmpp:restart"))
            {
                body.SetAttribute("xmlns:xmpp", "urn:xmpp:xbosh");
            }
            body.RemoveAllChildNodes();
        }
示例#25
0
        public Vcard GetVCard(string user)
        {
            if (string.IsNullOrEmpty(user))
            {
                throw new ArgumentNullException("user");
            }

            lock (vcardsCache)
            {
                if (!vcardsCache.ContainsKey(user))
                {
                    using (var connect = GetDbConnection())
                        using (var command = connect.CreateCommand())
                        {
                            command.CommandText = "select VCard from VCard where UserName = @userName";
                            AddCommandParameter(command, "userName", user);
                            var vcardStr = command.ExecuteScalar() as string;
                            vcardsCache[user] = !string.IsNullOrEmpty(vcardStr) ? ElementSerializer.DeSerializeElement <Vcard>(vcardStr) : null;
                        }
                }
                return(vcardsCache[user]);
            }
        }
示例#26
0
        public void SetVCard(string user, Vcard vcard)
        {
            if (string.IsNullOrEmpty(user))
            {
                throw new ArgumentNullException("user");
            }
            if (vcard == null)
            {
                throw new ArgumentNullException("vcard");
            }

            lock (vcardsCache)
            {
                using (var connect = GetDbConnection())
                    using (var command = connect.CreateCommand())
                    {
                        command.CommandText = "insert or replace into VCard(UserName, VCard) values (@userName, @vCard)";
                        AddCommandParameter(command, "userName", user);
                        AddCommandParameter(command, "vCard", ElementSerializer.SerializeElement(vcard));
                        command.ExecuteNonQuery();
                    }
                vcardsCache[user] = vcard;
            }
        }
示例#27
0
        public void SaveOfflineMessages(params Message[] messages)
        {
            if (messages == null)
            {
                throw new ArgumentNullException("messages");
            }
            if (messages.Length == 0)
            {
                return;
            }

            var batch = new List <ISqlInstruction>(messages.Length);
            var jids  = new List <Jid>();

            foreach (var m in messages)
            {
                if (m == null || !m.HasTo || string.IsNullOrEmpty(m.To.Bare))
                {
                    continue;
                }

                if (string.IsNullOrEmpty(m.Body) &&
                    string.IsNullOrEmpty(m.Subject) &&
                    string.IsNullOrEmpty(m.Thread) &&
                    m.Html == null)
                {
                    continue;
                }

                if (!jids.Contains(m.To))
                {
                    jids.Add(m.To);
                }

                if (m.XDelay == null)
                {
                    m.XDelay = new Delay();
                }
                if (m.XDelay.Stamp == default(DateTime))
                {
                    m.XDelay.Stamp = DateTime.UtcNow;
                }

                batch.Add(
                    new SqlInsert("jabber_offmessage")
                    .InColumnValue("jid", GetBareJid(m.To))
                    .InColumnValue("message", ElementSerializer.SerializeElement(m)));

                lock (countCache) countCache.Remove(GetBareJid(m.To));
            }
            ExecuteBatch(batch);

            if (enableSignalr == "true" && jids.Count > 0)
            {
                Dictionary <string, int> unreadCounts = new Dictionary <string, int>();
                string domain = null;
                foreach (var jid in jids)
                {
                    int count = GetOfflineMessagesCount(jid);
                    if (count > 0)
                    {
                        domain = jid.Server;
                        unreadCounts.Add(jid.User, count);
                    }
                }
                if (unreadCounts.Count > 0)
                {
                    signalrServiceClient.SendUnreadCounts(unreadCounts, domain);
                }
            }
        }
示例#28
0
 public List <Message> GetOfflineMessages(Jid jid)
 {
     return(ExecuteList(new SqlQuery("jabber_offmessage").Select("message").Where("jid", GetBareJid(jid)).OrderBy("id", true))
            .ConvertAll(r => ElementSerializer.DeSerializeElement <Message>((string)r[0])));
 }
示例#29
0
        public void SetVCard(string user, Vcard vcard)
        {
            if (string.IsNullOrEmpty(user))
            {
                throw new ArgumentNullException("user");
            }
            if (vcard == null)
            {
                throw new ArgumentNullException("vcard");
            }
            if (CoreContext.UserManager.IsUserNameExists(user))
            {
                throw new JabberForbiddenException();
            }

            try
            {
                lock (vcardsCache)
                {
                    ExecuteNonQuery("insert or replace into VCard(UserName, VCard) values (@userName, @vCard)",
                                    new[] { "userName", "vCard" }, new object[] { user, ElementSerializer.SerializeElement(vcard) }
                                    );
                    vcardsCache[user] = vcard;
                }
            }
            catch (Exception e)
            {
                throw new JabberServiceUnavailableException("Could not set vcard", e);
            }
        }