AmiiboWindowViewModel.cs 13 KB

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