TLSharp/TLSharp.Core/TelegramClient.cs

250 lines
6.7 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-01-17 10:16:44 +01:00
using System.Text;
2016-02-07 11:28:41 +01:00
using System.Text.RegularExpressions;
2015-09-28 04:01:17 +02:00
using System.Threading.Tasks;
using TLSharp.Core.Auth;
using TLSharp.Core.MTProto;
using TLSharp.Core.MTProto.Crypto;
using TLSharp.Core.Network;
using TLSharp.Core.Requests;
2016-01-27 12:02:18 +01:00
using MD5 = System.Security.Cryptography.MD5;
2015-09-28 04:01:17 +02:00
namespace TLSharp.Core
{
public class TelegramClient
{
private MtProtoSender _sender;
private AuthKey _key;
2016-01-27 12:02:18 +01:00
private TcpTransport _transport;
2015-10-01 14:55:02 +02:00
private string _apiHash = "a2514f96431a228e4b9ee473f6c51945";
private int _apiId = 19474;
2015-09-28 04:01:17 +02:00
private Session _session;
2016-01-27 12:02:18 +01:00
private List<DcOption> dcOptions;
2015-09-28 04:01:17 +02:00
2016-01-27 12:02:18 +01:00
public TelegramClient(ISessionStore store, string sessionUserId)
2015-09-28 04:01:17 +02:00
{
2015-10-01 14:55:02 +02:00
if (_apiId == 0)
throw new InvalidOperationException("Your API_ID is invalid. Do a configuration first https://github.com/sochix/TLSharp#quick-configuration");
if (string.IsNullOrEmpty(_apiHash))
throw new InvalidOperationException("Your API_ID is invalid. Do a configuration first https://github.com/sochix/TLSharp#quick-configuration");
2015-09-28 04:01:17 +02:00
_session = Session.TryLoadOrCreateNew(store, sessionUserId);
2016-01-27 12:02:18 +01:00
_transport = new TcpTransport(_session.ServerAddress, _session.Port);
2015-09-28 04:01:17 +02:00
}
2016-01-27 12:02:18 +01:00
public async Task<bool> Connect(bool reconnect = false)
2015-09-28 04:01:17 +02:00
{
2016-01-27 12:02:18 +01:00
if (_session.AuthKey == null || reconnect)
2015-09-28 04:01:17 +02:00
{
var result = await Authenticator.DoAuthentication(_transport);
_session.AuthKey = result.AuthKey;
_session.TimeOffset = result.TimeOffset;
}
_sender = new MtProtoSender(_transport, _session);
2016-01-27 12:02:18 +01:00
if (!reconnect)
{
var request = new InitConnectionRequest(_apiId);
2015-09-28 04:01:17 +02:00
2016-01-27 12:02:18 +01:00
await _sender.Send(request);
await _sender.Recieve(request);
dcOptions = request.ConfigConstructor.dc_options;
}
2015-09-28 04:01:17 +02:00
return true;
}
2016-01-27 12:02:18 +01:00
private async Task ReconnectToDc(int dcId)
{
if (dcOptions == null || !dcOptions.Any())
throw new InvalidOperationException($"Can't reconnect. Establish initial connection first.");
var dc = dcOptions.Cast<DcOptionConstructor>().First(d => d.id == dcId);
_transport = new TcpTransport(dc.ip_address, dc.port);
_session.ServerAddress = dc.ip_address;
_session.Port = dc.port;
await Connect(true);
}
2015-09-28 04:01:17 +02:00
public bool IsUserAuthorized()
{
return _session.User != null;
}
public async Task<bool> IsPhoneRegistered(string phoneNumber)
{
if (_sender == null)
throw new InvalidOperationException("Not connected!");
var authCheckPhoneRequest = new AuthCheckPhoneRequest(phoneNumber);
await _sender.Send(authCheckPhoneRequest);
await _sender.Recieve(authCheckPhoneRequest);
return authCheckPhoneRequest._phoneRegistered;
}
public async Task<string> SendCodeRequest(string phoneNumber)
{
2016-01-27 12:02:18 +01:00
var completed = false;
AuthSendCodeRequest request = null;
while (!completed)
{
request = new AuthSendCodeRequest(phoneNumber, 5, _apiId, _apiHash, "en");
try
{
await _sender.Send(request);
await _sender.Recieve(request);
completed = true;
}
catch (InvalidOperationException ex)
{
if (ex.Message.StartsWith("Your phone number registered to") && ex.Data["dcId"] != null)
{
await ReconnectToDc((int) ex.Data["dcId"]);
}
else
{
throw;
}
}
}
2015-09-28 04:01:17 +02:00
return request._phoneCodeHash;
}
public async Task<User> MakeAuth(string phoneNumber, string phoneHash, string code)
{
var request = new AuthSignInRequest(phoneNumber, phoneHash, code);
await _sender.Send(request);
await _sender.Recieve(request);
_session.SessionExpires = request.SessionExpires;
_session.User = request.user;
_session.Save();
return request.user;
}
2016-01-27 12:02:18 +01:00
public async Task<InputFile> UploadFile(string name, byte[] data)
{
var partSize = 65536;
2016-01-17 10:16:44 +01:00
2016-01-27 12:02:18 +01:00
var file_id = DateTime.Now.Ticks;
2016-01-17 10:16:44 +01:00
2016-01-27 12:02:18 +01:00
var partedData = new Dictionary<int, byte[]>();
var parts = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(data.Length) / Convert.ToDouble(partSize)));
var remainBytes = data.Length;
for (int i = 0; i < parts; i++)
{
partedData.Add(i, data
.Skip(i * partSize)
.Take(remainBytes < partSize ? remainBytes : partSize)
.ToArray());
2016-01-17 10:16:44 +01:00
2016-01-27 12:02:18 +01:00
remainBytes -= partSize;
}
2016-01-17 10:16:44 +01:00
2016-01-27 12:02:18 +01:00
for (int i = 0; i < parts; i++)
{
var saveFilePartRequest = new Upload_SaveFilePartRequest(file_id, i, partedData[i]);
await _sender.Send(saveFilePartRequest);
await _sender.Recieve(saveFilePartRequest);
2016-01-17 10:16:44 +01:00
2016-01-27 12:02:18 +01:00
if (saveFilePartRequest.Done == false)
throw new InvalidOperationException($"File part {i} does not uploaded");
}
2016-01-17 10:16:44 +01:00
2016-01-27 12:02:18 +01:00
string md5_checksum;
using (var md5 = MD5.Create())
{
var hash = md5.ComputeHash(data);
var hashResult = new StringBuilder(hash.Length * 2);
2016-01-17 10:16:44 +01:00
2016-01-27 12:02:18 +01:00
for (int i = 0; i < hash.Length; i++)
hashResult.Append(hash[i].ToString("x2"));
2016-01-17 10:16:44 +01:00
2016-01-27 12:02:18 +01:00
md5_checksum = hashResult.ToString();
}
2016-01-17 10:16:44 +01:00
2016-01-27 12:02:18 +01:00
var inputFile = new InputFileConstructor(file_id, parts, name, md5_checksum);
2016-01-17 10:16:44 +01:00
2016-01-27 12:02:18 +01:00
return inputFile;
}
2016-01-17 10:16:44 +01:00
2016-02-07 11:28:41 +01:00
public async Task<bool> SendMediaMessage(int contactId, InputFile file)
2016-01-27 12:02:18 +01:00
{
2016-02-04 15:05:48 +01:00
var request = new Message_SendMediaRequest(
new InputPeerContactConstructor(contactId),
new InputMediaUploadedPhotoConstructor(file));
2016-01-27 12:02:18 +01:00
await _sender.Send(request);
await _sender.Recieve(request);
2016-01-17 10:16:44 +01:00
return true;
2016-01-27 12:02:18 +01:00
}
2016-01-17 10:16:44 +01:00
2016-02-07 11:28:41 +01:00
public async Task<int?> ImportContactByPhoneNumber(string phoneNumber)
2015-09-28 04:01:17 +02:00
{
2016-02-07 11:28:41 +01:00
if (!validateNumber(phoneNumber))
throw new InvalidOperationException("Invalid phone number. It should be only digit string, from 5 to 20 digits.");
2016-01-27 12:02:18 +01:00
var request = new ImportContactRequest(new InputPhoneContactConstructor(0, phoneNumber, "My Test Name", String.Empty));
2015-09-28 04:01:17 +02:00
await _sender.Send(request);
await _sender.Recieve(request);
2016-02-01 21:06:15 +01:00
var importedUser = (ImportedContactConstructor)request.imported.FirstOrDefault();
2015-09-28 04:01:17 +02:00
2016-02-01 21:06:15 +01:00
return importedUser?.user_id;
2015-09-28 04:01:17 +02:00
}
public async Task<int?> ImportByUserName(string username)
{
2016-02-07 11:28:41 +01:00
if (string.IsNullOrEmpty(username))
throw new InvalidOperationException("Username can't be null");
var request = new ImportByUserName(username);
await _sender.Send(request);
await _sender.Recieve(request);
2016-02-01 21:58:51 +01:00
return request.id;
}
2015-09-28 04:01:17 +02:00
public async Task SendMessage(int id, string message)
{
2016-01-27 12:02:18 +01:00
var request = new SendMessageRequest(new InputPeerContactConstructor(id), message);
await _sender.Send(request);
await _sender.Recieve(request);
}
2015-09-28 04:01:17 +02:00
2016-02-04 14:04:31 +01:00
public async Task<List<Message>> GetMessagesHistoryForContact(int user_id, int offset, int limit, int max_id = -1)
2016-01-27 12:02:18 +01:00
{
var request = new GetHistoryRequest(new InputPeerContactConstructor(user_id), offset, max_id, limit);
await _sender.Send(request);
await _sender.Recieve(request);
return request.messages;
}
2016-02-07 11:28:41 +01:00
private bool validateNumber(string number)
{
var regex = new Regex("^\\d{7,20}$");
return regex.IsMatch(number);
}
2016-01-27 12:02:18 +01:00
}
2015-09-28 04:01:17 +02:00
}