add console projects

This commit is contained in:
meysam navaei 2018-02-06 00:57:15 +03:30
parent a3b58d6bb0
commit d86d7609e0
13 changed files with 760 additions and 70 deletions

View file

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ApiHash" value="d4a1f5268c9af7bc69cc336a443b4ac4" />
<add key="ApiId" value="171836" />
<add key="NumberToAuthenticate" value="989224913689" />
<add key="CodeToAuthenticate" value="" />
<add key="PasswordToAuthenticate" value=""/>
<add key="NotRegisteredNumberToSignUp" value=""/>
<add key="NumberToSendMessage" value="989128702514"/>
<add key="UserNameToSendMessage" value="getmedia_contact"/>
<add key="NumberToGetUserFull" value=""/>
<add key="NumberToAddToChat" value="989128702514"/>
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
</configuration>

View file

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{15296FBD-23B9-4786-8CC0-65C872FBFDAC}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>ClientConsoleApp</RootNamespace>
<AssemblyName>ClientConsoleApp</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\TeleSharp.TL\TeleSharp.TL.csproj">
<Project>{d6144517-91d2-4880-86df-e9ff5d7f383a}</Project>
<Name>TeleSharp.TL</Name>
</ProjectReference>
<ProjectReference Include="..\..\TLSharp.Core\TLSharp.Core.csproj">
<Project>{400d2544-1cc6-4d8a-a62c-2292d9947a16}</Project>
<Name>TLSharp.Core</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -0,0 +1,115 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TeleSharp.TL;
using TLSharp.Core;
namespace ClientConsoleApp
{
class Program
{
private static string NumberToSendMessage => ConfigurationManager.AppSettings[nameof(NumberToSendMessage)];
static void Main(string[] args)
{
System.Threading.Thread.Sleep(2000);
Console.WriteLine("Hello World!");
var client = GetTlgClient().Result;
var normalizedNumber = NumberToSendMessage.StartsWith("+") ?
NumberToSendMessage.Substring(1, NumberToSendMessage.Length - 1) :
NumberToSendMessage;
var result = client.GetContactsAsync().Result;
var user = result.Users
.OfType<TLUser>()
.FirstOrDefault(x => x.Phone == normalizedNumber);
var rr = client.SendTypingAsync(new TLInputPeerUser() { UserId = user.Id }).Result;
Thread.Sleep(3000);
var rrr = client.SendMessageAsync(new TLInputPeerUser() { UserId = user.Id }, "TEST").Result;
}
private static async Task<TLSharp.Core.TelegramClient> GetTlgClient()
{
string ApiHash = ConfigurationManager.AppSettings["ApiHash"];
int ApiId = int.Parse(ConfigurationManager.AppSettings["ApiId"]);
//string AuthCode = ConfigurationManager.AppSettings["AuthCode"];
string MainPhoneNumber = ConfigurationManager.AppSettings["NumberToAuthenticate"];
var client = new TelegramClient(ApiId, ApiHash, null, "session", null, "127.0.0.1", 5000);
var phoneCodeHash = string.Empty;
authenticated:
Console.WriteLine("Start app");
client.ConnectAsync().Wait();
Console.WriteLine("MakeAuthentication");
await MakeAuthentication(client, MainPhoneNumber);
Console.WriteLine("Connected");
if (!client.IsUserAuthorized())
{
Console.WriteLine("User not autorized");
if (string.IsNullOrEmpty(phoneCodeHash))
{
phoneCodeHash = await client.SendCodeRequestAsync(MainPhoneNumber);
goto authenticated;
}
Console.WriteLine("Plase enter new AuthCode:");
var AuthCode = Console.ReadLine();
var user = await client.MakeAuthAsync(MainPhoneNumber, phoneCodeHash, AuthCode);
Console.WriteLine("Login successfull.");
}
return client;
}
private static async Task MakeAuthentication(TLSharp.Core.TelegramClient client, string mainPhoneNumber)
{
var hash = await client.SendCodeRequestAsync(mainPhoneNumber);
Console.WriteLine("waiting for code");
var code = Console.ReadLine();
var user = await client.MakeAuthAsync(mainPhoneNumber, hash, code);
if (!client.IsUserAuthorized())
{
hash = await client.SendCodeRequestAsync(mainPhoneNumber);
Console.WriteLine("please try again.add code");
code = Console.ReadLine();
user = await client.MakeAuthAsync(mainPhoneNumber, hash, code);
}
}
private static void TestTcpClient()
{
var tcpClient = new TcpClient();
tcpClient.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5000));
if (tcpClient.Connected)
{
using (var memoryStream = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(memoryStream))
{
binaryWriter.Write((long)0);
binaryWriter.Write(1234);
binaryWriter.Write(20);
binaryWriter.Write(8000);
byte[] packet = memoryStream.ToArray();
tcpClient.GetStream().WriteAsync(packet, 0, packet.Length).Wait();
}
}
}
System.Threading.Thread.Sleep(20000);
}
}
}

