Beispiel #1
0
        public IActionResult AuthWithTelegram([FromBody] TelegramAuthModel model)
        {
            // todo Validate telegram request
            var group = _repository.GetGroupByName(model.Group);

            if (group == null)
            {
                return(BadRequest(new { message = "Group not exist!" }));
            }
            var authReuqest = new AuthenticateRequestTelegram
            {
                GroupId      = group.Id,
                TelegramUser = model.TelegramUser
            };
            var authResult = _userSerice.AuthenticateWithTelegram(authReuqest, ipAddress());

            if (authResult == null)
            {
                return(BadRequest("Group is not match user group!"));
            }

            setTokenCookie(authResult.RefreshToken);

            return(Ok(new AuthentificateDto
            {
                Id = authResult.Student.Id,
                Group = authResult.Student.Group.Group_Name,
                Username = authResult.Student.Username,
                FirstName = authResult.Student.FirstName,
                LastName = authResult.Student.LastName,
                Token = authResult.JwtToken,
                RefreshToken = authResult.RefreshToken
            }));
        }
Beispiel #2
0
        public virtual async Task SendBigFileToContactTest()
        {
            TelegramClient client = this.NewClient();

            TelegramAuthModel authModel = new TelegramAuthModel()
            {
                ApiId   = this.ApiId,
                ApiHash = this.ApiHash
            };
            await client.AuthenticateAsync(authModel);

            TeleSharp.TL.Contacts.TLContacts result = await client.GetContactsAsync();

            TLUser user = result.Users
                          .OfType <TLUser>()
                          .FirstOrDefault(x => x.Phone == this.NumberToSendMessage);

            TLInputFileBig fileResult = (TLInputFileBig)await client.UploadFile("some.zip", new StreamReader("<some big file path>"));

            await client.SendUploadedDocument(
                new TLInputPeerUser()
            {
                UserId = user.Id
            },
                fileResult,
                "some zips",
                "application/zip",
                new TLVector <TLAbsDocumentAttribute>());
        }
Beispiel #3
0
        public virtual async Task DownloadFileFromWrongLocationTest()
        {
            TelegramClient client = this.NewClient();

            TelegramAuthModel authModel = new TelegramAuthModel()
            {
                ApiId   = this.ApiId,
                ApiHash = this.ApiHash
            };
            await client.AuthenticateAsync(authModel);

            TeleSharp.TL.Contacts.TLContacts result = await client.GetContactsAsync();

            TLUser user = result.Users
                          .OfType <TLUser>()
                          .FirstOrDefault(x => x.Id == 5880094);

            TLUserProfilePhoto photo         = ((TLUserProfilePhoto)user.Photo);
            TLFileLocation     photoLocation = (TLFileLocation)photo.PhotoBig;

            TeleSharp.TL.Upload.TLFile resFile = await client.GetFile(new TLInputFileLocation()
            {
                LocalId  = photoLocation.LocalId,
                Secret   = photoLocation.Secret,
                VolumeId = photoLocation.VolumeId
            }, 1024);

            TLAbsDialogs res = await client.GetUserDialogsAsync();

            Assert.IsTrue(resFile.Bytes.Length > 0);
        }
Beispiel #4
0
        public virtual async Task SendMessageByUserNameTest()
        {
            this.UserNameToSendMessage = ConfigurationManager.AppSettings[nameof(this.UserNameToSendMessage)];
            if (string.IsNullOrWhiteSpace(this.UserNameToSendMessage))
            {
                throw new Exception($"Please fill the '{nameof(this.UserNameToSendMessage)}' setting in app.config file first");
            }

            TelegramClient client = this.NewClient();

            TelegramAuthModel authModel = new TelegramAuthModel()
            {
                ApiId   = this.ApiId,
                ApiHash = this.ApiHash
            };
            await client.AuthenticateAsync(authModel);

            TeleSharp.TL.Contacts.TLFound result = await client.SearchUserAsync(this.UserNameToSendMessage);

            TLUser user = result.Users
                          .Where(x => x.GetType() == typeof(TLUser))
                          .OfType <TLUser>()
                          .FirstOrDefault(x => x.Username == this.UserNameToSendMessage.TrimStart('@'));

            if (user == null)
            {
                TeleSharp.TL.Contacts.TLContacts contacts = await client.GetContactsAsync();

                user = contacts.Users
                       .Where(x => x.GetType() == typeof(TLUser))
                       .OfType <TLUser>()
                       .FirstOrDefault(x => x.Username == this.UserNameToSendMessage.TrimStart('@'));
            }

            if (user == null)
            {
                throw new System.Exception("Username was not found: " + this.UserNameToSendMessage);
            }

            await client.SendTypingAsync(new TLInputPeerUser()
            {
                UserId = user.Id
            });

            Thread.Sleep(3000);
            await client.SendMessageAsync(new TLInputPeerUser()
            {
                UserId = user.Id
            }, "TEST");
        }
