This commit is contained in:
2024-10-10 19:05:48 +00:00
commit cffdcba6af
1880 changed files with 813614 additions and 0 deletions

5
td/example/csharp/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
/.vs/
/bin/
/obj/
/project.lock.json
/TdExample.csproj.user

View File

@@ -0,0 +1,40 @@
# TDLib C# example
This is an example of building TDLib with `C++/CLI` support and an example of TDLib usage from C#.
## Building TDLib
* Download and install Microsoft Visual Studio 2015 or later.
* Download and install [CMake](https://cmake.org/download/); choose "Add CMake to the system PATH" option while installing.
* Install `gperf`, `zlib`, and `openssl` using [vcpkg](https://github.com/Microsoft/vcpkg#quick-start):
```
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
git checkout cd5e746ec203c8c3c61647e0886a8df8c1e78e41
.\bootstrap-vcpkg.bat
.\vcpkg.exe install gperf:x64-windows gperf:x86-windows openssl:x64-windows openssl:x86-windows zlib:x64-windows zlib:x86-windows
```
* (Optional. For XML documentation generation.) Download [PHP](https://windows.php.net/download). Add the path to php.exe to the PATH environment variable.
* Build `TDLib` with CMake enabling `.NET` support and specifying correct path to `vcpkg` toolchain file:
```
cd <path to TDLib sources>/example/csharp
mkdir build
cd build
cmake -A Win32 -DTD_ENABLE_DOTNET=ON -DCMAKE_TOOLCHAIN_FILE=<path to vcpkg>/scripts/buildsystems/vcpkg.cmake ../../..
cmake --build . --config Release
cmake --build . --config Debug
cd ..
mkdir build64
cd build64
cmake -A x64 -DTD_ENABLE_DOTNET=ON -DCMAKE_TOOLCHAIN_FILE=<path to vcpkg>/scripts/buildsystems/vcpkg.cmake ../../..
cmake --build . --config Release
cmake --build . --config Debug
```
## Example of usage
After `TDLib` is built you can open and run TdExample project.
It contains a simple console C# application with implementation of authorization and message sending.
Just open it with Visual Studio 2015 or later and run.
Also, see TdExample.csproj for example of including TDLib in C# project with all native shared library dependencies.

View File

@@ -0,0 +1,293 @@
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2024
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
using Td = Telegram.Td;
using TdApi = Telegram.Td.Api;
using System;
using System.Threading;
namespace TdExample
{
/// <summary>
/// Example class for TDLib usage from C#.
/// </summary>
class Example
{
private static Td.Client _client = null;
private readonly static Td.ClientResultHandler _defaultHandler = new DefaultHandler();
private static TdApi.AuthorizationState _authorizationState = null;
private static volatile bool _haveAuthorization = false;
private static volatile bool _needQuit = false;
private static volatile bool _canQuit = false;
private static volatile AutoResetEvent _gotAuthorization = new AutoResetEvent(false);
private static readonly string _newLine = Environment.NewLine;
private static readonly string _commandsLine = "Enter command (gc <chatId> - GetChat, me - GetMe, sm <chatId> <message> - SendMessage, lo - LogOut, r - Restart, q - Quit): ";
private static volatile string _currentPrompt = null;
private static Td.Client CreateTdClient()
{
return Td.Client.Create(new UpdateHandler());
}
private static void Print(string str)
{
if (_currentPrompt != null)
{
Console.WriteLine();
}
Console.WriteLine(str);
if (_currentPrompt != null)
{
Console.Write(_currentPrompt);
}
}
private static string ReadLine(string str)
{
Console.Write(str);
_currentPrompt = str;
var result = Console.ReadLine();
_currentPrompt = null;
return result;
}
private static void OnAuthorizationStateUpdated(TdApi.AuthorizationState authorizationState)
{
if (authorizationState != null)
{
_authorizationState = authorizationState;
}
if (_authorizationState is TdApi.AuthorizationStateWaitTdlibParameters)
{
TdApi.SetTdlibParameters request = new TdApi.SetTdlibParameters();
request.DatabaseDirectory = "tdlib";
request.UseMessageDatabase = true;
request.UseSecretChats = true;
request.ApiId = 94575;
request.ApiHash = "a3406de8d171bb422bb6ddf3bbd800e2";
request.SystemLanguageCode = "en";
request.DeviceModel = "Desktop";
request.ApplicationVersion = "1.0";
_client.Send(request, new AuthorizationRequestHandler());
}
else if (_authorizationState is TdApi.AuthorizationStateWaitPhoneNumber)
{
string phoneNumber = ReadLine("Please enter phone number: ");
_client.Send(new TdApi.SetAuthenticationPhoneNumber(phoneNumber, null), new AuthorizationRequestHandler());
}
else if (_authorizationState is TdApi.AuthorizationStateWaitEmailAddress)
{
string emailAddress = ReadLine("Please enter email address: ");
_client.Send(new TdApi.SetAuthenticationEmailAddress(emailAddress), new AuthorizationRequestHandler());
}
else if (_authorizationState is TdApi.AuthorizationStateWaitEmailCode)
{
string code = ReadLine("Please enter email authentication code: ");
_client.Send(new TdApi.CheckAuthenticationEmailCode(new TdApi.EmailAddressAuthenticationCode(code)), new AuthorizationRequestHandler());
}
else if (_authorizationState is TdApi.AuthorizationStateWaitOtherDeviceConfirmation state)
{
Console.WriteLine("Please confirm this login link on another device: " + state.Link);
}
else if (_authorizationState is TdApi.AuthorizationStateWaitCode)
{
string code = ReadLine("Please enter authentication code: ");
_client.Send(new TdApi.CheckAuthenticationCode(code), new AuthorizationRequestHandler());
}
else if (_authorizationState is TdApi.AuthorizationStateWaitRegistration)
{
string firstName = ReadLine("Please enter your first name: ");
string lastName = ReadLine("Please enter your last name: ");
_client.Send(new TdApi.RegisterUser(firstName, lastName, false), new AuthorizationRequestHandler());
}
else if (_authorizationState is TdApi.AuthorizationStateWaitPassword)
{
string password = ReadLine("Please enter password: ");
_client.Send(new TdApi.CheckAuthenticationPassword(password), new AuthorizationRequestHandler());
}
else if (_authorizationState is TdApi.AuthorizationStateReady)
{
_haveAuthorization = true;
_gotAuthorization.Set();
}
else if (_authorizationState is TdApi.AuthorizationStateLoggingOut)
{
_haveAuthorization = false;
Print("Logging out");
}
else if (_authorizationState is TdApi.AuthorizationStateClosing)
{
_haveAuthorization = false;
Print("Closing");
}
else if (_authorizationState is TdApi.AuthorizationStateClosed)
{
Print("Closed");
if (!_needQuit)
{
_client = CreateTdClient(); // recreate _client after previous has closed
} else {
_canQuit = true;
}
}
else
{
Print("Unsupported authorization state:" + _newLine + _authorizationState);
}
}
private static long GetChatId(string arg)
{
long chatId = 0;
try
{
chatId = Convert.ToInt64(arg);
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
return chatId;
}
private static void GetCommand()
{
string command = ReadLine(_commandsLine);
string[] commands = command.Split(new char[] { ' ' }, 2);
try
{
switch (commands[0])
{
case "gc":
_client.Send(new TdApi.GetChat(GetChatId(commands[1])), _defaultHandler);
break;
case "me":
_client.Send(new TdApi.GetMe(), _defaultHandler);
break;
case "sm":
string[] args = commands[1].Split(new char[] { ' ' }, 2);
sendMessage(GetChatId(args[0]), args[1]);
break;
case "lo":
_haveAuthorization = false;
_client.Send(new TdApi.LogOut(), _defaultHandler);
break;
case "r":
_haveAuthorization = false;
_client.Send(new TdApi.Close(), _defaultHandler);
break;
case "q":
_needQuit = true;
_haveAuthorization = false;
_client.Send(new TdApi.Close(), _defaultHandler);
break;
default:
Print("Unsupported command: " + command);
break;
}
}
catch (IndexOutOfRangeException)
{
Print("Not enough arguments");
}
}
private static void sendMessage(long chatId, string message)
{
// initialize reply markup just for testing
TdApi.InlineKeyboardButton[] row = { new TdApi.InlineKeyboardButton("https://telegram.org?1", new TdApi.InlineKeyboardButtonTypeUrl()), new TdApi.InlineKeyboardButton("https://telegram.org?2", new TdApi.InlineKeyboardButtonTypeUrl()), new TdApi.InlineKeyboardButton("https://telegram.org?3", new TdApi.InlineKeyboardButtonTypeUrl()) };
TdApi.ReplyMarkup replyMarkup = new TdApi.ReplyMarkupInlineKeyboard(new TdApi.InlineKeyboardButton[][] { row, row, row });
TdApi.InputMessageContent content = new TdApi.InputMessageText(new TdApi.FormattedText(message, null), null, true);
_client.Send(new TdApi.SendMessage(chatId, 0, null, null, replyMarkup, content), _defaultHandler);
}
static void Main()
{
// disable TDLib log
Td.Client.Execute(new TdApi.SetLogVerbosityLevel(0));
if (Td.Client.Execute(new TdApi.SetLogStream(new TdApi.LogStreamFile("tdlib.log", 1 << 27, false))) is TdApi.Error)
{
throw new System.IO.IOException("Write access to the current directory is required");
}
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
Td.Client.Run();
}).Start();
// create Td.Client
_client = CreateTdClient();
// test Client.Execute
_defaultHandler.OnResult(Td.Client.Execute(new TdApi.GetTextEntities("@telegram /test_command https://telegram.org telegram.me @gif @test")));
// main loop
while (!_needQuit)
{
// await authorization
_gotAuthorization.Reset();
_gotAuthorization.WaitOne();
_client.Send(new TdApi.LoadChats(null, 100), _defaultHandler); // preload main chat list
while (_haveAuthorization)
{
GetCommand();
}
}
while (!_canQuit) {
Thread.Sleep(1);
}
}
private class DefaultHandler : Td.ClientResultHandler
{
void Td.ClientResultHandler.OnResult(TdApi.BaseObject @object)
{
Print(@object.ToString());
}
}
private class UpdateHandler : Td.ClientResultHandler
{
void Td.ClientResultHandler.OnResult(TdApi.BaseObject @object)
{
if (@object is TdApi.UpdateAuthorizationState)
{
OnAuthorizationStateUpdated((@object as TdApi.UpdateAuthorizationState).AuthorizationState);
}
else
{
// Print("Unsupported update: " + @object);
}
}
}
private class AuthorizationRequestHandler : Td.ClientResultHandler
{
void Td.ClientResultHandler.OnResult(TdApi.BaseObject @object)
{
if (@object is TdApi.Error)
{
Print("Receive an error:" + _newLine + @object);
OnAuthorizationStateUpdated(null); // repeat last action
}
else
{
// result is already received through UpdateAuthorizationState, nothing to do
}
}
}
}
}

View File

@@ -0,0 +1,119 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProjectGuid>{3F9A93EA-DC26-4F8B-ACE0-131B33B00CA7}</ProjectGuid>
<OutputType>Exe</OutputType>
<NoStandardLibraries>false</NoStandardLibraries>
<AssemblyName>ConsoleApplication</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup>
<RootNamespace>TdExample</RootNamespace>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
<Reference Include="Telegram.Td, Version=0.0.0.0, Culture=neutral, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath Condition=" '$(Platform)' == 'x86' ">build\$(Configuration)\Telegram.Td.dll</HintPath>
<HintPath Condition=" '$(Platform)' == 'x64' ">build64\$(Configuration)\Telegram.Td.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="TdExample.cs" />
</ItemGroup>
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<Content Include="build\Debug\zlibd1.dll">
<Link>zlibd1.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<Content Include="build\Release\zlib1.dll">
<Link>zlib1.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
<Content Include="build64\Debug\zlibd1.dll">
<Link>zlibd1.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
<Content Include="build64\Release\zlib1.dll">
<Link>zlib1.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup Condition=" '$(Platform)' == 'x86' ">
<Content Include="build\$(Configuration)\libcrypto-3.dll">
<Link>libcrypto-3.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="build\$(Configuration)\libssl-3.dll">
<Link>libssl-3.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup Condition=" '$(Platform)' == 'x64' ">
<Content Include="build64\$(Configuration)\libcrypto-3-x64.dll">
<Link>libcrypto-3-x64.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="build64\$(Configuration)\libssl-3-x64.dll">
<Link>libssl-3-x64.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSHARP.Targets" />
<ProjectExtensions>
<VisualStudio AllowExistingFolder="true" />
</ProjectExtensions>
</Project>

View File

@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28010.2046
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TdExample", "TdExample.csproj", "{3F9A93EA-DC26-4F8B-ACE0-131B33B00CA7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3F9A93EA-DC26-4F8B-ACE0-131B33B00CA7}.Debug|x64.ActiveCfg = Debug|x64
{3F9A93EA-DC26-4F8B-ACE0-131B33B00CA7}.Debug|x64.Build.0 = Debug|x64
{3F9A93EA-DC26-4F8B-ACE0-131B33B00CA7}.Debug|x86.ActiveCfg = Debug|x86
{3F9A93EA-DC26-4F8B-ACE0-131B33B00CA7}.Debug|x86.Build.0 = Debug|x86
{3F9A93EA-DC26-4F8B-ACE0-131B33B00CA7}.Release|x64.ActiveCfg = Release|x64
{3F9A93EA-DC26-4F8B-ACE0-131B33B00CA7}.Release|x64.Build.0 = Release|x64
{3F9A93EA-DC26-4F8B-ACE0-131B33B00CA7}.Release|x86.ActiveCfg = Release|x86
{3F9A93EA-DC26-4F8B-ACE0-131B33B00CA7}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {865856BA-F733-45DF-B35F-12607605B023}
EndGlobalSection
EndGlobal