View file

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ClientConsoleApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ClientConsoleApp")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("15296fbd-23b9-4786-8cc0-65c872fbfdac")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
</configuration>

View file

@ -0,0 +1,343 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using Ionic.Crc;
using TLSharp.Core.Auth;
using TLSharp.Core.MTProto.Crypto;
using TLSharp.Core.Network;
using TLSharp.Core.Utils;
namespace TlgListenerApplication
{
class Program
{
private static int sequence = 0;
private static int timeOffset;
private static long lastMessageId;
private static Random random => new Random();
static void Main(string[] args)
{
Console.WriteLine("Listening...");
TcpListener();
Console.WriteLine("The end");
Console.ReadKey();
}
private static void TcpListener()
{
try
{
var tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 5000);
tcpListener.Start();
for (; ; )
{
if (tcpListener.Pending())
{
try
{
ProcessRequest(tcpListener);
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e);
Console.ForegroundColor = ConsoleColor.Gray;
}
}
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
private static void ProcessRequestBySocket(TcpListener tcpListener)
{
Console.WriteLine("Processing socket...");
var socketClient = tcpListener.AcceptSocket();
byte[] nonceFromClient = new byte[16];
var bytes = new byte[socketClient.ReceiveBufferSize];
socketClient.Receive(bytes);
var tcpMessage = TcpMessage.Decode(bytes);
var binaryReader = new BinaryReader(new MemoryStream(tcpMessage.Body, false));
var a = binaryReader.ReadInt64();
var msgId = binaryReader.ReadInt64();
var datalength = binaryReader.ReadInt32();
var data = binaryReader.ReadBytes(datalength);
var binaryReader2 = new BinaryReader(new MemoryStream(data, false));
const int responseConstructorNumber = 0x60469778;
var responseCode = binaryReader2.ReadInt32();
Console.WriteLine("Request code: " + responseCode);
if (responseCode == responseConstructorNumber)//---Step1_PQRequest
{
nonceFromClient = binaryReader2.ReadBytes(16);
}
var nonce = new byte[16];
new Random().NextBytes(nonce);
var fingerprint = StringToByteArray("216be86c022bb4c3");
var step1 = new Step1_Response()
{
Pq = new BigInteger(1, BitConverter.GetBytes(880)),
ServerNonce = nonceFromClient,
Nonce = nonce,
Fingerprints = new List<byte[]>() { fingerprint }
};
var bytestosend = PrepareToSend(step1.ToBytes());
var datatosend = Encode(bytestosend, 11);
socketClient.Send(datatosend);
}
private static void ProcessRequest(TcpListener tcpListener)
{
Console.WriteLine("Processing...");
var tcpClient = tcpListener.AcceptTcpClient();
var netStream = tcpClient.GetStream();
if (netStream.DataAvailable)
{
byte[] nonceFromClient = new byte[16];
if (netStream.CanRead)
{
var bytes = new byte[tcpClient.ReceiveBufferSize];
netStream.Read(bytes, 0, (int)tcpClient.ReceiveBufferSize);
var tcpMessage = TcpMessage.Decode(bytes);
var binaryReader = new BinaryReader(new MemoryStream(tcpMessage.Body, false));
//var a = binaryReader.ReadInt64();
var msgId = binaryReader.ReadInt64();
var datalength = binaryReader.ReadInt32();
var data = binaryReader.ReadBytes(datalength);
var binaryReader2 = new BinaryReader(new MemoryStream(data, false));
const int responseConstructorNumber = 0x60469778;
var responseCode = binaryReader2.ReadInt32();
Console.WriteLine("Request code: " + responseCode);
if (responseCode == responseConstructorNumber)//---Step1_PQRequest
{
nonceFromClient = binaryReader2.ReadBytes(16);
}
//var obj = new Step1_PQRequest().FromBytes(data);
//var rr = FromByteArray<Step1_PQRequest>(data);
//var binaryReader = new BinaryReader(netStream);
//var a = binaryReader.ReadInt64();
//var b = binaryReader.ReadInt32();
//var c = binaryReader.ReadInt32();
//var d = binaryReader.ReadInt32();
//Console.WriteLine("This is what the host returned to you: " + returndata);
}
if (netStream.CanWrite)
{
var nonce = new byte[16];
new Random().NextBytes(nonce);
var fingerprint = StringToByteArray("216be86c022bb4c3");
//var rr = BitConverter.ToString(fingerprint).Replace("-", "");
var step1 = new Step1_Response()
{
Pq = new BigInteger(1, BitConverter.GetBytes(880)),
ServerNonce = nonceFromClient,
Nonce = nonce,
Fingerprints = new List<byte[]>() { fingerprint }
};
var bytes = PrepareToSend(step1.ToBytes());
var datatosend = Encode(bytes, 11);
//Byte[] sendBytes = Encoding.UTF8.GetBytes("Is anybody there?");
netStream.Write(datatosend, 0, datatosend.Length);
}
else
{
Console.WriteLine("You cannot write data to this stream.");
netStream.Close();
tcpClient.Close();
}
}
}
public static async Task<TcpMessage> Receieve(TcpClient tcpClient)
{
var stream = tcpClient.GetStream();
var packetLengthBytes = new byte[4];
if (await stream.ReadAsync(packetLengthBytes, 0, 4) != 4)
throw new InvalidOperationException("Couldn't read the packet length");
int packetLength = BitConverter.ToInt32(packetLengthBytes, 0);
var seqBytes = new byte[4];
if (await stream.ReadAsync(seqBytes, 0, 4) != 4)
throw new InvalidOperationException("Couldn't read the sequence");
int seq = BitConverter.ToInt32(seqBytes, 0);
int readBytes = 0;
var body = new byte[packetLength - 12];
int neededToRead = packetLength - 12;
do
{
var bodyByte = new byte[packetLength - 12];
var availableBytes = await stream.ReadAsync(bodyByte, 0, neededToRead);
neededToRead -= availableBytes;
Buffer.BlockCopy(bodyByte, 0, body, readBytes, availableBytes);
readBytes += availableBytes;
}
while (readBytes != packetLength - 12);
var crcBytes = new byte[4];
if (await stream.ReadAsync(crcBytes, 0, 4) != 4)
throw new InvalidOperationException("Couldn't read the crc");
int checksum = BitConverter.ToInt32(crcBytes, 0);
byte[] rv = new byte[packetLengthBytes.Length + seqBytes.Length + body.Length];
Buffer.BlockCopy(packetLengthBytes, 0, rv, 0, packetLengthBytes.Length);
Buffer.BlockCopy(seqBytes, 0, rv, packetLengthBytes.Length, seqBytes.Length);
Buffer.BlockCopy(body, 0, rv, packetLengthBytes.Length + seqBytes.Length, body.Length);
var crc32 = new Ionic.Crc.CRC32();
crc32.SlurpBlock(rv, 0, rv.Length);
var validChecksum = crc32.Crc32Result;
if (checksum != validChecksum)
{
throw new InvalidOperationException("invalid checksum! skip");
}
return new TcpMessage(seq, body);
}
public static byte[] PrepareToSend(byte[] data)
{
using (var memoryStream = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(memoryStream))
{
binaryWriter.Write((long)0);
binaryWriter.Write(GetNewMessageId());
binaryWriter.Write(data.Length);
binaryWriter.Write(data);
byte[] packet = memoryStream.ToArray();
return packet;
}
}
}
private static long GetNewMessageId()
{
long time = Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds);
long newMessageId = ((time / 1000 + timeOffset) << 32) |
((time % 1000) << 22) |
(random.Next(524288) << 2); // 2^19
// [ unix timestamp : 32 bit] [ milliseconds : 10 bit ] [ buffer space : 1 bit ] [ random : 19 bit ] [ msg_id type : 2 bit ] = [ msg_id : 64 bit ]
if (lastMessageId >= newMessageId)
{
newMessageId = lastMessageId + 4;
}
lastMessageId = newMessageId;
return newMessageId;
}
private Tuple<byte[], ulong, int> DecodeMessage(byte[] body)
{
byte[] message;
ulong remoteMessageId;
int remoteSequence;
using (var inputStream = new MemoryStream(body))
using (var inputReader = new BinaryReader(inputStream))
{
if (inputReader.BaseStream.Length < 8)
throw new InvalidOperationException($"Can't decode packet");
ulong remoteAuthKeyId = inputReader.ReadUInt64(); // TODO: check auth key id
byte[] msgKey = inputReader.ReadBytes(16); // TODO: check msg_key correctness
AESKeyData keyData = Helpers.CalcKey(body, msgKey, false);
byte[] plaintext = AES.DecryptAES(keyData, inputReader.ReadBytes((int)(inputStream.Length - inputStream.Position)));
using (MemoryStream plaintextStream = new MemoryStream(plaintext))
using (BinaryReader plaintextReader = new BinaryReader(plaintextStream))
{
var remoteSalt = plaintextReader.ReadUInt64();
var remoteSessionId = plaintextReader.ReadUInt64();
remoteMessageId = plaintextReader.ReadUInt64();
remoteSequence = plaintextReader.ReadInt32();
int msgLen = plaintextReader.ReadInt32();
message = plaintextReader.ReadBytes(msgLen);
}
}
return new Tuple<byte[], ulong, int>(message, remoteMessageId, remoteSequence);
}
private static byte[] Encode(byte[] body, int sequneceNumber)
{
using (var memoryStream = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(memoryStream))
{
// https://core.telegram.org/mtproto#tcp-transport
/*
4 length bytes are added at the front
(to include the length, the sequence number, and CRC32; always divisible by 4)
and 4 bytes with the packet sequence number within this TCP connection
(the first packet sent is numbered 0, the next one 1, etc.),
and 4 CRC32 bytes at the end (length, sequence number, and payload together).
*/
binaryWriter.Write(body.Length + 12);
binaryWriter.Write(sequneceNumber);
binaryWriter.Write(body);
var crc32 = new CRC32();
crc32.SlurpBlock(memoryStream.GetBuffer(), 0, 8 + body.Length);
binaryWriter.Write(crc32.Crc32Result);
var transportPacket = memoryStream.ToArray();
// Debug.WriteLine("Tcp packet #{0}\n{1}", SequneceNumber, BitConverter.ToString(transportPacket));
return transportPacket;
}
}
}
public static T FromByteArray<T>(byte[] data)
{
if (data == null)
return default(T);
var bf = new BinaryFormatter();
using (var ms = new MemoryStream(data))
{
var obj = bf.Deserialize(ms);
return (T)obj;
}
}
public static byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
}
}

