public async Task <MTObject> Handle(IMessageContext <TLGetState> context) { MTObject result = null; var session = manager .GetSession(context.AuthKey()); var user = await session.GetUser(); try { result = new TLState { Date = MTServer.Instance.Services.Utils().ToTelegramDate(DateTime.UtcNow), Pts = user.UserData.Pts, Qts = 0, Seq = user.UserData.Seq, UnreadCount = 0 }; } catch (Exception err) { this.logger.LogError( $"An error occured while trying to handle GetState: \r\n{err.GetBaseException().Message}"); } return(result); }
public TransportMessage AddMessage(MTObject message, bool isContentRelated, bool isReply) { var msg_id = (long)this.NewMessageId(isReply); var seq = (int)this.GetNextMessageSequenceNumber(isContentRelated); byte[] content = new byte[] { }; if (message.GetType() == typeof(MTRpcResult)) { content = message.ToByteArray(); } else { content = message.ToByteArray(); // Utils.compress(message.ToByteArray()); } var _message = new TransportMessage { MsgId = msg_id, Seqno = seq, Bytes = content.Length, Body = new MTGzipPacked { PackedData = content } }; this.GetMessageQueue().AddMessage(_message); return(_message); }
public bool TryCreateResponseMessage(MTObject resp, ulong server_salt, ulong session_id, out byte[] encr, out byte[] messagekey, bool encrypt) { return(TryCreateResponseMessage(resp.ToByteArray(), server_salt, session_id, out encr, out messagekey, encrypt)); using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream)) { int c_alignment = 16; int c_v2_minimumPadding = 12; /// Write Header /// //writer.Write(session.GetServerSalt()); writer.Write(server_salt); writer.Write(session_id); //writer.Write(session.SessionId()); var id = NewMessageId(true); writer.Write(id); var seq = GetNextMessageSequenceNumber(true); writer.Write(seq); var content = resp.ToByteArray(); writer.Write(content.Length); writer.Write(content); var packageLength = writer.BaseStream.Length; #if USE_MTProto_V1 #else var padding = c_alignment - (packageLength % c_alignment); if (padding < c_v2_minimumPadding) { padding = padding += c_alignment; } if (padding > 0) { var paddingbytes = new byte[padding]; new Random().NextBytes(paddingbytes); writer.Write(paddingbytes); } var key = GetServerKeyPart(); writer.Flush(); writer.Close(); var decryptedData = stream.ToArray(); messagekey = SHA256.Create().ComputeHash(key.Concat(decryptedData).ToArray()).Skip(8).Take(16).ToArray(); var keys = MTProto.NET.Server.Infrastructure.Encryption.Helpers.Legacy.Helpers.CalcKey_2(GetAuthKey(), messagekey, false); var encrypted = MTProto.NET.Server.Infrastructure.Encryption.Helpers.Legacy.AES.EncryptAES(keys, decryptedData); if (encrypt) { encr = encrypted; } else { encr = decryptedData; } return(true); #endif } }
public byte[] Serialize(MTObject data) { using (var s = new MemoryStream()) using (var w = new BinaryWriter(s)) { Serialize(data, w); w.Close(); return(s.ToArray()); } }
private MTObject Accept(IAuthorizationSession session, MTPQInnerData req) { MTObject result = null; var m_dhPrime = session.DhGetPrime(); var m_a = session.NewDh_ma(); var m_g = session.Dh_mg(); var m_gA = new BigInteger(m_g.ToString()).ModPow(m_a, new BigInteger(1, m_dhPrime)); session.Data.SetNewNoce(req.NewNonce); session.Data.SetDh_ma(m_a); session.Data.Set_mgA(m_gA); var data = new MTServerDhInnerData(); data.ServerTime = (int)(DateTimeHelper.CurrentMsecsFromEpoch() / 1000ul); data.Nonce = req.Nonce; data.ServerNonce = req.ServerNonce; data.G = m_g; data.DhPrime = m_dhPrime; data.GA = m_gA.ToByteArray(); var inner_data = data.ToByteArray(); var sha = inner_data.sha1(); var length = sha.Length + inner_data.Length; byte[] padding = new byte[] { }; if (length % 16 != 0) { padding = new byte[16 - (length % 16)]; } try { var message = sha.Concat(inner_data).Concat(padding).ToArray(); var encryptedAnswer = session.EncryptWithServerNonce(req.ServerNonce.ToByteArray() , req.NewNonce.ToByteArray() , message); result = new MTServerDhParamsOk { EncryptedAnswer = encryptedAnswer, Nonce = req.Nonce, ServerNonce = req.ServerNonce }; } catch (Exception err) { this.logger.LogDebug( $"An error occured while trying to accept 'ReqDHParams': {err.Message}"); } return(result); }
public async Task <MTObject> Handle(IMessageContext <TLUpdateProfile> context) { MTObject result = null; try { var session = manager.GetSession(context.AuthKey()); if (session == null) { throw new Exception("Session not found!"); } var userId = session.GetUserId(); var profile = context.Body; var data = await this.profileService.UpdateProfile(userId, profile.FirstName, profile.LastName, profile.About); if (data != null) { result = new MTProto.NET.Schema.Layer72.TLUser { FirstName = data.FirstName, LastName = data.LastName, Id = data.Id, Self = true }; } else { result = new TLUserEmpty { }; } } catch (Exception err) { this.logger.LogError( "An error occured while trying to handle 'UpdateProfile': \r\n{0}", err.GetBaseException().Message); throw; } return(result); }
public async Task <MTObject> Handle(IMessageContext <TLGetHistory> context) { await Task.CompletedTask; MTObject result = null; try { var chats = new TLVector <TLAbsChat>(); var messages = new TLVector <TLAbsMessage>(); var users = new TLVector <TLAbsUser>(); var session = this.manager.GetSession(context.AuthKey()); if (session == null) { throw new Exception("Session not found."); } var request = context.Body; if (request == null) { throw new ArgumentException(nameof(TLGetHistory)); } if (request.Peer == null) { throw new ArgumentException(nameof(TLGetHistory.Peer)); } if (request.Peer is TLInputPeerUser) { var _messages = (await session.ChatManager.GetPrivateChatMessages(session.GetUserId(), (request.Peer as TLInputPeerUser).UserId)) .OrderByDescending(x => x.Data.Date); _messages.Select(x => new NET.Schema.Layer72.TLMessage { Message = x.Data.Message, FromId = x.Data.FromId, Id = x.Data.Id, Date = x.Data.Date, ToId = new TLPeerUser { UserId = x.Data.ToPeerId, } }).ToList().ForEach(x => messages.Add(x)); foreach (var m in _messages) { if (m.Data.FromId.HasValue && m.Data.FromId != session.GetUserId() && !users.Any(x => (x as MTProto.NET.Schema.Layer72.TLUser)?.Id == m.Data.FromId)) { using (var user_store = session.Services.Store().GetUserStore()) { var __user = await user_store.GetUserById(m.Data.FromId.Value); if (__user != null) { users.Add(new MTProto.NET.Schema.Layer72.TLUser { Id = __user.Id, FirstName = string.IsNullOrWhiteSpace(__user.FirstName)? $"{__user.Id}":__user.FirstName, Phone = __user.Phone, }); } } } } } else { throw new NotImplementedException(); } //users.Add(new NET.Schema.Layer72.TLUser //{ // Id = session.GetUserId(), // FirstName = "Babak", // Self = true //}); result = new TLMessages() { Messages = messages, // new TLVector<TLAbsMessage> { }, Chats = chats, Users = users }; } catch (Exception err) { this.logger.LogError( $"An error occured while trying to handle GetHistoryRequest. Error:\r\n{err.GetBaseException().Message}"); throw; } return(result); }
public void Write(MTObject @object) { MTObjectSerializer.Serialize(@object, this); }
public void Serialize(MTObject data, BinaryWriter writer) { MTProto.NET.Serializers.MTObjectSerializer.Serialize(data, writer); }
public static byte[] ToByteArray(this MTObject data) { return(MTServer.Services.Serialization().Serialize(data)); }