scratch-io 0.1.4

A rust library for managing, downloading, and launching games from itch.io
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
pub mod errors;
mod extract;
mod filesystem;
mod game_files;
mod heuristics;
pub mod itch_api;
pub mod itch_manifest;
pub mod wharf;

pub use crate::itch_api::ItchClient;
use crate::itch_api::{types::*, *};

use md5::{Digest, Md5};
use reqwest::{Method, Response, header};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::path::{Path, PathBuf};
use tokio::io::AsyncBufReadExt;
use tokio::time::{Duration, Instant};

// This isn't inside itch_types because it is not something that the itch API returns
// These platforms are *interpreted* from the data provided by the API
/// The different platforms a upload can be made for
#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize, clap::ValueEnum)]
pub enum GamePlatform {
  Linux,
  Windows,
  OSX,
  Android,
  Web,
  Flash,
  Java,
  UnityWebPlayer,
}

impl Upload {
  #[must_use]
  pub fn to_game_platforms(&self) -> Vec<GamePlatform> {
    let mut platforms: Vec<GamePlatform> = Vec::new();

    match self.r#type {
      UploadType::Html => platforms.push(GamePlatform::Web),
      UploadType::Flash => platforms.push(GamePlatform::Flash),
      UploadType::Java => platforms.push(GamePlatform::Java),
      UploadType::Unity => platforms.push(GamePlatform::UnityWebPlayer),
      _ => (),
    }

    for t in &self.traits {
      match t {
        UploadTrait::PLinux => platforms.push(GamePlatform::Linux),
        UploadTrait::PWindows => platforms.push(GamePlatform::Windows),
        UploadTrait::POsx => platforms.push(GamePlatform::OSX),
        UploadTrait::PAndroid => platforms.push(GamePlatform::Android),
        UploadTrait::Demo => (),
      }
    }

    platforms
  }
}

pub enum DownloadStatus {
  Warning(String),
  StartingDownload { bytes_to_download: u64 },
  DownloadProgress { downloaded_bytes: u64 },
  Extract,
}

pub enum LaunchMethod {
  AlternativeExecutable {
    executable_path: PathBuf,
  },
  ManifestAction {
    manifest_action_name: String,
  },
  Heuristics {
    game_platform: GamePlatform,
    game_title: String,
  },
}

/// Some information about a installed upload
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InstalledUpload {
  pub upload_id: UploadID,
  pub game_folder: PathBuf,
  pub game_id: GameID,
  pub game_title: String,
}

/// Hash a file into a MD5 hasher
///
/// # Arguments
///
/// * `readable` - Anything that implements [`tokio::io::AsyncRead`] to read the data from, could be a File
///
/// * `hasher` - A mutable reference to a MD5 hasher, which will be updated with the file data
///
/// # Returns
///
/// An error if something goes wrong
async fn hash_readable_async(
  readable: impl tokio::io::AsyncRead + Unpin,
  hasher: &mut Md5,
) -> Result<(), String> {
  let mut br = tokio::io::BufReader::new(readable);

  loop {
    let buffer = filesystem::fill_buffer(&mut br).await?;

    // If buffer is empty then BufReader has reached the EOF
    if buffer.is_empty() {
      break Ok(());
    }

    // Update the hasher
    hasher.update(buffer);

    // Marked the hashed bytes as read
    let len = buffer.len();
    br.consume(len);
  }
}

/// Stream a reqwest [`Response`] into a [`tokio::fs::File`] async
///
/// # Arguments
///
/// * `response` - A file download response
///
/// * `file` - An opened [`tokio::fs::File`] with write access
///
/// * `md5_hash` - If provided, the hasher to update with the received data
///
/// * `progress_callback` - A closure called with the number of downloaded bytes at the moment
///
/// * `callback_interval` - The minimum time span between each `progress_callback` call
///
/// # Returns
///
/// The total downloaded bytes
///
/// An error if something goes wrong
async fn stream_response_into_file(
  response: Response,
  file: &mut tokio::fs::File,
  mut md5_hash: Option<&mut Md5>,
  progress_callback: impl Fn(u64),
  callback_interval: Duration,
) -> Result<u64, String> {
  // Prepare the download and the callback variables
  let mut downloaded_bytes: u64 = 0;
  let mut stream = response.bytes_stream();
  let mut last_callback = Instant::now();

  use futures_util::StreamExt;

  // Save chunks to the file async
  // Also, compute the MD5 hash while it is being downloaded
  while let Some(chunk) = match stream.next().await {
    None => Ok(None),
    Some(result) => result
      .map(Some)
      .map_err(|e| format!("Couldn't read chunk from network!\n{e}")),
  }? {
    // Write the chunk to the file
    filesystem::write_all(file, &chunk).await?;

    // If the file has a MD5 hash, update the hasher
    if let Some(hasher) = &mut md5_hash {
      hasher.update(&chunk);
    }

    // Send a callback with the progress
    downloaded_bytes += chunk.len() as u64;
    if last_callback.elapsed() > callback_interval {
      last_callback = Instant::now();
      progress_callback(downloaded_bytes);
    }
  }

  progress_callback(downloaded_bytes);

  Ok(downloaded_bytes)
}

/// Download a file from an itch API URL
///
/// # Arguments
///
/// * `client` - An itch.io API client
///
/// * `url` - A itch.io API address to download the file from
///
/// * `file_path` - The path where the file will be placed
///
/// * `md5_hash` - A MD5 hash to check the file against. If none, don't verify the download
///
/// * `file_size_callback` - A clousure called with total size the downloaded file will have after the download
///
/// * `progress_callback` - A closure called with the number of downloaded bytes at the moment
///
/// * `callback_interval` - The minimum time span between each `progress_callback` call
///
/// # Returns
///
/// An error if something goes wrong
async fn download_file(
  client: &ItchClient,
  url: &ItchApiUrl,
  file_path: &Path,
  md5_hash: Option<&str>,
  file_size_callback: impl Fn(u64),
  progress_callback: impl Fn(u64),
  callback_interval: Duration,
) -> Result<(), String> {
  // Create the hasher variable
  let mut md5_hash: Option<(Md5, &str)> = md5_hash.map(|s| (Md5::new(), s));

  // The file will be downloaded to this file with the .part extension,
  // and then the extension will be removed when the download ends
  let partial_file_path: PathBuf = game_files::add_part_extension(file_path)?;

  // If there already exists a file in file_path, then move it to partial_file_path
  // This way, the file's length and its hash are verified
  if filesystem::exists(file_path).await? {
    filesystem::rename(file_path, &partial_file_path).await?;
  }

  // Open the file where the data is going to be downloaded
  // Use the append option to ensure that the old download data isn't deleted
  let mut file = filesystem::open_file(
    &partial_file_path,
    tokio::fs::OpenOptions::new()
      .create(true)
      .append(true)
      .read(true),
  )
  .await?;

  let mut downloaded_bytes: u64 = filesystem::read_file_metadata(&file).await?.len();

  let file_response: Option<Response> = 'r: {
    // Send a request for the whole file
    let res = client
      .itch_request(url, Method::GET, |b| b)
      .await
      .map_err(|e| e.to_string())?;

    let download_size = res.content_length().ok_or_else(|| {
      format!(
        "Couldn't get content length!
  URL: {url}"
      )
    })?;

    file_size_callback(download_size);

    // If the file is empty, then return the request for the whole file
    if downloaded_bytes == 0 {
      break 'r Some(res);
    }
    // If the file is exactly the size it should be, then return None so nothing more is downloaded
    else if downloaded_bytes == download_size {
      break 'r None;
    }
    // If the file is not empty, and smaller than the whole file, download the remaining file range
    else if downloaded_bytes < download_size {
      let part_res = client
        .itch_request(url, Method::GET, |b| {
          b.header(header::RANGE, format!("bytes={downloaded_bytes}-"))
        })
        .await
        .map_err(|e| e.to_string())?;

      match part_res.status() {
        // 206 Partial Content code means the server will send the requested range
        // https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/206
        reqwest::StatusCode::PARTIAL_CONTENT => break 'r Some(part_res),

        // 200 OK code means the server doesn't support ranges
        // https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Range
        // Don't break, so the fallback code is run instead and the whole file is downloaded
        reqwest::StatusCode::OK => (),

        // Any code other than 200 or 206 means that something went wrong
        _ => {
          return Err(format!(
            "The HTTP server to download the file from didn't return HTTP code 200 nor 206, so exiting!
  It returned code: {}
  URL: {url}", part_res.status().as_str()));
        }
      }
    }

    // If we're here, that means one of two things:
    //
    // 1. The file is bigger than it should
    // 2. The server doesn't support ranges
    //
    // In either case, the current file should be removed and downloaded again fully
    downloaded_bytes = 0;
    filesystem::set_file_len(&file, 0).await?;

    Some(res)
  };

  // If a partial file was already downloaded, hash the old downloaded data
  if let Some((ref mut hasher, _)) = md5_hash
    && downloaded_bytes > 0
  {
    hash_readable_async(&mut file, hasher).await?;
  }

  // Stream the Response into the File
  if let Some(res) = file_response {
    stream_response_into_file(
      res,
      &mut file,
      md5_hash.as_mut().map(|(h, _)| h),
      |b| progress_callback(downloaded_bytes + b),
      callback_interval,
    )
    .await?;
  }

  // If the hashes aren't equal, exit with an error
  if let Some((hasher, hash)) = md5_hash {
    let file_hash = format!("{:x}", hasher.finalize());

    if !file_hash.eq_ignore_ascii_case(hash) {
      return Err(format!("File verification failed! The file hash and the hash provided by the server are different.\n
  File hash:   {file_hash}
  Server hash: {hash}"
      ));
    }
  }

  // Sync the file to ensure all the data has been written
  filesystem::file_sync_all(&file).await?;

  // Move the downloaded file to its final destination
  // This has to be the last call in this function because after it, the File is not longer valid
  filesystem::rename(&partial_file_path, file_path).await?;

  Ok(())
}

/// Find out which platforms a game's uploads are available in
///
/// # Arguments
///
/// * `uploads` - A list of a game's uploads
///
/// # Returns
///
/// A vector of tuples containing an upload ID and the [`GamePlatform`] in which it is available
#[must_use]
pub fn get_game_platforms(uploads: &[Upload]) -> Vec<(UploadID, GamePlatform)> {
  let mut platforms: Vec<(UploadID, GamePlatform)> = Vec::new();

  for u in uploads {
    for p in u.to_game_platforms() {
      platforms.push((u.id, p));
    }
  }

  platforms
}

/// Download a game cover image from its game ID
///
/// The image will be a PNG. This is because the itch.io servers return that type of image
///
/// # Arguments
///
/// * `client` - An itch.io API client
///
/// * `game_id` - The ID of the game from which the cover will be downloaded
///
/// * `folder` - The game folder where the cover will be placed
///
/// * `cover_filename` - The new filename of the cover
///
/// * `force_download` - If true, download the cover image again, even if it already exists
///
/// # Returns
///
/// The path of the downloaded image, or None if the game doesn't have one
///
/// # Errors
///
/// If something goes wrong
pub async fn download_game_cover(
  client: &ItchClient,
  game_id: GameID,
  folder: &Path,
  cover_filename: Option<&str>,
  force_download: bool,
) -> Result<Option<PathBuf>, String> {
  // Get the game info from the server
  let game = get_game_info(client, game_id)
    .await
    .map_err(|e| e.to_string())?;
  // If the game doesn't have a cover, return
  let Some(cover_url) = game.game_info.cover_url else {
    return Ok(None);
  };

  // Create the folder where the file is going to be placed if it doesn't already exist
  filesystem::create_dir(folder).await?;

  // If the cover filename isn't set, set it to "cover"
  let cover_filename = match cover_filename {
    Some(f) => f,
    None => game_files::COVER_IMAGE_DEFAULT_FILENAME,
  };

  let cover_path = folder.join(cover_filename);

  // If the cover image already exists and the force variable is false, don't replace the original image
  if !force_download && filesystem::exists(&cover_path).await? {
    return Ok(Some(cover_path));
  }

  download_file(
    client,
    &ItchApiUrl::from_api_endpoint(ItchApiVersion::Other, cover_url),
    &cover_path,
    None,
    |_| (),
    |_| (),
    Duration::MAX,
  )
  .await?;

  Ok(Some(cover_path))
}

/// Download a game upload
///
/// # Arguments
///
/// * `client` - An itch.io API client
///
/// * `upload_id` - The ID of the upload which will be downloaded
///
/// * `game_folder` - The folder where the downloadeded game files will be placed
///
/// * `skip_hash_verification` - If true, don't check the downloaded upload integrity (insecure)
///
/// * `upload_info` - A closure which reports the upload and the game info before the download starts
///
/// * `progress_callback` - A closure which reports the download progress
///
/// * `callback_interval` - The minimum time span between each `progress_callback` call
///
/// # Returns
///
/// The installation info about the upload
///
/// # Errors
///
/// If something goes wrong
pub async fn download_upload(
  client: &ItchClient,
  upload_id: UploadID,
  game_folder: Option<&Path>,
  skip_hash_verification: bool,
  upload_info: impl FnOnce(&Upload, &Game),
  progress_callback: impl Fn(DownloadStatus),
  callback_interval: Duration,
) -> Result<InstalledUpload, String> {
  // --- DOWNLOAD PREPARATION ---

  // Obtain information about the game and the upload that will be downloaeded
  let upload: Upload = get_upload_info(client, upload_id)
    .await
    .map_err(|e| e.to_string())?;
  let game: Game = get_game_info(client, upload.game_id)
    .await
    .map_err(|e| e.to_string())?;

  // Send to the caller the game and the upload info
  upload_info(&upload, &game);

  // Set the game_folder and the file variables
  // If the game_folder is unset, set it to ~/Games/{game_name}/
  let game_folder = match game_folder {
    Some(f) => f,
    None => &game_files::get_game_folder(&game.game_info.title)?,
  };

  // upload_archive is the location where the upload will be downloaded
  let upload_archive: PathBuf =
    game_files::get_upload_archive_path(game_folder, upload_id, &upload.filename);

  // Create the game folder if it doesn't already exist
  filesystem::create_dir(game_folder).await?;

  // Get the upload's hash
  let hash: Option<&str> = upload.get_hash();

  // --- DOWNLOAD ---

  // Download the file
  download_file(
    client,
    &ItchApiUrl::from_api_endpoint(ItchApiVersion::V2, format!("uploads/{upload_id}/download")),
    &upload_archive,
    // Only pass the hash if skip_hash_verification is false
    hash.filter(|_| !skip_hash_verification),
    |bytes| {
      progress_callback(DownloadStatus::StartingDownload {
        bytes_to_download: bytes,
      });
    },
    |bytes| {
      progress_callback(DownloadStatus::DownloadProgress {
        downloaded_bytes: bytes,
      });
    },
    callback_interval,
  )
  .await?;

  // Print a warning if the upload doesn't have a hash in the server
  // or the hash verification is skipped
  if skip_hash_verification {
    progress_callback(DownloadStatus::Warning(
      "Skipping hash verification! The file integrity won't be checked!".to_string(),
    ));
  } else if hash.is_none() {
    progress_callback(DownloadStatus::Warning(
      "Missing MD5 hash. Couldn't verify the file integrity!".to_string(),
    ));
  }

  // --- FILE EXTRACTION ---

  progress_callback(DownloadStatus::Extract);

  // The new upload_folder is game_folder + the upload id
  let upload_folder: PathBuf = game_files::get_upload_folder(game_folder, upload_id);

  // Extracts the downloaded archive (if it's an archive)
  // game_files can be the path of an executable or the path to the extracted folder
  extract::extract(&upload_archive, &upload_folder)
    .await
    .map_err(|e| e.to_string())?;

  Ok(InstalledUpload {
    upload_id,
    // Get the absolute (canonical) form of the path
    game_folder: filesystem::get_canonical_path(game_folder).await?,
    game_id: game.game_info.id,
    game_title: game.game_info.title,
  })
}

/// Import an already installed upload
///
/// # Arguments
///
/// * `client` - An itch.io API client
///
/// * `upload_id` - The ID of the upload which will be imported
///
/// * `game_folder` - The folder where the game files are currectly placed
///
/// # Returns
///
/// The installation info about the upload
///
/// # Errors
///
/// If something goes wrong
pub async fn import(
  client: &ItchClient,
  upload_id: UploadID,
  game_folder: &Path,
) -> Result<InstalledUpload, String> {
  // Obtain information about the game and the upload that will be downloaeded
  let upload: Upload = get_upload_info(client, upload_id)
    .await
    .map_err(|e| e.to_string())?;
  let game: Game = get_game_info(client, upload.game_id)
    .await
    .map_err(|e| e.to_string())?;

  Ok(InstalledUpload {
    upload_id,
    // Get the absolute (canonical) form of the path
    game_folder: filesystem::get_canonical_path(game_folder).await?,
    game_id: game.game_info.id,
    game_title: game.game_info.title,
  })
}

/// Remove partially downloaded game files from a cancelled download
///
/// # Arguments
///
/// * `client` - An itch.io API client
///
/// * `upload_id` - The ID of the upload whose download was canceled
///
/// * `game_folder` - The folder where the game files are currectly placed
///
/// # Returns
///
/// True if something was actually deleted
///
/// # Errors
///
/// If something goes wrong
pub async fn remove_partial_download(
  client: &ItchClient,
  upload_id: UploadID,
  game_folder: Option<&Path>,
) -> Result<bool, String> {
  // Obtain information about the game and the upload
  let upload: Upload = get_upload_info(client, upload_id)
    .await
    .map_err(|e| e.to_string())?;
  let game: Game = get_game_info(client, upload.game_id)
    .await
    .map_err(|e| e.to_string())?;

  // If the game_folder is unset, set it to ~/Games/{game_name}/
  let game_folder = match game_folder {
    Some(f) => f,
    None => &game_files::get_game_folder(&game.game_info.title)?,
  };

  // Vector of files and folders to be removed
  let to_be_removed_folders: &[PathBuf] = &[
    // **Do not remove the upload folder!**

    // The upload partial folder
    // Example: ~/Games/ExampleGame/123456.part/
    game_files::add_part_extension(&game_files::get_upload_folder(game_folder, upload_id))?,
  ];

  let to_be_removed_files: &[PathBuf] = {
    let upload_archive =
      game_files::get_upload_archive_path(game_folder, upload_id, &upload.filename);

    &[
      // The upload partial archive
      // Example: ~/Games/ExampleGame/123456-download-ArchiveName.zip.part
      game_files::add_part_extension(&upload_archive)?,
      // The upload downloaded archive
      // Example: ~/Games/ExampleGame/123456-download-ArchiveName.zip
      upload_archive,
    ]
  };

  // Set this variable to true if some file or folder was deleted
  let mut was_something_deleted: bool = false;

  // Remove the partially downloaded files
  for f in to_be_removed_files {
    if filesystem::exists(f).await? {
      filesystem::remove_file(f).await?;
      was_something_deleted = true;
    }
  }

  // Remove the partially downloaded folders
  for f in to_be_removed_folders {
    if filesystem::exists(f).await? {
      game_files::remove_folder_safely(f).await?;
      was_something_deleted = true;
    }
  }

  // If the game folder is now useless, remove it
  was_something_deleted |= game_files::remove_folder_if_empty(game_folder).await?;

  Ok(was_something_deleted)
}

/// Remove an installed upload
///
/// # Arguments
///
/// * `upload_id` - The ID of upload which will be removed
///
/// * `game_folder` - The folder with the game files where the upload will be removed from
///
/// # Errors
///
/// If something goes wrong
pub async fn remove(upload_id: UploadID, game_folder: &Path) -> Result<(), String> {
  let upload_folder = game_files::get_upload_folder(game_folder, upload_id);

  // If there isn't a upload_folder, or it is empty, that means the game
  // has already been removed, so return Ok(())
  if filesystem::is_folder_empty(&upload_folder).await? {
    return Ok(());
  }

  game_files::remove_folder_safely(&upload_folder).await?;
  // The upload folder has been removed

  // If the game folder is empty, remove it
  game_files::remove_folder_if_empty(game_folder).await?;

  Ok(())
}

/// Move an installed upload to a new game folder
///
/// # Arguments
///
/// * `upload_id` - The ID of upload which will be moved
///
/// * `src_game_folder` - The folder where the game files are currently placed
///
/// * `dst_game_folder` - The folder where the game files will be moved to
///
/// # Returns
///
/// The new game folder in its absolute (canonical) form
///
/// # Errors
///
/// If something goes wrong
pub async fn r#move(
  upload_id: UploadID,
  src_game_folder: &Path,
  dst_game_folder: &Path,
) -> Result<PathBuf, String> {
  let src_upload_folder = game_files::get_upload_folder(src_game_folder, upload_id);

  // If there isn't a src_upload_folder, exit with error
  filesystem::ensure_is_dir(&src_upload_folder).await?;

  let dst_upload_folder = game_files::get_upload_folder(dst_game_folder, upload_id);

  // If there is a dst_upload_folder with contents, exit with error
  filesystem::ensure_is_empty(&dst_upload_folder).await?;

  // Move the upload folder
  game_files::move_folder(&src_upload_folder, &dst_upload_folder).await?;

  // If src_game_folder is empty, remove it
  game_files::remove_folder_if_empty(src_game_folder).await?;

  filesystem::get_canonical_path(dst_game_folder)
    .await
    .map_err(std::convert::Into::into)
}