View file

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TlgListenerApplication")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TlgListenerApplication")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("15f1cfa2-e099-48fd-97e7-be06aa5b3ea6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View file

@ -0,0 +1,66 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{15F1CFA2-E099-48FD-97E7-BE06AA5B3EA6}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>TlgListenerApplication</RootNamespace>
<AssemblyName>TlgListenerApplication</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Ionic.ZLib, Version=2.0.0.14, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MarkerMetro.Unity.Ionic.Zlib.2.0.0.14\lib\net35\Ionic.ZLib.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\TeleSharp.TL\TeleSharp.TL.csproj">
<Project>{d6144517-91d2-4880-86df-e9ff5d7f383a}</Project>
<Name>TeleSharp.TL</Name>
</ProjectReference>
<ProjectReference Include="..\..\TLSharp.Core\TLSharp.Core.csproj">
<Project>{400d2544-1cc6-4d8a-a62c-2292d9947a16}</Project>
<Name>TLSharp.Core</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="MarkerMetro.Unity.Ionic.Zlib" version="2.0.0.14" targetFramework="net46" />
</packages>

View file

@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using TLSharp.Core.MTProto;
using TLSharp.Core.MTProto.Crypto;
@ -9,10 +10,43 @@ namespace TLSharp.Core.Auth
{
public class Step1_Response
{
public Step1_Response()
{
Nonce = new byte[16];
ServerNonce = new byte[16];
}
public byte[] Nonce { get; set; }
public byte[] ServerNonce { get; set; }
public BigInteger Pq { get; set; }
public List<byte[]> Fingerprints { get; set; }
public byte[] ToBytes()
{
new Random().NextBytes(Nonce);
const int constructorNumber = 0x05162463;
const int vectorConstructorNumber = 0x1cb5c415;
using (var memoryStream = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(memoryStream))
{
binaryWriter.Write(constructorNumber);
binaryWriter.Write(ServerNonce);
binaryWriter.Write(Nonce);
Serializers.Bytes.write(binaryWriter, Pq.ToByteArrayUnsigned());
binaryWriter.Write(vectorConstructorNumber);
binaryWriter.Write(Fingerprints.Count);
foreach (var fingerprint in Fingerprints)
{
binaryWriter.Write(fingerprint);
}
return memoryStream.ToArray();
}
}
}
}
public class Step1_PQRequest
@ -62,7 +96,6 @@ namespace TLSharp.Core.Auth
{
throw new InvalidOperationException("invalid nonce from server");
}
var serverNonce = binaryReader.ReadBytes(16);
byte[] pqbytes = Serializers.Bytes.read(binaryReader);
@ -92,5 +125,6 @@ namespace TLSharp.Core.Auth
}
}
}
}
}

