Advertisement
Guest User

Untitled

a guest
May 28th, 2023
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 45.79 KB | None | 0 0
  1. using System.Collections.ObjectModel;
  2. using System.ComponentModel;
  3. using System.Diagnostics;
  4. using System.Runtime.CompilerServices;
  5. using System.Windows.Input;
  6. using GraphQL;
  7. using GraphQL.Client.Http;
  8. using GraphQL.Client.Serializer.Newtonsoft;
  9. using Newtonsoft.Json;
  10. using MauiApp2.Models;
  11. using CommunityToolkit.Maui.Alerts;
  12. using CommunityToolkit.Maui.Core;
  13. using MauiApp2.Views;
  14.  
  15. namespace MauiApp2.ViewModels
  16. {
  17. class AnimeListPageViewModel : INotifyPropertyChanged
  18. {
  19. public event PropertyChangedEventHandler PropertyChanged;
  20.  
  21. void OnPropertyChanged([CallerMemberName] string name = "")
  22. {
  23. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
  24. }
  25.  
  26. CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
  27.  
  28. ToastDuration duration = ToastDuration.Short;
  29. double fontSize = 14;
  30.  
  31. public ICommand OpenMediaCommand { get; }
  32. public ICommand RefreshCommand { get; }
  33. public ICommand IncreaseCommand { get; private set; }
  34. public ICommand DecreaseCommand { get; private set; }
  35. public ICommand ShowPopupCommand { get; }
  36.  
  37. public ICommand SearchCommand { get; }
  38.  
  39. public bool isBusy = false;
  40.  
  41. public bool IsBusy
  42. {
  43. get => isBusy;
  44. set
  45. {
  46. if (value == isBusy)
  47. return;
  48.  
  49. isBusy = value;
  50. OnPropertyChanged();
  51. }
  52. }
  53.  
  54. public bool _Indicating = false;
  55.  
  56. public bool Indicating
  57. {
  58. get => _Indicating;
  59. set
  60. {
  61. if (value == _Indicating)
  62. return;
  63.  
  64. _Indicating = value;
  65. OnPropertyChanged();
  66. }
  67. }
  68.  
  69. private GraphQLResponse<Data> _apiListData;
  70. public GraphQLResponse<Data> apiListData
  71. {
  72. get => _apiListData;
  73. set
  74. {
  75. if (value == _apiListData)
  76. return;
  77.  
  78. _apiListData = value;
  79. }
  80. }
  81.  
  82. public ObservableCollection<Models.Group> _AnimeGroupObservable;
  83.  
  84. public ObservableCollection<Models.Group> AnimeGroupObservable
  85. {
  86. get => _AnimeGroupObservable;
  87. set
  88. {
  89. if (value == _AnimeGroupObservable)
  90. return;
  91.  
  92. _AnimeGroupObservable = value;
  93. OnPropertyChanged();
  94. }
  95. }
  96.  
  97. private List<string> searchResults;
  98. public List<string> SearchResults
  99. {
  100. get
  101. {
  102. return searchResults;
  103. }
  104. set
  105. {
  106. searchResults = value;
  107. OnPropertyChanged();
  108. }
  109. }
  110.  
  111. public AnimeListPageViewModel()
  112. {
  113. MessagingCenter.Subscribe<AnimeListPage> (this, "ClearFilter", (sender) =>
  114. {
  115. SearchTask(string.Empty);
  116. });
  117.  
  118. RefreshCommand = new Command(async () => await Refresh().ConfigureAwait(false));
  119. IncreaseCommand = new Command<ListEntry>((x) => IncreaseTask(x));
  120. DecreaseCommand = new Command<ListEntry>((x) => DecreaseTask(x));
  121. ShowPopupCommand = new Command(async () => await ShowPopup());
  122. OpenMediaCommand = new Command<Media>((x) => OpenMediaTask(x));
  123. SearchCommand = new Command<string>((x) => SearchTask(x));
  124. IsBusy = true;
  125. }
  126.  
  127. async Task SearchTask(string query)
  128. {
  129. //var SearchTerm = query;
  130.  
  131. //if (string.IsNullOrWhiteSpace(SearchTerm))
  132. //{
  133. // SearchTerm = string.Empty;
  134. //}
  135.  
  136. //SearchTerm = SearchTerm.ToLowerInvariant();
  137.  
  138. //foreach (var group in AnimeGroupObservable)
  139. //{
  140. // var filteredItems = group
  141. // .Where(value => value.media.Title.UserPreferred.ToLowerInvariant().Contains(SearchTerm)).ToList();
  142.  
  143. // if (string.IsNullOrWhiteSpace(SearchTerm))
  144. // {
  145. // filteredItems = group.ToList();
  146. // }
  147.  
  148. // foreach (var value in group)
  149. // {
  150. // if (!filteredItems.Contains(value))
  151. // {
  152. // group.Remove(value);
  153. // }
  154. // else if (!group.Contains(value))
  155. // {
  156. // group.Add(value);
  157. // }
  158. // }
  159. //}
  160.  
  161. //var SearchTerm = query;
  162.  
  163. //if (string.IsNullOrWhiteSpace(SearchTerm))
  164. //{
  165. // SearchTerm = string.Empty;
  166. //}
  167.  
  168. //SearchTerm = SearchTerm.ToLowerInvariant();
  169.  
  170. //foreach (var group in TechnicList)
  171. //{
  172. // var filteredItems = group
  173. // .Where(value => value.media.Title.UserPreferred.ToLowerInvariant().Contains(SearchTerm)).ToList();
  174.  
  175. // if (string.IsNullOrWhiteSpace(SearchTerm))
  176. // {
  177. // filteredItems = group.Entries.ToList();
  178. // }
  179.  
  180. // foreach (var value in group)
  181. // {
  182.  
  183. // if (!filteredItems.Contains(value))
  184. // {
  185. // foreach (var VARIABLE in AnimeGroupObservable)
  186. // {
  187. // if (VARIABLE.Name == group.Name)
  188. // {
  189. // VARIABLE.Remove(value);
  190. // }
  191. // }
  192. // }
  193.  
  194. // foreach (var VARIABLE in AnimeGroupObservable)
  195. // {
  196. // if (VARIABLE.Name == group.Name)
  197. // {
  198.  
  199. // if (!VARIABLE.Contains(value))
  200. // {
  201. // group.Add(value);
  202. // }
  203. // }
  204. // }
  205. // }
  206. //}
  207.  
  208. //if (string.IsNullOrEmpty(query))
  209. //{
  210. // AnimeGroupObservable = TechnicList;
  211. //}
  212. //else
  213. //{
  214. // foreach (var Group in TechnicList)
  215. // {
  216. // foreach (var Ani in AnimeGroupObservable)
  217. // {
  218. // if (Ani.Name == Group.Name)
  219. // {
  220. // Ani.Where(p => p.media.Title.UserPreferred.Contains(query, StringComparison.CurrentCultureIgnoreCase)).ToList();
  221. // }
  222. // }
  223. // }
  224. //}
  225.  
  226.  
  227.  
  228. //string token = Preferences.Get("token", "default_value");
  229. // var anilistGraphQlHttpClient = new GraphQLHttpClient(
  230. // "https://graphql.anilist.co",
  231. // new NewtonsoftJsonSerializer()
  232. // );
  233.  
  234. // anilistGraphQlHttpClient.HttpClient.DefaultRequestHeaders.Add(
  235. // "Authorization",
  236. // "Bearer " + token
  237. // );
  238.  
  239. // var requestAnimeList = new GraphQLRequest
  240. // {
  241. // Query =
  242. // @"query AnimeList($userId: Int) { MediaListCollection(userId: $userId, type: ANIME) { user { mediaListOptions{ animeList{ sectionOrder } } } lists { name isCustomList isSplitCompletedList status entries { id customLists startedAt { year month day } media { id nextAiringEpisode { id airingAt timeUntilAiring } airingSchedule { nodes { id airingAt timeUntilAiring } } episodes startDate { year month day } title { userPreferred } coverImage { large } } progress status score } } } } ",
  243. // OperationName = "AnimeList",
  244. // Variables = new { userId = Preferences.Get("userID", "default_value") }
  245. // };
  246.  
  247. // var graphQlResponseAnimeList =
  248. // await anilistGraphQlHttpClient.SendQueryAsync<Data>(requestAnimeList);
  249.  
  250. // foreach (
  251. // var VARIABLE1 in graphQlResponseAnimeList.Data.MediaListCollection.lists
  252. // )
  253. // {
  254. // foreach (var VARIABLE in VARIABLE1.entries)
  255. // {
  256. // if (VARIABLE.startedAt.year is null)
  257. // {
  258. // VARIABLE.startedAt.Time = new DateTime(1970, 01, 01);
  259. // }
  260. // else
  261. // {
  262. // VARIABLE.startedAt.Time = VARIABLE.startedAt.Time = new DateTime(
  263. // (int)VARIABLE.startedAt.year,
  264. // (int)VARIABLE.startedAt.month,
  265. // (int)VARIABLE.startedAt.day
  266. // );
  267. // }
  268.  
  269. // if (
  270. // VARIABLE.media.startDate.year is null
  271. // && VARIABLE.media.startDate.month is null
  272. // && VARIABLE.media.startDate.day is null
  273. // )
  274. // {
  275. // VARIABLE.media.startDate.Time = new DateTime(2070, 1, 1);
  276. // }
  277. // else if (
  278. // VARIABLE.media.startDate.month is null
  279. // && VARIABLE.media.startDate.day is null
  280. // )
  281. // {
  282. // VARIABLE.media.startDate.Time = new DateTime(
  283. // (int)VARIABLE.media.startDate.year,
  284. // 1,
  285. // 1
  286. // );
  287. // }
  288. // else if (VARIABLE.media.startDate.day is null)
  289. // {
  290. // VARIABLE.media.startDate.Time = new DateTime(
  291. // (int)VARIABLE.media.startDate.year,
  292. // (int)VARIABLE.media.startDate.month,
  293. // 1
  294. // );
  295. // }
  296. // else
  297. // {
  298. // VARIABLE.media.startDate.Time = new DateTime(
  299. // (int)VARIABLE.media.startDate.year,
  300. // (int)VARIABLE.media.startDate.month,
  301. // (int)VARIABLE.media.startDate.day
  302. // );
  303. // }
  304. // }
  305. // }
  306.  
  307. if (query == string.Empty)
  308. {
  309. GraphQLResponse<Data> filt = apiListData;
  310.  
  311. GraphQLResponse<Data> startFilter = filt;
  312.  
  313. foreach (var List in startFilter.Data.MediaListCollection.lists)
  314. {
  315. foreach (var listEntry in List.entries)
  316. {
  317. listEntry.CustomListsList = new ObservableCollection<customListItem>();
  318. if (listEntry.CustomLists != null)
  319. {
  320. foreach (var VARIABLE in listEntry.CustomLists)
  321. {
  322. listEntry.CustomListsList.Add(
  323. new customListItem
  324. {
  325. key = VARIABLE.Key,
  326. value = VARIABLE.Value
  327. }
  328. );
  329. }
  330. }
  331. }
  332. }
  333.  
  334. var sorted = startFilter.Data.MediaListCollection.lists.OrderBy(
  335. x =>
  336. startFilter.Data.MediaListCollection.user.mediaListOptions.animeList
  337. .sectionOrder.IndexOf(
  338. x.name
  339. )
  340. );
  341.  
  342.  
  343. MediaGroups userGroups = new MediaGroups()
  344. {
  345. groups = sorted
  346. .Select(
  347. List =>
  348. new Models.Group(
  349. List.name,
  350. List.isCustomList,
  351. List.isSplitCompletedList,
  352. List.status,
  353. List.entries
  354. )
  355. {
  356. Name = List.name,
  357. isCustomList = List.isCustomList,
  358. isSplitCompletedList = List.isSplitCompletedList,
  359. status = List.status,
  360. entryCount = List.entries.Count,
  361. Entries = List.entries
  362. }
  363. )
  364. .ToList()
  365. };
  366.  
  367. MainThread.BeginInvokeOnMainThread(() =>
  368. {
  369. AnimeGroupObservable = new ObservableCollection<Models.Group>(userGroups.groups);
  370.  
  371. MessagingCenter.Send(AnimeGroupObservable, "AllAnimeGroups");
  372.  
  373. });
  374.  
  375. }
  376. else
  377. {
  378. GraphQLResponse<Data> filt = apiListData;
  379.  
  380. GraphQLResponse<Data> startFilter = filt;
  381.  
  382. foreach (var List in startFilter.Data.MediaListCollection.lists)
  383. {
  384. foreach (var listEntry in List.entries)
  385. {
  386. listEntry.CustomListsList = new ObservableCollection<customListItem>();
  387. if (listEntry.CustomLists != null)
  388. {
  389. foreach (var VARIABLE in listEntry.CustomLists)
  390. {
  391. listEntry.CustomListsList.Add(
  392. new customListItem
  393. {
  394. key = VARIABLE.Key,
  395. value = VARIABLE.Value
  396. }
  397. );
  398. }
  399. }
  400. }
  401. }
  402.  
  403. var filtered = startFilter.Data.MediaListCollection.lists;
  404.  
  405. foreach (var x in filtered)
  406. {
  407. x.entries = x.entries.Where(x => x.media.Title.UserPreferred.ToLowerInvariant().Contains(query))
  408. .ToList();
  409. }
  410. Console.WriteLine(filtered);
  411.  
  412. var sorted = filtered.OrderBy(
  413. x =>
  414. startFilter.Data.MediaListCollection.user.mediaListOptions.animeList
  415. .sectionOrder.IndexOf(
  416. x.name
  417. )
  418. );
  419.  
  420.  
  421. MediaGroups userGroups = new MediaGroups()
  422. {
  423. groups = sorted
  424. .Select(
  425. List =>
  426. new Models.Group(
  427. List.name,
  428. List.isCustomList,
  429. List.isSplitCompletedList,
  430. List.status,
  431. List.entries
  432. )
  433. {
  434. Name = List.name,
  435. isCustomList = List.isCustomList,
  436. isSplitCompletedList = List.isSplitCompletedList,
  437. status = List.status,
  438. entryCount = List.entries.Count,
  439. Entries = List.entries
  440. }
  441. )
  442. .ToList()
  443. };
  444.  
  445. MainThread.BeginInvokeOnMainThread(() =>
  446. {
  447. AnimeGroupObservable = new ObservableCollection<Models.Group>(userGroups.groups);
  448.  
  449. MessagingCenter.Send(AnimeGroupObservable, "AllAnimeGroups");
  450.  
  451. });
  452. }
  453.  
  454.  
  455. }
  456.  
  457. async Task OpenMediaTask(Media x)
  458. {
  459. var navigationParameter = new Dictionary<string, object> { { "pushMedia", x } };
  460.  
  461. await Shell.Current.GoToAsync(
  462. "MediaDetailsPage",
  463. parameters: navigationParameter,
  464. animate: true
  465. );
  466. }
  467.  
  468. async Task ShowPopup()
  469. {
  470. if (AnimeGroupObservable != null)
  471. {
  472. //await Shell.Current.ShowPopupAsync(new AnimeListGroupsPopup(AnimeGroupObservable));
  473. }
  474. }
  475.  
  476. async Task IncreaseTask(ListEntry x)
  477. {
  478. await Task.Run(async () =>
  479. {
  480. Console.WriteLine(x);
  481. Indicating = true;
  482. try
  483. {
  484. Debug.WriteLine("Cos2");
  485. if (x.media.startDate.Time > DateTime.Now)
  486. {
  487. MainThread.BeginInvokeOnMainThread(() =>
  488. {
  489.  
  490. var toast = Toast.Make("Anime hasn't aired yet.", duration, fontSize);
  491.  
  492. toast.Show(cancellationTokenSource.Token);
  493. });
  494. }
  495. else
  496. {
  497. if (x.media.Episodes is null || x.progress < x.media.Episodes)
  498. {
  499. string token = Preferences.Get("token", "default_value");
  500. var anilistGraphQlHttpClient = new GraphQLHttpClient(
  501. "https://graphql.anilist.co",
  502. new NewtonsoftJsonSerializer()
  503. );
  504.  
  505. anilistGraphQlHttpClient.HttpClient.DefaultRequestHeaders.Add(
  506. "Authorization",
  507. "Bearer " + token
  508. );
  509.  
  510. var IncreaseProgressEntry = new GraphQLRequest
  511. {
  512. Query =
  513. @"mutation IncreaseProgress($id: Int, $progress: Int) { SaveMediaListEntry(id: $id, progress: $progress) { id progress status } } ",
  514. OperationName = "IncreaseProgress",
  515. Variables = new { id = x.id, progress = x.progress + 1 }
  516. };
  517. var graphQlResponseAnimeList =
  518. await anilistGraphQlHttpClient.SendQueryAsync<Data>(
  519. IncreaseProgressEntry
  520. );
  521.  
  522. foreach (var VARIABLE in AnimeGroupObservable)
  523. {
  524. foreach (var VARIABLE2 in VARIABLE)
  525. {
  526. if (VARIABLE2.id == x.id)
  527. {
  528. VARIABLE2.progress++;
  529. }
  530. }
  531. }
  532. }
  533. }
  534. }
  535. catch (HttpRequestException httpRequestException)
  536. {
  537. Debug.WriteLine(httpRequestException);
  538. MainThread.BeginInvokeOnMainThread(() =>
  539. {
  540. var toast = Toast.Make("No internet.", duration, fontSize);
  541.  
  542. toast.Show(cancellationTokenSource.Token);
  543. });
  544. }
  545. catch (GraphQLHttpRequestException e)
  546. {
  547. Root exception = JsonConvert.DeserializeObject<Root>(e.Content);
  548. if (exception.errors[0].status == 400)
  549. {
  550. if (exception.errors[0].message == "Invalid token")
  551. {
  552. Preferences.Set("token", "default_value");
  553. await Shell.Current.GoToAsync($"//LandingPage");
  554.  
  555. MainThread.BeginInvokeOnMainThread(() =>
  556. {
  557. var toast = Toast.Make("Invalid token.", duration, fontSize);
  558.  
  559. toast.Show(cancellationTokenSource.Token);
  560. });
  561. }
  562. else if (exception.errors[0].message == "validation")
  563. {
  564. MainThread.BeginInvokeOnMainThread(() =>
  565. {
  566. var toast = Toast.Make(
  567. "Missing parameter in query.",
  568. duration,
  569. fontSize
  570. );
  571.  
  572. toast.Show(cancellationTokenSource.Token);
  573. });
  574. }
  575. else
  576. {
  577. MainThread.BeginInvokeOnMainThread(() =>
  578. {
  579. var toast = Toast.Make(
  580. $"new exception other than invalid token and missing parameter in 400 - {exception.errors[0].message}",
  581. duration,
  582. fontSize
  583. );
  584.  
  585. toast.Show(cancellationTokenSource.Token);
  586. });
  587. }
  588. }
  589. else if (exception.errors[0].status == 401)
  590. {
  591. Debug.WriteLine(
  592. $"new exception other than unauthorized in 401 - {exception.errors[0].message}"
  593. );
  594. MainThread.BeginInvokeOnMainThread(() =>
  595. {
  596. var toast = Toast.Make("Unauthorized.", duration, fontSize);
  597.  
  598. toast.Show(cancellationTokenSource.Token);
  599. });
  600. }
  601. else if (exception.errors[0].status == 429)
  602. {
  603. MainThread.BeginInvokeOnMainThread(() =>
  604. {
  605. var toast = Toast.Make("Too Many Requests.", duration, fontSize);
  606.  
  607. toast.Show(cancellationTokenSource.Token);
  608. });
  609. }
  610. else
  611. {
  612. Debug.WriteLine(
  613. $"new status code and message {exception.errors[0].status} {exception.errors[0].message}"
  614. );
  615. }
  616. }
  617. catch (Exception e)
  618. {
  619. Console.WriteLine(e.Message);
  620. if (e.Message.Contains("Unable to resolve host"))
  621. {
  622. MainThread.BeginInvokeOnMainThread(() =>
  623. {
  624. //DependencyService.Get<Toast>().Show("Unexpected error happened");
  625.  
  626. var toast = Toast.Make("No internet.", duration, fontSize);
  627.  
  628. toast.Show(cancellationTokenSource.Token);
  629. });
  630. }
  631. else
  632. {
  633. MainThread.BeginInvokeOnMainThread(() =>
  634. {
  635. //DependencyService.Get<Toast>().Show("Unexpected error happened");
  636.  
  637. var toast = Toast.Make(
  638. "Unexpected error happened.",
  639. duration,
  640. fontSize
  641. );
  642.  
  643. toast.Show(cancellationTokenSource.Token);
  644. });
  645. }
  646. }
  647. finally
  648. {
  649. Indicating = false;
  650. Debug.WriteLine("increase happens");
  651. }
  652. });
  653. }
  654.  
  655. async Task DecreaseTask(ListEntry x)
  656. {
  657. await Task.Run(async () =>
  658. {
  659. Indicating = true;
  660. try
  661. {
  662. if (x.media.startDate.Time > DateTime.Now)
  663. {
  664. MainThread.BeginInvokeOnMainThread(() =>
  665. {
  666. // DependencyService.Get<Toast>().Show("Anime hasn't aired yet.");
  667. });
  668. }
  669. else
  670. {
  671. if (x.progress > 0)
  672. {
  673. string token = Preferences.Get("token", "default_value");
  674. var anilistGraphQlHttpClient = new GraphQLHttpClient(
  675. "https://graphql.anilist.co",
  676. new NewtonsoftJsonSerializer()
  677. );
  678.  
  679. anilistGraphQlHttpClient.HttpClient.DefaultRequestHeaders.Add(
  680. "Authorization",
  681. "Bearer " + token
  682. );
  683.  
  684. var IncreaseProgressEntry = new GraphQLRequest
  685. {
  686. Query =
  687. @"mutation IncreaseProgress($id: Int, $progress: Int) { SaveMediaListEntry(id: $id, progress: $progress) { id progress status } } ",
  688. OperationName = "IncreaseProgress",
  689. Variables = new { id = x.id, progress = x.progress - 1 }
  690. };
  691. var graphQlResponseAnimeList =
  692. await anilistGraphQlHttpClient.SendQueryAsync<Data>(
  693. IncreaseProgressEntry
  694. );
  695.  
  696. //CurrentEntry.progress = currentEntry.progress - 1;
  697.  
  698. foreach (var VARIABLE in AnimeGroupObservable)
  699. {
  700. foreach (var VARIABLE2 in VARIABLE)
  701. {
  702. if (VARIABLE2.id == x.id)
  703. {
  704. VARIABLE2.progress--;
  705. }
  706. }
  707. }
  708. }
  709. }
  710. }
  711. catch (HttpRequestException httpRequestException)
  712. {
  713. Debug.WriteLine(httpRequestException);
  714. MainThread.BeginInvokeOnMainThread(() =>
  715. {
  716. var toast = Toast.Make("No internet.", duration, fontSize);
  717.  
  718. toast.Show(cancellationTokenSource.Token);
  719. });
  720. }
  721. catch (GraphQLHttpRequestException e)
  722. {
  723. Root exception = JsonConvert.DeserializeObject<Root>(e.Content);
  724. if (exception.errors[0].status == 400)
  725. {
  726. if (exception.errors[0].message == "Invalid token")
  727. {
  728. Preferences.Set("token", "default_value");
  729. await Shell.Current.GoToAsync($"//LandingPage");
  730.  
  731. MainThread.BeginInvokeOnMainThread(() =>
  732. {
  733. var toast = Toast.Make("Invalid token.", duration, fontSize);
  734.  
  735. toast.Show(cancellationTokenSource.Token);
  736. });
  737. }
  738. else if (exception.errors[0].message == "validation")
  739. {
  740. MainThread.BeginInvokeOnMainThread(() =>
  741. {
  742. var toast = Toast.Make(
  743. "Missing parameter in query.",
  744. duration,
  745. fontSize
  746. );
  747.  
  748. toast.Show(cancellationTokenSource.Token);
  749. });
  750. }
  751. else
  752. {
  753. MainThread.BeginInvokeOnMainThread(() =>
  754. {
  755. var toast = Toast.Make(
  756. $"new exception other than invalid token and missing parameter in 400 - {exception.errors[0].message}",
  757. duration,
  758. fontSize
  759. );
  760.  
  761. toast.Show(cancellationTokenSource.Token);
  762. });
  763. }
  764. }
  765. else if (exception.errors[0].status == 401)
  766. {
  767. Debug.WriteLine(
  768. $"new exception other than unauthorized in 401 - {exception.errors[0].message}"
  769. );
  770. MainThread.BeginInvokeOnMainThread(() =>
  771. {
  772. var toast = Toast.Make("Unauthorized.", duration, fontSize);
  773.  
  774. toast.Show(cancellationTokenSource.Token);
  775. });
  776. }
  777. else if (exception.errors[0].status == 429)
  778. {
  779. MainThread.BeginInvokeOnMainThread(() =>
  780. {
  781. var toast = Toast.Make("Too Many Requests.", duration, fontSize);
  782.  
  783. toast.Show(cancellationTokenSource.Token);
  784. });
  785. }
  786. else
  787. {
  788. Debug.WriteLine(
  789. $"new status code and message {exception.errors[0].status} {exception.errors[0].message}"
  790. );
  791. }
  792. }
  793. catch (Exception e)
  794. {
  795. Console.WriteLine(e.Message);
  796. if (e.Message.Contains("Unable to resolve host"))
  797. {
  798. MainThread.BeginInvokeOnMainThread(() =>
  799. {
  800. //DependencyService.Get<Toast>().Show("Unexpected error happened");
  801.  
  802. var toast = Toast.Make("No internet.", duration, fontSize);
  803.  
  804. toast.Show(cancellationTokenSource.Token);
  805. });
  806. }
  807. else
  808. {
  809. MainThread.BeginInvokeOnMainThread(() =>
  810. {
  811. //DependencyService.Get<Toast>().Show("Unexpected error happened");
  812.  
  813. var toast = Toast.Make(
  814. "Unexpected error happened.",
  815. duration,
  816. fontSize
  817. );
  818.  
  819. toast.Show(cancellationTokenSource.Token);
  820. });
  821. }
  822. }
  823. finally
  824. {
  825. Indicating = false;
  826. }
  827. });
  828. }
  829.  
  830. async Task Refresh()
  831. {
  832. await Task.Run(async () =>
  833. {
  834. try
  835. {
  836. string token = Preferences.Get("token", "default_value");
  837. var anilistGraphQlHttpClient = new GraphQLHttpClient(
  838. "https://graphql.anilist.co",
  839. new NewtonsoftJsonSerializer()
  840. );
  841.  
  842. anilistGraphQlHttpClient.HttpClient.DefaultRequestHeaders.Add(
  843. "Authorization",
  844. "Bearer " + token
  845. );
  846.  
  847. var requestAnimeList = new GraphQLRequest
  848. {
  849. Query =
  850. @"query AnimeList($userId: Int) { MediaListCollection(userId: $userId, type: ANIME) { user { mediaListOptions{ animeList{ sectionOrder } } } lists { name isCustomList isSplitCompletedList status entries { id customLists startedAt { year month day } media { id nextAiringEpisode { id airingAt timeUntilAiring } airingSchedule { nodes { id airingAt timeUntilAiring } } episodes startDate { year month day } title { userPreferred } coverImage { large } } progress status score } } } } ",
  851. OperationName = "AnimeList",
  852. Variables = new { userId = Preferences.Get("userID", "default_value") }
  853. };
  854.  
  855. var graphQlResponseAnimeList =
  856. await anilistGraphQlHttpClient.SendQueryAsync<Data>(requestAnimeList);
  857.  
  858. foreach (
  859. var VARIABLE1 in graphQlResponseAnimeList.Data.MediaListCollection.lists
  860. )
  861. {
  862. foreach (var VARIABLE in VARIABLE1.entries)
  863. {
  864. if (VARIABLE.startedAt.year is null)
  865. {
  866. VARIABLE.startedAt.Time = new DateTime(1970, 01, 01);
  867. }
  868. else
  869. {
  870. VARIABLE.startedAt.Time = VARIABLE.startedAt.Time = new DateTime(
  871. (int)VARIABLE.startedAt.year,
  872. (int)VARIABLE.startedAt.month,
  873. (int)VARIABLE.startedAt.day
  874. );
  875. }
  876.  
  877. if (
  878. VARIABLE.media.startDate.year is null
  879. && VARIABLE.media.startDate.month is null
  880. && VARIABLE.media.startDate.day is null
  881. )
  882. {
  883. VARIABLE.media.startDate.Time = new DateTime(2070, 1, 1);
  884. }
  885. else if (
  886. VARIABLE.media.startDate.month is null
  887. && VARIABLE.media.startDate.day is null
  888. )
  889. {
  890. VARIABLE.media.startDate.Time = new DateTime(
  891. (int)VARIABLE.media.startDate.year,
  892. 1,
  893. 1
  894. );
  895. }
  896. else if (VARIABLE.media.startDate.day is null)
  897. {
  898. VARIABLE.media.startDate.Time = new DateTime(
  899. (int)VARIABLE.media.startDate.year,
  900. (int)VARIABLE.media.startDate.month,
  901. 1
  902. );
  903. }
  904. else
  905. {
  906. VARIABLE.media.startDate.Time = new DateTime(
  907. (int)VARIABLE.media.startDate.year,
  908. (int)VARIABLE.media.startDate.month,
  909. (int)VARIABLE.media.startDate.day
  910. );
  911. }
  912. }
  913. }
  914.  
  915. foreach (var List in graphQlResponseAnimeList.Data.MediaListCollection.lists)
  916. {
  917. foreach (var listEntry in List.entries)
  918. {
  919. listEntry.CustomListsList = new ObservableCollection<customListItem>();
  920. if (listEntry.CustomLists != null)
  921. {
  922. foreach (var VARIABLE in listEntry.CustomLists)
  923. {
  924. listEntry.CustomListsList.Add(
  925. new customListItem
  926. {
  927. key = VARIABLE.Key,
  928. value = VARIABLE.Value
  929. }
  930. );
  931. }
  932. }
  933. }
  934. }
  935.  
  936. apiListData = graphQlResponseAnimeList;
  937.  
  938. var sorted = graphQlResponseAnimeList.Data.MediaListCollection.lists.OrderBy(
  939. x =>
  940. graphQlResponseAnimeList.Data.MediaListCollection.user.mediaListOptions.animeList
  941. .sectionOrder.IndexOf(
  942. x.name
  943. )
  944. );
  945.  
  946.  
  947.  
  948.  
  949. MediaGroups userGroups = new MediaGroups()
  950. {
  951. groups = sorted
  952. .Select(
  953. List =>
  954. new Models.Group(
  955. List.name,
  956. List.isCustomList,
  957. List.isSplitCompletedList,
  958. List.status,
  959. List.entries
  960. )
  961. {
  962. Name = List.name,
  963. isCustomList = List.isCustomList,
  964. isSplitCompletedList = List.isSplitCompletedList,
  965. status = List.status,
  966. entryCount = List.entries.Count,
  967. Entries = List.entries
  968. }
  969. )
  970. .ToList()
  971. };
  972.  
  973. MainThread.BeginInvokeOnMainThread(() =>
  974. {
  975.  
  976. AnimeGroupObservable = new ObservableCollection<Models.Group>(userGroups.groups);
  977.  
  978. MessagingCenter.Send(AnimeGroupObservable, "AllAnimeGroups");
  979.  
  980. });
  981.  
  982.  
  983. }
  984. catch (HttpRequestException httpRequestException)
  985. {
  986. Debug.WriteLine(httpRequestException);
  987. MainThread.BeginInvokeOnMainThread(() =>
  988. {
  989. var toast = Toast.Make("No internet.", duration, fontSize);
  990.  
  991. toast.Show(cancellationTokenSource.Token);
  992. });
  993. }
  994. catch (GraphQLHttpRequestException e)
  995. {
  996. Root exception = JsonConvert.DeserializeObject<Root>(e.Content);
  997. if (exception.errors[0].status == 400)
  998. {
  999. if (exception.errors[0].message == "Invalid token")
  1000. {
  1001. Preferences.Set("token", "default_value");
  1002. await Shell.Current.GoToAsync($"//LandingPage");
  1003.  
  1004. MainThread.BeginInvokeOnMainThread(() =>
  1005. {
  1006. var toast = Toast.Make("Invalid token.", duration, fontSize);
  1007.  
  1008. toast.Show(cancellationTokenSource.Token);
  1009. });
  1010. }
  1011. else if (exception.errors[0].message == "validation")
  1012. {
  1013. MainThread.BeginInvokeOnMainThread(() =>
  1014. {
  1015. var toast = Toast.Make(
  1016. "Missing parameter in query.",
  1017. duration,
  1018. fontSize
  1019. );
  1020.  
  1021. toast.Show(cancellationTokenSource.Token);
  1022. });
  1023. }
  1024. else
  1025. {
  1026. MainThread.BeginInvokeOnMainThread(() =>
  1027. {
  1028. var toast = Toast.Make(
  1029. $"new exception other than invalid token and missing parameter in 400 - {exception.errors[0].message}",
  1030. duration,
  1031. fontSize
  1032. );
  1033.  
  1034. toast.Show(cancellationTokenSource.Token);
  1035. });
  1036. }
  1037. }
  1038. else if (exception.errors[0].status == 401)
  1039. {
  1040. Debug.WriteLine(
  1041. $"new exception other than unauthorized in 401 - {exception.errors[0].message}"
  1042. );
  1043. MainThread.BeginInvokeOnMainThread(() =>
  1044. {
  1045. var toast = Toast.Make("Unauthorized.", duration, fontSize);
  1046.  
  1047. toast.Show(cancellationTokenSource.Token);
  1048. });
  1049. }
  1050. else if (exception.errors[0].status == 429)
  1051. {
  1052. MainThread.BeginInvokeOnMainThread(() =>
  1053. {
  1054. var toast = Toast.Make("Too Many Requests.", duration, fontSize);
  1055.  
  1056. toast.Show(cancellationTokenSource.Token);
  1057. });
  1058. }
  1059. else
  1060. {
  1061. Debug.WriteLine(
  1062. $"new status code and message {exception.errors[0].status} {exception.errors[0].message}"
  1063. );
  1064. }
  1065. }
  1066. catch (Exception e)
  1067. {
  1068. Console.WriteLine(e.Message);
  1069. if (e.Message.Contains("Unable to resolve host"))
  1070. {
  1071. MainThread.BeginInvokeOnMainThread(() =>
  1072. {
  1073. //DependencyService.Get<Toast>().Show("Unexpected error happened");
  1074.  
  1075. var toast = Toast.Make("No internet.", duration, fontSize);
  1076.  
  1077. toast.Show(cancellationTokenSource.Token);
  1078. });
  1079. }
  1080. else
  1081. {
  1082. MainThread.BeginInvokeOnMainThread(() =>
  1083. {
  1084. //DependencyService.Get<Toast>().Show("Unexpected error happened");
  1085.  
  1086. var toast = Toast.Make(
  1087. "Unexpected error happened.",
  1088. duration,
  1089. fontSize
  1090. );
  1091.  
  1092. toast.Show(cancellationTokenSource.Token);
  1093. });
  1094. }
  1095. }
  1096. finally
  1097. {
  1098. IsBusy = false;
  1099. Debug.WriteLine("refresh happens");
  1100. }
  1101. });
  1102. }
  1103. }
  1104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement