AmiiboWindowViewModel.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. using Avalonia;
  2. using Avalonia.Collections;
  3. using Avalonia.Media.Imaging;
  4. using Avalonia.Threading;
  5. using Ryujinx.Ava.Common.Locale;
  6. using Ryujinx.Ava.UI.Helpers;
  7. using Ryujinx.Ava.UI.Windows;
  8. using Ryujinx.Common;
  9. using Ryujinx.Common.Configuration;
  10. using Ryujinx.Common.Logging;
  11. using Ryujinx.Common.Utilities;
  12. using Ryujinx.Ui.Common.Models.Amiibo;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Collections.ObjectModel;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Net.Http;
  19. using System.Text;
  20. using System.Threading.Tasks;
  21. using AmiiboJsonSerializerContext = Ryujinx.Ui.Common.Models.Amiibo.AmiiboJsonSerializerContext;
  22. namespace Ryujinx.Ava.UI.ViewModels
  23. {
  24. public class AmiiboWindowViewModel : BaseModel, IDisposable
  25. {
  26. private const string DefaultJson = "{ \"amiibo\": [] }";
  27. private const float AmiiboImageSize = 350f;
  28. private readonly string _amiiboJsonPath;
  29. private readonly byte[] _amiiboLogoBytes;
  30. private readonly HttpClient _httpClient;
  31. private readonly StyleableWindow _owner;
  32. private Bitmap _amiiboImage;
  33. private List<AmiiboApi> _amiiboList;
  34. private AvaloniaList<AmiiboApi> _amiibos;
  35. private ObservableCollection<string> _amiiboSeries;
  36. private int _amiiboSelectedIndex;
  37. private int _seriesSelectedIndex;
  38. private bool _enableScanning;
  39. private bool _showAllAmiibo;
  40. private bool _useRandomUuid;
  41. private string _usage;
  42. private static readonly AmiiboJsonSerializerContext SerializerContext = new(JsonHelper.GetDefaultSerializerOptions());
  43. public AmiiboWindowViewModel(StyleableWindow owner, string lastScannedAmiiboId, string titleId)
  44. {
  45. _owner = owner;
  46. _httpClient = new HttpClient
  47. {
  48. Timeout = TimeSpan.FromSeconds(30)
  49. };
  50. LastScannedAmiiboId = lastScannedAmiiboId;
  51. TitleId = titleId;
  52. Directory.CreateDirectory(Path.Join(AppDataManager.BaseDirPath, "system", "amiibo"));
  53. _amiiboJsonPath = Path.Join(AppDataManager.BaseDirPath, "system", "amiibo", "Amiibo.json");
  54. _amiiboList = new List<AmiiboApi>();
  55. _amiiboSeries = new ObservableCollection<string>();
  56. _amiibos = new AvaloniaList<AmiiboApi>();
  57. _amiiboLogoBytes = EmbeddedResources.Read("Ryujinx.Ui.Common/Resources/Logo_Amiibo.png");
  58. _ = LoadContentAsync();
  59. }
  60. public AmiiboWindowViewModel() { }
  61. public string TitleId { get; set; }
  62. public string LastScannedAmiiboId { get; set; }
  63. public UserResult Response { get; private set; }
  64. public bool UseRandomUuid
  65. {
  66. get => _useRandomUuid;
  67. set
  68. {
  69. _useRandomUuid = value;
  70. OnPropertyChanged();
  71. }
  72. }
  73. public bool ShowAllAmiibo
  74. {
  75. get => _showAllAmiibo;
  76. set
  77. {
  78. _showAllAmiibo = value;
  79. ParseAmiiboData();
  80. OnPropertyChanged();
  81. }
  82. }
  83. public AvaloniaList<AmiiboApi> AmiiboList
  84. {
  85. get => _amiibos;
  86. set
  87. {
  88. _amiibos = value;
  89. OnPropertyChanged();
  90. }
  91. }
  92. public ObservableCollection<string> AmiiboSeries
  93. {
  94. get => _amiiboSeries;
  95. set
  96. {
  97. _amiiboSeries = value;
  98. OnPropertyChanged();
  99. }
  100. }
  101. public int SeriesSelectedIndex
  102. {
  103. get => _seriesSelectedIndex;
  104. set
  105. {
  106. _seriesSelectedIndex = value;
  107. FilterAmiibo();
  108. OnPropertyChanged();
  109. }
  110. }
  111. public int AmiiboSelectedIndex
  112. {
  113. get => _amiiboSelectedIndex;
  114. set
  115. {
  116. _amiiboSelectedIndex = value;
  117. EnableScanning = _amiiboSelectedIndex >= 0 && _amiiboSelectedIndex < _amiibos.Count;
  118. SetAmiiboDetails();
  119. OnPropertyChanged();
  120. }
  121. }
  122. public Bitmap AmiiboImage
  123. {
  124. get => _amiiboImage;
  125. set
  126. {
  127. _amiiboImage = value;
  128. OnPropertyChanged();
  129. }
  130. }
  131. public string Usage
  132. {
  133. get => _usage;
  134. set
  135. {
  136. _usage = value;
  137. OnPropertyChanged();
  138. }
  139. }
  140. public bool EnableScanning
  141. {
  142. get => _enableScanning;
  143. set
  144. {
  145. _enableScanning = value;
  146. OnPropertyChanged();
  147. }
  148. }
  149. public void Dispose()
  150. {
  151. _httpClient.Dispose();
  152. }
  153. private async Task LoadContentAsync()
  154. {
  155. string amiiboJsonString = DefaultJson;
  156. if (File.Exists(_amiiboJsonPath))
  157. {
  158. amiiboJsonString = await File.ReadAllTextAsync(_amiiboJsonPath);
  159. if (await NeedsUpdate(JsonHelper.Deserialize(amiiboJsonString, SerializerContext.AmiiboJson).LastUpdated))
  160. {
  161. amiiboJsonString = await DownloadAmiiboJson();
  162. }
  163. }
  164. else
  165. {
  166. try
  167. {
  168. amiiboJsonString = await DownloadAmiiboJson();
  169. }
  170. catch (Exception ex)
  171. {
  172. Logger.Error?.Print(LogClass.Application, $"Failed to download amiibo data: {ex}");
  173. ShowInfoDialog();
  174. }
  175. }
  176. _amiiboList = JsonHelper.Deserialize(amiiboJsonString, SerializerContext.AmiiboJson).Amiibo;
  177. _amiiboList = _amiiboList.OrderBy(amiibo => amiibo.AmiiboSeries).ToList();
  178. ParseAmiiboData();
  179. }
  180. private void ParseAmiiboData()
  181. {
  182. _amiiboSeries.Clear();
  183. _amiibos.Clear();
  184. for (int i = 0; i < _amiiboList.Count; i++)
  185. {
  186. if (!_amiiboSeries.Contains(_amiiboList[i].AmiiboSeries))
  187. {
  188. if (!ShowAllAmiibo)
  189. {
  190. foreach (AmiiboApiGamesSwitch game in _amiiboList[i].GamesSwitch)
  191. {
  192. if (game != null)
  193. {
  194. if (game.GameId.Contains(TitleId))
  195. {
  196. AmiiboSeries.Add(_amiiboList[i].AmiiboSeries);
  197. break;
  198. }
  199. }
  200. }
  201. }
  202. else
  203. {
  204. AmiiboSeries.Add(_amiiboList[i].AmiiboSeries);
  205. }
  206. }
  207. }
  208. if (LastScannedAmiiboId != "")
  209. {
  210. SelectLastScannedAmiibo();
  211. }
  212. else
  213. {
  214. SeriesSelectedIndex = 0;
  215. }
  216. }
  217. private void SelectLastScannedAmiibo()
  218. {
  219. AmiiboApi scanned = _amiiboList.FirstOrDefault(amiibo => amiibo.GetId() == LastScannedAmiiboId);
  220. SeriesSelectedIndex = AmiiboSeries.IndexOf(scanned.AmiiboSeries);
  221. AmiiboSelectedIndex = AmiiboList.IndexOf(scanned);
  222. }
  223. private void FilterAmiibo()
  224. {
  225. _amiibos.Clear();
  226. if (_seriesSelectedIndex < 0)
  227. {
  228. return;
  229. }
  230. List<AmiiboApi> amiiboSortedList = _amiiboList
  231. .Where(amiibo => amiibo.AmiiboSeries == _amiiboSeries[SeriesSelectedIndex])
  232. .OrderBy(amiibo => amiibo.Name).ToList();
  233. for (int i = 0; i < amiiboSortedList.Count; i++)
  234. {
  235. if (!_amiibos.Contains(amiiboSortedList[i]))
  236. {
  237. if (!_showAllAmiibo)
  238. {
  239. foreach (AmiiboApiGamesSwitch game in amiiboSortedList[i].GamesSwitch)
  240. {
  241. if (game != null)
  242. {
  243. if (game.GameId.Contains(TitleId))
  244. {
  245. _amiibos.Add(amiiboSortedList[i]);
  246. break;
  247. }
  248. }
  249. }
  250. }
  251. else
  252. {
  253. _amiibos.Add(amiiboSortedList[i]);
  254. }
  255. }
  256. }
  257. AmiiboSelectedIndex = 0;
  258. }
  259. private void SetAmiiboDetails()
  260. {
  261. ResetAmiiboPreview();
  262. Usage = string.Empty;
  263. if (_amiiboSelectedIndex < 0)
  264. {
  265. return;
  266. }
  267. AmiiboApi selected = _amiibos[_amiiboSelectedIndex];
  268. string imageUrl = _amiiboList.FirstOrDefault(amiibo => amiibo.Equals(selected)).Image;
  269. string usageString = "";
  270. for (int i = 0; i < _amiiboList.Count; i++)
  271. {
  272. if (_amiiboList[i].Equals(selected))
  273. {
  274. bool writable = false;
  275. foreach (AmiiboApiGamesSwitch item in _amiiboList[i].GamesSwitch)
  276. {
  277. if (item.GameId.Contains(TitleId))
  278. {
  279. foreach (AmiiboApiUsage usageItem in item.AmiiboUsage)
  280. {
  281. usageString += Environment.NewLine +
  282. $"- {usageItem.Usage.Replace("/", Environment.NewLine + "-")}";
  283. writable = usageItem.Write;
  284. }
  285. }
  286. }
  287. if (usageString.Length == 0)
  288. {
  289. usageString = LocaleManager.Instance[LocaleKeys.Unknown] + ".";
  290. }
  291. Usage = $"{LocaleManager.Instance[LocaleKeys.Usage]} {(writable ? $" ({LocaleManager.Instance[LocaleKeys.Writable]})" : "")} : {usageString}";
  292. }
  293. }
  294. _ = UpdateAmiiboPreview(imageUrl);
  295. }
  296. private async Task<bool> NeedsUpdate(DateTime oldLastModified)
  297. {
  298. try
  299. {
  300. HttpResponseMessage response =
  301. await _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, "https://amiibo.ryujinx.org/"));
  302. if (response.IsSuccessStatusCode)
  303. {
  304. return response.Content.Headers.LastModified != oldLastModified;
  305. }
  306. return false;
  307. }
  308. catch (Exception ex)
  309. {
  310. Logger.Error?.Print(LogClass.Application, $"Failed to check for amiibo updates: {ex}");
  311. ShowInfoDialog();
  312. return false;
  313. }
  314. }
  315. private async Task<string> DownloadAmiiboJson()
  316. {
  317. HttpResponseMessage response = await _httpClient.GetAsync("https://amiibo.ryujinx.org/");
  318. if (response.IsSuccessStatusCode)
  319. {
  320. string amiiboJsonString = await response.Content.ReadAsStringAsync();
  321. using (FileStream amiiboJsonStream = File.Create(_amiiboJsonPath, 4096, FileOptions.WriteThrough))
  322. {
  323. amiiboJsonStream.Write(Encoding.UTF8.GetBytes(amiiboJsonString));
  324. }
  325. return amiiboJsonString;
  326. }
  327. Logger.Error?.Print(LogClass.Application, $"Failed to download amiibo data. Response status code: {response.StatusCode}");
  328. await ContentDialogHelper.CreateInfoDialog(LocaleManager.Instance[LocaleKeys.DialogAmiiboApiTitle],
  329. LocaleManager.Instance[LocaleKeys.DialogAmiiboApiFailFetchMessage],
  330. LocaleManager.Instance[LocaleKeys.InputDialogOk],
  331. "",
  332. LocaleManager.Instance[LocaleKeys.RyujinxInfo]);
  333. Close();
  334. return DefaultJson;
  335. }
  336. private void Close()
  337. {
  338. Dispatcher.UIThread.Post(_owner.Close);
  339. }
  340. private async Task UpdateAmiiboPreview(string imageUrl)
  341. {
  342. HttpResponseMessage response = await _httpClient.GetAsync(imageUrl);
  343. if (response.IsSuccessStatusCode)
  344. {
  345. byte[] amiiboPreviewBytes = await response.Content.ReadAsByteArrayAsync();
  346. using (MemoryStream memoryStream = new(amiiboPreviewBytes))
  347. {
  348. Bitmap bitmap = new(memoryStream);
  349. double ratio = Math.Min(AmiiboImageSize / bitmap.Size.Width,
  350. AmiiboImageSize / bitmap.Size.Height);
  351. int resizeHeight = (int)(bitmap.Size.Height * ratio);
  352. int resizeWidth = (int)(bitmap.Size.Width * ratio);
  353. AmiiboImage = bitmap.CreateScaledBitmap(new PixelSize(resizeWidth, resizeHeight));
  354. }
  355. }
  356. else
  357. {
  358. Logger.Error?.Print(LogClass.Application, $"Failed to get amiibo preview. Response status code: {response.StatusCode}");
  359. }
  360. }
  361. private void ResetAmiiboPreview()
  362. {
  363. using (MemoryStream memoryStream = new(_amiiboLogoBytes))
  364. {
  365. Bitmap bitmap = new(memoryStream);
  366. AmiiboImage = bitmap;
  367. }
  368. }
  369. private async void ShowInfoDialog()
  370. {
  371. await ContentDialogHelper.CreateInfoDialog(LocaleManager.Instance[LocaleKeys.DialogAmiiboApiTitle],
  372. LocaleManager.Instance[LocaleKeys.DialogAmiiboApiConnectErrorMessage],
  373. LocaleManager.Instance[LocaleKeys.InputDialogOk],
  374. "",
  375. LocaleManager.Instance[LocaleKeys.RyujinxInfo]);
  376. }
  377. }
  378. }