actr-cli 0.1.15

Command line tool for Actor-RTC framework projects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
use super::{InitContext, ProjectInitializer, create_local_proto, create_protoc_plugin_config};
use crate::error::Result;
use crate::templates::ProjectTemplateName;
use crate::utils::read_fixture_text;
use async_trait::async_trait;
use std::path::{Path, PathBuf};
use tracing::info;

pub struct KotlinInitializer;

#[async_trait]
impl ProjectInitializer for KotlinInitializer {
    async fn generate_project_structure(&self, context: &InitContext) -> Result<()> {
        match context.template {
            ProjectTemplateName::Echo => self.generate_echo_project(context).await,
            ProjectTemplateName::DataStream => self.generate_data_stream_project(context).await,
        }
    }

    fn print_next_steps(&self, context: &InitContext) {
        let _project_name_pascal = to_pascal_case(&context.project_name);
        let package_path = to_package_name(&context.project_name).replace('.', "/");

        info!("");
        info!("Next steps:");
        if !context.is_current_dir {
            info!("  cd {}", context.project_dir.display());
        }
        info!("  actr install  # Install remote protobuf dependencies from Actr.toml");

        match context.template {
            ProjectTemplateName::Echo => {
                info!(
                    "  actr gen -l kotlin -i protos/remote/echo-echo-server/echo.proto -o app/src/main/java/{}/generated",
                    package_path
                );
            }
            ProjectTemplateName::DataStream => {
                info!("  actr gen -l kotlin  # Generate code for stream-echo-server-python");
            }
        }
        info!("  ./gradlew assembleDebug");
        info!("  # Install APK: adb install app/build/outputs/apk/debug/app-debug.apk");
        info!("");
        info!("💡 Tips:");
        info!("  - For Android emulator, use ws://10.0.2.2:PORT to reach host localhost");
        info!("  - actr-kotlin library is fetched from JitPack automatically");
        info!(
            "  - Generated framework code is in app/src/main/java/{}/generated/",
            package_path
        );
        info!("  - Run tests: ./gradlew connectedDebugAndroidTest");
    }
}

impl KotlinInitializer {
    async fn generate_echo_project(&self, context: &InitContext) -> Result<()> {
        // Note: proto files are no longer created during init, they will be pulled via actr install

        let project_name_pascal = to_pascal_case(&context.project_name);
        let package_name = to_package_name(&context.project_name);
        let package_path = package_name.replace('.', "/");

        let signaling_host = extract_signaling_host(&context.signaling_url);

        let replacements = vec![
            ("{{PROJECT_NAME}}".to_string(), context.project_name.clone()),
            (
                "{{PROJECT_NAME_PASCAL}}".to_string(),
                project_name_pascal.clone(),
            ),
            ("{{PACKAGE_NAME}}".to_string(), package_name.clone()),
            ("{{PACKAGE_PATH}}".to_string(), package_path.clone()),
            (
                "{{SIGNALING_URL}}".to_string(),
                context.signaling_url.clone(),
            ),
            ("{{SIGNALING_HOST}}".to_string(), signaling_host),
        ];

        let fixtures_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures");
        let app_dir = context.project_dir.join("app");
        let java_dir = app_dir.join("src/main/java").join(&package_path);

        let files = vec![
            // Root level files
            (
                fixtures_root.join("kotlin/settings.gradle.kts"),
                context.project_dir.join("settings.gradle.kts"),
            ),
            (
                fixtures_root.join("kotlin/build.gradle.kts"),
                context.project_dir.join("build.gradle.kts"),
            ),
            (
                fixtures_root.join("kotlin/gradle.properties"),
                context.project_dir.join("gradle.properties"),
            ),
            (
                fixtures_root.join("kotlin/echo/Actr.toml"),
                context.project_dir.join("Actr.toml"),
            ),
            (
                fixtures_root.join("kotlin/gitignore"),
                context.project_dir.join(".gitignore"),
            ),
            // App module files
            (
                fixtures_root.join("kotlin/app/build.gradle.kts"),
                app_dir.join("build.gradle.kts"),
            ),
            (
                fixtures_root.join("kotlin/app/src/main/AndroidManifest.xml"),
                app_dir.join("src/main/AndroidManifest.xml"),
            ),
            // Resources
            (
                fixtures_root.join("kotlin/app/src/main/res/values/strings.xml"),
                app_dir.join("src/main/res/values/strings.xml"),
            ),
            (
                fixtures_root.join("kotlin/app/src/main/res/values/colors.xml"),
                app_dir.join("src/main/res/values/colors.xml"),
            ),
            (
                fixtures_root.join("kotlin/app/src/main/res/values/themes.xml"),
                app_dir.join("src/main/res/values/themes.xml"),
            ),
            (
                fixtures_root.join("kotlin/app/src/main/res/layout/activity_main.xml"),
                app_dir.join("src/main/res/layout/activity_main.xml"),
            ),
            // Kotlin source files
            (
                fixtures_root.join("kotlin/echo/MainActivity.kt"),
                java_dir.join("MainActivity.kt"),
            ),
            // Android Test files
            (
                fixtures_root.join("kotlin/echo/EchoIntegrationTest.kt"),
                app_dir
                    .join("src/androidTest/java")
                    .join(&package_path)
                    .join("EchoIntegrationTest.kt"),
            ),
        ];

        for (fixture_path, output_path) in files {
            let template = read_fixture_text(&fixture_path)?;
            let rendered = apply_placeholders(&template, &replacements);
            write_file(&output_path, &rendered)?;
        }

        create_protoc_plugin_config(&context.project_dir)?;

        // Copy gradle wrapper
        copy_gradle_wrapper(&context.project_dir)?;

        // Create local.proto file
        create_local_proto(
            &context.project_dir,
            &context.project_name,
            "protos/local",
            context.template,
        )?;

        info!("📁 Created Android Echo project structure");
        Ok(())
    }

    async fn generate_data_stream_project(&self, context: &InitContext) -> Result<()> {
        let project_name_pascal = to_pascal_case(&context.project_name);
        let package_name = to_package_name(&context.project_name);
        let package_path = package_name.replace('.', "/");

        let signaling_host = extract_signaling_host(&context.signaling_url);

        let replacements = vec![
            ("{{PROJECT_NAME}}".to_string(), context.project_name.clone()),
            (
                "{{PROJECT_NAME_PASCAL}}".to_string(),
                project_name_pascal.clone(),
            ),
            ("{{PACKAGE_NAME}}".to_string(), package_name.clone()),
            ("{{PACKAGE_PATH}}".to_string(), package_path.clone()),
            (
                "{{SIGNALING_URL}}".to_string(),
                context.signaling_url.clone(),
            ),
            ("{{SIGNALING_HOST}}".to_string(), signaling_host),
        ];

        let fixtures_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures");
        let app_dir = context.project_dir.join("app");
        let java_dir = app_dir.join("src/main/java").join(&package_path);

        let files = vec![
            // Root level files
            (
                fixtures_root.join("kotlin/settings.gradle.kts"),
                context.project_dir.join("settings.gradle.kts"),
            ),
            (
                fixtures_root.join("kotlin/build.gradle.kts"),
                context.project_dir.join("build.gradle.kts"),
            ),
            (
                fixtures_root.join("kotlin/gradle.properties"),
                context.project_dir.join("gradle.properties"),
            ),
            (
                fixtures_root.join("kotlin/data-stream/Actr.toml"),
                context.project_dir.join("Actr.toml"),
            ),
            (
                fixtures_root.join("kotlin/gitignore"),
                context.project_dir.join(".gitignore"),
            ),
            // App module files
            (
                fixtures_root.join("kotlin/app/build.gradle.kts"),
                app_dir.join("build.gradle.kts"),
            ),
            (
                fixtures_root.join("kotlin/app/src/main/AndroidManifest.xml"),
                app_dir.join("src/main/AndroidManifest.xml"),
            ),
            // Resources
            (
                fixtures_root.join("kotlin/app/src/main/res/values/strings.xml"),
                app_dir.join("src/main/res/values/strings.xml"),
            ),
            (
                fixtures_root.join("kotlin/app/src/main/res/values/colors.xml"),
                app_dir.join("src/main/res/values/colors.xml"),
            ),
            (
                fixtures_root.join("kotlin/app/src/main/res/values/themes.xml"),
                app_dir.join("src/main/res/values/themes.xml"),
            ),
            (
                fixtures_root.join("kotlin/data-stream/activity_main.xml"),
                app_dir.join("src/main/res/layout/activity_main.xml"),
            ),
            // Kotlin source files
            (
                fixtures_root.join("kotlin/data-stream/MainActivity.kt"),
                java_dir.join("MainActivity.kt"),
            ),
            (
                fixtures_root.join("kotlin/data-stream/MyUnifiedHandler.kt"),
                java_dir.join("MyUnifiedHandler.kt"),
            ),
            // Android Test files
            (
                fixtures_root.join("kotlin/data-stream/DataStreamIntegrationTest.kt"),
                app_dir
                    .join("src/androidTest/java")
                    .join(&package_path)
                    .join("DataStreamIntegrationTest.kt"),
            ),
        ];

        for (fixture_path, output_path) in files {
            let template = read_fixture_text(&fixture_path)?;
            let rendered = apply_placeholders(&template, &replacements);
            write_file(&output_path, &rendered)?;
        }

        // Copy gradle wrapper
        copy_gradle_wrapper(&context.project_dir)?;

        // Create local stream_client.proto file for data-stream template
        create_data_stream_local_proto(&context.project_dir)?;

        info!("📁 Created Android DataStream project structure");
        Ok(())
    }
}

/// Extract host from signaling URL
/// e.g., "ws://10.30.3.206:8081/signaling/ws" -> "10.30.3.206"
/// or "wss://actrix1.develenv.com/signaling/ws" -> "actrix1.develenv.com"
fn extract_signaling_host(signaling_url: &str) -> String {
    signaling_url
        .trim_start_matches("ws://")
        .trim_start_matches("wss://")
        .split('/')
        .next()
        .unwrap_or("10.0.2.2")
        .split(':')
        .next()
        .unwrap_or("10.0.2.2")
        .to_string()
}