/// Retrieve the itch manifest from an installed upload
///
/// # Arguments
///
/// * `upload_id` - The ID of upload from which the info will be retrieved
///
/// * `game_folder` - The folder with the game files where the upload folder is placed
///
/// # Returns
///
/// A [`Manifest`] struct with the manifest actions info, or None if the manifest isn't present
///
/// # Errors
///
/// If something goes wrong
pub async fn get_upload_manifest(
  upload_id: UploadID,
  game_folder: &Path,
) -> Result<Option<Manifest>, String> {
  let upload_folder = game_files::get_upload_folder(game_folder, upload_id);

  itch_manifest::read_manifest(&upload_folder).await
}

/// Launchs an installed upload
///
/// # Arguments
///
/// * `upload_id` - The ID of upload which will be launched
///
/// * `game_folder` - The folder where the game uploads are placed
///
/// * `launch_method` - The launch method to use to determine the upload executable file
///
/// * `wrapper` - A list of a wrapper and its options to run the upload executable with
///
/// * `game_arguments` - A list of arguments to launch the upload executable with
///
/// * `environment_variables` - A list of environment variables to be added to the upload executable process's environment
///
/// * `launch_start_callback` - A callback triggered just before the upload executable runs, providing information about what is about to be executed
///
/// # Errors
///
/// If something goes wrong
pub async fn launch(
  upload_id: UploadID,
  game_folder: &Path,
  launch_method: LaunchMethod,
  wrapper: &[String],
  game_arguments: &[String],
  environment_variables: &[(String, String)],
  launch_start_callback: impl FnOnce(&Path, &tokio::process::Command),
) -> Result<(), String> {
  let upload_folder: PathBuf = game_files::get_upload_folder(game_folder, upload_id);

  // Determine the upload executable and its launch arguments from the function arguments, manifest, or heuristics.
  let (upload_executable, game_arguments): (PathBuf, Cow<[String]>) = match launch_method {
    // 1. If the launch method is an alternative executable, then that executable with the arguments provided to the function
    LaunchMethod::AlternativeExecutable { executable_path } => {
      (executable_path, Cow::Borrowed(game_arguments))
    }
    // 2. If the launch method is a manifest action, use its executable
    LaunchMethod::ManifestAction {
      manifest_action_name,
    } => {
      let ma = itch_manifest::launch_action(&upload_folder, Some(&manifest_action_name))
        .await?
        .ok_or_else(|| {
          format!(
            "The provided launch action doesn't exist in the manifest: {manifest_action_name}"
          )
        })?;
      (
        ma.get_canonical_path(&upload_folder).await?,
        // a) If the function's game arguments are empty, use the ones from the manifest
        if game_arguments.is_empty() {
          Cow::Owned(ma.args.unwrap_or_default())
        }
        // b) Otherwise, use the provided ones
        else {
          Cow::Borrowed(game_arguments)
        },
      )
    }
    // 3. Otherwise, if the launch method are the heuristics, use them to locate the executable
    LaunchMethod::Heuristics {
      game_platform,
      game_title,
    } => {
      // But first, check if the game has a manifest with a "play" action, and use it if possible
      let mao = itch_manifest::launch_action(&upload_folder, None).await?;

      match mao {
        // If the manifest has a "play" action, launch from it
        Some(ma) => (
          ma.get_canonical_path(&upload_folder).await?,
          // a) If the function's game arguments are empty, use the ones from the manifest
          if game_arguments.is_empty() {
            Cow::Owned(ma.args.unwrap_or_default())
          }
          // b) Otherwise, use the provided ones
          else {
            Cow::Borrowed(game_arguments)
          },
        ),
        // Else, now use the heuristics to determine the executable, with the function's game arguments
        None => (
          heuristics::get_game_executable(&upload_folder, game_platform, game_title).await?,
          Cow::Borrowed(game_arguments),
        ),
      }
    }
  };

  let upload_executable = filesystem::get_canonical_path(&upload_executable).await?;

  // Make the file executable
  filesystem::make_executable(&upload_executable).await?;

  // Create the tokio process
  let mut game_process = {
    let mut wrapper_iter = wrapper.iter();
    match wrapper_iter.next() {
      // If it doesn't have a wrapper, just run the executable
      None => tokio::process::Command::new(&upload_executable),
      Some(w) => {
        // If the game has a wrapper, then run the wrapper with its
        // arguments and add the game executable as the last argument
        let mut gp = tokio::process::Command::new(w);
        gp.args(wrapper_iter).arg(&upload_executable);
        gp
      }
    }
  };

  // Add the working directory, the game arguments and the environment variables
  game_process
    .current_dir(&upload_folder)
    .args(&*game_arguments)
    .envs(environment_variables.iter().map(|(k, v)| (k, v)));

  launch_start_callback(&upload_executable, &game_process);

  let mut child = filesystem::spawn_command(&mut game_process)?;
  filesystem::wait_child(&mut child).await?;

  Ok(())
}

/// Get the url to a itch.io web game
///
/// # Arguments
///
/// * `upload_id` - The ID of the html upload
///
/// # Returns
///
/// The web game URL
#[must_use]
pub fn get_web_game_url(upload_id: UploadID) -> String {
  format!("https://html-classic.itch.zone/html/{upload_id}/index.html")
}