### Execute Asynchronous TDLib Commands Source: https://context7.com/up9cloud/flutter_libtdjson/llms.txt Shows how to use the send() method to dispatch TDLib functions asynchronously. This includes examples for sending messages, setting parameters, and adjusting log verbosity levels. ```dart import 'package:libtdjson/libtdjson.dart' show Service; void sendMessageAsync(Service service, int chatId, String message) async { await service.send({ '@type': 'sendMessage', 'chat_id': chatId, 'input_message_content': { '@type': 'inputMessageText', 'text': { '@type': 'formattedText', 'text': message, } } }); print('Message sent (response will come via afterReceive callback)'); } void setTdlibParams(Service service) async { await service.send({ '@type': 'setTdlibParameters', ...service.tdlibParameters, }); } void setLogLevel(Service service, int level) async { await service.send({ '@type': 'setLogVerbosityLevel', 'new_verbosity_level': level, }); } ``` -------------------------------- ### Troubleshoot iOS Pod Install Issues Source: https://github.com/up9cloud/flutter_libtdjson/blob/master/example/README.md Commands to resolve issues with CocoaPods installation on iOS. This includes removing the Podfile.lock, updating the pod repository, and reinstalling pods. ```bash cd ios rm Podfile.lock pod install --repo-update cd .. ./ios_cleanup_run.sh ``` -------------------------------- ### Manage TDLib Client Lifecycle Source: https://context7.com/up9cloud/flutter_libtdjson/llms.txt Provides a pattern for managing the TDLib client lifecycle, including initialization, starting the receive loop, and graceful shutdown. ```dart import 'package:libtdjson/libtdjson.dart' show Service; class TelegramManager { Service? _service; bool get isRunning => _service?.isRunning ?? false; Future initialize(Map tdlibParams) async { _service = Service( start: false, tdlibParameters: tdlibParams, afterReceive: _handleReceive, ); } Future start() async { if (!isRunning) { await _service?.start(); print('Telegram service started'); } } Future stop() async { if (isRunning) { await _service?.stop(); print('Telegram service stopped'); } } void _handleReceive(Map event) { switch (event['@type']) { case 'updateAuthorizationState': _handleAuthState(event['authorization_state']); break; case 'updateNewMessage': print('New message: ${event['message']}'); break; case 'updateUser': print('User updated: ${event['user']}'); break; } } void _handleAuthState(Map state) { switch (state['@type']) { case 'authorizationStateWaitPhoneNumber': print('Waiting for phone number'); break; case 'authorizationStateWaitCode': print('Waiting for verification code'); break; case 'authorizationStateReady': print('Authentication complete!'); break; case 'authorizationStateClosed': print('Session closed'); break; } } } ``` -------------------------------- ### Send Asynchronous TDLib Commands with sendSync Source: https://context7.com/up9cloud/flutter_libtdjson/llms.txt Demonstrates how to send asynchronous TDLib functions using the sendSync method. It includes examples for authentication, verification, and user profile retrieval while handling potential errors. ```dart import 'package:libtdjson/libtdjson.dart' show Service, Error; Future setPhoneNumber(Service service, String phoneNumber) async { try { final result = await service.sendSync({ '@type': 'setAuthenticationPhoneNumber', 'phone_number': phoneNumber, 'settings': { 'allow_flash_call': false, 'is_current_phone_number': false, 'allow_sms_retriever_api': false, } }); print('Phone number accepted: $result'); } on Error catch (e) { print('Failed: ${e.code} - ${e.message}'); } } Future checkAuthCode(Service service, String code) async { try { final result = await service.sendSync({ '@type': 'checkAuthenticationCode', 'code': code, }); print('Code verified: $result'); } on Error catch (e) { print('Invalid code: ${e.message}'); } } Future> getMe(Service service) async { return await service.sendSync({'@type': 'getMe'}); } Future logout(Service service) async { await service.sendSync({'@type': 'logOut'}); print('Logged out successfully'); } ``` -------------------------------- ### Initialize TDLib Service Source: https://context7.com/up9cloud/flutter_libtdjson/llms.txt Demonstrates how to instantiate the high-level Service class. It configures essential TDLib parameters like api_id, api_hash, and directory paths while setting up event logging handlers. ```dart import 'dart:io' show Directory; import 'package:libtdjson/libtdjson.dart' show Service, Error; import 'package:path_provider/path_provider.dart'; Future createTelegramService() async { Directory appDir = await getApplicationDocumentsDirectory(); Directory tempDir = await getTemporaryDirectory(); final service = Service( start: true, timeout: 10, newVerbosityLevel: 3, tdlibParameters: { 'api_id': 12345678, 'api_hash': 'your_api_hash_here', 'device_model': 'Flutter App', 'database_directory': appDir.path, 'files_directory': tempDir.path, 'system_language_code': 'en', 'application_version': '1.0.0', 'enable_storage_optimizer': true, 'use_test_dc': false, }, beforeSend: (obj) => print('Sending: $obj'), afterReceive: (obj) => print('Received: $obj'), onReceiveError: (Error e) => print('Error: ${e.code} - ${e.message}'), beforeExecute: (obj) => print('Executing: $obj'), afterExecute: (obj) => print('Execute result: $obj'), ); return service; } ``` -------------------------------- ### Configure macOS Network Entitlements Source: https://github.com/up9cloud/flutter_libtdjson/blob/master/example/README.md This snippet shows the XML structure to be added to the './macos/Runner/DebugProfile.entitlements' file. It grants the application network client access, which is often required for network-dependent applications. ```xml com.apple.security.network.client ``` -------------------------------- ### Run Android Application Source: https://github.com/up9cloud/flutter_libtdjson/blob/master/example/README.md Command to run the Flutter application on a specified Android device or emulator. Ensure the device ID is correctly provided. ```bash flutter run -d emulator-5554 ``` -------------------------------- ### Run macOS Application Source: https://github.com/up9cloud/flutter_libtdjson/blob/master/example/README.md Command to run the Flutter application on macOS. Ensure the target device is set to 'macos'. ```bash flutter run -d macos ``` -------------------------------- ### Regenerate macOS Project Files Source: https://github.com/up9cloud/flutter_libtdjson/blob/master/example/README.md Command sequence to regenerate the macOS project files for the libtdjson Flutter plugin. This process is analogous to the Android and iOS regeneration steps. ```bash flutter create --template plugin --platforms macos --project-name libtdjson _tmp rm -fr macos mv ./_tmp/example/macos . rm -fr _tmp ``` -------------------------------- ### Execute Synchronous Native TDLib Operations Source: https://context7.com/up9cloud/flutter_libtdjson/llms.txt Shows how to use the execute method for operations that do not require network calls, such as parsing text entities or retrieving file MIME types. ```dart import 'package:libtdjson/libtdjson.dart' show Service, Error; Future> parseMarkdown(Service service, String text) async { try { return await service.execute({ '@type': 'parseMarkdown', 'text': { '@type': 'formattedText', 'text': text, } }); } on Error catch (e) { print('Parse error: ${e.message}'); rethrow; } } Future getMimeType(Service service, String extension) async { final result = await service.execute({ '@type': 'getFileMimeType', 'file_name': 'file.$extension', }); return result['text']; } Future> parseTextEntities(Service service, String text, String parseMode) async { return await service.execute({ '@type': 'parseTextEntities', 'text': text, 'parse_mode': {'@type': parseMode}, }); } ``` -------------------------------- ### Implement Telegram Authentication Flow in Flutter Source: https://context7.com/up9cloud/flutter_libtdjson/llms.txt This snippet demonstrates a wrapper class for the libtdjson Service to handle the Telegram authentication state machine. It includes methods for initializing the service, submitting credentials, and handling authorization updates. ```dart import 'dart:io'; import 'package:libtdjson/libtdjson.dart' show Service, Error; import 'package:path_provider/path_provider.dart'; class TelegramAuth { late Service _service; String _currentAuthState = ''; Future initialize({ required int apiId, required String apiHash, }) async { final appDir = await getApplicationDocumentsDirectory(); final tempDir = await getTemporaryDirectory(); _service = Service( start: true, newVerbosityLevel: 2, tdlibParameters: { 'api_id': apiId, 'api_hash': apiHash, 'device_model': Platform.operatingSystem, 'database_directory': '${appDir.path}/tdlib', 'files_directory': '${tempDir.path}/tdlib', 'application_version': '1.0.0', 'enable_storage_optimizer': true, }, afterReceive: _handleUpdate, onReceiveError: (e) => print('TDLib Error: ${e.code} - ${e.message}'), ); } void _handleUpdate(Map update) { if (update['@type'] == 'updateAuthorizationState') { _currentAuthState = update['authorization_state']['@type']; print('Auth state: $_currentAuthState'); } } String get authState => _currentAuthState; bool get isReady => _currentAuthState == 'authorizationStateReady'; Future submitPhoneNumber(String phone) async { if (_currentAuthState != 'authorizationStateWaitPhoneNumber') { throw StateError('Not waiting for phone number'); } await _service.sendSync({ '@type': 'setAuthenticationPhoneNumber', 'phone_number': phone, 'settings': { 'allow_flash_call': false, 'is_current_phone_number': false, }, }); } Future submitCode(String code) async { if (_currentAuthState != 'authorizationStateWaitCode') { throw StateError('Not waiting for code'); } await _service.sendSync({ '@type': 'checkAuthenticationCode', 'code': code, }); } Future submitPassword(String password) async { if (_currentAuthState != 'authorizationStateWaitPassword') { throw StateError('Not waiting for password'); } await _service.sendSync({ '@type': 'checkAuthenticationPassword', 'password': password, }); } Future logout() async { await _service.sendSync({'@type': 'logOut'}); } Future dispose() async { await _service.stop(); } } ``` -------------------------------- ### Troubleshoot iOS Undefined Symbols Error Source: https://github.com/up9cloud/flutter_libtdjson/blob/master/example/README.md Command to help resolve 'Undefined symbols' errors on iOS, likely related to linking or build configurations. It executes a cleanup script. ```bash ./ios_cleanup_run.sh ``` -------------------------------- ### POST /auth/password Source: https://context7.com/up9cloud/flutter_libtdjson/llms.txt Submits the two-factor authentication password if enabled on the account. ```APIDOC ## POST /auth/password ### Description Submits the 2FA password required to complete the authentication process. ### Method POST ### Endpoint checkAuthenticationPassword ### Parameters #### Request Body - **password** (string) - Required - The 2FA password for the account. ### Request Example { "@type": "checkAuthenticationPassword", "password": "my_secret_password" } ``` -------------------------------- ### NativeClient: Direct FFI Bindings for TDLib in Dart Source: https://context7.com/up9cloud/flutter_libtdjson/llms.txt The NativeClient class provides the lowest-level access to TDLib via direct Foreign Function Interface (FFI) bindings. Function names precisely mirror the C symbols of the TDLib library. This class is intended for advanced users who require maximum control over native library interactions. It requires the Dart FFI and `libtdjson` packages. ```dart import 'dart:ffi'; import 'package:ffi/ffi.dart'; import 'package:libtdjson/libtdjson.dart' show NativeClient; // Load native library with custom path final nativeClient = NativeClient( dir: '/custom/lib/path', // Optional directory file: 'libtdjson.dylib', // Optional filename ); // Create client ID (new API) int clientId = nativeClient.td_create_client_id(); // Send request String request = '{"@type": "getOption", "name": "version"}'; nativeClient.td_send(clientId, request.toNativeUtf8()); // Receive response Pointer response = nativeClient.td_receive(10.0); if (response.address != nullptr.address) { print('Response: ${response.toDartString()}'); } // Execute synchronously Pointer result = nativeClient.td_execute( '{"@type": "getFileMimeType", "file_name": "test.pdf"}'.toNativeUtf8() ); print('Result: ${result.toDartString()}'); ``` -------------------------------- ### Regenerate iOS Project Files Source: https://github.com/up9cloud/flutter_libtdjson/blob/master/example/README.md Command sequence to regenerate the iOS project files for the libtdjson Flutter plugin. Similar to Android, it creates a temporary plugin, moves the iOS files, and cleans up. ```bash flutter create -i objc --template plugin --platforms ios --project-name libtdjson _tmp rm -fr ios mv ./_tmp/example/ios . rm -fr _tmp ``` -------------------------------- ### Regenerate Android Project Files Source: https://github.com/up9cloud/flutter_libtdjson/blob/master/example/README.md Command sequence to regenerate the Android project files for the libtdjson Flutter plugin. This involves creating a temporary plugin project, moving the generated Android files, and cleaning up the temporary directory. It also reminds the user to re-add necessary permissions to the AndroidManifest.xml. ```bash flutter create -a java --template plugin --platforms android --project-name libtdjson --org io.github.up9cloud _tmp rm -fr android mv ./_tmp/example/android . rm -fr _tmp # remember add the permission back to file "./android/app/src/main/AndroidManifest.xml" ``` -------------------------------- ### Initialize Flutter Web Application with Service Worker Source: https://github.com/up9cloud/flutter_libtdjson/blob/master/example/web/index.html This JavaScript snippet checks for service worker support in the browser. It registers the Flutter service worker and ensures that the main.dart.js file is loaded either via the service worker or as a fallback if the registration fails or is unsupported. ```javascript var serviceWorkerVersion = null; var scriptLoaded = false; function loadMainDartJs() { if (scriptLoaded) { return; } scriptLoaded = true; var scriptTag = document.createElement('script'); scriptTag.src = 'main.dart.js'; scriptTag.type = 'application/javascript'; document.body.append(scriptTag); } if ('serviceWorker' in navigator) { window.addEventListener('load', function () { var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion; navigator.serviceWorker.register(serviceWorkerUrl).then((reg) => { function waitForActivation(serviceWorker) { serviceWorker.addEventListener('statechange', () => { if (serviceWorker.state == 'activated') { console.log('Installed new service worker.'); loadMainDartJs(); } }); } if (!reg.active && (reg.installing || reg.waiting)) { waitForActivation(reg.installing ?? reg.waiting); } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) { console.log('New service worker available.'); reg.update(); waitForActivation(reg.installing); } else { console.log('Loading app from service worker.'); loadMainDartJs(); } }); setTimeout(() => { if (!scriptLoaded) { console.warn('Failed to load app from service worker. Falling back to plain