Beispiel #5
0
        public virtual async Task CheckPhones()
        {
            TelegramClient    client    = this.NewClient();
            TelegramAuthModel authModel = new TelegramAuthModel()
            {
                ApiId   = this.ApiId,
                ApiHash = this.ApiHash
            };
            await client.AuthenticateAsync(authModel);

            bool result = await client.IsPhoneRegisteredAsync(this.NumberToAuthenticate);

            Assert.IsTrue(result);
        }
Beispiel #6
0
        /// <summary>
        /// Authenticate to Telegram
        /// </summary>
        /// <param name="reconnect"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task AuthenticateAsync(
            TelegramAuthModel authModel,
            bool reconnect          = false,
            CancellationToken token = default)
        {
            if (authModel == null ||
                authModel.ApiId <= 0 ||
                string.IsNullOrWhiteSpace(authModel.ApiHash))
            {
                throw new ArgumentException($"Argument {nameof(authModel)} can't be null or contains empty properties. See https://core.telegram.org/api/obtaining_api_id");
            }

            token.ThrowIfCancellationRequested();

            if (this._session.AuthKey == null || reconnect)
            {
                Step3_Response result = await Authenticator.DoAuthentication(this.transport, token);

                this._session.AuthKey    = result.AuthKey;
                this._session.TimeOffset = result.TimeOffset;
            }

            this.sender = new MtProtoSender(this.transport, this._session);

            TLRequestGetConfig      config  = new TLRequestGetConfig();
            TLRequestInitConnection request = new TLRequestInitConnection()
            {
                ApiId         = apiId,
                AppVersion    = "1.0.0",
                DeviceModel   = "PC",
                LangCode      = "en",
                Query         = config,
                SystemVersion = "Win 10.0"
            };
            TLRequestInvokeWithLayer invokewithLayer = new TLRequestInvokeWithLayer()
            {
                Layer = 66,
                Query = request
            };

            await this.sender.Send(invokewithLayer, token);

            await this.sender.Receive(invokewithLayer, token);

            this.dcOptions = ((TLConfig)invokewithLayer.Response).DcOptions.ToList();
        }
Beispiel #7
0
        public virtual async Task DownloadFileFromContactTest()
        {
            TelegramClient client = this.NewClient();

            TelegramAuthModel authModel = new TelegramAuthModel()
            {
                ApiId   = this.ApiId,
                ApiHash = this.ApiHash
            };
            await client.AuthenticateAsync(authModel);

            TeleSharp.TL.Contacts.TLContacts result = await client.GetContactsAsync();

            TLUser user = result.Users
                          .OfType <TLUser>()
                          .FirstOrDefault(x => x.Phone == this.NumberToSendMessage);

            TLInputPeerUser inputPeer = new TLInputPeerUser()
            {
                UserId = user.Id
            };
            TLMessagesSlice res = await client.SendRequestAsync <TLMessagesSlice>(new TLRequestGetHistory()
            {
                Peer = inputPeer
            });

            TLDocument document = res.Messages
                                  .OfType <TLMessage>()
                                  .Where(m => m.Media != null)
                                  .Select(m => m.Media)
                                  .OfType <TLMessageMediaDocument>()
                                  .Select(md => md.Document)
                                  .OfType <TLDocument>()
                                  .First();

            TeleSharp.TL.Upload.TLFile resFile = await client.GetFile(
                new TLInputDocumentFileLocation()
            {
                AccessHash = document.AccessHash,
                Id         = document.Id,
                Version    = document.Version
            },
                document.Size);

            Assert.IsTrue(resFile.Bytes.Length > 0);
        }
Beispiel #8
0
        public virtual async Task SendMessageTest()
        {
            this.NumberToSendMessage = ConfigurationManager.AppSettings[nameof(this.NumberToSendMessage)];
            if (string.IsNullOrWhiteSpace(this.NumberToSendMessage))
            {
                throw new Exception($"Please fill the '{nameof(this.NumberToSendMessage)}' setting in app.config file first");
            }

            // this is because the contacts in the address come without the "+" prefix
            string normalizedNumber = this.NumberToSendMessage.StartsWith("+") ?
                                      this.NumberToSendMessage.Substring(1, this.NumberToSendMessage.Length - 1) :
                                      this.NumberToSendMessage;

            TelegramClient client = this.NewClient();

            TelegramAuthModel authModel = new TelegramAuthModel()
            {
                ApiId   = this.ApiId,
                ApiHash = this.ApiHash
            };
            await client.AuthenticateAsync(authModel);

            TeleSharp.TL.Contacts.TLContacts result = await client.GetContactsAsync();

            TLUser user = result.Users
                          .OfType <TLUser>()
                          .FirstOrDefault(x => x.Phone == normalizedNumber);

            if (user == null)
            {
                throw new System.Exception("Number was not found in Contacts List of user: "******"TEST");
        }
Beispiel #9
0
        public virtual async Task AuthUser()
        {
            TelegramClient client = this.NewClient();

            TelegramAuthModel authModel = new TelegramAuthModel()
            {
                ApiId   = this.ApiId,
                ApiHash = this.ApiHash
            };
            await client.AuthenticateAsync(authModel);

            string hash = await client.SendCodeRequestAsync(this.NumberToAuthenticate);

            string code = this.CodeToAuthenticate; // you can change code in debugger too

            if (String.IsNullOrWhiteSpace(code))
            {
                throw new Exception("CodeToAuthenticate is empty in the app.config file, fill it with the code you just got now by SMS/Telegram");
            }

            TLUser user = null;

            try
            {
                user = await client.MakeAuthAsync(this.NumberToAuthenticate, hash, code);
            }
            catch (CloudPasswordNeededException ex)
            {
                TeleSharp.TL.Account.TLPassword passwordSetting = await client.GetPasswordSetting();

                string password = this.PasswordToAuthenticate;

                user = await client.MakeAuthWithPasswordAsync(passwordSetting, password);
            }
            catch (InvalidPhoneCodeException ex)
            {
                throw new Exception("CodeToAuthenticate is wrong in the app.config file, fill it with the code you just got now by SMS/Telegram",
                                    ex);
            }
            Assert.IsNotNull(user);
            Assert.IsTrue(client.IsUserAuthorized());
        }
Beispiel #10
0
        public virtual async Task SendMessageToChannelTest()
        {
            TelegramClient client = this.NewClient();

            TelegramAuthModel authModel = new TelegramAuthModel()
            {
                ApiId   = this.ApiId,
                ApiHash = this.ApiHash
            };
            await client.AuthenticateAsync(authModel);

            TLDialogs dialogs = (TLDialogs)await client.GetUserDialogsAsync();

            TLChannel chat = dialogs.Chats
                             .OfType <TLChannel>()
                             .FirstOrDefault(c => c.Title == "TestGroup");

            await client.SendMessageAsync(new TLInputPeerChannel()
            {
                ChannelId = chat.Id, AccessHash = chat.AccessHash.Value
            }, "TEST MSG");
        }
Beispiel #11
0
        public virtual async Task SignUpNewUser()
        {
            TelegramClient    client    = this.NewClient();
            TelegramAuthModel authModel = new TelegramAuthModel()
            {
                ApiId   = this.ApiId,
                ApiHash = this.ApiHash
            };
            await client.AuthenticateAsync(authModel);

            string hash = await client.SendCodeRequestAsync(this.NotRegisteredNumberToSignUp);

            string code = "";

            TLUser registeredUser = await client.SignUpAsync(this.NotRegisteredNumberToSignUp, hash, code, "TLSharp", "User");

            Assert.IsNotNull(registeredUser);
            Assert.IsTrue(client.IsUserAuthorized());

            TLUser loggedInUser = await client.MakeAuthAsync(this.NotRegisteredNumberToSignUp, hash, code);

            Assert.IsNotNull(loggedInUser);
        }
Beispiel #12
0
        public virtual async Task SendPhotoToContactTest()
        {
            TelegramClient client = this.NewClient();

            TelegramAuthModel authModel = new TelegramAuthModel()
            {
                ApiId   = this.ApiId,
                ApiHash = this.ApiHash
            };
            await client.AuthenticateAsync(authModel);

            TeleSharp.TL.Contacts.TLContacts result = await client.GetContactsAsync();

            TLUser user = result.Users
                          .OfType <TLUser>()
                          .FirstOrDefault(x => x.Phone == this.NumberToSendMessage);

            TLInputFile fileResult = (TLInputFile)await client.UploadFile("cat.jpg", new StreamReader("data/cat.jpg"));

            await client.SendUploadedPhoto(new TLInputPeerUser()
            {
                UserId = user.Id
            }, fileResult, "kitty");
        }