示例#1
0
        private static async Task <TlAbsInputFile> UploadFile(string name, StreamReader reader,
                                                              ITelegramClient client, bool isBigFileUpload)
        {
            var file      = GetFile(reader);
            var fileParts = GetFileParts(file);

            var partNumber = 0;
            var partsCount = fileParts.Count;
            var fileId     = BitConverter.ToInt64(TlHelpers.GenerateRandomBytes(8), 0);

            while (fileParts.Count != 0)
            {
                var part = fileParts.Dequeue();

                if (isBigFileUpload)
                {
                    await client.SendRequestAsync <bool>(new TlRequestSaveBigFilePart
                    {
                        FileId         = fileId,
                        FilePart       = partNumber,
                        Bytes          = part,
                        FileTotalParts = partsCount
                    });
                }
                else
                {
                    await client.SendRequestAsync <bool>(new TlRequestSaveFilePart
                    {
                        FileId   = fileId,
                        FilePart = partNumber,
                        Bytes    = part
                    });
                }
                partNumber++;
            }

            if (isBigFileUpload)
            {
                return new TlInputFileBig
                       {
                           Id    = fileId,
                           Name  = name,
                           Parts = partsCount
                       }
            }
            ;
            return(new TlInputFile
            {
                Id = fileId,
                Name = name,
                Parts = partsCount,
                Md5Checksum = GetFileHash(file)
            });
        }
    }
        public static async Task <string> SendCodeRequestAsync(this ITelegramClient client, string phoneNumber)
        {
            Guard.That(phoneNumber, nameof(phoneNumber)).IsNotNullOrWhiteSpace();

            var completed      = false;
            var clientSettings = client.GetSettings();

            var request = new TlRequestSendCode {
                PhoneNumber = phoneNumber, ApiId = clientSettings.AppId, ApiHash = clientSettings.AppHash
            };

            while (!completed)
            {
                try
                {
                    await client.SendRequestAsync <TlSentCode>(request);

                    completed = true;
                }
                catch (PhoneMigrationException ex)
                {
                    await client.ReconnectToDcAsync(ex.Dc);
                }
            }

            return(request.Response.PhoneCodeHash);
        }
        public static async Task <bool> IsPhoneRegisteredAsync(this ITelegramClient client, string phoneNumber)
        {
            Guard.That(phoneNumber, nameof(phoneNumber)).IsNotNullOrWhiteSpace();

            var authCheckPhoneRequest = new TlRequestCheckPhone {
                PhoneNumber = phoneNumber
            };
            var completed = false;

            while (!completed)
            {
                try
                {
                    await client.SendRequestAsync <TlRequestCheckPhone>(authCheckPhoneRequest);

                    completed = true;
                }
                catch (PhoneMigrationException e)
                {
                    await client.ReconnectToDcAsync(e.Dc);
                }
            }

            return(authCheckPhoneRequest.Response.PhoneRegistered);
        }
        public static async Task <TlPassword> GetPasswordSetting(this ITelegramClient client)
        {
            var request = new TlRequestGetPassword();

            await client.SendRequestAsync <TlPassword>(request);

            return((TlPassword)request.Response);
        }
        public async Task AddContact(string firstName, string lastName, string phone)
        {
            var contacts = new TlVector <TlInputPhoneContact>();

            contacts.Lists.Add(new TlInputPhoneContact {
                FirstName = firstName ?? String.Empty, LastName = lastName ?? String.Empty, Phone = phone ?? String.Empty
            });

            //Create request
            var req = new TlRequestImportContacts
            {
                Contacts = contacts
            };
            await _client.SendRequestAsync <TlImportedContacts>(req);

            //FillContacts();
        }
        public static async Task <TlFile> GetFile(this ITelegramClient client, TlAbsInputFileLocation location, int filePartSize, int offset = 0)
        {
            try
            {
                return(await client.SendRequestAsync <TlFile>(new TlRequestGetFile
                {
                    Location = location,
                    Limit = filePartSize,
                    Offset = offset
                }));
            }
            catch (FileMigrationException ex)
            {
                var exportedAuth =
                    await client.SendRequestAsync <TlExportedAuthorization>(new TlRequestExportAuthorization { DcId = ex.Dc });

                var clientSettings = client.GetSettings();
                Guard.That(clientSettings).IsNotNull();
                Guard.That(clientSettings.Session).IsNotNull();

                var authKey       = clientSettings.Session.AuthKey;
                var timeOffset    = clientSettings.Session.TimeOffset;
                var serverAddress = clientSettings.Session.ServerAddress;
                var serverPort    = clientSettings.Session.Port;

                await client.ReconnectToDcAsync(ex.Dc);

                await client.SendRequestAsync <TlAuthorization>(new TlRequestImportAuthorization
                {
                    Bytes = exportedAuth.Bytes,
                    Id    = exportedAuth.Id
                });

                var result = await client.GetFile(location, filePartSize, offset);

                clientSettings.Session.AuthKey       = authKey;
                clientSettings.Session.TimeOffset    = timeOffset;
                clientSettings.Session.ServerAddress = serverAddress;
                clientSettings.Session.Port          = serverPort;
                await client.ConnectAsync();

                return(result);
            }
        }
        public static async Task <bool> SendTypingAsync(this ITelegramClient client, TlAbsInputPeer peer)
        {
            var req = new TlRequestSetTyping
            {
                Action = new TlSendMessageTypingAction(),
                Peer   = peer
            };

            return(await client.SendRequestAsync <bool>(req));
        }
        /// <summary>
        ///     Serch user or chat. API: contacts.search#11f812d8 q:string limit:int = contacts.Found;
        /// </summary>
        /// <param name="q">User or chat name</param>
        /// <param name="limit">Max result count</param>
        /// <returns></returns>
        public static async Task <TlFound> SearchUserAsync(this ITelegramClient client, string q, int limit = 10)
        {
            var r = new TlRequestSearch
            {
                Q     = q,
                Limit = limit
            };

            return(await client.SendRequestAsync <TlFound>(r));
        }
        public static async Task <TlAbsDifference> GetUpdates(this ITelegramClient telegramClient, TlState currentState)
        {
            var getDiffRequest = new TlRequestGetDifference
            {
                Pts  = currentState.Pts,
                Qts  = currentState.Qts,
                Date = currentState.Date
            };

            return(await telegramClient.SendRequestAsync <TlAbsDifference>(getDiffRequest));
        }
        public static async Task <TlAbsDialogs> GetUserDialogsAsync(this ITelegramClient client, int limit = 100)
        {
            var getDialogs = new TlRequestGetDialogs
            {
                OffsetDate = 0,
                OffsetPeer = new TlInputPeerSelf(),
                Limit      = limit
            };

            return(await client.SendRequestAsync <TlAbsDialogs>(getDialogs));
        }
        public static async Task <TlContacts> GetContactsAsync(this ITelegramClient client)
        {
            if (!client.IsUserAuthorized())
            {
                throw new InvalidOperationException("Authorize user first!");
            }

            var req = new TlRequestGetContacts {
                Hash = ""
            };

            return(await client.SendRequestAsync <TlContacts>(req));
        }
 public static async Task <TlAbsUpdates> SendUploadedPhoto(this ITelegramClient client, TlAbsInputPeer peer,
                                                           TlAbsInputFile file, string caption)
 {
     return(await client.SendRequestAsync <TlAbsUpdates>(new TlRequestSendMedia
     {
         RandomId = TlHelpers.GenerateRandomLong(),
         Background = false,
         ClearDraft = false,
         Media = new TlInputMediaUploadedPhoto {
             File = file, Caption = caption
         },
         Peer = peer
     }));
 }
        public static async Task <TlAbsMessages> GetHistoryAsync(this ITelegramClient client, TlAbsInputPeer peer, int offset, int maxId, int limit)
        {
            if (!client.IsUserAuthorized())
            {
                throw new InvalidOperationException("Authorize user first!");
            }

            var req = new TlRequestGetHistory
            {
                Peer      = peer,
                AddOffset = offset,
                MaxId     = maxId,
                Limit     = limit
            };

            return(await client.SendRequestAsync <TlAbsMessages>(req));
        }
        public static async Task <TlUser> MakeAuthAsync(this ITelegramClient client, string phoneNumber, string phoneCodeHash, string code)
        {
            Guard.That(phoneNumber, nameof(phoneNumber)).IsNotNullOrWhiteSpace();
            Guard.That(phoneCodeHash, nameof(phoneCodeHash)).IsNotNullOrWhiteSpace();
            Guard.That(code, nameof(code)).IsNotNullOrWhiteSpace();

            var request = new TlRequestSignIn
            {
                PhoneNumber   = phoneNumber,
                PhoneCodeHash = phoneCodeHash,
                PhoneCode     = code
            };

            await client.SendRequestAsync <TlAuthorization>(request);

            OnUserAuthenticated(client.Container, (TlUser)request.Response.User);

            return((TlUser)request.Response.User);
        }
        public static async Task <TlUser> SignUpAsync(this ITelegramClient client, string phoneNumber, string phoneCodeHash, string code, string firstName,
                                                      string lastName)
        {
            Guard.That(client.Container).IsNotNull();

            var request = new TlRequestSignUp
            {
                PhoneNumber   = phoneNumber,
                PhoneCode     = code,
                PhoneCodeHash = phoneCodeHash,
                FirstName     = firstName,
                LastName      = lastName
            };
            await client.SendRequestAsync <TlAuthorization>(request);

            OnUserAuthenticated(client.Container, (TlUser)request.Response.User);

            return((TlUser)request.Response.User);
        }
        public static async Task <TlUser> MakeAuthWithPasswordAsync(this ITelegramClient client, TlPassword password, string passwordStr)
        {
            var passwordBytes = Encoding.UTF8.GetBytes(passwordStr);
            var rv            = password.CurrentSalt.Concat(passwordBytes).Concat(password.CurrentSalt);

            byte[] passwordHash;
            using (var sha = SHA256.Create())
            {
                passwordHash = sha.ComputeHash(rv.ToArray());
            }

            var request = new TlRequestCheckPassword {
                PasswordHash = passwordHash
            };
            await client.SendRequestAsync <TlAuthorization>(request);

            OnUserAuthenticated(client.Container, (TlUser)request.Response.User);

            return((TlUser)request.Response.User);
        }
 public static async Task <TlAbsUpdates> SendUploadedDocument(
     this ITelegramClient client,
     TlAbsInputPeer peer,
     TlAbsInputFile file,
     string caption,
     string mimeType,
     TlVector <TlAbsDocumentAttribute> attributes)
 {
     return(await client.SendRequestAsync <TlAbsUpdates>(new TlRequestSendMedia
     {
         RandomId = TlHelpers.GenerateRandomLong(),
         Background = false,
         ClearDraft = false,
         Media = new TlInputMediaUploadedDocument
         {
             File = file,
             Caption = caption,
             MimeType = mimeType,
             Attributes = attributes
         },
         Peer = peer
     }));
 }
 public static async Task <TlState> GetCurrentState(this ITelegramClient telegramClient)
 {
     return(await telegramClient.SendRequestAsync <TlState>(new TlRequestGetState()));
 }