TLSharp/TLSharp.Core/TelegramClient.cs

424 lines
16 KiB
C#
Raw Normal View History

2015-09-28 04:01:17 +02:00
using System;
using System.Collections.Generic;
2015-09-28 04:01:17 +02:00
using System.Linq;
2016-11-16 14:31:00 +01:00
using System.Security.Cryptography;
using System.Text;
using System.Threading;
2015-09-28 04:01:17 +02:00
using System.Threading.Tasks;
2016-09-24 15:38:26 +02:00
using TeleSharp.TL;
2016-10-29 10:47:18 +02:00
using TeleSharp.TL.Account;
2016-09-24 15:38:26 +02:00
using TeleSharp.TL.Auth;
2016-10-11 15:28:57 +02:00
using TeleSharp.TL.Contacts;
2016-10-11 15:32:38 +02:00
using TeleSharp.TL.Help;
2016-10-11 15:28:57 +02:00
using TeleSharp.TL.Messages;
2016-10-23 12:29:18 +02:00
using TeleSharp.TL.Upload;
2016-10-11 15:32:38 +02:00
using TLSharp.Core.Auth;
using TLSharp.Core.Network;
using TLSharp.Core.Utils;
2016-10-29 10:47:18 +02:00
using TLAuthorization = TeleSharp.TL.Auth.TLAuthorization;
2015-09-28 04:01:17 +02:00
namespace TLSharp.Core
{
2016-12-15 21:02:23 +01:00
public class TelegramClient : IDisposable
2016-04-18 12:50:57 +02:00
{
private MtProtoSender _sender;
private TcpTransport _transport;
private readonly string _apiHash = "";
private readonly int _apiId;
private List<TLDcOption> _dcOptions;
private readonly TcpClientConnectionHandler _handler;
2016-07-20 08:26:55 +02:00
public Session Session { get; }
public TelegramClient(int apiId, string apiHash,
ISessionStore store = null, string sessionUserId = "session", TcpClientConnectionHandler handler = null)
2016-04-18 12:50:57 +02:00
{
if (apiId == default(int))
throw new MissingApiConfigurationException("API_ID");
if (string.IsNullOrEmpty(apiHash))
throw new MissingApiConfigurationException("API_HASH");
if (store == null)
store = new FileSessionStore();
2016-10-11 16:31:30 +02:00
_apiHash = apiHash;
_apiId = apiId;
_handler = handler;
Session = Session.TryLoadOrCreateNew(store, sessionUserId);
_transport = new TcpTransport(Session.DataCenter.Address, Session.DataCenter.Port, _handler);
2016-04-18 12:50:57 +02:00
}
public async Task ConnectAsync(bool reconnect = false, CancellationToken token = default(CancellationToken))
{
token.ThrowIfCancellationRequested();
if (Session.AuthKey == null || reconnect)
2016-04-18 12:50:57 +02:00
{
var result = await Authenticator.DoAuthentication(_transport, token).ConfigureAwait(false);
Session.AuthKey = result.AuthKey;
Session.TimeOffset = result.TimeOffset;
2016-04-18 12:50:57 +02:00
}
_sender = new MtProtoSender(_transport, Session);
2016-04-18 12:50:57 +02:00
//set-up layer
var config = new TLRequestGetConfig();
var request = new TLRequestInitConnection()
{
ApiId = _apiId,
AppVersion = "1.0.0",
DeviceModel = "PC",
LangCode = "en",
Query = config,
SystemVersion = "Win 10.0"
};
var invokewithLayer = new TLRequestInvokeWithLayer() { Layer = 66, Query = request };
await _sender.Send(invokewithLayer, token).ConfigureAwait(false);
await _sender.Receive(invokewithLayer, token).ConfigureAwait(false);
2016-04-18 12:50:57 +02:00
_dcOptions = ((TLConfig)invokewithLayer.Response).DcOptions.ToList();
2016-04-18 12:50:57 +02:00
}
private async Task ReconnectToDcAsync(int dcId, CancellationToken token)
2016-04-18 12:50:57 +02:00
{
token.ThrowIfCancellationRequested();
if (_dcOptions == null || !_dcOptions.Any())
2016-04-18 12:50:57 +02:00
throw new InvalidOperationException($"Can't reconnect. Establish initial connection first.");
2018-03-03 17:38:51 +01:00
TLExportedAuthorization exported = null;
if (Session.TLUser != null)
2018-03-03 17:38:51 +01:00
{
TLRequestExportAuthorization exportAuthorization = new TLRequestExportAuthorization() { DcId = dcId };
exported = await SendRequestAsync<TLExportedAuthorization>(exportAuthorization, token).ConfigureAwait(false);
2018-03-03 17:38:51 +01:00
}
2016-04-18 12:50:57 +02:00
var dc = _dcOptions.First(d => d.Id == dcId);
var dataCenter = new DataCenter (dcId, dc.IpAddress, dc.Port);
2016-04-18 12:50:57 +02:00
_transport = new TcpTransport(dc.IpAddress, dc.Port, _handler);
Session.DataCenter = dataCenter;
2016-04-18 12:50:57 +02:00
await ConnectAsync(true, token).ConfigureAwait(false);
2018-03-03 17:38:51 +01:00
if (Session.TLUser != null)
2018-03-03 17:38:51 +01:00
{
TLRequestImportAuthorization importAuthorization = new TLRequestImportAuthorization() { Id = exported.Id, Bytes = exported.Bytes };
var imported = await SendRequestAsync<TLAuthorization>(importAuthorization, token).ConfigureAwait(false);
2018-03-03 17:38:51 +01:00
OnUserAuthenticated(((TLUser)imported.User));
}
2016-04-18 12:50:57 +02:00
}
private async Task RequestWithDcMigration(TLMethod request, CancellationToken token)
2018-03-03 17:38:51 +01:00
{
if (_sender == null)
2018-03-03 17:38:51 +01:00
throw new InvalidOperationException("Not connected!");
var completed = false;
while(!completed)
{
try
{
await _sender.Send(request, token).ConfigureAwait(false);
await _sender.Receive(request, token).ConfigureAwait(false);
completed = true;
}
catch(DataCenterMigrationException e)
{
if (Session.DataCenter.DataCenterId.HasValue &&
Session.DataCenter.DataCenterId.Value == e.DC)
{
throw new Exception($"Telegram server replied requesting a migration to DataCenter {e.DC} when this connection was already using this DataCenter", e);
}
await ReconnectToDcAsync(e.DC, token).ConfigureAwait(false);
// prepare the request for another try
request.ConfirmReceived = false;
}
2018-03-03 17:38:51 +01:00
}
}
2016-04-18 12:50:57 +02:00
public bool IsUserAuthorized()
{
return Session.TLUser != null;
2016-09-24 15:38:26 +02:00
}
public async Task<bool> IsPhoneRegisteredAsync(string phoneNumber, CancellationToken token = default(CancellationToken))
2016-09-24 15:38:26 +02:00
{
if (String.IsNullOrWhiteSpace(phoneNumber))
throw new ArgumentNullException(nameof(phoneNumber));
var authCheckPhoneRequest = new TLRequestCheckPhone() { PhoneNumber = phoneNumber };
await RequestWithDcMigration(authCheckPhoneRequest, token).ConfigureAwait(false);
return authCheckPhoneRequest.Response.PhoneRegistered;
2016-04-18 12:50:57 +02:00
}
public async Task<string> SendCodeRequestAsync(string phoneNumber, CancellationToken token = default(CancellationToken))
2016-04-18 12:50:57 +02:00
{
if (String.IsNullOrWhiteSpace(phoneNumber))
throw new ArgumentNullException(nameof(phoneNumber));
var request = new TLRequestSendCode() { PhoneNumber = phoneNumber, ApiId = _apiId, ApiHash = _apiHash };
2016-04-18 12:50:57 +02:00
await RequestWithDcMigration(request, token).ConfigureAwait(false);
2016-04-18 12:50:57 +02:00
return request.Response.PhoneCodeHash;
2016-04-18 12:50:57 +02:00
}
public async Task<TLUser> MakeAuthAsync(string phoneNumber, string phoneCodeHash, string code, CancellationToken token = default(CancellationToken))
2016-04-18 12:50:57 +02:00
{
if (String.IsNullOrWhiteSpace(phoneNumber))
throw new ArgumentNullException(nameof(phoneNumber));
if (String.IsNullOrWhiteSpace(phoneCodeHash))
throw new ArgumentNullException(nameof(phoneCodeHash));
if (String.IsNullOrWhiteSpace(code))
throw new ArgumentNullException(nameof(code));
2018-03-03 17:38:51 +01:00
var request = new TLRequestSignIn() { PhoneNumber = phoneNumber, PhoneCodeHash = phoneCodeHash, PhoneCode = code };
await RequestWithDcMigration(request, token).ConfigureAwait(false);
2016-01-17 10:16:44 +01:00
OnUserAuthenticated(((TLUser)request.Response.User));
2016-04-18 12:50:57 +02:00
return ((TLUser)request.Response.User);
2016-09-06 17:37:05 +02:00
}
public async Task<TLPassword> GetPasswordSetting(CancellationToken token = default(CancellationToken))
2016-11-16 14:31:00 +01:00
{
var request = new TLRequestGetPassword();
await RequestWithDcMigration(request, token).ConfigureAwait(false);
2016-11-16 14:31:00 +01:00
return ((TLPassword)request.Response);
}
public async Task<TLUser> MakeAuthWithPasswordAsync(TLPassword password, string password_str, CancellationToken token = default(CancellationToken))
{
token.ThrowIfCancellationRequested();
2016-11-16 14:31:00 +01:00
byte[] password_Bytes = Encoding.UTF8.GetBytes(password_str);
IEnumerable<byte> rv = password.CurrentSalt.Concat(password_Bytes).Concat(password.CurrentSalt);
2016-11-16 14:31:00 +01:00
SHA256Managed hashstring = new SHA256Managed();
var password_hash = hashstring.ComputeHash(rv.ToArray());
var request = new TLRequestCheckPassword() { PasswordHash = password_hash };
await RequestWithDcMigration(request, token).ConfigureAwait(false);
2016-11-16 14:31:00 +01:00
OnUserAuthenticated(((TLUser)request.Response.User));
2016-11-16 14:31:00 +01:00
return ((TLUser)request.Response.User);
2016-11-16 14:31:00 +01:00
}
2016-09-06 17:37:05 +02:00
public async Task<TLUser> SignUpAsync(string phoneNumber, string phoneCodeHash, string code, string firstName, string lastName, CancellationToken token = default(CancellationToken))
2016-09-24 15:38:26 +02:00
{
var request = new TLRequestSignUp() { PhoneNumber = phoneNumber, PhoneCode = code, PhoneCodeHash = phoneCodeHash, FirstName = firstName, LastName = lastName };
await RequestWithDcMigration(request, token).ConfigureAwait(false);
2016-04-18 12:50:57 +02:00
OnUserAuthenticated(((TLUser)request.Response.User));
2016-04-18 12:50:57 +02:00
return ((TLUser)request.Response.User);
2016-09-24 15:38:26 +02:00
}
public async Task<T> SendRequestAsync<T>(TLMethod methodToExecute, CancellationToken token = default(CancellationToken))
{
await RequestWithDcMigration(methodToExecute, token).ConfigureAwait(false);
2016-10-29 10:47:18 +02:00
var result = methodToExecute.GetType().GetProperty("Response").GetValue(methodToExecute);
return (T)result;
}
public async Task<TLContacts> GetContactsAsync(CancellationToken token = default(CancellationToken))
{
if (!IsUserAuthorized())
throw new InvalidOperationException("Authorize user first!");
var req = new TLRequestGetContacts() { Hash = "" };
return await SendRequestAsync<TLContacts>(req, token).ConfigureAwait(false);
}
public async Task<TLAbsUpdates> SendMessageAsync(TLAbsInputPeer peer, string message, CancellationToken token = default(CancellationToken))
{
if (!IsUserAuthorized())
throw new InvalidOperationException("Authorize user first!");
return await SendRequestAsync<TLAbsUpdates>(
new TLRequestSendMessage()
{
Peer = peer,
Message = message,
RandomId = Helpers.GenerateRandomLong()
}, token).ConfigureAwait(false);
2016-09-24 15:38:26 +02:00
}
2016-10-11 15:28:57 +02:00
public async Task<Boolean> SendTypingAsync(TLAbsInputPeer peer, CancellationToken token = default(CancellationToken))
{
var req = new TLRequestSetTyping()
{
Action = new TLSendMessageTypingAction(),
Peer = peer
};
return await SendRequestAsync<Boolean>(req, token).ConfigureAwait(false);
}
2016-10-11 15:28:57 +02:00
public async Task<TLAbsDialogs> GetUserDialogsAsync(int offsetDate = 0, int offsetId = 0, TLAbsInputPeer offsetPeer = null, int limit = 100,
CancellationToken token = default(CancellationToken))
{
if (!IsUserAuthorized())
throw new InvalidOperationException("Authorize user first!");
if (offsetPeer == null)
offsetPeer = new TLInputPeerSelf();
var req = new TLRequestGetDialogs()
{
OffsetDate = offsetDate,
OffsetId = offsetId,
OffsetPeer = offsetPeer,
Limit = limit
};
return await SendRequestAsync<TLAbsDialogs>(req, token).ConfigureAwait(false);
}
public async Task<TLAbsUpdates> SendUploadedPhoto(TLAbsInputPeer peer, TLAbsInputFile file, string caption, CancellationToken token = default(CancellationToken))
2016-10-29 10:47:18 +02:00
{
return await SendRequestAsync<TLAbsUpdates>(new TLRequestSendMedia()
{
RandomId = Helpers.GenerateRandomLong(),
Background = false,
ClearDraft = false,
Media = new TLInputMediaUploadedPhoto() { File = file, Caption = caption },
Peer = peer
}, token).ConfigureAwait(false);
}
public async Task<TLAbsUpdates> SendUploadedDocument(TLAbsInputPeer peer, TLAbsInputFile file, string caption, string mimeType, TLVector<TLAbsDocumentAttribute> attributes,
CancellationToken token = default(CancellationToken))
{
2016-10-29 10:47:18 +02:00
return await SendRequestAsync<TLAbsUpdates>(new TLRequestSendMedia()
{
RandomId = Helpers.GenerateRandomLong(),
Background = false,
ClearDraft = false,
Media = new TLInputMediaUploadedDocument()
{
File = file,
Caption = caption,
MimeType = mimeType,
Attributes = attributes
},
Peer = peer
}, token).ConfigureAwait(false);
}
public async Task<TLFile> GetFile(TLAbsInputFileLocation location, int filePartSize, int offset = 0, CancellationToken token = default(CancellationToken))
{
var result = await SendRequestAsync<TLFile>(new TLRequestGetFile()
2016-10-23 12:29:18 +02:00
{
Location = location,
Limit = filePartSize,
Offset = offset
}, token).ConfigureAwait(false);
2016-10-29 10:47:18 +02:00
return result;
}
2016-10-23 12:29:18 +02:00
public async Task SendPingAsync(CancellationToken token = default(CancellationToken))
{
await _sender.SendPingAsync(token).ConfigureAwait(false);
2018-03-03 17:38:51 +01:00
}
public async Task<TLAbsMessages> GetHistoryAsync(TLAbsInputPeer peer, int offsetId = 0, int offsetDate = 0, int addOffset = 0, int limit = 100, int maxId = 0,
int minId = 0, CancellationToken token = default(CancellationToken))
2018-03-03 17:38:51 +01:00
{
if (!IsUserAuthorized())
throw new InvalidOperationException("Authorize user first!");
var req = new TLRequestGetHistory()
{
Peer = peer,
OffsetId = offsetId,
OffsetDate = offsetDate,
AddOffset = addOffset,
Limit = limit,
MaxId = maxId,
MinId = minId
2018-03-03 17:38:51 +01:00
};
return await SendRequestAsync<TLAbsMessages>(req, token).ConfigureAwait(false);
}
/// <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>
/// <param name="token"></param>
/// <returns></returns>
public async Task<TLFound> SearchUserAsync(string q, int limit = 10, CancellationToken token = default(CancellationToken))
{
var r = new TeleSharp.TL.Contacts.TLRequestSearch
{
Q = q,
Limit = limit
};
return await SendRequestAsync<TLFound>(r, token).ConfigureAwait(false);
}
private void OnUserAuthenticated(TLUser TLUser)
2016-09-06 17:37:05 +02:00
{
Session.TLUser = TLUser;
Session.SessionExpires = int.MaxValue;
2016-09-06 17:37:05 +02:00
Session.Save();
2018-03-03 17:38:51 +01:00
}
public bool IsConnected
{
get
{
if (_transport == null)
return false;
return _transport.IsConnected;
}
}
2016-12-15 21:02:23 +01:00
public void Dispose()
{
if (_transport != null)
{
_transport.Dispose();
_transport = null;
}
}
}
public class MissingApiConfigurationException : Exception
{
public const string InfoUrl = "https://github.com/sochix/TLSharp#quick-configuration";
2016-10-29 10:47:18 +02:00
internal MissingApiConfigurationException(string invalidParamName) :
base($"Your {invalidParamName} setting is missing. Adjust the configuration first, see {InfoUrl}")
{
}
2016-04-18 12:50:57 +02:00
}
public class InvalidPhoneCodeException : Exception
{
internal InvalidPhoneCodeException(string msg) : base(msg) { }
}
2016-11-16 14:31:00 +01:00
public class CloudPasswordNeededException : Exception
{
internal CloudPasswordNeededException(string msg) : base(msg) { }
}
2015-09-28 04:01:17 +02:00
}