View file

@ -26,7 +26,7 @@ namespace TLSharp.Core
public Session Load(string sessionUserId)
{
var sessionFileName = $"{sessionUserId}.dat";
if (!File.Exists(sessionFileName))
//if (!File.Exists(sessionFileName))
return null;
using (var stream = new FileStream(sessionFileName, FileMode.Open))
@ -73,7 +73,7 @@ namespace TLSharp.Core
private ISessionStore _store;
private Session(ISessionStore store)
public Session(ISessionStore store)
{
random = new Random();
_store = store;
@ -155,14 +155,14 @@ namespace TLSharp.Core
_store.Save(this);
}
public static Session TryLoadOrCreateNew(ISessionStore store, string sessionUserId)
public static Session TryLoadOrCreateNew(ISessionStore store, string sessionUserId, string serverAddress = "", int? serverPort = null)
{
return store.Load(sessionUserId) ?? new Session(store)
{
Id = GenerateRandomUlong(),
SessionUserId = sessionUserId,
ServerAddress = defaultConnectionAddress,
Port = defaultConnectionPort
ServerAddress = string.IsNullOrEmpty(serverAddress) ? defaultConnectionAddress : serverAddress,
Port = serverPort ?? defaultConnectionPort
};
}

View file

@ -31,7 +31,7 @@ namespace TLSharp.Core
private TcpClientConnectionHandler _handler;
public TelegramClient(int apiId, string apiHash,
ISessionStore store = null, string sessionUserId = "session", TcpClientConnectionHandler handler = null)
ISessionStore store = null, string sessionUserId = "session", TcpClientConnectionHandler handler = null, string serverAddress = "", int? serverPort = null)
{
if (apiId == default(int))
throw new MissingApiConfigurationException("API_ID");
@ -46,8 +46,8 @@ namespace TLSharp.Core
_apiId = apiId;
_handler = handler;
_session = Session.TryLoadOrCreateNew(store, sessionUserId);
_transport = new TcpTransport(_session.ServerAddress, _session.Port, _handler);
_session = Session.TryLoadOrCreateNew(store, sessionUserId, serverAddress, serverPort);
_transport = new TcpTransport(string.IsNullOrEmpty(serverAddress) ? _session.ServerAddress : serverAddress, serverPort ?? _session.Port, _handler);
}
public async Task<bool> ConnectAsync(bool reconnect = false)
@ -251,45 +251,7 @@ namespace TLSharp.Core
});
}
public async Task<TLAbsUpdates> ForwardMessageAsync(TLAbsInputPeer peer, TLAbsInputPeer peerto, int messageId)
{
if (!IsUserAuthorized())
throw new InvalidOperationException("Authorize user first!");
var rand = new Random();
var a = new TLVector<long>();
a.Add(rand.Next());
var b = new TLVector<int>();
b.Add(messageId);
var aa = new TLRequestForwardMessages();
aa.FromPeer = peer;
aa.ToPeer = peerto;
aa.RandomId = a;
aa.MessageId = messageId;
aa.Id = b;
aa.Silent = true;
aa.WithMyScore = true;
return await SendRequestAsync<TLUpdates>(aa);
}
public async Task<TLAbsUpdates> ForwardMessagesAsync(TLAbsInputPeer peerfrom, TLAbsInputPeer peerto, TLVector<int> messagesId)
{
if (!IsUserAuthorized())
throw new InvalidOperationException("Authorize user first!");
return await SendRequestAsync<TLAbsUpdates>(
new TLRequestForwardMessages()
{
Id = messagesId,
ToPeer = peerto,
FromPeer = peerfrom,
RandomId = new TLVector<long>() { Helpers.GenerateRandomLong() }
});
}
public async Task<TLAbsUpdates> ForwardMessageAsync(TLAbsInputPeer peer, int messageId)
public async Task<TLAbsUpdates> ForwardMessageAsync(TLAbsInputPeer target, int messageId)
{
if (!IsUserAuthorized())
throw new InvalidOperationException("Authorize user first!");
@ -297,12 +259,13 @@ namespace TLSharp.Core
return await SendRequestAsync<TLAbsUpdates>(
new TLRequestForwardMessage()
{
Peer = target,
Id = messageId,
Peer = peer,
RandomId = Helpers.GenerateRandomLong()
});
}
public async Task<Boolean> SendTypingAsync(TLAbsInputPeer peer)
{
var req = new TLRequestSetTyping()
@ -383,22 +346,6 @@ namespace TLSharp.Core
return await SendRequestAsync<TLAbsMessages>(req);
}
public async Task<TLAbsMessages> GetHistoryAsync(TLAbsInputPeer peer, int offset, int max_id, int min_id, int limit)
{
if (!IsUserAuthorized())
throw new InvalidOperationException("Authorize user first!");
var req = new TLRequestGetHistory()
{
Peer = peer,
AddOffset = offset,
MaxId = max_id,
MinId = min_id,
Limit = limit
};
return await SendRequestAsync<TLAbsMessages>(req);
}
/// <summary>
/// Serch user or chat. API: contacts.search#11f812d8 q:string limit:int = contacts.Found;
/// </summary>

