Example #1
0
        private List <Contact> GetGlobalPartyContacts(ContactsFound contactsFound)
        {
            var globalContacts = new List <Contact>();

            _dialogs.AddChats(contactsFound.Chats);
            Utils.DebugPrint("Chats found " + ObjectDumper.Dump(contactsFound.Chats));
            foreach (var chat in contactsFound.Chats)
            {
                var name   = TelegramUtils.GetChatTitle(chat);
                var kicked = TelegramUtils.GetChatKicked(chat);
                if (kicked)
                {
                    continue;
                }
                globalContacts.Add(new TelegramPartyContact
                {
                    FirstName = name,
                    Ids       = new List <Contact.ID>
                    {
                        new Contact.PartyID
                        {
                            Service       = this,
                            Id            = TelegramUtils.GetChatId(chat),
                            ExtendedParty = chat is Channel
                        }
                    },
                });
            }
            return(globalContacts);
        }
Example #2
0
 public Task FetchBubbleGroupAddress(Tuple <Contact, Contact.ID>[] contacts, Action <bool, string> result)
 {
     return(Task.Factory.StartNew(async() =>
     {
         if (contacts.Length > 1)
         {
             var userContacts = await FetchContacts();
             var inputUsers = new List <IInputUser>();
             var names = new List <string>();
             foreach (var contact in contacts)
             {
                 names.Add(contact.Item1.FullName);
                 var id = uint.Parse(contact.Item2.Id);
                 foreach (var userContact in userContacts)
                 {
                     if (userContact.Id == id)
                     {
                         var inputUser = TelegramUtils.CastUserToInputUser(userContact);
                         if (inputUser != null)
                         {
                             inputUsers.Add(inputUser);
                             break;
                         }
                     }
                 }
             }
             if (inputUsers.Any())
             {
                 var subject = BubbleGroupUtils.GeneratePartyTitle(names.ToArray());
                 if (subject.Length > 25)
                 {
                     subject = subject.Substring(0, 22);
                     subject += "...";
                 }
                 using (var client = new FullClientDisposable(this))
                 {
                     var response = await client.Client.Methods.MessagesCreateChatAsync(
                         new MessagesCreateChatArgs
                     {
                         Users = inputUsers,
                         Title = subject,
                     });
                     ProcessIncomingPayload(response, true);
                     SaveState(response);
                     var chat = TelegramUtils.GetChatFromStatedMessage(response);
                     result(true, TelegramUtils.GetChatId(chat));
                 }
             }
             else
             {
                 result(false, null);
             }
         }
         else
         {
             result(true, contacts[0].Item2.Id);
         }
     }));
 }
Example #3
0
 /// <summary>
 /// Adds a chat or updates it if it already exists
 /// </summary>
 /// <param name="chat">chat to add or update</param>
 public void AddChat(IChat chat)
 {
     lock (_chatLock)
     {
         using (var database = new SqlDatabase <CachedChat>(GetDatabasePath(false)))
         {
             var chatId = TelegramUtils.GetChatId(chat);
             if (chatId == null)
             {
                 return;
             }
             CreateCachedChatAndAdd(chat, Convert.ToUInt32(chatId), database);
         }
     }
 }
Example #4
0
 /// <summary>
 /// Adds the users to the current map in memory and serilaizes it
 /// </summary>
 /// <param name="chats">List of IChat objects</param>
 public void AddChats(List <IChat> chats)
 {
     lock (_chatLock)
     {
         using (var database = new SqlDatabase <CachedChat>(GetDatabasePath(false)))
         {
             foreach (var chat in chats)
             {
                 var chatId = TelegramUtils.GetChatId(chat);
                 if (chatId == null)
                 {
                     continue;
                 }
                 CreateCachedChatAndAdd(chat, Convert.ToUInt32(chatId), database);
             }
         }
     }
 }
