public Task LeaveParty(BubbleGroup group) { return(Task.Factory.StartNew(() => { var inputUser = new InputUser { UserId = Settings.AccountId }; using (var client = new FullClientDisposable(this)) { if (!group.IsExtendedParty) { var update = TelegramUtils.RunSynchronously(client.Client.Methods.MessagesDeleteChatUserAsync(new MessagesDeleteChatUserArgs { ChatId = uint.Parse(group.Address), UserId = inputUser, })); SendToResponseDispatcher(update, client.Client); } else { var update = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsLeaveChannelAsync(new ChannelsLeaveChannelArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) } })); SendToResponseDispatcher(update, client.Client); } } })); }
private List <IChannelParticipant> GetChannelParticipants(ChannelFull channelFull, IChannelParticipantsFilter filter) { var participantsList = new List <IChannelParticipant>(); using (var client = new FullClientDisposable(this)) { uint count = 100; uint offset = 0; var result = (ChannelsChannelParticipants)TelegramUtils.RunSynchronously( client.Client.Methods.ChannelsGetParticipantsAsync(new ChannelsGetParticipantsArgs { Channel = new InputChannel { ChannelId = channelFull.Id, AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(channelFull.Id)) }, Filter = filter, Limit = 100, Offset = offset })); participantsList.AddRange(result.Participants); _dialogs.AddUsers(result.Users); } return(participantsList); }
public Task SetPartyAddNewMembersRestriction(BubbleGroup group, PartyOptionsSettingsAddNewMembersRestriction restriction, Action <bool> result) { return(Task.Factory.StartNew(() => { using (var client = new FullClientDisposable(this)) { try { var response = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsToggleInvitesAsync(new ChannelsToggleInvitesArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, Enabled = restriction == PartyOptionsSettingsAddNewMembersRestriction.Everyone })); SendToResponseDispatcher(response, client.Client); result(true); } catch (Exception e) { DebugPrint("##### Exeption while setting all members are admins type " + e); result(false); } } })); }
private bool CheckLink(string linkUsefulPart, out IChat alreadyJoinedChat) { using (var client = new FullClientDisposable(this)) { try { var result = TelegramUtils.RunSynchronously(client.Client.Methods.MessagesCheckChatInviteAsync(new MessagesCheckChatInviteArgs { Hash = linkUsefulPart })); var chatInvite = result as ChatInvite; var chatInviteAlready = result as ChatInviteAlready; if (chatInvite != null) { alreadyJoinedChat = null; return(true); } if (chatInviteAlready != null) { alreadyJoinedChat = chatInviteAlready.Chat; return(true); } alreadyJoinedChat = null; return(false); } catch (Exception ex) { DebugPrint("Exception while checking invite" + ex); alreadyJoinedChat = null; return(false); } } }
public Task SetPartyDescription(BubbleGroup group, string description, Action <bool> result) { return(Task.Factory.StartNew(() => { if (description != null) { using (var client = new FullClientDisposable(this)) { var edited = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsEditAboutAsync(new ChannelsEditAboutArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, About = description })); if (edited) { result(true); } else { result(false); } } } })); }
public Task UnblockPartyParticipant(BubbleGroup group, DisaParticipant participant, Action<bool> result) { return Task.Factory.StartNew(() => { using (var client = new FullClientDisposable(this)) { try { var response = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsKickFromChannelAsync(new ChannelsKickFromChannelArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, Kicked = false, UserId = new InputUser { UserId = uint.Parse(participant.Address), AccessHash = GetUserAccessHashIfForeign(participant.Address) } })); result(true); } catch (Exception e) { DebugPrint("#### Exception " + e); result(false); } } }); }
public Task UnblockPartyParticipant(BubbleGroup group, DisaParticipant participant, Action <bool> result) { return(Task.Factory.StartNew(() => { using (var client = new FullClientDisposable(this)) { try { var response = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsKickFromChannelAsync(new ChannelsKickFromChannelArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, Kicked = false, UserId = new InputUser { UserId = uint.Parse(participant.Address), AccessHash = GetUserAccessHashIfForeign(participant.Address) } })); result(true); } catch (Exception e) { DebugPrint("#### Exception " + e); result(false); } } })); }
public Task GetBotCallbackAnswer(BubbleGroup group, VisualBubble bubble, Bots.KeyboardButton button, Action <Bots.MessagesBotCallbackAnswer> answer) { return(Task.Factory.StartNew(() => { using (var client = new FullClientDisposable(this)) { // Note: Telegram also has KeyboardButtonGame which functions as a callback also if (button is Bots.KeyboardButtonCallback) { var keyboardButtonCallback = button as Bots.KeyboardButtonCallback; var args = new MessagesGetBotCallbackAnswerArgs { MsgId = uint.Parse(bubble.IdService), Data = keyboardButtonCallback.Data, Peer = GetInputPeer(group.Address, group.IsParty, group.IsExtendedParty) }; SharpTelegram.Schema.MessagesBotCallbackAnswer telegramBotCallbackAnswer = (SharpTelegram.Schema.MessagesBotCallbackAnswer) TelegramUtils.RunSynchronously( client.Client.Methods.MessagesGetBotCallbackAnswerAsync(args)); var disaBotCallbackAnswer = new Bots.MessagesBotCallbackAnswer { Alert = telegramBotCallbackAnswer.Alert != null ? true : false, Message = telegramBotCallbackAnswer.Message }; answer(disaBotCallbackAnswer); } } })); }
public Task SetPartyName(BubbleGroup group, string name) { return(Task.Factory.StartNew(() => { using (var client = new FullClientDisposable(this)) { if (!group.IsExtendedParty) { var update = TelegramUtils.RunSynchronously( client.Client.Methods.MessagesEditChatTitleAsync(new MessagesEditChatTitleArgs { ChatId = uint.Parse(group.Address), Title = name, })); SendToResponseDispatcher(update, client.Client); } else { var update = TelegramUtils.RunSynchronously( client.Client.Methods.ChannelsEditTitleAsync(new ChannelsEditTitleArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, Title = name })); SendToResponseDispatcher(update, client.Client); } } })); }
public Task SignMessages(BubbleGroup group, bool sign, Action <bool> result) { return(Task.Factory.StartNew(() => { using (var client = new FullClientDisposable(this)) { try { var response = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsToggleSignaturesAsync(new ChannelsToggleSignaturesArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, Enabled = sign })); SendToResponseDispatcher(response, client.Client); result(true); } catch (Exception e) { DebugPrint("## exception while migrating the chat " + e); result(false); } } })); }
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); } })); }
public Task DemotePartyParticipantsFromLeader(BubbleGroup group, DisaParticipant participant, Action <DemotePartyParticipantsResult> result) { return(Task.Factory.StartNew(() => { var inputUser = new InputUser { UserId = uint.Parse(participant.Address), AccessHash = GetUserAccessHashIfForeign(participant.Address) }; using (var client = new FullClientDisposable(this)) { if (!group.IsExtendedParty) { if (!ChatAdminsEnabled(group.Address)) { result(DemotePartyParticipantsResult.AllMembersAreAdministratorsEnabled); return; } try { TelegramUtils.RunSynchronously(client.Client.Methods.MessagesEditChatAdminAsync(new MessagesEditChatAdminArgs { ChatId = uint.Parse(group.Address), IsAdmin = false, UserId = inputUser, })); result(DemotePartyParticipantsResult.Success); } catch (Exception e) { result(DemotePartyParticipantsResult.Failure); } } else { try { var response = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsEditAdminAsync(new ChannelsEditAdminArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, Role = new ChannelRoleEmpty(), UserId = inputUser })); SendToResponseDispatcher(response, client.Client); result(DemotePartyParticipantsResult.Success); } catch (Exception e) { result(DemotePartyParticipantsResult.Failure); } } } })); }
public Task GetPrivacyList(Action <string[]> addresses) { List <string> addressList; return(Task.Factory.StartNew(() => { uint offset = 0; //TODO: check when it returns a chunk or a full list using (var client = new FullClientDisposable(this)) { Again: var blocked = TelegramUtils.RunSynchronously( client.Client.Methods.ContactsGetBlockedAsync(new ContactsGetBlockedArgs { Limit = 100, Offset = offset })); var contactsBlocked = blocked as ContactsBlocked; var contactsBlockedSlice = blocked as ContactsBlockedSlice; addressList = new List <string>(); if (contactsBlocked != null) { foreach (var blockedContact in contactsBlocked.Blocked) { var contactBlocked = blockedContact as ContactBlocked; if (contactBlocked == null) { continue; } addressList.Add(contactBlocked.UserId.ToString(CultureInfo.InvariantCulture)); } _dialogs.AddUsers(contactsBlocked.Users); } if (contactsBlockedSlice != null) { foreach (var blockedContact in contactsBlockedSlice.Blocked) { var contactBlocked = blockedContact as ContactBlocked; if (contactBlocked == null) { continue; } addressList.Add(contactBlocked.UserId.ToString(CultureInfo.InvariantCulture)); } _dialogs.AddUsers(contactsBlockedSlice.Users); if (contactsBlockedSlice.Blocked.Any()) { offset += contactsBlockedSlice.Count; goto Again; } } previousAddresses = addressList.ToArray(); addresses(addressList.ToArray()); } })); }
public Task GetContactsFavorites(Action <List <Contact> > result) { return(Task.Factory.StartNew(async() => { var count = 0; var inputUsers = new List <IInputUser>(); foreach (var bubbleGroup in BubbleGroupManager.SortByMostPopular(this, true)) { var address = bubbleGroup.Address; foreach (var user in _dialogs.Users) { var userId = TelegramUtils.GetUserId(user); if (userId == address) { var inputUser = TelegramUtils.CastUserToInputUser(user); if (inputUser != null) { inputUsers.Add(inputUser); break; } } } count++; if (count > 6) { break; } } if (!inputUsers.Any()) { result(null); } else { using (var client = new FullClientDisposable(this)) { var users = await GetUsers(inputUsers, client.Client); var contacts = users.Select(x => new TelegramContact { Available = TelegramUtils.GetAvailable(x), LastSeen = TelegramUtils.GetLastSeenTime(x), FirstName = TelegramUtils.GetUserName(x), Ids = new List <Contact.ID> { new Contact.ID { Service = this, Id = TelegramUtils.GetUserId(x).ToString(CultureInfo.InvariantCulture) } }, }).OfType <Contact>().OrderBy(x => x.FirstName).ToList(); result(contacts); } } })); }
public Task SetPrivacyList(string[] addresses) { return(Task.Factory.StartNew(() => { using (var client = new FullClientDisposable(this)) { if (addresses.Length < previousAddresses.Length) { //address was removed foreach (var address in previousAddresses) { if (addresses.Contains(address)) { continue; } TelegramUtils.RunSynchronously( client.Client.Methods.ContactsUnblockAsync(new ContactsUnblockArgs { Id = new InputUser { UserId = uint.Parse(address), AccessHash = GetUserAccessHashIfForeign(address) } })); break; } } else //address was added { foreach (var address in addresses) { if (previousAddresses.Contains(address)) { continue; } TelegramUtils.RunSynchronously( client.Client.Methods.ContactsBlockAsync(new ContactsBlockArgs { Id = new InputUser { UserId = uint.Parse(address), AccessHash = GetUserAccessHashIfForeign(address) } })); break; } } } ServiceEvents.RaisePrivacyListUpdated(); previousAddresses = addresses; })); }
private MessagesChatFull FetchFullChat(string address, bool superGroup) { //Classic check lock check pattern for concurrent access from all the methods if (_fullChat != null) { return(_fullChat); } lock (_fullChatLock) { if (_fullChat != null) { return(_fullChat); } using (var client = new FullClientDisposable(this)) { if (!superGroup) { _fullChat = (MessagesChatFull) TelegramUtils.RunSynchronously( client.Client.Methods.MessagesGetFullChatAsync(new MessagesGetFullChatArgs { ChatId = uint.Parse(address) })); } else { try { _fullChat = (MessagesChatFull) TelegramUtils.RunSynchronously( client.Client.Methods.ChannelsGetFullChannelAsync(new ChannelsGetFullChannelArgs { Channel = new InputChannel { ChannelId = uint.Parse(address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(address))) } })); } catch (Exception e) { DebugPrint(">>>> get full channel exception " + e); } } //DebugPrint("#### fullchat " + ObjectDumper.Dump(_fullChat)); _dialogs.AddUsers(_fullChat.Users); _dialogs.AddChats(_fullChat.Chats); return(_fullChat); } } }
public Task SetPartyPhoto(BubbleGroup group, byte[] bytes, Action <DisaThumbnail> result) { return(Task.Factory.StartNew(() => { //MessagesEditChatPhotoAsync byte[] resizedImage = Platform.GenerateJpegBytes(bytes, 640, 640); var inputFile = UploadPartyImage(resizedImage); using (var client = new FullClientDisposable(this)) { if (!group.IsExtendedParty) { var update = TelegramUtils.RunSynchronously( client.Client.Methods.MessagesEditChatPhotoAsync(new MessagesEditChatPhotoArgs { ChatId = uint.Parse(group.Address), Photo = new InputChatUploadedPhoto { Crop = new InputPhotoCropAuto(), File = inputFile } })); SendToResponseDispatcher(update, client.Client); } else { //ChannelsEditPhoto var update = TelegramUtils.RunSynchronously( client.Client.Methods.ChannelsEditPhotoAsync(new ChannelsEditPhotoArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, Photo = new InputChatUploadedPhoto { Crop = new InputPhotoCropAuto(), File = inputFile } })); SendToResponseDispatcher(update, client.Client); } } byte[] disaImage = Platform.GenerateJpegBytes(bytes, 96, 96); var thumbnail = new DisaThumbnail(this, disaImage, GenerateRandomId().ToString()); result(thumbnail); })); }
public Task SetPrivacyList(string[] addresses) { return Task.Factory.StartNew(() => { using (var client = new FullClientDisposable(this)) { if (addresses.Length < previousAddresses.Length) { //address was removed foreach (var address in previousAddresses) { if (addresses.Contains(address)) { continue;} TelegramUtils.RunSynchronously( client.Client.Methods.ContactsUnblockAsync(new ContactsUnblockArgs { Id = new InputUser { UserId = uint.Parse(address) } })); break; } } else //address was added { foreach (var address in addresses) { if (previousAddresses.Contains(address)) { continue; } TelegramUtils.RunSynchronously( client.Client.Methods.ContactsBlockAsync(new ContactsBlockArgs { Id = new InputUser { UserId = uint.Parse(address) } })); break; } } } ServiceEvents.RaisePrivacyListUpdated(); previousAddresses = addresses; }); }
private IExportedChatInvite ExportChatInvite(BubbleGroup group) { using (var client = new FullClientDisposable(this)) { var response = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsExportInviteAsync(new ChannelsExportInviteArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) } })); return(response); } }
public Task SetPartyType(BubbleGroup group, PartyOptionsSettingsPartyType type, Action <bool> result) { return(Task.Factory.StartNew(() => { try { if (type == PartyOptionsSettingsPartyType.Public) { var randomUserName = RandomString(32); DebugPrint("The random username is " + randomUserName); using (var client = new FullClientDisposable(this)) { var response = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsUpdateUsernameAsync(new SharpTelegram.Schema.ChannelsUpdateUsernameArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, Username = randomUserName })); result(response); } } else { using (var client = new FullClientDisposable(this)) { var response = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsUpdateUsernameAsync(new SharpTelegram.Schema.ChannelsUpdateUsernameArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, Username = "" })); result(response); } } } catch (Exception e) { DebugPrint("##### Exeption while setting group type " + e); result(false); } })); }
private bool SetChannelUserName(BubbleGroup group, string name) { using (var client = new FullClientDisposable(this)) { var response = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsUpdateUsernameAsync(new ChannelsUpdateUsernameArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, Username = name })); return(response); } }
private IMessagesMessages GetMessageHistory(string address, bool isParty, bool isExtendedParty, long fromTime, int max) { using (var client = new FullClientDisposable(this)) { var peer = GetInputPeer(address, isParty, isExtendedParty); var response = TelegramUtils.RunSynchronously( client.Client.Methods.MessagesGetHistoryAsync(new MessagesGetHistoryArgs { Peer = peer, OffsetDate = (uint) fromTime, Limit = (uint) max })); return response; } }
public Task DeletePartyParticipant(BubbleGroup group, DisaParticipant participant) { return(Task.Factory.StartNew(() => { var inputUser = new InputUser { UserId = uint.Parse(participant.Address), AccessHash = GetUserAccessHashIfForeign(participant.Address) }; using (var client = new FullClientDisposable(this)) { if (!group.IsExtendedParty) { var update = TelegramUtils.RunSynchronously(client.Client.Methods.MessagesDeleteChatUserAsync(new MessagesDeleteChatUserArgs { ChatId = uint.Parse(group.Address), UserId = inputUser, })); SendToResponseDispatcher(update, client.Client); } else { try { var update = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsKickFromChannelAsync(new ChannelsKickFromChannelArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, Kicked = true, UserId = inputUser })); SendToResponseDispatcher(update, client.Client); } catch (Exception e) { DebugPrint("Exception " + e); } } } })); }
private ContactsResolvedPeer ResolvePeer(string path) { using (var client = new FullClientDisposable(this)) { try { var result = (ContactsResolvedPeer)TelegramUtils.RunSynchronously(client.Client.Methods.ContactsResolveUsernameAsync(new ContactsResolveUsernameArgs { Username = path })); return(result); } catch (Exception e) { DebugPrint("Exception while resolving peer" + e); return(null); } } }
public Task PromotePartyParticipantToLeader(BubbleGroup group, DisaParticipant participant) { return(Task.Factory.StartNew(() => { var inputUser = new InputUser { UserId = uint.Parse(participant.Address), AccessHash = GetUserAccessHashIfForeign(participant.Address) }; using (var client = new FullClientDisposable(this)) { if (!ChatAdminsEnabled(group.Address)) { //this condition should ideally never be hit // if chat admins are disabled, everyone is an admin and hence the ui never allows anyone to be promoted to an admin } if (!group.IsExtendedParty) { TelegramUtils.RunSynchronously(client.Client.Methods.MessagesEditChatAdminAsync(new MessagesEditChatAdminArgs { ChatId = uint.Parse(group.Address), IsAdmin = true, UserId = inputUser, })); } else { TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsEditAdminAsync(new ChannelsEditAdminArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, Role = new ChannelRoleModerator(), UserId = inputUser })); } } })); }
private IInputFile UploadPartyImage(byte[] resizedImage) { var fileId = GenerateRandomId(); const int chunkSize = 65536; var chunk = new byte[chunkSize]; uint chunkNumber = 0; var offset = 0; using (var memoryStream = new MemoryStream(resizedImage)) { using (var client = new FullClientDisposable(this)) { int bytesRead; while ((bytesRead = memoryStream.Read(chunk, 0, chunk.Length)) > 0) { //RPC call var uploaded = TelegramUtils.RunSynchronously( client.Client.Methods.UploadSaveFilePartAsync(new UploadSaveFilePartArgs { Bytes = chunk, FileId = fileId, FilePart = chunkNumber })); if (!uploaded) { return(null); } chunkNumber++; offset += bytesRead; } return(new InputFile { Id = fileId, Md5Checksum = "", Name = GenerateRandomId() + ".jpeg", Parts = chunkNumber }); } } }
public Task GetPrivacyList(Action<string[]> addresses) { List<string> addressList; return Task.Factory.StartNew(() => { //TODO: check when it returns a chunk or a full list using (var client = new FullClientDisposable(this)) { var blocked = TelegramUtils.RunSynchronously( client.Client.Methods.ContactsGetBlockedAsync(new ContactsGetBlockedArgs { Limit = 100, Offset = 0 })); var contactsBlocked = blocked as ContactsBlocked; var contatsBlockedSlice = blocked as ContactsBlockedSlice; addressList = new List<string>(); if (contactsBlocked != null) { foreach (var blockedContact in contactsBlocked.Blocked) { var contactBlocked = blockedContact as ContactBlocked; if (contactBlocked == null) continue; addressList.Add(contactBlocked.UserId.ToString(CultureInfo.InvariantCulture)); } } if (contatsBlockedSlice != null) { foreach (var blockedContact in contatsBlockedSlice.Blocked) { var contactBlocked = blockedContact as ContactBlocked; if (contactBlocked == null) continue; addressList.Add(contactBlocked.UserId.ToString(CultureInfo.InvariantCulture)); } } previousAddresses = addressList.ToArray(); addresses(addressList.ToArray()); } }); }
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); } } } })); }
private IUpdates JoinChat(string linkUsefulPart) { using (var client = new FullClientDisposable(this)) { try { var result = TelegramUtils.RunSynchronously(client.Client.Methods.MessagesImportChatInviteAsync(new MessagesImportChatInviteArgs { Hash = linkUsefulPart })); SendToResponseDispatcher(result, client.Client); return(result); } catch (Exception e) { Utils.DebugPrint("Exception e " + e); return(null); } } }
private Tuple<bool,byte[]> GetThumbnailBytes(string id, string address, bool superGroup) { if (!Platform.HasInternetConnection()) { return Tuple.Create<bool, byte[]>(false, null); } if (id == null) { return Tuple.Create<bool,byte[]>(true,null); } using (var client = new FullClientDisposable(this)) { var iMessage = GetMessage(uint.Parse(id), client.Client, uint.Parse(address), superGroup); var message = iMessage as Message; if (message != null) { var messageMediaPhoto = message.Media as MessageMediaPhoto; if (messageMediaPhoto != null) { var bytes = GetCachedPhotoBytes(messageMediaPhoto.Photo); if (bytes == null) { //try to get bytes from the server var fileLocation = GetCachedPhotoFileLocation(messageMediaPhoto.Photo); DebugPrint(">>>> Filelocation " + ObjectDumper.Dump(fileLocation)); var bytesSecond = FetchFileBytes(fileLocation); if (bytesSecond != null) { return Tuple.Create(true, bytesSecond); } } return Tuple.Create(true, bytes); } } return Tuple.Create<bool, byte[]>(true, null); } }
public Task AddPartyParticipant(BubbleGroup group, DisaParticipant participant) { var inputUser = new InputUser { UserId = uint.Parse(participant.Address), AccessHash = GetUserAccessHashIfForeign(participant.Address) }; return(Task.Factory.StartNew(() => { using (var client = new FullClientDisposable(this)) { if (!group.IsExtendedParty) { var update = TelegramUtils.RunSynchronously(client.Client.Methods.MessagesAddChatUserAsync(new MessagesAddChatUserArgs { UserId = inputUser, ChatId = uint.Parse(group.Address), FwdLimit = 0 })); SendToResponseDispatcher(update, client.Client); } else { var update = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsInviteToChannelAsync(new ChannelsInviteToChannelArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, Users = new List <IInputUser> { inputUser } })); SendToResponseDispatcher(update, client.Client); } } })); }
public Task GetUserInformation(string address, Action<Disa.Framework.UserInformation> result) { return Task.Factory.StartNew(async () => { if (address == null) { return; } var user = _dialogs.GetUser(uint.Parse(address)); using (var client = new FullClientDisposable(this)) { var inputUser = TelegramUtils.CastUserToInputUser(user); var updatedUser = await GetUser(inputUser, client.Client); var name = TelegramUtils.GetUserName(updatedUser); var lastSeen = TelegramUtils.GetLastSeenTime(updatedUser); var presence = TelegramUtils.GetAvailable(updatedUser); var phoneNumber = TelegramUtils.GetUserPhoneNumber(updatedUser); if (string.IsNullOrWhiteSpace(name)) { result(null); //TODO: ensure this doesn't crash Disa return; } result(new UserInformation { Title = name, SubtitleType = string.IsNullOrWhiteSpace(phoneNumber) ? UserInformation.TypeSubtitle.Other : UserInformation.TypeSubtitle.PhoneNumber, Subtitle = string.IsNullOrWhiteSpace(phoneNumber) ? TelegramUtils.GetUserHandle(updatedUser) : TelegramUtils.ConvertTelegramPhoneNumberIntoInternational(phoneNumber), LastSeen = lastSeen, Presence = presence, }); } }); }
public Task GetUserInformation(string address, Action <Disa.Framework.UserInformation> result) { return(Task.Factory.StartNew(async() => { foreach (var user in _dialogs.Users) { var userId = TelegramUtils.GetUserId(user); if (userId == address) { using (var client = new FullClientDisposable(this)) { var inputUser = TelegramUtils.CastUserToInputUser(user); var updatedUser = await GetUser(inputUser, client.Client); var name = TelegramUtils.GetUserName(updatedUser); var lastSeen = TelegramUtils.GetLastSeenTime(updatedUser); var presence = TelegramUtils.GetAvailable(updatedUser); var phoneNumber = TelegramUtils.GetUserPhoneNumber(updatedUser); if (string.IsNullOrWhiteSpace(name)) { result(null); //TODO: ensure this doesn't crash Disa return; } result(new UserInformation { Title = name, SubtitleType = string.IsNullOrWhiteSpace(phoneNumber) ? UserInformation.TypeSubtitle.Other : UserInformation.TypeSubtitle.PhoneNumber, Subtitle = string.IsNullOrWhiteSpace(phoneNumber) ? address : TelegramUtils.ConvertTelegramPhoneNumberIntoInternational(phoneNumber), LastSeen = lastSeen, Presence = presence, }); return; } } } result(null); //TODO: ensure this doesn't crash Disa })); }
private Tuple <bool, byte[]> GetThumbnailBytes(string id, string address, bool superGroup) { if (!Platform.HasInternetConnection()) { return(Tuple.Create <bool, byte[]>(false, null)); } if (id == null) { return(Tuple.Create <bool, byte[]>(true, null)); } using (var client = new FullClientDisposable(this)) { var iMessage = GetMessage(uint.Parse(id), client.Client, uint.Parse(address), superGroup); var message = iMessage as Message; if (message != null) { var messageMediaPhoto = message.Media as MessageMediaPhoto; if (messageMediaPhoto != null) { var bytes = GetCachedPhotoBytes(messageMediaPhoto.Photo); if (bytes == null) { //try to get bytes from the server var fileLocation = GetCachedPhotoFileLocation(messageMediaPhoto.Photo); DebugPrint(">>>> Filelocation " + ObjectDumper.Dump(fileLocation)); var bytesSecond = FetchFileBytes(fileLocation); if (bytesSecond != null) { return(Tuple.Create(true, bytesSecond)); } } return(Tuple.Create(true, bytes)); } } return(Tuple.Create <bool, byte[]>(true, null)); } }
public Task GetUserInformation(string address, Action <Disa.Framework.UserInformation> result) { return(Task.Factory.StartNew(() => { if (address == null) { return; } var user = _dialogs.GetUser(uint.Parse(address)); using (var client = new FullClientDisposable(this)) { var name = TelegramUtils.GetUserName(user); var lastSeen = TelegramUtils.GetLastSeenTime(user); var presence = TelegramUtils.GetAvailable(user); var phoneNumber = TelegramUtils.GetUserPhoneNumber(user); if (string.IsNullOrWhiteSpace(name)) { result(null); //TODO: ensure this doesn't crash Disa return; } result(new UserInformation { Title = name, SubtitleType = string.IsNullOrWhiteSpace(phoneNumber) ? UserInformation.TypeSubtitle.Other : UserInformation.TypeSubtitle.PhoneNumber, Subtitle = string.IsNullOrWhiteSpace(phoneNumber) ? TelegramUtils.GetUserHandle(user) : TelegramUtils.ConvertTelegramPhoneNumberIntoInternational(phoneNumber), LastSeen = lastSeen, Presence = presence, UserHandle = TelegramUtils.GetUserHandle(user), }); } })); }
private void JoinChannelIfLeft(string id) { var channel = _dialogs.GetChat(uint.Parse(id)) as Channel; if (channel != null) { if (channel.Left != null) { using (var client = new FullClientDisposable(this)) { var updates = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsJoinChannelAsync(new ChannelsJoinChannelArgs { Channel = new InputChannel { ChannelId = uint.Parse(id), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(id))) } })); SendToResponseDispatcher(updates, client.Client); } } } }
public Task ConvertToExtendedParty(BubbleGroup group, Action<bool> result) { return Task.Factory.StartNew(() => { using (var client = new FullClientDisposable(this)) { try { var response = TelegramUtils.RunSynchronously(client.Client.Methods.MessagesMigrateChatAsync(new MessagesMigrateChatArgs { ChatId = uint.Parse(group.Address) })); SendToResponseDispatcher(response, client.Client); result(true); } catch (Exception e) { DebugPrint("## exception while migrating the chat " + e); result(false); } } }); }
public Task AddPartyParticipant(BubbleGroup group, DisaParticipant participant) { var inputUser = new InputUser { UserId = uint.Parse(participant.Address) }; return Task.Factory.StartNew(() => { using (var client = new FullClientDisposable(this)) { if (!group.IsExtendedParty) { var update = TelegramUtils.RunSynchronously(client.Client.Methods.MessagesAddChatUserAsync(new MessagesAddChatUserArgs { UserId = inputUser, ChatId = uint.Parse(group.Address), FwdLimit = 0 })); SendToResponseDispatcher(update, client.Client); } else { var update = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsInviteToChannelAsync(new ChannelsInviteToChannelArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, Users = new List<IInputUser> { inputUser } })); SendToResponseDispatcher(update, client.Client); } } }); }
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) { result(true, contacts[0].Item2.Id); } else { var telegramContact = contacts[0].Item1 as TelegramContact; _dialogs.AddUser(telegramContact.User); result(true, contacts[0].Item2.Id); } } }); }
public Task DemotePartyParticipantsFromLeader(BubbleGroup group, DisaParticipant participant, Action<DemotePartyParticipantsResult> result) { return Task.Factory.StartNew(() => { var inputUser = new InputUser { UserId = uint.Parse(participant.Address), AccessHash = GetUserAccessHashIfForeign(participant.Address) }; using (var client = new FullClientDisposable(this)) { if (!group.IsExtendedParty) { if (!ChatAdminsEnabled(group.Address)) { result(DemotePartyParticipantsResult.AllMembersAreAdministratorsEnabled); return; } try { TelegramUtils.RunSynchronously(client.Client.Methods.MessagesEditChatAdminAsync(new MessagesEditChatAdminArgs { ChatId = uint.Parse(group.Address), IsAdmin = false, UserId = inputUser, })); result(DemotePartyParticipantsResult.Success); } catch (Exception e) { result(DemotePartyParticipantsResult.Failure); } } else { try { var response = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsEditAdminAsync(new ChannelsEditAdminArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, Role = new ChannelRoleEmpty(), UserId = inputUser })); SendToResponseDispatcher(response, client.Client); result(DemotePartyParticipantsResult.Success); } catch (Exception e) { result(DemotePartyParticipantsResult.Failure); } } } }); }
private IExportedChatInvite ExportChatInvite(BubbleGroup group) { using (var client = new FullClientDisposable(this)) { var response = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsExportInviteAsync(new ChannelsExportInviteArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) } })); return response; } }
public OptionalClientDisposable(Telegram telegram, TelegramClient optionalClient = null) { _optionalClient = optionalClient; if (_optionalClient == null) { _fullClient = new FullClientDisposable(telegram); } }
private IMessage GetMessage(uint messageId, TelegramClient optionalClient, uint senderId = 0, bool superGroup = false) { Func<TelegramClient,IMessage> fetch = client => { var messagesmessages = FetchMessage(messageId, client, senderId, superGroup); var messages = TelegramUtils.GetMessagesFromMessagesMessages(messagesmessages); var chats = TelegramUtils.GetChatsFromMessagesMessages(messagesmessages); var users = TelegramUtils.GetUsersFromMessagesMessages(messagesmessages); _dialogs.AddUsers(users); _dialogs.AddChats(chats); if (messages != null && messages.Count > 0) { return messages[0]; } return null; }; if (optionalClient != null) { return fetch(optionalClient); } else { using (var client = new FullClientDisposable(this)) { return fetch(client.Client); } } }
private void SendContact(ContactBubble contactBubble) { var inputPeer = GetInputPeer(contactBubble.Address, contactBubble.Party, contactBubble.ExtendedParty); var contactCard = Platform.GenerateContactCardFromBytes(contactBubble.VCardData); if (contactCard != null) { using (var client = new FullClientDisposable(this)) { var updates = TelegramUtils.RunSynchronously( client.Client.Methods.MessagesSendMediaAsync(new MessagesSendMediaArgs { Flags = 0, Peer = inputPeer, Media = new InputMediaContact { FirstName = contactCard.GivenName, LastName = contactCard.FamilyName, PhoneNumber = contactCard.Phones?.FirstOrDefault()?.Number }, RandomId = GenerateRandomId(), })); var id = GetMessageId(updates); contactBubble.IdService = id; SendToResponseDispatcher(updates, client.Client); } } }
private byte[] FetchDocumentBytes(Document document, uint offset, uint limit) { if (document.DcId == _settings.NearestDcId) { using (var clientDisposable = new FullClientDisposable(this)) { return FetchDocumentBytes(clientDisposable.Client, document, offset, limit); } } else { try { if (cachedClient == null) { cachedClient = GetClient((int) document.DcId); } return FetchDocumentBytes(cachedClient, document, offset, limit); } catch (Exception ex) { DebugPrint("Failed to obtain client from DC manager: " + ex); return null; } } }
public override void RefreshPhoneBookContacts() { Utils.DebugPrint("Phone book contacts have been updated! Sending information to Telegram servers..."); var contacts = PhoneBook.PhoneBookContacts; var inputContacts = new List<IInputContact>(); foreach (var contact in contacts) { foreach (var phoneNumber in contact.PhoneNumbers) { var clientId = "0"; if (contact.ContactId != null) { clientId = contact.ContactId; } inputContacts.Add(new InputPhoneContact { ClientId = ulong.Parse(clientId), Phone = phoneNumber.Number, FirstName = contact.FirstName, LastName = contact.LastName, }); } } if (!inputContacts.Any()) { Utils.DebugPrint("There are no input contacts!"); return; } try { using (var client = new FullClientDisposable(this)) { var importedContacts = TelegramUtils.RunSynchronously(client.Client.Methods.ContactsImportContactsAsync( new ContactsImportContactsArgs { Contacts = inputContacts, Replace = false, })); var contactsImportedcontacts = importedContacts as ContactsImportedContacts; if (contactsImportedcontacts != null) { _dialogs.AddUsers(contactsImportedcontacts.Users); } //invalidate the cache contactsCache = new List<User>(); } } catch (Exception ex) { Utils.DebugPrint("Failed to update contacts: " + ex); } }
private IUser GetUser(string id) { lock (_quickUserLock) { try { using (var client = new FullClientDisposable(this)) { var inputUser = new InputUser(); inputUser.UserId = uint.Parse(id); var inputList = new List<IInputUser>(); inputList.Add(inputUser); DebugPrint(">>>> inputlist " + ObjectDumper.Dump(inputList)); var users = TelegramUtils.RunSynchronously( client.Client.Methods.UsersGetUsersAsync(new UsersGetUsersArgs { Id = inputList, })); DebugPrint(">>>> get users response " + ObjectDumper.Dump(users)); var user = users.FirstOrDefault(); return user; } } catch (Exception e) { DebugPrint(">>>>>> exception " + e); return null; } } }
private void SendFile(VisualBubble bubble, IInputFile inputFile) { var inputPeer = GetInputPeer(bubble.Address, bubble.Party, bubble.ExtendedParty); var imageBubble = bubble as ImageBubble; var fileBubble = bubble as FileBubble; var audioBubble = bubble as AudioBubble; using (var client = new FullClientDisposable(this)) { if (imageBubble != null) { var iUpdates = TelegramUtils.RunSynchronously( client.Client.Methods.MessagesSendMediaAsync(new MessagesSendMediaArgs { Flags = 0, Peer = inputPeer, Media = new InputMediaUploadedPhoto { Caption = "", File = inputFile, }, RandomId = GenerateRandomId(), })); var messageId = GetMessageId(iUpdates); imageBubble.IdService = messageId; var updates = iUpdates as Updates; SendToResponseDispatcher(iUpdates, client.Client); } else if (fileBubble != null) { var documentAttributes = new List<IDocumentAttribute> { new DocumentAttributeFilename { FileName = fileBubble.FileName } }; var iUpdates = TelegramUtils.RunSynchronously( client.Client.Methods.MessagesSendMediaAsync(new MessagesSendMediaArgs { Flags = 0, Peer = inputPeer, Media = new InputMediaUploadedDocument { Attributes = documentAttributes, Caption = "", File = inputFile, MimeType = fileBubble.MimeType, }, RandomId = GenerateRandomId(), })); var messageId = GetMessageId(iUpdates); fileBubble.IdService = messageId; SendToResponseDispatcher(iUpdates, client.Client); } else if (audioBubble != null) { var documentAttributes = new List<IDocumentAttribute>(); if (audioBubble.Recording) { documentAttributes.Add(new DocumentAttributeAudio { Flags = 1024, Duration = (uint)audioBubble.Seconds, Voice = new True() }); } else if (audioBubble.FileName != null) { documentAttributes.Add(new DocumentAttributeAudio { Flags = 1, Duration = (uint)audioBubble.Seconds, Title = audioBubble.FileName }); } else { documentAttributes.Add(new DocumentAttributeAudio { Flags = 0, Duration = (uint)audioBubble.Seconds }); } var mimeType = Platform.GetMimeTypeFromPath(audioBubble.AudioPath); var inputMedia = new InputMediaUploadedDocument { Attributes = documentAttributes, Caption = "", File = inputFile, MimeType = mimeType, }; var media = new MessagesSendMediaArgs { Flags = 0, Media = inputMedia, Peer = inputPeer, RandomId = GenerateRandomId(), }; var iUpdates = TelegramUtils.RunSynchronously( client.Client.Methods.MessagesSendMediaAsync(media)); var messageId = GetMessageId(iUpdates); audioBubble.IdService = messageId; SendToResponseDispatcher(iUpdates, client.Client); } } }
private async Task<List<User>> FetchContacts() { if (contactsCache.Count != 0) { return contactsCache; } using (var client = new FullClientDisposable(this)) { var response = (ContactsContacts)await client.Client.Methods.ContactsGetContactsAsync( new ContactsGetContactsArgs { Hash = string.Empty }); contactsCache.AddRange(response.Users.OfType<User>().ToList()); _dialogs.AddUsers(response.Users); return contactsCache; } }
private IInputFile UploadFile(VisualBubble bubble, ulong fileId, long fileSize) { const int chunkSize = 65536; var chunk = new byte[chunkSize]; uint chunkNumber = 0; var offset = 0; using (var file = File.OpenRead(GetPathFromBubble(bubble))) { using (var client = new FullClientDisposable(this)) { int bytesRead; while ((bytesRead = file.Read(chunk, 0, chunk.Length)) > 0) { //RPC call var uploaded = TelegramUtils.RunSynchronously( client.Client.Methods.UploadSaveFilePartAsync(new UploadSaveFilePartArgs { Bytes = chunk, FileId = fileId, FilePart = chunkNumber })); if (!uploaded) { throw new Exception("The file chunk failed to be uploaded"); } chunkNumber++; offset += bytesRead; UpdateSendProgress(bubble, offset, fileSize); } return new InputFile { Id = fileId, Md5Checksum = "", Name = GetNameFromBubble(bubble), Parts = chunkNumber }; } } }
private IInputFile UploadBigFile(VisualBubble bubble, ulong fileId, long fileSize) { uint chunkSize = (uint)CalculateChunkSize(fileSize); var fileTotalParts = (uint)fileSize/chunkSize; if (fileSize % 1024 != 0) { fileTotalParts++; } var chunk = new byte[chunkSize]; uint chunkNumber = 0; var offset = 0; using (var file = File.OpenRead(GetPathFromBubble(bubble))) { using (var client = new FullClientDisposable(this)) { int bytesRead; while ((bytesRead = file.Read(chunk, 0, chunk.Length)) > 0) { var uploaded = TelegramUtils.RunSynchronously( client.Client.Methods.UploadSaveBigFilePartAsync(new UploadSaveBigFilePartArgs { Bytes = chunk, FileId = fileId, FilePart = chunkNumber, FileTotalParts = fileTotalParts, })); DebugPrint("Uploading File part " + chunkNumber + " of " + fileTotalParts); if (!uploaded) { throw new Exception("The file chunk failed to be uploaded"); } chunkNumber++; offset += bytesRead; UpdateSendProgress(bubble, offset, fileSize); } return new InputFileBig { Id = fileId, Name = GetNameFromBubble(bubble), Parts = chunkNumber }; } } }
private void SendGeoLocation(LocationBubble locationBubble) { var inputPeer = GetInputPeer(locationBubble.Address, locationBubble.Party, locationBubble.ExtendedParty); using (var client = new FullClientDisposable(this)) { var updates = TelegramUtils.RunSynchronously( client.Client.Methods.MessagesSendMediaAsync(new MessagesSendMediaArgs { Flags = 0, Peer = inputPeer, Media = new InputMediaGeoPoint { GeoPoint = new InputGeoPoint { Lat = locationBubble.Latitude, Long = locationBubble.Longitude } }, RandomId = GenerateRandomId(), })); var id = GetMessageId(updates); locationBubble.IdService = id; SendToResponseDispatcher(updates,client.Client); } }
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, 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); partyContacts.Add(new TelegramPartyContact { FirstName = name, Ids = new List<Contact.ID> { new Contact.PartyID { Service = this, Id = TelegramUtils.GetChatId(chat), ExtendedParty = chat is Channel } }, }); } if (string.IsNullOrWhiteSpace(query)) { result(partyContacts); } else { result(partyContacts.FindAll(x => Utils.Search(x.FullName, query))); } } }); }
private byte[] FetchFileBytes(FileLocation fileLocation,uint offset,uint limit) { if (fileLocation.DcId == _settings.NearestDcId) { using (var clientDisposable = new FullClientDisposable(this)) { return FetchFileBytes(clientDisposable.Client, fileLocation,offset,limit); } } else { try { var client = GetClient((int)fileLocation.DcId); return FetchFileBytes(client, fileLocation,offset,limit); } catch (Exception ex) { DebugPrint("Failed to obtain client from DC manager: " + ex); return null; } } }
private IUpdates JoinChat(string linkUsefulPart) { using (var client = new FullClientDisposable(this)) { try { var result = TelegramUtils.RunSynchronously(client.Client.Methods.MessagesImportChatInviteAsync(new MessagesImportChatInviteArgs { Hash = linkUsefulPart })); SendToResponseDispatcher(result, client.Client); return result; } catch (Exception e) { Utils.DebugPrint("Exception e " + e); return null; } } }
public override void SendBubble(Bubble b) { var presenceBubble = b as PresenceBubble; if (presenceBubble != null) { _hasPresence = presenceBubble.Available; SetFullClientPingDelayDisconnect(); using (var client = new FullClientDisposable(this)) { if (_hasPresence) { if (_mutableSettings.Date != 0) { // as thy come forth, thy shall get difference FetchDifference(client.Client); } var updatedUsers = GetUpdatedUsersOfAllDialogs(client.Client); if (updatedUsers != null) { foreach (var updatedUser in updatedUsers) { EventBubble(new PresenceBubble(Time.GetNowUnixTimestamp(), Bubble.BubbleDirection.Incoming, TelegramUtils.GetUserId(updatedUser), false, this, TelegramUtils.GetAvailable(updatedUser))); } } } SendPresence(client.Client); } } var typingBubble = b as TypingBubble; if (typingBubble != null) { var peer = GetInputPeer(typingBubble.Address, typingBubble.Party, typingBubble.ExtendedParty); using (var client = new FullClientDisposable(this)) { TelegramUtils.RunSynchronously(client.Client.Methods.MessagesSetTypingAsync( new MessagesSetTypingArgs { Peer = peer, Action = typingBubble.IsAudio ? (ISendMessageAction)new SendMessageRecordAudioAction() : (ISendMessageAction)new SendMessageTypingAction() })); } } var textBubble = b as TextBubble; if (textBubble != null) { var peer = GetInputPeer(textBubble.Address, textBubble.Party, textBubble.ExtendedParty); using (var client = new FullClientDisposable(this)) { var iUpdates = TelegramUtils.RunSynchronously( client.Client.Methods.MessagesSendMessageAsync(new MessagesSendMessageArgs { Flags = 0, Peer = peer, Message = textBubble.Message, RandomId = ulong.Parse(textBubble.IdService2) })); DebugPrint(">>>> IUpdates message sent " + ObjectDumper.Dump(iUpdates)); var updateShortSentMessage = iUpdates as UpdateShortSentMessage; if (updateShortSentMessage != null) { textBubble.IdService = updateShortSentMessage.Id.ToString(CultureInfo.InvariantCulture); } var updates = iUpdates as Updates; if (updates != null) { foreach (var update in updates.UpdatesProperty) { var updateNewChannelMessage = update as UpdateNewChannelMessage; if (updateNewChannelMessage == null) continue; var message = updateNewChannelMessage.Message as Message; if (message != null) { textBubble.IdService = message.Id.ToString(CultureInfo.InvariantCulture); } } } SendToResponseDispatcher(iUpdates, client.Client); } } var readBubble = b as ReadBubble; if (readBubble != null) { using (var client = new FullClientDisposable(this)) { var peer = GetInputPeer(readBubble.Address, readBubble.Party, readBubble.ExtendedParty); if (peer is InputPeerChannel) { TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsReadHistoryAsync(new ChannelsReadHistoryArgs { Channel = new InputChannel { ChannelId = uint.Parse(readBubble.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(readBubble.Address))) }, MaxId = 0 })); } else { var messagesAffectedMessages = TelegramUtils.RunSynchronously(client.Client.Methods.MessagesReadHistoryAsync( new MessagesReadHistoryArgs { Peer = peer, MaxId = 0, })) as MessagesAffectedMessages; if (messagesAffectedMessages != null) { SaveState(0, messagesAffectedMessages.Pts, 0, 0); } } } } var imageBubble = b as ImageBubble; if (imageBubble != null) { var fileId = GenerateRandomId(); try { var inputFile = UploadFile(imageBubble, fileId, 0); SendFile(imageBubble, inputFile); } catch (Exception e) { DebugPrint("File upload error " + e); throw; } } var fileBubble = b as FileBubble; if (fileBubble != null) { var fileId = GenerateRandomId(); try { var fileInfo = new FileInfo(fileBubble.Path); DebugPrint(">>>>>>> the size of the file is " + fileInfo.Length); if (fileInfo.Length <= 10485760) { var inputFile = UploadFile(fileBubble, fileId, fileInfo.Length); SendFile(fileBubble, inputFile); } else { var inputFile = UploadBigFile(fileBubble, fileId, fileInfo.Length); SendFile(fileBubble, inputFile); } } catch (Exception e) { DebugPrint("File upload error " + e); throw; } } var audioBubble = b as AudioBubble; if (audioBubble != null) { var fileId = GenerateRandomId(); try { var fileInfo = new FileInfo(audioBubble.AudioPath); DebugPrint(">>>>>>> the size of the file is " + fileInfo.Length); if (fileInfo.Length <= 10485760) { var inputFile = UploadFile(audioBubble, fileId, fileInfo.Length); SendFile(audioBubble, inputFile); } else { var inputFile = UploadBigFile(audioBubble, fileId, fileInfo.Length); SendFile(audioBubble, inputFile); } } catch (Exception e) { DebugPrint("File upload error " + e); throw; } } var locationBubble = b as LocationBubble; if (locationBubble != null) { SendGeoLocation(locationBubble); } var contactBubble = b as ContactBubble; if (contactBubble != null) { SendContact(contactBubble); } DebugPrint(">>>> Sending visual bubble " + ObjectDumper.Dump(b)); }
public Task SetPartyDescription(BubbleGroup group, string description, Action<bool> result) { return Task.Factory.StartNew(() => { if (description != null) { using (var client = new FullClientDisposable(this)) { var edited = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsEditAboutAsync(new ChannelsEditAboutArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, About = description })); if (edited) { result(true); } else { result(false); } } } }); }
private bool CheckLink(string linkUsefulPart, out IChat alreadyJoinedChat) { using (var client = new FullClientDisposable(this)) { try { var result = TelegramUtils.RunSynchronously(client.Client.Methods.MessagesCheckChatInviteAsync(new MessagesCheckChatInviteArgs { Hash = linkUsefulPart })); var chatInvite = result as ChatInvite; var chatInviteAlready = result as ChatInviteAlready; if (chatInvite != null) { alreadyJoinedChat = null; return true; } if (chatInviteAlready != null) { alreadyJoinedChat = chatInviteAlready.Chat; return true; } alreadyJoinedChat = null; return false; } catch (Exception ex) { DebugPrint("Exception while checking invite" + ex); alreadyJoinedChat = null; return false; } } }
private bool SetChannelUserName(BubbleGroup group, string name) { using (var client = new FullClientDisposable(this)) { var response = TelegramUtils.RunSynchronously(client.Client.Methods.ChannelsUpdateUsernameAsync(new ChannelsUpdateUsernameArgs { Channel = new InputChannel { ChannelId = uint.Parse(group.Address), AccessHash = TelegramUtils.GetChannelAccessHash(_dialogs.GetChat(uint.Parse(group.Address))) }, Username = name })); return response; } }
private ContactsResolvedPeer ResolvePeer(string path) { using (var client = new FullClientDisposable(this)) { try { var result = (ContactsResolvedPeer)TelegramUtils.RunSynchronously(client.Client.Methods.ContactsResolveUsernameAsync(new ContactsResolveUsernameArgs { Username = path })); return result; } catch (Exception e) { DebugPrint("Exception while resolving peer" + e); return null; } } }