View file

@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.24720.0
# Visual Studio 15
VisualStudioVersion = 15.0.27004.2002
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TLSharp.Core", "TLSharp.Core\TLSharp.Core.csproj", "{400D2544-1CC6-4D8A-A62C-2292D9947A16}"
EndProject
@ -15,6 +15,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TLSharp.Tests.VS", "TLSharp
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TLSharp.Tests.NUnit", "TLSharp.Tests.NUnit\TLSharp.Tests.NUnit.csproj", "{E90B705B-19FA-43BA-B952-69957976D12C}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Apps", "Apps", "{AECAC38E-472B-4D0A-94F7-C818DC71D3A6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClientConsoleApp", "Apps\ClientConsoleApp\ClientConsoleApp.csproj", "{15296FBD-23B9-4786-8CC0-65C872FBFDAC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TlgListenerApplication", "Apps\TlgListenerApplication\TlgListenerApplication.csproj", "{15F1CFA2-E099-48FD-97E7-BE06AA5B3EA6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -45,6 +51,24 @@ Global
{E90B705B-19FA-43BA-B952-69957976D12C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E90B705B-19FA-43BA-B952-69957976D12C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E90B705B-19FA-43BA-B952-69957976D12C}.Release|Any CPU.Build.0 = Release|Any CPU
{15296FBD-23B9-4786-8CC0-65C872FBFDAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{15296FBD-23B9-4786-8CC0-65C872FBFDAC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{15296FBD-23B9-4786-8CC0-65C872FBFDAC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{15296FBD-23B9-4786-8CC0-65C872FBFDAC}.Release|Any CPU.Build.0 = Release|Any CPU
{15F1CFA2-E099-48FD-97E7-BE06AA5B3EA6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{15F1CFA2-E099-48FD-97E7-BE06AA5B3EA6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{15F1CFA2-E099-48FD-97E7-BE06AA5B3EA6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{15F1CFA2-E099-48FD-97E7-BE06AA5B3EA6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{15296FBD-23B9-4786-8CC0-65C872FBFDAC} = {AECAC38E-472B-4D0A-94F7-C818DC71D3A6}
{15F1CFA2-E099-48FD-97E7-BE06AA5B3EA6} = {AECAC38E-472B-4D0A-94F7-C818DC71D3A6}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E4B0D0B6-F353-4A26-91A4-BCE2E1904E06}
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
Policies = $0
@ -81,7 +105,4 @@ Global
$2.inheritsScope = text/x-csharp
$2.scope = text/x-csharp
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal