subconverter 0.2.34

A more powerful utility to convert between proxy subscription format
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
use crate::utils::file_wasm;
use crate::utils::system::safe_system_time;
use crate::vfs::vercel_kv_vfs::VercelKvVfs;
use crate::vfs::{vercel_kv_types::VirtualFileSystem, VfsError};
use js_sys::Math;
use log::{error, info};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::time::UNIX_EPOCH;
use wasm_bindgen::prelude::*;

const SHORT_URL_DIR: &str = "/short";
const ALPHABET: [char; 62] = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
    'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
    'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
    'V', 'W', 'X', 'Y', 'Z',
];

#[derive(Serialize, Deserialize, Debug)]
pub struct ShortUrlData {
    pub target_url: String,
    pub created_at: u64,
    pub last_used: Option<u64>,
    pub use_count: u64,
    pub custom_id: bool,
    pub description: Option<String>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct CreateShortUrlRequest {
    pub target_url: String,
    pub custom_id: Option<String>,
    pub description: Option<String>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct ShortUrlResponse {
    pub id: String,
    pub target_url: String,
    pub short_url: String,
    pub created_at: u64,
    pub last_used: Option<u64>,
    pub use_count: u64,
    pub custom_id: bool,
    pub description: Option<String>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct ShortUrlList {
    pub urls: Vec<ShortUrlResponse>,
}

async fn get_vfs() -> Result<VercelKvVfs, VfsError> {
    file_wasm::get_vfs()
        .await
        .map_err(|e| VfsError::Other(format!("Failed to get VFS: {}", e)))
}

// Generate a short ID using WASM-compatible random generation
fn generate_short_id(length: usize) -> String {
    let mut id = String::with_capacity(length);
    let alphabet_len = ALPHABET.len();

    for _ in 0..length {
        let random_index = (Math::random() * alphabet_len as f64).floor() as usize;
        id.push(ALPHABET[random_index]);
    }

    id
}

// Get current timestamp in seconds
fn current_timestamp() -> u64 {
    safe_system_time()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs()
}

// Create short URL directory if it doesn't exist
async fn ensure_short_dir_exists(vfs: &VercelKvVfs) -> Result<(), VfsError> {
    if !vfs.exists(SHORT_URL_DIR).await? {
        vfs.create_directory(SHORT_URL_DIR).await?;
        info!("Created short URL directory: {}", SHORT_URL_DIR);
    }
    Ok(())
}

// Build the full file path for a short ID
fn get_short_url_path(id: &str) -> String {
    format!("{}/{}.json", SHORT_URL_DIR, id)
}

// Build the full short URL for a short ID
fn get_full_short_url(request_url: &str, id: &str) -> String {
    // Extract base URL from the request
    let url_parts: Vec<&str> = request_url.split("/api/").collect();
    let base_url = url_parts[0];
    format!("{}/api/s/{}", base_url, id)
}

#[wasm_bindgen]
pub async fn short_url_create(
    request_json: String,
    request_url: String,
) -> Result<JsValue, JsValue> {
    info!("short_url_create called");

    // Parse request
    let request: CreateShortUrlRequest = match serde_json::from_str(&request_json) {
        Ok(req) => req,
        Err(e) => {
            error!("Error parsing create short URL request: {}", e);
            return Err(JsValue::from_str(&format!("Invalid request format: {}", e)));
        }
    };

    if request.target_url.is_empty() {
        return Err(JsValue::from_str("Target URL is required"));
    }

    let vfs = match get_vfs().await {
        Ok(vfs) => vfs,
        Err(e) => {
            error!("Error getting VFS: {}", e);
            return Err(JsValue::from_str(&format!("VFS error: {}", e)));
        }
    };

    // Ensure short URL directory exists
    if let Err(e) = ensure_short_dir_exists(&vfs).await {
        error!("Error ensuring short URL directory exists: {}", e);
        return Err(JsValue::from_str(&format!(
            "Error creating directory: {}",
            e
        )));
    }

    // Generate or use custom ID
    let id = if let Some(custom_id) = &request.custom_id {
        // Check if custom ID already exists
        let path = get_short_url_path(custom_id);
        if vfs.exists(&path).await.unwrap_or(false) {
            return Err(JsValue::from_str("Custom ID already exists"));
        }
        custom_id.clone()
    } else {
        // Generate a unique short ID
        let mut attempts = 0;
        let mut id;
        loop {
            // Start with 6 chars, increase if needed
            let length = 6 + attempts / 3;
            id = generate_short_id(length);
            let path = get_short_url_path(&id);
            if !vfs.exists(&path).await.unwrap_or(true) {
                break;
            }
            attempts += 1;
            if attempts > 10 {
                return Err(JsValue::from_str("Failed to generate a unique short ID"));
            }
        }
        id
    };

    // Create short URL data
    let short_url_data = ShortUrlData {
        target_url: request.target_url.clone(),
        created_at: current_timestamp(),
        last_used: None,
        use_count: 0,
        custom_id: request.custom_id.is_some(),
        description: request.description,
    };

    // Serialize to JSON
    let json_content = match serde_json::to_string(&short_url_data) {
        Ok(json) => json,
        Err(e) => {
            error!("Error serializing short URL data: {}", e);
            return Err(JsValue::from_str(&format!("Serialization error: {}", e)));
        }
    };

    // Write to VFS
    let path = get_short_url_path(&id);
    if let Err(e) = vfs.write_file(&path, json_content.into_bytes()).await {
        error!("Error writing short URL to VFS: {}", e);
        return Err(JsValue::from_str(&format!("Error saving short URL: {}", e)));
    }

    // Build response
    let short_url = get_full_short_url(&request_url, &id);
    let response = ShortUrlResponse {
        id: id.clone(),
        target_url: request.target_url,
        short_url,
        created_at: short_url_data.created_at,
        last_used: None,
        use_count: 0,
        custom_id: request.custom_id.is_some(),
        description: short_url_data.description,
    };

    // Return response
    match serde_json::to_string(&response) {
        Ok(json) => Ok(JsValue::from_str(&json)),
        Err(e) => {
            error!("Error serializing response: {}", e);
            Err(JsValue::from_str(&format!(
                "Error creating response: {}",
                e
            )))
        }
    }
}

#[wasm_bindgen]
pub async fn short_url_resolve(id: String) -> Result<JsValue, JsValue> {
    info!("short_url_resolve called for ID: {}", id);

    // Validate ID
    if id.is_empty() {
        return Err(JsValue::from_str("Short URL ID is required"));
    }

    let vfs = match get_vfs().await {
        Ok(vfs) => vfs,
        Err(e) => {
            error!("Error getting VFS: {}", e);
            return Err(JsValue::from_str(&format!("VFS error: {}", e)));
        }
    };

    // Get the short URL data
    let path = get_short_url_path(&id);
    let content = match vfs.read_file(&path).await {
        Ok(content) => content,
        Err(e) => {
            error!("Error reading short URL: {}", e);
            return Err(JsValue::from_str(&format!("Short URL not found: {}", e)));
        }
    };

    // Parse short URL data
    let mut short_url_data: ShortUrlData = match serde_json::from_slice(&content) {
        Ok(data) => data,
        Err(e) => {
            error!("Error parsing short URL data: {}", e);
            return Err(JsValue::from_str(&format!("Invalid short URL data: {}", e)));
        }
    };

    // Update usage statistics
    short_url_data.last_used = Some(current_timestamp());
    short_url_data.use_count += 1;

    // Write updated data back
    let updated_json = match serde_json::to_string(&short_url_data) {
        Ok(json) => json,
        Err(e) => {
            error!("Error serializing updated short URL data: {}", e);
            return Err(JsValue::from_str(&format!("Serialization error: {}", e)));
        }
    };

    if let Err(e) = vfs.write_file(&path, updated_json.into_bytes()).await {
        error!("Error updating short URL stats: {}", e);
        // Continue even if update fails
    }

    // Return target URL for redirection
    let response = json!({
        "target_url": short_url_data.target_url,
        "use_count": short_url_data.use_count
    });

    Ok(JsValue::from_str(&response.to_string()))
}

#[wasm_bindgen]
pub async fn short_url_delete(id: String) -> Result<JsValue, JsValue> {
    info!("short_url_delete called for ID: {}", id);

    // Validate ID
    if id.is_empty() {
        return Err(JsValue::from_str("Short URL ID is required"));
    }

    let vfs = match get_vfs().await {
        Ok(vfs) => vfs,
        Err(e) => {
            error!("Error getting VFS: {}", e);
            return Err(JsValue::from_str(&format!("VFS error: {}", e)));
        }
    };

    // Check if the short URL exists
    let path = get_short_url_path(&id);
    if !vfs.exists(&path).await.unwrap_or(false) {
        return Err(JsValue::from_str("Short URL not found"));
    }

    // Delete the short URL
    if let Err(e) = vfs.delete_file(&path).await {
        error!("Error deleting short URL: {}", e);
        return Err(JsValue::from_str(&format!(
            "Error deleting short URL: {}",
            e
        )));
    }

    // Return success
    Ok(JsValue::from_str("{\"success\":true}"))
}

/// List all short URLs in the system.
///
/// This function uses list_directory_skip_github to avoid loading repository data from GitHub,
/// as short URLs are exclusively stored in the KV store and never in the GitHub repository.
/// This improves performance by skipping unnecessary GitHub API calls.
#[wasm_bindgen]
pub async fn short_url_list() -> Result<JsValue, JsValue> {
    info!("short_url_list called");

    let vfs = match get_vfs().await {
        Ok(vfs) => vfs,
        Err(e) => {
            error!("Error getting VFS: {}", e);
            return Err(JsValue::from_str(&format!("VFS error: {}", e)));
        }
    };

    // Ensure short URL directory exists
    if let Err(e) = ensure_short_dir_exists(&vfs).await {
        error!("Error ensuring short URL directory exists: {}", e);
        return Err(JsValue::from_str(&format!(
            "Error accessing directory: {}",
            e
        )));
    }

    // List all files in the short URL directory (skip GitHub loading)
    let entries = match vfs.list_directory_skip_github(SHORT_URL_DIR).await {
        Ok(entries) => entries,
        Err(e) => {
            error!("Error listing short URLs: {}", e);
            return Err(JsValue::from_str(&format!(
                "Error listing short URLs: {}",
                e
            )));
        }
    };

    // Process each short URL file
    let mut urls = Vec::new();
    for entry in entries {
        if entry.is_directory || !entry.path.ends_with(".json") {
            continue;
        }

        // Extract ID from filename
        let filename = entry.name.strip_suffix(".json").unwrap_or(&entry.name);

        // Read short URL data
        let content = match vfs.read_file(&entry.path).await {
            Ok(content) => content,
            Err(e) => {
                error!("Error reading short URL {}: {}", entry.path, e);
                continue;
            }
        };

        // Parse short URL data
        let short_url_data: ShortUrlData = match serde_json::from_slice(&content) {
            Ok(data) => data,
            Err(e) => {
                error!("Error parsing short URL data {}: {}", entry.path, e);
                continue;
            }
        };

        // Base URL can't be determined here, will be filled in on frontend
        let short_url = format!("/api/s/{}", filename);

        // Create response object
        let url = ShortUrlResponse {
            id: filename.to_string(),
            target_url: short_url_data.target_url,
            short_url,
            created_at: short_url_data.created_at,
            last_used: short_url_data.last_used,
            use_count: short_url_data.use_count,
            custom_id: short_url_data.custom_id,
            description: short_url_data.description,
        };

        urls.push(url);
    }

    // Sort by creation date (newest first)
    urls.sort_by(|a, b| b.created_at.cmp(&a.created_at));

    // Return the list
    let response = ShortUrlList { urls };
    match serde_json::to_string(&response) {
        Ok(json) => Ok(JsValue::from_str(&json)),
        Err(e) => {
            error!("Error serializing response: {}", e);
            Err(JsValue::from_str(&format!(
                "Error creating response: {}",
                e
            )))
        }
    }
}

#[wasm_bindgen]
pub async fn short_url_update(id: String, request_json: String) -> Result<JsValue, JsValue> {
    info!("short_url_update called for ID: {}", id);

    // Validate ID
    if id.is_empty() {
        return Err(JsValue::from_str("Short URL ID is required"));
    }

    // Parse request
    let request: Value = match serde_json::from_str(&request_json) {
        Ok(req) => req,
        Err(e) => {
            error!("Error parsing update short URL request: {}", e);
            return Err(JsValue::from_str(&format!("Invalid request format: {}", e)));
        }
    };

    let vfs = match get_vfs().await {
        Ok(vfs) => vfs,
        Err(e) => {
            error!("Error getting VFS: {}", e);
            return Err(JsValue::from_str(&format!("VFS error: {}", e)));
        }
    };

    // Get the short URL data
    let path = get_short_url_path(&id);
    let content = match vfs.read_file(&path).await {
        Ok(content) => content,
        Err(e) => {
            error!("Error reading short URL: {}", e);
            return Err(JsValue::from_str(&format!("Short URL not found: {}", e)));
        }
    };

    // Parse short URL data
    let mut short_url_data: ShortUrlData = match serde_json::from_slice(&content) {
        Ok(data) => data,
        Err(e) => {
            error!("Error parsing short URL data: {}", e);
            return Err(JsValue::from_str(&format!("Invalid short URL data: {}", e)));
        }
    };

    // Update fields
    if let Some(target_url) = request.get("target_url").and_then(|v| v.as_str()) {
        if !target_url.is_empty() {
            short_url_data.target_url = target_url.to_string();
        }
    }

    if let Some(description) = request.get("description") {
        short_url_data.description = if description.is_null() {
            None
        } else {
            description.as_str().map(|s| s.to_string())
        };
    }

    // Write updated data
    let updated_json = match serde_json::to_string(&short_url_data) {
        Ok(json) => json,
        Err(e) => {
            error!("Error serializing updated short URL data: {}", e);
            return Err(JsValue::from_str(&format!("Serialization error: {}", e)));
        }
    };

    if let Err(e) = vfs.write_file(&path, updated_json.into_bytes()).await {
        error!("Error updating short URL: {}", e);
        return Err(JsValue::from_str(&format!(
            "Error updating short URL: {}",
            e
        )));
    }

    // Return updated data
    let response = json!({
        "id": id,
        "target_url": short_url_data.target_url,
        "short_url": format!("/api/s/{}", id),
        "created_at": short_url_data.created_at,
        "last_used": short_url_data.last_used,
        "use_count": short_url_data.use_count,
        "custom_id": short_url_data.custom_id,
        "description": short_url_data.description
    });

    Ok(JsValue::from_str(&response.to_string()))
}

#[wasm_bindgen]
pub async fn short_url_move(
    id: String,
    new_id: String,
    request_url: String,
) -> Result<JsValue, JsValue> {
    info!("short_url_move called for ID: {} -> {}", id, new_id);

    // Validate IDs
    if id.is_empty() || new_id.is_empty() {
        return Err(JsValue::from_str(
            "Both source and destination IDs are required",
        ));
    }

    // Ensure IDs are different
    if id == new_id {
        return Err(JsValue::from_str(
            "Source and destination IDs must be different",
        ));
    }

    let vfs = match get_vfs().await {
        Ok(vfs) => vfs,
        Err(e) => {
            error!("Error getting VFS: {}", e);
            return Err(JsValue::from_str(&format!("VFS error: {}", e)));
        }
    };

    // Ensure short URL directory exists
    if let Err(e) = ensure_short_dir_exists(&vfs).await {
        error!("Error ensuring short URL directory exists: {}", e);
        return Err(JsValue::from_str(&format!(
            "Error with short URL directory: {}",
            e
        )));
    }

    // Check if source exists
    let source_path = get_short_url_path(&id);
    if !vfs.exists(&source_path).await.unwrap_or(false) {
        return Err(JsValue::from_str("Source short URL not found"));
    }

    // Check if destination already exists
    let dest_path = get_short_url_path(&new_id);
    if vfs.exists(&dest_path).await.unwrap_or(false) {
        return Err(JsValue::from_str("Destination ID already exists"));
    }

    // Read the source file content
    let content = match vfs.read_file(&source_path).await {
        Ok(content) => content,
        Err(e) => {
            error!("Error reading source short URL: {}", e);
            return Err(JsValue::from_str(&format!(
                "Error reading source short URL: {}",
                e
            )));
        }
    };

    // Parse short URL data
    let mut short_url_data: ShortUrlData = match serde_json::from_slice(&content) {
        Ok(data) => data,
        Err(e) => {
            error!("Error parsing short URL data: {}", e);
            return Err(JsValue::from_str(&format!("Invalid short URL data: {}", e)));
        }
    };

    // Update the custom_id flag based on whether new_id is a custom ID or not
    short_url_data.custom_id = true; // Since we're explicitly moving it, it's a custom ID now

    // Serialize updated data
    let updated_json = match serde_json::to_string(&short_url_data) {
        Ok(json) => json,
        Err(e) => {
            error!("Error serializing updated short URL data: {}", e);
            return Err(JsValue::from_str(&format!("Serialization error: {}", e)));
        }
    };

    // Write to destination
    if let Err(e) = vfs.write_file(&dest_path, updated_json.into_bytes()).await {
        error!("Error writing to destination path: {}", e);
        return Err(JsValue::from_str(&format!(
            "Error creating new short URL: {}",
            e
        )));
    }

    // Delete the source file
    if let Err(e) = vfs.delete_file(&source_path).await {
        error!("Error deleting source short URL: {}", e);
        return Err(JsValue::from_str(&format!(
            "Warning: Created new short URL but failed to delete old one: {}",
            e
        )));
    }

    // Return updated data
    let short_url = get_full_short_url(&request_url, &new_id);
    let response = json!({
        "id": new_id,
        "target_url": short_url_data.target_url,
        "short_url": short_url,
        "created_at": short_url_data.created_at,
        "last_used": short_url_data.last_used,
        "use_count": short_url_data.use_count,
        "custom_id": short_url_data.custom_id,
        "description": short_url_data.description,
        "old_id": id
    });

    Ok(JsValue::from_str(&response.to_string()))
}