identity_create.rs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. //! Example for creating a new Threema ID.
  2. #![expect(unused_crate_dependencies, reason = "Example triggered false positive")]
  3. #![expect(clippy::print_stdout, reason = "Examples are allowed to print")]
  4. use clap::{ArgAction, Parser};
  5. use libthreema::{
  6. cli::config::{CommonConfig, CommonConfigOptions},
  7. common::ClientInfo,
  8. csp_e2e::identity::create::{
  9. CreateIdentityContext, CreateIdentityLoop, CreateIdentityResponse, CreateIdentityResult,
  10. CreateIdentityTask,
  11. },
  12. https::cli::https_client_builder,
  13. utils::logging::init_stderr_logging,
  14. };
  15. use libthreema_dependencies::data_encoding::HEXLOWER_PERMISSIVE;
  16. use tracing::Level;
  17. #[derive(Parser)]
  18. #[command()]
  19. struct CreateIdentityCommand {
  20. #[command(flatten)]
  21. config: CommonConfigOptions,
  22. /// Turn on debugging information.
  23. /// Use -v -vv to control log level.
  24. #[arg(short, action = ArgAction::Count)]
  25. verbose: u8,
  26. }
  27. async fn run_create_identity(
  28. http_client: reqwest::Client,
  29. context: CreateIdentityContext,
  30. ) -> anyhow::Result<CreateIdentityResult> {
  31. let mut task = CreateIdentityTask::new(context);
  32. loop {
  33. match task.poll()? {
  34. CreateIdentityLoop::Instruction(instruction) => {
  35. let result = instruction.request.send(&http_client).await;
  36. task.response(CreateIdentityResponse { result })?;
  37. },
  38. CreateIdentityLoop::Done(result) => return Ok(result),
  39. }
  40. }
  41. }
  42. #[tokio::main]
  43. async fn main() -> anyhow::Result<()> {
  44. // Parse arguments for command
  45. let arguments = CreateIdentityCommand::parse();
  46. // Configure logging
  47. let log_level = match arguments.verbose {
  48. 1 => Level::DEBUG,
  49. 2 => Level::TRACE,
  50. _ => Level::INFO,
  51. };
  52. init_stderr_logging(log_level);
  53. // Create HTTP client
  54. let http_client = https_client_builder().build()?;
  55. let config = CommonConfig::from_options(&http_client, arguments.config).await?;
  56. // Create identity
  57. let CreateIdentityResult {
  58. identity,
  59. client_key,
  60. server_group,
  61. } = run_create_identity(
  62. http_client,
  63. CreateIdentityContext {
  64. client_info: ClientInfo::Libthreema,
  65. config: config.config,
  66. flavor: config.flavor,
  67. },
  68. )
  69. .await?;
  70. println!("--threema-id {identity}");
  71. println!(
  72. "--client-key {}",
  73. HEXLOWER_PERMISSIVE.encode(client_key.as_bytes())
  74. );
  75. println!("--csp-server-group {}", server_group.as_str());
  76. Ok(())
  77. }
  78. #[test]
  79. fn verify_cli() {
  80. use clap::CommandFactory;
  81. CreateIdentityCommand::command().debug_assert();
  82. }