fn write_file(path: &Path, content: &str) -> Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(path, content)?;
    Ok(())
}

fn apply_placeholders(template: &str, replacements: &[(String, String)]) -> String {
    let mut rendered = template.to_string();
    for (key, value) in replacements {
        rendered = rendered.replace(key, value);
    }
    rendered
}

/// Create the local stream_client.proto file for data-stream template
fn create_data_stream_local_proto(project_dir: &Path) -> Result<()> {
    let proto_dir = project_dir.join("protos/local/stream_client");
    std::fs::create_dir_all(&proto_dir)?;

    let proto_content = r#"syntax = "proto3";

// Must use the same package as the remote proto for route key matching
// Server callback uses route key: stream_server.StreamClient.PrepareClientStream
package stream_server;

// Import the remote proto to reuse RegisterStreamResponse
import "remote/stream-echo-server-python/stream_server.proto";

// Request from server to client to prepare for receiving data stream
// NOTE: This is only defined here (server side has its own definition that matches)
message PrepareClientStreamRequest {
  string stream_id = 1;
  int32 expected_count = 2;
}

// Response for prepare client stream (local only)
message PrepareClientStreamResponse {
  bool ready = 1;
  string message = 2;
}

// Request to start a stream (local only, different name to avoid conflict)
message ClientStartStreamRequest {
  string client_id = 1;
  string stream_id = 2;
  int32 message_count = 3;
}

// Response for starting a stream (local only, different name to avoid conflict)
message ClientStartStreamResponse {
  bool accepted = 1;
  string message = 2;
}

// StreamClient service - must match server's expectation
// Server will callback using: stream_server.StreamClient.PrepareClientStream
service StreamClient {
  // Called by the server to prepare the client for receiving data stream
  rpc PrepareClientStream(PrepareClientStreamRequest) returns (PrepareClientStreamResponse);
  // Called locally to start a stream transfer (uses different message names to avoid conflict)
  rpc StartStream(ClientStartStreamRequest) returns (ClientStartStreamResponse);
}
"#;

    std::fs::write(proto_dir.join("stream_client.proto"), proto_content)?;
    info!("📄 Created local stream_client.proto");
    Ok(())
}

fn to_pascal_case(input: &str) -> String {
    let mut result = String::new();
    let mut start_of_word = true;

    for c in input.chars() {
        if !c.is_alphanumeric() {
            start_of_word = true;
            continue;
        }

        if c.is_uppercase() {
            result.push(c);
            start_of_word = false;
        } else if start_of_word {
            result.push(c.to_uppercase().next().unwrap_or(c));
            start_of_word = false;
        } else {
            result.push(c.to_lowercase().next().unwrap_or(c));
        }
    }

    result
}

fn to_package_name(project_name: &str) -> String {
    // Convert project name to valid Android package name
    // e.g., "my-echo-client" -> "io.actr.myechoclient"
    let clean_name: String = project_name
        .chars()
        .filter(|c| c.is_alphanumeric())
        .collect::<String>()
        .to_lowercase();
    format!("io.actr.{}", clean_name)
}

fn copy_gradle_wrapper(project_dir: &Path) -> Result<()> {
    // Create gradle wrapper directory
    let wrapper_dir = project_dir.join("gradle/wrapper");
    std::fs::create_dir_all(&wrapper_dir)?;

    // Create gradle-wrapper.properties
    // Note: AGP 8.12+ requires Gradle 8.13+
    let wrapper_properties = r#"distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
"#;
    std::fs::write(
        wrapper_dir.join("gradle-wrapper.properties"),
        wrapper_properties,
    )?;

    // Copy gradle-wrapper.jar (binary file)
    let wrapper_jar = include_bytes!("../../../fixtures/kotlin/gradle-wrapper.jar");
    std::fs::write(wrapper_dir.join("gradle-wrapper.jar"), wrapper_jar)?;

    // Create gradlew script
    let gradlew = include_str!("../../../fixtures/kotlin/gradlew");
    if !gradlew.is_empty() {
        std::fs::write(project_dir.join("gradlew"), gradlew)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(
                project_dir.join("gradlew"),
                std::fs::Permissions::from_mode(0o755),
            )?;
        }
    } else {
        // Fallback: create a minimal gradlew that downloads the wrapper
        let gradlew_fallback = r#"#!/bin/sh
echo "Please download gradle wrapper from https://gradle.org/releases/"
echo "Or run: gradle wrapper --gradle-version 8.11.1"
exit 1
"#;
        std::fs::write(project_dir.join("gradlew"), gradlew_fallback)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(
                project_dir.join("gradlew"),
                std::fs::Permissions::from_mode(0o755),
            )?;
        }
    }

    info!("📦 Created Gradle wrapper configuration");
    Ok(())
}