AmiiboWindowViewModel.cs 13 KB

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