Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.ObjectModel;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.Runtime.CompilerServices;
- using System.Windows.Input;
- using GraphQL;
- using GraphQL.Client.Http;
- using GraphQL.Client.Serializer.Newtonsoft;
- using Newtonsoft.Json;
- using MauiApp2.Models;
- using CommunityToolkit.Maui.Alerts;
- using CommunityToolkit.Maui.Core;
- using MauiApp2.Views;
- namespace MauiApp2.ViewModels
- {
- class AnimeListPageViewModel : INotifyPropertyChanged
- {
- public event PropertyChangedEventHandler PropertyChanged;
- void OnPropertyChanged([CallerMemberName] string name = "")
- {
- PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
- }
- CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
- ToastDuration duration = ToastDuration.Short;
- double fontSize = 14;
- public ICommand OpenMediaCommand { get; }
- public ICommand RefreshCommand { get; }
- public ICommand IncreaseCommand { get; private set; }
- public ICommand DecreaseCommand { get; private set; }
- public ICommand ShowPopupCommand { get; }
- public ICommand SearchCommand { get; }
- public bool isBusy = false;
- public bool IsBusy
- {
- get => isBusy;
- set
- {
- if (value == isBusy)
- return;
- isBusy = value;
- OnPropertyChanged();
- }
- }
- public bool _Indicating = false;
- public bool Indicating
- {
- get => _Indicating;
- set
- {
- if (value == _Indicating)
- return;
- _Indicating = value;
- OnPropertyChanged();
- }
- }
- private GraphQLResponse<Data> _apiListData;
- public GraphQLResponse<Data> apiListData
- {
- get => _apiListData;
- set
- {
- if (value == _apiListData)
- return;
- _apiListData = value;
- }
- }
- public ObservableCollection<Models.Group> _AnimeGroupObservable;
- public ObservableCollection<Models.Group> AnimeGroupObservable
- {
- get => _AnimeGroupObservable;
- set
- {
- if (value == _AnimeGroupObservable)
- return;
- _AnimeGroupObservable = value;
- OnPropertyChanged();
- }
- }
- private List<string> searchResults;
- public List<string> SearchResults
- {
- get
- {
- return searchResults;
- }
- set
- {
- searchResults = value;
- OnPropertyChanged();
- }
- }
- public AnimeListPageViewModel()
- {
- MessagingCenter.Subscribe<AnimeListPage> (this, "ClearFilter", (sender) =>
- {
- SearchTask(string.Empty);
- });
- RefreshCommand = new Command(async () => await Refresh().ConfigureAwait(false));
- IncreaseCommand = new Command<ListEntry>((x) => IncreaseTask(x));
- DecreaseCommand = new Command<ListEntry>((x) => DecreaseTask(x));
- ShowPopupCommand = new Command(async () => await ShowPopup());
- OpenMediaCommand = new Command<Media>((x) => OpenMediaTask(x));
- SearchCommand = new Command<string>((x) => SearchTask(x));
- IsBusy = true;
- }
- async Task SearchTask(string query)
- {
- //var SearchTerm = query;
- //if (string.IsNullOrWhiteSpace(SearchTerm))
- //{
- // SearchTerm = string.Empty;
- //}
- //SearchTerm = SearchTerm.ToLowerInvariant();
- //foreach (var group in AnimeGroupObservable)
- //{
- // var filteredItems = group
- // .Where(value => value.media.Title.UserPreferred.ToLowerInvariant().Contains(SearchTerm)).ToList();
- // if (string.IsNullOrWhiteSpace(SearchTerm))
- // {
- // filteredItems = group.ToList();
- // }
- // foreach (var value in group)
- // {
- // if (!filteredItems.Contains(value))
- // {
- // group.Remove(value);
- // }
- // else if (!group.Contains(value))
- // {
- // group.Add(value);
- // }
- // }
- //}
- //var SearchTerm = query;
- //if (string.IsNullOrWhiteSpace(SearchTerm))
- //{
- // SearchTerm = string.Empty;
- //}
- //SearchTerm = SearchTerm.ToLowerInvariant();
- //foreach (var group in TechnicList)
- //{
- // var filteredItems = group
- // .Where(value => value.media.Title.UserPreferred.ToLowerInvariant().Contains(SearchTerm)).ToList();
- // if (string.IsNullOrWhiteSpace(SearchTerm))
- // {
- // filteredItems = group.Entries.ToList();
- // }
- // foreach (var value in group)
- // {
- // if (!filteredItems.Contains(value))
- // {
- // foreach (var VARIABLE in AnimeGroupObservable)
- // {
- // if (VARIABLE.Name == group.Name)
- // {
- // VARIABLE.Remove(value);
- // }
- // }
- // }
- // foreach (var VARIABLE in AnimeGroupObservable)
- // {
- // if (VARIABLE.Name == group.Name)
- // {
- // if (!VARIABLE.Contains(value))
- // {
- // group.Add(value);
- // }
- // }
- // }
- // }
- //}
- //if (string.IsNullOrEmpty(query))
- //{
- // AnimeGroupObservable = TechnicList;
- //}
- //else
- //{
- // foreach (var Group in TechnicList)
- // {
- // foreach (var Ani in AnimeGroupObservable)
- // {
- // if (Ani.Name == Group.Name)
- // {
- // Ani.Where(p => p.media.Title.UserPreferred.Contains(query, StringComparison.CurrentCultureIgnoreCase)).ToList();
- // }
- // }
- // }
- //}
- //string token = Preferences.Get("token", "default_value");
- // var anilistGraphQlHttpClient = new GraphQLHttpClient(
- // "https://graphql.anilist.co",
- // new NewtonsoftJsonSerializer()
- // );
- // anilistGraphQlHttpClient.HttpClient.DefaultRequestHeaders.Add(
- // "Authorization",
- // "Bearer " + token
- // );
- // var requestAnimeList = new GraphQLRequest
- // {
- // Query =
- // @"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 } } } } ",
- // OperationName = "AnimeList",
- // Variables = new { userId = Preferences.Get("userID", "default_value") }
- // };
- // var graphQlResponseAnimeList =
- // await anilistGraphQlHttpClient.SendQueryAsync<Data>(requestAnimeList);
- // foreach (
- // var VARIABLE1 in graphQlResponseAnimeList.Data.MediaListCollection.lists
- // )
- // {
- // foreach (var VARIABLE in VARIABLE1.entries)
- // {
- // if (VARIABLE.startedAt.year is null)
- // {
- // VARIABLE.startedAt.Time = new DateTime(1970, 01, 01);
- // }
- // else
- // {
- // VARIABLE.startedAt.Time = VARIABLE.startedAt.Time = new DateTime(
- // (int)VARIABLE.startedAt.year,
- // (int)VARIABLE.startedAt.month,
- // (int)VARIABLE.startedAt.day
- // );
- // }
- // if (
- // VARIABLE.media.startDate.year is null
- // && VARIABLE.media.startDate.month is null
- // && VARIABLE.media.startDate.day is null
- // )
- // {
- // VARIABLE.media.startDate.Time = new DateTime(2070, 1, 1);
- // }
- // else if (
- // VARIABLE.media.startDate.month is null
- // && VARIABLE.media.startDate.day is null
- // )
- // {
- // VARIABLE.media.startDate.Time = new DateTime(
- // (int)VARIABLE.media.startDate.year,
- // 1,
- // 1
- // );
- // }
- // else if (VARIABLE.media.startDate.day is null)
- // {
- // VARIABLE.media.startDate.Time = new DateTime(
- // (int)VARIABLE.media.startDate.year,
- // (int)VARIABLE.media.startDate.month,
- // 1
- // );
- // }
- // else
- // {
- // VARIABLE.media.startDate.Time = new DateTime(
- // (int)VARIABLE.media.startDate.year,
- // (int)VARIABLE.media.startDate.month,
- // (int)VARIABLE.media.startDate.day
- // );
- // }
- // }
- // }
- if (query == string.Empty)
- {
- GraphQLResponse<Data> filt = apiListData;
- GraphQLResponse<Data> startFilter = filt;
- foreach (var List in startFilter.Data.MediaListCollection.lists)
- {
- foreach (var listEntry in List.entries)
- {
- listEntry.CustomListsList = new ObservableCollection<customListItem>();
- if (listEntry.CustomLists != null)
- {
- foreach (var VARIABLE in listEntry.CustomLists)
- {
- listEntry.CustomListsList.Add(
- new customListItem
- {
- key = VARIABLE.Key,
- value = VARIABLE.Value
- }
- );
- }
- }
- }
- }
- var sorted = startFilter.Data.MediaListCollection.lists.OrderBy(
- x =>
- startFilter.Data.MediaListCollection.user.mediaListOptions.animeList
- .sectionOrder.IndexOf(
- x.name
- )
- );
- MediaGroups userGroups = new MediaGroups()
- {
- groups = sorted
- .Select(
- List =>
- new Models.Group(
- List.name,
- List.isCustomList,
- List.isSplitCompletedList,
- List.status,
- List.entries
- )
- {
- Name = List.name,
- isCustomList = List.isCustomList,
- isSplitCompletedList = List.isSplitCompletedList,
- status = List.status,
- entryCount = List.entries.Count,
- Entries = List.entries
- }
- )
- .ToList()
- };
- MainThread.BeginInvokeOnMainThread(() =>
- {
- AnimeGroupObservable = new ObservableCollection<Models.Group>(userGroups.groups);
- MessagingCenter.Send(AnimeGroupObservable, "AllAnimeGroups");
- });
- }
- else
- {
- GraphQLResponse<Data> filt = apiListData;
- GraphQLResponse<Data> startFilter = filt;
- foreach (var List in startFilter.Data.MediaListCollection.lists)
- {
- foreach (var listEntry in List.entries)
- {
- listEntry.CustomListsList = new ObservableCollection<customListItem>();
- if (listEntry.CustomLists != null)
- {
- foreach (var VARIABLE in listEntry.CustomLists)
- {
- listEntry.CustomListsList.Add(
- new customListItem
- {
- key = VARIABLE.Key,
- value = VARIABLE.Value
- }
- );
- }
- }
- }
- }
- var filtered = startFilter.Data.MediaListCollection.lists;
- foreach (var x in filtered)
- {
- x.entries = x.entries.Where(x => x.media.Title.UserPreferred.ToLowerInvariant().Contains(query))
- .ToList();
- }
- Console.WriteLine(filtered);
- var sorted = filtered.OrderBy(
- x =>
- startFilter.Data.MediaListCollection.user.mediaListOptions.animeList
- .sectionOrder.IndexOf(
- x.name
- )
- );
- MediaGroups userGroups = new MediaGroups()
- {
- groups = sorted
- .Select(
- List =>
- new Models.Group(
- List.name,
- List.isCustomList,
- List.isSplitCompletedList,
- List.status,
- List.entries
- )
- {
- Name = List.name,
- isCustomList = List.isCustomList,
- isSplitCompletedList = List.isSplitCompletedList,
- status = List.status,
- entryCount = List.entries.Count,
- Entries = List.entries
- }
- )
- .ToList()
- };
- MainThread.BeginInvokeOnMainThread(() =>
- {
- AnimeGroupObservable = new ObservableCollection<Models.Group>(userGroups.groups);
- MessagingCenter.Send(AnimeGroupObservable, "AllAnimeGroups");
- });
- }
- }
- async Task OpenMediaTask(Media x)
- {
- var navigationParameter = new Dictionary<string, object> { { "pushMedia", x } };
- await Shell.Current.GoToAsync(
- "MediaDetailsPage",
- parameters: navigationParameter,
- animate: true
- );
- }
- async Task ShowPopup()
- {
- if (AnimeGroupObservable != null)
- {
- //await Shell.Current.ShowPopupAsync(new AnimeListGroupsPopup(AnimeGroupObservable));
- }
- }
- async Task IncreaseTask(ListEntry x)
- {
- await Task.Run(async () =>
- {
- Console.WriteLine(x);
- Indicating = true;
- try
- {
- Debug.WriteLine("Cos2");
- if (x.media.startDate.Time > DateTime.Now)
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make("Anime hasn't aired yet.", duration, fontSize);
- toast.Show(cancellationTokenSource.Token);
- });
- }
- else
- {
- if (x.media.Episodes is null || x.progress < x.media.Episodes)
- {
- string token = Preferences.Get("token", "default_value");
- var anilistGraphQlHttpClient = new GraphQLHttpClient(
- "https://graphql.anilist.co",
- new NewtonsoftJsonSerializer()
- );
- anilistGraphQlHttpClient.HttpClient.DefaultRequestHeaders.Add(
- "Authorization",
- "Bearer " + token
- );
- var IncreaseProgressEntry = new GraphQLRequest
- {
- Query =
- @"mutation IncreaseProgress($id: Int, $progress: Int) { SaveMediaListEntry(id: $id, progress: $progress) { id progress status } } ",
- OperationName = "IncreaseProgress",
- Variables = new { id = x.id, progress = x.progress + 1 }
- };
- var graphQlResponseAnimeList =
- await anilistGraphQlHttpClient.SendQueryAsync<Data>(
- IncreaseProgressEntry
- );
- foreach (var VARIABLE in AnimeGroupObservable)
- {
- foreach (var VARIABLE2 in VARIABLE)
- {
- if (VARIABLE2.id == x.id)
- {
- VARIABLE2.progress++;
- }
- }
- }
- }
- }
- }
- catch (HttpRequestException httpRequestException)
- {
- Debug.WriteLine(httpRequestException);
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make("No internet.", duration, fontSize);
- toast.Show(cancellationTokenSource.Token);
- });
- }
- catch (GraphQLHttpRequestException e)
- {
- Root exception = JsonConvert.DeserializeObject<Root>(e.Content);
- if (exception.errors[0].status == 400)
- {
- if (exception.errors[0].message == "Invalid token")
- {
- Preferences.Set("token", "default_value");
- await Shell.Current.GoToAsync($"//LandingPage");
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make("Invalid token.", duration, fontSize);
- toast.Show(cancellationTokenSource.Token);
- });
- }
- else if (exception.errors[0].message == "validation")
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make(
- "Missing parameter in query.",
- duration,
- fontSize
- );
- toast.Show(cancellationTokenSource.Token);
- });
- }
- else
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make(
- $"new exception other than invalid token and missing parameter in 400 - {exception.errors[0].message}",
- duration,
- fontSize
- );
- toast.Show(cancellationTokenSource.Token);
- });
- }
- }
- else if (exception.errors[0].status == 401)
- {
- Debug.WriteLine(
- $"new exception other than unauthorized in 401 - {exception.errors[0].message}"
- );
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make("Unauthorized.", duration, fontSize);
- toast.Show(cancellationTokenSource.Token);
- });
- }
- else if (exception.errors[0].status == 429)
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make("Too Many Requests.", duration, fontSize);
- toast.Show(cancellationTokenSource.Token);
- });
- }
- else
- {
- Debug.WriteLine(
- $"new status code and message {exception.errors[0].status} {exception.errors[0].message}"
- );
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e.Message);
- if (e.Message.Contains("Unable to resolve host"))
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- //DependencyService.Get<Toast>().Show("Unexpected error happened");
- var toast = Toast.Make("No internet.", duration, fontSize);
- toast.Show(cancellationTokenSource.Token);
- });
- }
- else
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- //DependencyService.Get<Toast>().Show("Unexpected error happened");
- var toast = Toast.Make(
- "Unexpected error happened.",
- duration,
- fontSize
- );
- toast.Show(cancellationTokenSource.Token);
- });
- }
- }
- finally
- {
- Indicating = false;
- Debug.WriteLine("increase happens");
- }
- });
- }
- async Task DecreaseTask(ListEntry x)
- {
- await Task.Run(async () =>
- {
- Indicating = true;
- try
- {
- if (x.media.startDate.Time > DateTime.Now)
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- // DependencyService.Get<Toast>().Show("Anime hasn't aired yet.");
- });
- }
- else
- {
- if (x.progress > 0)
- {
- string token = Preferences.Get("token", "default_value");
- var anilistGraphQlHttpClient = new GraphQLHttpClient(
- "https://graphql.anilist.co",
- new NewtonsoftJsonSerializer()
- );
- anilistGraphQlHttpClient.HttpClient.DefaultRequestHeaders.Add(
- "Authorization",
- "Bearer " + token
- );
- var IncreaseProgressEntry = new GraphQLRequest
- {
- Query =
- @"mutation IncreaseProgress($id: Int, $progress: Int) { SaveMediaListEntry(id: $id, progress: $progress) { id progress status } } ",
- OperationName = "IncreaseProgress",
- Variables = new { id = x.id, progress = x.progress - 1 }
- };
- var graphQlResponseAnimeList =
- await anilistGraphQlHttpClient.SendQueryAsync<Data>(
- IncreaseProgressEntry
- );
- //CurrentEntry.progress = currentEntry.progress - 1;
- foreach (var VARIABLE in AnimeGroupObservable)
- {
- foreach (var VARIABLE2 in VARIABLE)
- {
- if (VARIABLE2.id == x.id)
- {
- VARIABLE2.progress--;
- }
- }
- }
- }
- }
- }
- catch (HttpRequestException httpRequestException)
- {
- Debug.WriteLine(httpRequestException);
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make("No internet.", duration, fontSize);
- toast.Show(cancellationTokenSource.Token);
- });
- }
- catch (GraphQLHttpRequestException e)
- {
- Root exception = JsonConvert.DeserializeObject<Root>(e.Content);
- if (exception.errors[0].status == 400)
- {
- if (exception.errors[0].message == "Invalid token")
- {
- Preferences.Set("token", "default_value");
- await Shell.Current.GoToAsync($"//LandingPage");
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make("Invalid token.", duration, fontSize);
- toast.Show(cancellationTokenSource.Token);
- });
- }
- else if (exception.errors[0].message == "validation")
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make(
- "Missing parameter in query.",
- duration,
- fontSize
- );
- toast.Show(cancellationTokenSource.Token);
- });
- }
- else
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make(
- $"new exception other than invalid token and missing parameter in 400 - {exception.errors[0].message}",
- duration,
- fontSize
- );
- toast.Show(cancellationTokenSource.Token);
- });
- }
- }
- else if (exception.errors[0].status == 401)
- {
- Debug.WriteLine(
- $"new exception other than unauthorized in 401 - {exception.errors[0].message}"
- );
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make("Unauthorized.", duration, fontSize);
- toast.Show(cancellationTokenSource.Token);
- });
- }
- else if (exception.errors[0].status == 429)
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make("Too Many Requests.", duration, fontSize);
- toast.Show(cancellationTokenSource.Token);
- });
- }
- else
- {
- Debug.WriteLine(
- $"new status code and message {exception.errors[0].status} {exception.errors[0].message}"
- );
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e.Message);
- if (e.Message.Contains("Unable to resolve host"))
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- //DependencyService.Get<Toast>().Show("Unexpected error happened");
- var toast = Toast.Make("No internet.", duration, fontSize);
- toast.Show(cancellationTokenSource.Token);
- });
- }
- else
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- //DependencyService.Get<Toast>().Show("Unexpected error happened");
- var toast = Toast.Make(
- "Unexpected error happened.",
- duration,
- fontSize
- );
- toast.Show(cancellationTokenSource.Token);
- });
- }
- }
- finally
- {
- Indicating = false;
- }
- });
- }
- async Task Refresh()
- {
- await Task.Run(async () =>
- {
- try
- {
- string token = Preferences.Get("token", "default_value");
- var anilistGraphQlHttpClient = new GraphQLHttpClient(
- "https://graphql.anilist.co",
- new NewtonsoftJsonSerializer()
- );
- anilistGraphQlHttpClient.HttpClient.DefaultRequestHeaders.Add(
- "Authorization",
- "Bearer " + token
- );
- var requestAnimeList = new GraphQLRequest
- {
- Query =
- @"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 } } } } ",
- OperationName = "AnimeList",
- Variables = new { userId = Preferences.Get("userID", "default_value") }
- };
- var graphQlResponseAnimeList =
- await anilistGraphQlHttpClient.SendQueryAsync<Data>(requestAnimeList);
- foreach (
- var VARIABLE1 in graphQlResponseAnimeList.Data.MediaListCollection.lists
- )
- {
- foreach (var VARIABLE in VARIABLE1.entries)
- {
- if (VARIABLE.startedAt.year is null)
- {
- VARIABLE.startedAt.Time = new DateTime(1970, 01, 01);
- }
- else
- {
- VARIABLE.startedAt.Time = VARIABLE.startedAt.Time = new DateTime(
- (int)VARIABLE.startedAt.year,
- (int)VARIABLE.startedAt.month,
- (int)VARIABLE.startedAt.day
- );
- }
- if (
- VARIABLE.media.startDate.year is null
- && VARIABLE.media.startDate.month is null
- && VARIABLE.media.startDate.day is null
- )
- {
- VARIABLE.media.startDate.Time = new DateTime(2070, 1, 1);
- }
- else if (
- VARIABLE.media.startDate.month is null
- && VARIABLE.media.startDate.day is null
- )
- {
- VARIABLE.media.startDate.Time = new DateTime(
- (int)VARIABLE.media.startDate.year,
- 1,
- 1
- );
- }
- else if (VARIABLE.media.startDate.day is null)
- {
- VARIABLE.media.startDate.Time = new DateTime(
- (int)VARIABLE.media.startDate.year,
- (int)VARIABLE.media.startDate.month,
- 1
- );
- }
- else
- {
- VARIABLE.media.startDate.Time = new DateTime(
- (int)VARIABLE.media.startDate.year,
- (int)VARIABLE.media.startDate.month,
- (int)VARIABLE.media.startDate.day
- );
- }
- }
- }
- foreach (var List in graphQlResponseAnimeList.Data.MediaListCollection.lists)
- {
- foreach (var listEntry in List.entries)
- {
- listEntry.CustomListsList = new ObservableCollection<customListItem>();
- if (listEntry.CustomLists != null)
- {
- foreach (var VARIABLE in listEntry.CustomLists)
- {
- listEntry.CustomListsList.Add(
- new customListItem
- {
- key = VARIABLE.Key,
- value = VARIABLE.Value
- }
- );
- }
- }
- }
- }
- apiListData = graphQlResponseAnimeList;
- var sorted = graphQlResponseAnimeList.Data.MediaListCollection.lists.OrderBy(
- x =>
- graphQlResponseAnimeList.Data.MediaListCollection.user.mediaListOptions.animeList
- .sectionOrder.IndexOf(
- x.name
- )
- );
- MediaGroups userGroups = new MediaGroups()
- {
- groups = sorted
- .Select(
- List =>
- new Models.Group(
- List.name,
- List.isCustomList,
- List.isSplitCompletedList,
- List.status,
- List.entries
- )
- {
- Name = List.name,
- isCustomList = List.isCustomList,
- isSplitCompletedList = List.isSplitCompletedList,
- status = List.status,
- entryCount = List.entries.Count,
- Entries = List.entries
- }
- )
- .ToList()
- };
- MainThread.BeginInvokeOnMainThread(() =>
- {
- AnimeGroupObservable = new ObservableCollection<Models.Group>(userGroups.groups);
- MessagingCenter.Send(AnimeGroupObservable, "AllAnimeGroups");
- });
- }
- catch (HttpRequestException httpRequestException)
- {
- Debug.WriteLine(httpRequestException);
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make("No internet.", duration, fontSize);
- toast.Show(cancellationTokenSource.Token);
- });
- }
- catch (GraphQLHttpRequestException e)
- {
- Root exception = JsonConvert.DeserializeObject<Root>(e.Content);
- if (exception.errors[0].status == 400)
- {
- if (exception.errors[0].message == "Invalid token")
- {
- Preferences.Set("token", "default_value");
- await Shell.Current.GoToAsync($"//LandingPage");
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make("Invalid token.", duration, fontSize);
- toast.Show(cancellationTokenSource.Token);
- });
- }
- else if (exception.errors[0].message == "validation")
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make(
- "Missing parameter in query.",
- duration,
- fontSize
- );
- toast.Show(cancellationTokenSource.Token);
- });
- }
- else
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make(
- $"new exception other than invalid token and missing parameter in 400 - {exception.errors[0].message}",
- duration,
- fontSize
- );
- toast.Show(cancellationTokenSource.Token);
- });
- }
- }
- else if (exception.errors[0].status == 401)
- {
- Debug.WriteLine(
- $"new exception other than unauthorized in 401 - {exception.errors[0].message}"
- );
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make("Unauthorized.", duration, fontSize);
- toast.Show(cancellationTokenSource.Token);
- });
- }
- else if (exception.errors[0].status == 429)
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- var toast = Toast.Make("Too Many Requests.", duration, fontSize);
- toast.Show(cancellationTokenSource.Token);
- });
- }
- else
- {
- Debug.WriteLine(
- $"new status code and message {exception.errors[0].status} {exception.errors[0].message}"
- );
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e.Message);
- if (e.Message.Contains("Unable to resolve host"))
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- //DependencyService.Get<Toast>().Show("Unexpected error happened");
- var toast = Toast.Make("No internet.", duration, fontSize);
- toast.Show(cancellationTokenSource.Token);
- });
- }
- else
- {
- MainThread.BeginInvokeOnMainThread(() =>
- {
- //DependencyService.Get<Toast>().Show("Unexpected error happened");
- var toast = Toast.Make(
- "Unexpected error happened.",
- duration,
- fontSize
- );
- toast.Show(cancellationTokenSource.Token);
- });
- }
- }
- finally
- {
- IsBusy = false;
- Debug.WriteLine("refresh happens");
- }
- });
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement