techno_kitchen_dart 1.1.2 copy "techno_kitchen_dart: ^1.1.2" to clipboard
techno_kitchen_dart: ^1.1.2 copied to clipboard

A library for interacting with the SDGB API.

example/techno_kitchen_dart_example.dart

import 'package:dotenv/dotenv.dart';
import 'package:techno_kitchen_dart/techno_kitchen_dart.dart';
import 'package:timezone/data/latest_10y.dart' as tzdata;

/// Example usage of Techno Kitchen Dart API client with UserSession.
///
/// ⚠️ DO NOT USE YOUR MAIN ACCOUNT.
///
/// The server-side API may change at any time,
/// which could make this library temporarily incompatible with newer versions.
/// However, you can still use it by customizing the parameters of
/// the TechnoKitchenClient to adapt to the latest API behavior.
///
/// This example shows how to:
/// 1. Create a UserSession from QR code or URL
/// 2. Initialize and login the session
/// 3. Fetch user data and music
/// 4. Handle session expiration
///
/// You must replace the sample QR code and user ID with valid test values.
void main() async {
  // Initialize time zones (required by some API logic)
  tzdata.initializeTimeZones();

  // Load configuration from environment variables
  final config = Config.fromEnv(DotEnv()..load());

  // === Example 1: Using UserSession with standard QR code format ===
  print('=== Example 1: UserSession with QR code ===\n');

  // Standard QR code format: SGWCMAID<16-digit timestamp YYMMDDHHMMSS><64-character code>
  final qrCode =
      'SGWCMAID250721114514A3CD1B92DB405AC9A0ED4C1B9E4AD0CDA23BE4C191D93C92BA0BD9A2C3D1EBCA';

  await runUserSessionExample(qrCode, config);

  // === Example 2: Using UserSession from URL format ===
  print('\n=== Example 2: UserSession from URL ===\n');

  // URL format from WeChat
  final qrUrl =
      'https://wq.waleak.net/qrcode/req/MAID250721114514A3CD1B92DB405AC9A0ED4C1B9E4AD0CDA23BE4C191D93C92BA0BD9A2C3D1EBCA.html?l=1770803025&t=E8889EE8908C4458202F20E4B8ADE4BA8CE88A82E5A58F20E799BBE585A5E4BA8CE7BBB4E7A081&d=E68A8AE4B88BE696B9E4BA8CE7BBB4E7A081EAE58FB0E689ABE68F8FE5A484EFBC8CE58FAFE794A8E69CBAE58FB0E69C89E34458090E4BE8889EE8908091E5928CE3CE88A82E5A5AFB9E5878CE8ADE4BA888090386E69CB58FE38091';

  try {
    final session = UserSession.fromUrl(qrUrl, config: config);
    print('Created session from URL');
    print('Parsed QR code: ${session.qrCode}');
    print('QR code generated at: ${_extractQRCodeTime(session.qrCode)}');
  } catch (e) {
    print('Error parsing URL: $e');
  }

  // === Example 3: Using TechnoKitchen.createSession ===
  print('\n=== Example 3: Using TechnoKitchen.createSession ===\n');

  final technoKitchen = TechnoKitchen(config);
  final session3 = technoKitchen.createSession(qrCode);
  print('Created session via TechnoKitchen.createSession');
  print('Session config: ${session3.config.requestAdapter.openGameID}');
}

/// Runs a complete UserSession example with the given QR code and config.
Future<void> runUserSessionExample(String qrCode, Config config) async {
  // Create a new UserSession
  final session = UserSession(qrCode, config);

  try {
    // === Step 1: Initialize Session ===
    // This validates the QR code (checks 10-minute expiration)
    // and exchanges it for a userId and token via qrApi
    print('Initializing session...');
    final userId = await session.init();
    print('Session initialized successfully!');
    print('User ID: $userId');
    print('Token: ${session.token.substring(0, 16)}...');

    // === Step 2: Get User Preview (can be called before login) ===
    print('\nFetching user preview...');
    final preview = await session.getUserPreview();
    print('User Preview: ${preview.userName}, Rating: ${preview.playerRating}');

    // === Step 3: Login ===
    // This establishes a session with the server (20-minute expiration)
    print('\nLogging in...');
    await session.login();
    print('Login successful!');
    print('Login ID: ${session.loginId ?? "N/A"}');
    print('Session expires in: ${session.remainingTime.inMinutes} minutes');

    // === Step 4: Fetch User Data (requires login) ===
    print('\nFetching user data...');
    final userData = await session.getUserData();
    print('User Name: ${userData.userData.userName}');
    print('Rating: ${userData.userData.playerRating}');
    print('Play Count: ${userData.userData.playCount}');
    print('DX Score: ${userData.userData.totalDeluxscore}');

    // === Step 5: Fetch User Music (requires login) ===
    print('\nFetching user music...');
    final userMusic = await session.getUserMusic(maxCount: 50);
    print('User Music received (${userMusic.length} chars)');

    // === Step 6: Logout ===
    print('\nLogging out...');
    await session.logout();
    print('Logout successful!');
    print('Session invalidated: ${session.isInvalidated}');
  } on QRCodeExpiredException catch (e) {
    print('QR code expired! Please generate a new QR code.');
    print('Details: $e');
  } on SessionExpiredException catch (e) {
    print('Session expired! Please login again.');
    print('Details: $e');
  } on NotInitializedException catch (e) {
    print('Session not initialized! Call init() first.');
    print('Details: $e');
  } on NotLoggedInException catch (e) {
    print('Not logged in! Call login() first.');
    print('Details: $e');
  } on SessionInvalidatedException catch (e) {
    print('Session invalidated! Create a new session.');
    print('Details: $e');
  } catch (e) {
    print('An error occurred: $e');
  }
}

/// Helper function to extract and format QR code generation time.
String _extractQRCodeTime(String qrCode) {
  try {
    // Extract timestamp (YYMMDDHHMMSS) from position 8 to 24
    final timestampStr = qrCode.substring(8, 24);
    final year = int.parse(timestampStr.substring(0, 2)) + 2000;
    final month = int.parse(timestampStr.substring(2, 4));
    final day = int.parse(timestampStr.substring(4, 6));
    final hour = int.parse(timestampStr.substring(6, 8));
    final minute = int.parse(timestampStr.substring(8, 10));
    final second = int.parse(timestampStr.substring(10, 12));

    return '$year-$month-$day $hour:$minute:$second';
  } catch (e) {
    return 'Unknown';
  }
}
1
likes
140
points
307
downloads

Publisher

verified publisherkamitsubaki.city

Weekly Downloads

A library for interacting with the SDGB API.

Repository (GitHub)

Documentation

API reference

License

MIT (license)

Dependencies

archive, cookie_jar, crypto, dio, dio_cookie_manager, dotenv, encrypt, intl, timezone

More

Packages that depend on techno_kitchen_dart