Example #5
0
        public Task FetchChannelBubbleGroupAddress(string name, string description, Action <bool, string> result)
        {
            return(Task.Factory.StartNew(async() =>
            {
                using (var client = new FullClientDisposable(this))
                {
                    try
                    {
                        var response = await client.Client.Methods.ChannelsCreateChannelAsync(new ChannelsCreateChannelArgs
                        {
                            Flags = 0,
                            Broadcast = null,
                            Megagroup = null,
                            Title = name,
                            About = description
                        });

                        var updates = response as Updates;
                        if (updates != null)
                        {
                            SendToResponseDispatcher(updates, client.Client);
                            _dialogs.AddChats(updates.Chats);
                            var chat = TelegramUtils.GetChatFromUpdate(updates);
                            result(true, TelegramUtils.GetChatId(chat));
                        }
                        else
                        {
                            result(false, null);
                        }
                    }
                    catch (Exception e)
                    {
                        //we get an exception if the user is not allowed to create groups
                        var rpcError = e as RpcErrorException;
                        if (rpcError != null)
                        {
                            result(false, null);
                        }
                    }
                }
            }));
        }
Example #6
0
 public Task FetchBubbleGroupAddress(Tuple <Contact, Contact.ID>[] contacts, Action <bool, string> result)
 {
     return(Task.Factory.StartNew(async() =>
     {
         if (contacts.Length > 1)
         {
             var inputUsers = new List <IInputUser>();
             var names = new List <string>();
             foreach (var contact in contacts)
             {
                 names.Add(contact.Item1.FullName);
                 var telegramContact = contact.Item1 as TelegramContact;
                 var inputUser = TelegramUtils.CastUserToInputUser(telegramContact.User);
                 if (inputUser != null)
                 {
                     inputUsers.Add(inputUser);
                 }
             }
             if (inputUsers.Any())
             {
                 var subject = BubbleGroupUtils.GeneratePartyTitle(names.ToArray());
                 if (subject.Length > 25)
                 {
                     subject = subject.Substring(0, 22);
                     subject += "...";
                 }
                 using (var client = new FullClientDisposable(this))
                 {
                     try
                     {
                         var response = await client.Client.Methods.MessagesCreateChatAsync(
                             new MessagesCreateChatArgs
                         {
                             Users = inputUsers,
                             Title = subject,
                         });
                         var updates = response as Updates;
                         if (updates != null)
                         {
                             SendToResponseDispatcher(updates, client.Client);
                             _dialogs.AddUsers(updates.Users);
                             _dialogs.AddChats(updates.Chats);
                             var chat = TelegramUtils.GetChatFromUpdate(updates);
                             result(true, TelegramUtils.GetChatId(chat));
                         }
                         else
                         {
                             result(false, null);
                         }
                     }
                     catch (Exception e)
                     {
                         //we get an exception if the user is not allowed to create groups
                         var rpcError = e as RpcErrorException;
                         if (rpcError != null)
                         {
                             result(false, null);
                         }
                     }
                 }
             }
             else
             {
                 result(false, null);
             }
         }
         else
         {
             if (contacts[0].Item2 is Contact.PartyID)
             {
                 JoinChannelIfLeft(contacts[0].Item2.Id);
                 result(true, contacts[0].Item2.Id);
             }
             else
             {
                 var telegramContact = contacts[0].Item1 as TelegramContact;
                 _dialogs.AddUser(telegramContact.User);
                 result(true, contacts[0].Item2.Id);
             }
         }
     }));
 }
Example #7
0
        Task INewMessage.GetContacts(string query, bool searchForParties, Action <List <Contact> > result)
        {
            Contract.Ensures(Contract.Result <Task>() != null);
            return(Task.Factory.StartNew(async() =>
            {
                if (!searchForParties)
                {
                    var users = await FetchContacts();
                    var contacts = users.Select(x =>
                                                new TelegramContact
                    {
                        Available = TelegramUtils.GetAvailable(x),
                        LastSeen = TelegramUtils.GetLastSeenTime(x),
                        FirstName = x.FirstName,
                        LastName = x.LastName,
                        User = x,
                        Ids = new List <Contact.ID>
                        {
                            new Contact.ID
                            {
                                Service = this,
                                Id = x.Id.ToString(CultureInfo.InvariantCulture)
                            }
                        },
                    }).OfType <Contact>().OrderBy(x => x.FirstName).ToList();
                    if (string.IsNullOrWhiteSpace(query))
                    {
                        result(contacts);
                    }
                    else
                    {
                        if (query.Length >= 5)
                        {
                            var localContacts = contacts.FindAll(x => Utils.Search(x.FullName, query));
                            using (var client = new FullClientDisposable(this))
                            {
                                var searchResult =
                                    TelegramUtils.RunSynchronously(
                                        client.Client.Methods.ContactsSearchAsync(new ContactsSearchArgs
                                {
                                    Q = query,
                                    Limit = 50         //like the official client
                                }));
                                var contactsFound = searchResult as ContactsFound;
                                var globalContacts = GetGlobalContacts(contactsFound);
                                localContacts.AddRange(globalContacts);
                            }
                            result(localContacts);
                        }
                        else
                        {
                            result(contacts.FindAll(x => Utils.Search(x.FullName, query)));
                        }
                    }
                }
                else
                {
                    var partyContacts = new List <Contact>();
                    foreach (var chat in _dialogs.GetAllChats())
                    {
                        var name = TelegramUtils.GetChatTitle(chat);
                        var upgraded = TelegramUtils.GetChatUpgraded(chat);
                        if (upgraded)
                        {
                            continue;
                        }
                        var left = TelegramUtils.GetChatLeft(chat);
                        if (left)
                        {
                            continue;
                        }
                        var kicked = TelegramUtils.GetChatKicked(chat);
                        if (kicked)
                        {
                            continue;
                        }
                        partyContacts.Add(new TelegramPartyContact
                        {
                            FirstName = name,
                            Ids = new List <Contact.ID>
                            {
                                new Contact.PartyID
                                {
                                    Service = this,
                                    Id = TelegramUtils.GetChatId(chat),
                                    ExtendedParty = chat is Channel
                                }
                            },
                        });
                    }

                    //partyContacts.Sort((x, y) => x.FullName.CompareTo(y.FullName));


                    if (string.IsNullOrWhiteSpace(query))
                    {
                        result(partyContacts);
                    }
                    else
                    {
                        if (query.Length >= 5)
                        {
                            var localContacts = partyContacts.FindAll(x => Utils.Search(x.FirstName, query));
                            using (var client = new FullClientDisposable(this))
                            {
                                var searchResult =
                                    TelegramUtils.RunSynchronously(
                                        client.Client.Methods.ContactsSearchAsync(new ContactsSearchArgs
                                {
                                    Q = query,
                                    Limit = 50         //like the official client
                                }));
                                var contactsFound = searchResult as ContactsFound;
                                var globalContacts = GetGlobalPartyContacts(contactsFound);
                                localContacts.AddRange(globalContacts);
                            }
                            result(localContacts);
                        }
                        else
                        {
                            var searchResult = partyContacts.FindAll(x => Utils.Search(x.FirstName, query));
                            result(searchResult);
                        }
                    }
                }
            }));
        }
Example #8
0
        public Task FetchBubbleGroupAddressFromLink(string link, Action <Tuple <Contact, Contact.ID> > result)
        {
            return(Task.Factory.StartNew(() =>
            {
                string linkUsefulPart;
                var linkType = GetLinkType(link, out linkUsefulPart);
                switch (linkType)
                {
                case LinkType.Invalid:
                    result(new Tuple <Contact, Contact.ID>(null, null));
                    break;

                case LinkType.PrivateGroup:
                    IChat alreadyJoinedChat;
                    bool linkCheck = CheckLink(linkUsefulPart, out alreadyJoinedChat);
                    if (linkCheck)
                    {
                        if (alreadyJoinedChat != null)
                        {
                            SetResultAsChat(alreadyJoinedChat, TelegramUtils.GetChatId(alreadyJoinedChat), result);
                            return;
                        }
                        var updates = JoinChat(linkUsefulPart);
                        var updatesObj = updates as Updates;
                        if (updatesObj != null)
                        {
                            var chatObj = updatesObj.Chats[0];
                            SetResultAsChat(chatObj, TelegramUtils.GetChatId(chatObj), result);
                        }
                    }
                    else
                    {
                        result(new Tuple <Contact, Contact.ID>(null, null));
                    }
                    break;

                case LinkType.PublicGroup:
                    JoinChannelIfLeft(linkUsefulPart);
                    var chat = _dialogs.GetChat(uint.Parse(linkUsefulPart));
                    SetResultAsChat(chat, linkUsefulPart, result);
                    break;

                case LinkType.PublicUser:
                    var user = _dialogs.GetUser(uint.Parse(linkUsefulPart));
                    var userObj = user as User;
                    var userContact = new TelegramContact
                    {
                        Available = TelegramUtils.GetAvailable(user),
                        LastSeen = TelegramUtils.GetLastSeenTime(user),
                        FirstName = userObj?.FirstName,
                        LastName = userObj?.LastName,
                        User = userObj,
                    };
                    var userContactId = new Contact.ID
                    {
                        Id = linkUsefulPart,
                        Service = this
                    };
                    result(new Tuple <Contact, Contact.ID>(userContact, userContactId));
                    break;

                default:
                    result(new Tuple <Contact, Contact.ID>(null, null));
                    break;
                }
            }));
        }
Example #9
0
        private List <Contact> GetGlobalPartyContacts(ContactsFound contactsFound, bool forChannels)
        {
            var globalContacts = new List <Contact>();

            _dialogs.AddChats(contactsFound.Chats);
            foreach (var chat in contactsFound.Chats)
            {
                var name   = TelegramUtils.GetChatTitle(chat);
                var kicked = TelegramUtils.GetChatKicked(chat);
                if (kicked)
                {
                    continue;
                }
                var channel = chat as Channel;

                if (forChannels)
                {
                    if (channel != null)
                    {
                        if (channel.Broadcast != null)
                        {
                            // it is a channel
                        }
                        else
                        {
                            continue;
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                else
                {
                    if (channel != null)
                    {
                        if (channel.Broadcast != null)
                        {
                            continue;
                        }
                        else
                        {
                            // it is not a channel
                        }
                    }
                    else
                    {
                        // it is not a channel
                    }
                }

                // Public channels require us knowing the AccessHash for them in order
                // to join them
                ulong channelAccessHash = 0;
                if (channel != null)
                {
                    channelAccessHash = channel.AccessHash;
                }

                globalContacts.Add(new TelegramPartyContact
                {
                    FirstName = name,
                    Ids       = new List <Contact.ID>
                    {
                        new Contact.PartyID
                        {
                            Service       = this,
                            Id            = TelegramUtils.GetChatId(chat),
                            ExtendedParty = channel != null,
                        }
                    },
                    AccessHash = channelAccessHash
                });
            }
            return(globalContacts);
        }
Example #10
0
        Task INewMessage.GetContacts(string query, bool searchForParties, Action <List <Contact> > result)
        {
            Contract.Ensures(Contract.Result <Task>() != null);
            return(Task.Factory.StartNew(async() =>
            {
                if (!searchForParties)
                {
                    var users = await FetchContacts();
                    var contacts = users.Select(x => CreateTelegramContact(x))
                                   .Where(x => !string.IsNullOrWhiteSpace(x.FirstName)).OfType <Contact>().OrderBy(x => x.FirstName).ToList();

                    if (string.IsNullOrWhiteSpace(query))
                    {
                        result(contacts);
                    }
                    else
                    {
                        if (query.Length >= 5)
                        {
                            var localContacts = contacts.FindAll(x => Utils.Search(x.FullName, query));
                            using (var client = new FullClientDisposable(this))
                            {
                                var searchResult =
                                    TelegramUtils.RunSynchronously(
                                        client.Client.Methods.ContactsSearchAsync(new ContactsSearchArgs
                                {
                                    Q = query,
                                    Limit = 50         //like the official client
                                }));
                                var contactsFound = searchResult as ContactsFound;
                                var globalContacts = GetGlobalContacts(contactsFound);
                                localContacts.AddRange(globalContacts);
                            }
                            result(localContacts);
                        }
                        else
                        {
                            result(contacts.FindAll(x => Utils.Search(x.FullName, query)));
                        }
                    }
                }
                else
                {
                    var partyContacts = new List <Contact>();

                    // Only grab disa solo, party and super groups.
                    // Important: Don't get confused between disa channels and telegram channels.
                    //            Telegram channels include both super groups and channels, differentiated
                    //            by the telegram Channel.Broadcast and Channel.Megagroup fields.

                    foreach (var chat in _dialogs.GetAllChats())
                    {
                        var name = TelegramUtils.GetChatTitle(chat);
                        var upgraded = TelegramUtils.GetChatUpgraded(chat);
                        if (upgraded)
                        {
                            continue;
                        }
                        var left = TelegramUtils.GetChatLeft(chat);
                        if (left)
                        {
                            continue;
                        }
                        var kicked = TelegramUtils.GetChatKicked(chat);
                        if (kicked)
                        {
                            continue;
                        }
                        var isChannel = chat is Channel;
                        if (isChannel)
                        {
                            var channel = chat as Channel;
                            if (channel.Megagroup == null)
                            {
                                continue;
                            }
                        }
                        partyContacts.Add(new TelegramPartyContact
                        {
                            FirstName = name,
                            Ids = new List <Contact.ID>
                            {
                                new Contact.PartyID
                                {
                                    Service = this,
                                    Id = TelegramUtils.GetChatId(chat),
                                    ExtendedParty = isChannel
                                }
                            },
                        });
                    }

                    if (string.IsNullOrWhiteSpace(query))
                    {
                        result(partyContacts.OrderBy(c => c.FirstName).ToList());
                    }
                    else
                    {
                        if (query.Length >= 5)
                        {
                            var localContacts = partyContacts.FindAll(x => Utils.Search(x.FirstName, query));
                            using (var client = new FullClientDisposable(this))
                            {
                                var searchResult =
                                    TelegramUtils.RunSynchronously(
                                        client.Client.Methods.ContactsSearchAsync(new ContactsSearchArgs
                                {
                                    Q = query,
                                    Limit = 50         //like the official client
                                }));
                                var contactsFound = searchResult as ContactsFound;
                                var globalContacts = GetGlobalPartyContacts(contactsFound: contactsFound, forChannels: false);
                                localContacts.AddRange(globalContacts);
                            }
                            result(localContacts.OrderBy(c => c.FirstName).ToList());
                        }
                        else
                        {
                            var searchResult = partyContacts.FindAll(x => Utils.Search(x.FirstName, query));
                            result(searchResult.OrderBy(c => c.FirstName).ToList());
                        }
                    }
                }
            }));
        }
Example #11
0
 public Task GetContacts(string query, bool searchForParties, Action <List <Contact> > result)
 {
     return(Task.Factory.StartNew(async() =>
     {
         if (!searchForParties)
         {
             var users = await FetchContacts();
             var contacts = users.Select(x =>
                                         new TelegramContact
             {
                 Available = TelegramUtils.GetAvailable(x),
                 LastSeen = TelegramUtils.GetLastSeenTime(x),
                 FirstName = x.FirstName,
                 LastName = x.LastName,
                 Ids = new List <Contact.ID>
                 {
                     new Contact.ID
                     {
                         Service = this,
                         Id = x.Id.ToString(CultureInfo.InvariantCulture)
                     }
                 },
             }).OfType <Contact>().OrderBy(x => x.FirstName).ToList();
             result(contacts);
         }
         else
         {
             var partyContacts = new List <Contact>();
             foreach (var iDialog in _dialogs.Dialogs)
             {
                 var dialog = iDialog as Dialog;
                 if (dialog == null)
                 {
                     continue;
                 }
                 var peerChat = dialog.Peer as PeerChat;
                 if (peerChat == null)
                 {
                     continue;
                 }
                 var peerChatId = peerChat.ChatId.ToString(CultureInfo.InvariantCulture);
                 string name = null;
                 foreach (var iChat in _dialogs.Chats)
                 {
                     var chatId = TelegramUtils.GetChatId(iChat);
                     if (chatId == peerChatId)
                     {
                         name = TelegramUtils.GetChatTitle(iChat);
                         break;
                     }
                 }
                 if (!string.IsNullOrWhiteSpace(name))
                 {
                     partyContacts.Add(new TelegramPartyContact
                     {
                         FirstName = name,
                         Ids = new List <Contact.ID>
                         {
                             new Contact.PartyID
                             {
                                 Service = this,
                                 Id = peerChatId,
                             }
                         },
                     });
                 }
             }
             result(partyContacts);
         }
     }));
 }
Example #12
0
        public Task FetchChannelBubbleGroup(Contact.ID[] contactIds, Action <BubbleGroup> result)
        {
            return(Task.Factory.StartNew(() =>
            {
                // Sanity check, we are currently only processing collections passed in with a cardinality of 1
                if (contactIds.Length != 1)
                {
                    result(null);
                    return;
                }

                foreach (var chat in _dialogs.GetAllChats())
                {
                    var name = TelegramUtils.GetChatTitle(chat);
                    var upgraded = TelegramUtils.GetChatUpgraded(chat);
                    if (upgraded)
                    {
                        continue;
                    }
                    var left = TelegramUtils.GetChatLeft(chat);
                    if (left)
                    {
                        continue;
                    }
                    var kicked = TelegramUtils.GetChatKicked(chat);
                    if (kicked)
                    {
                        continue;
                    }
                    var isChannel = chat is Channel;
                    if (isChannel)
                    {
                        var channel = chat as Channel;
                        if (channel.Broadcast == null)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        continue;
                    }

                    var channelAddress = TelegramUtils.GetChatId(chat);
                    if (BubbleGroupComparer(contactIds[0].Id, channelAddress))
                    {
                        var newBubble = new NewBubble(
                            time: Time.GetNowUnixTimestamp(),
                            direction: Bubble.BubbleDirection.Outgoing,
                            address: channelAddress,
                            participantAddress: null,
                            party: true,
                            service: this);
                        newBubble.ExtendedParty = true;

                        var newGroup = BubbleGroupFactory.AddNewIfNotExist(newBubble);
                        if (newGroup == null)
                        {
                            newGroup = BubbleGroupManager.FindWithAddress(this, channelAddress);
                        }

                        result(newGroup);

                        return;
                    }
                }

                // OK, we didn't get a channel locally, we must be trying to join a public channel
                using (var client = new FullClientDisposable(this))
                {
                    // A NewChannel flow will stuff away a Contact in the ContactId.Tag field
                    var telegramPartyContact = contactIds[0].Tag as TelegramPartyContact;
                    if (telegramPartyContact == null)
                    {
                        result(null);
                        return;
                    }

                    // Go for the public channel join
                    var response = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsJoinChannelAsync(new ChannelsJoinChannelArgs
                    {
                        Channel = new InputChannel
                        {
                            ChannelId = uint.Parse(contactIds[0].Id),
                            AccessHash = telegramPartyContact.AccessHash
                        }
                    }));

                    // Process the result and add in the new public channel to our local set of groups
                    var updates = response as Updates;
                    if (updates != null)
                    {
                        SendToResponseDispatcher(updates, client.Client);
                        _dialogs.AddChats(updates.Chats);
                        var chat = TelegramUtils.GetChatFromUpdate(updates);

                        var channelAddress = TelegramUtils.GetChatId(chat);

                        var newBubble = new NewBubble(
                            time: Time.GetNowUnixTimestamp(),
                            direction: Bubble.BubbleDirection.Outgoing,
                            address: channelAddress,
                            participantAddress: null,
                            party: true,
                            service: this);
                        newBubble.ExtendedParty = true;

                        var newGroup = BubbleGroupFactory.AddNew(newBubble);

                        result(newGroup);
                    }
                    else
                    {
                        result(null);
                    }
                }
            }));
        }