예제 #1
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferall = taskInstance.GetDeferral();

            try
            {
                ResourceLocator.RegisterAppDataServiceAdapter(new ApplicationDataServiceService());
                ResourceLocator.RegisterDataCacheAdapter(new DataCache());
                ResourceLocator.RegisterMessageDialogAdapter(new MessageDialogProvider());
            }
            catch (Exception)
            {
                //may be already registered... voodoo I guess
            }

            await LiveTilesManager.UpdateNewsTilesAsync();

            deferall.Complete();
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            Defferal = taskInstance?.GetDeferral();

            //var details = taskInstance.TriggerDetails as ToastNotificationActionTriggerDetail;
            //if (details != null)
            //{
            //    await Launcher.LaunchUriAsync(new Uri(details.Argument));
            //    Defferal.Complete();
            //    return;
            //}

            try
            {
                if (taskInstance != null) //we are already running -> started on demand
                {
                    ResourceLocator.RegisterBase();
                    ResourceLocator.RegisterAppDataServiceAdapter(new ApplicationDataServiceService());
                    ResourceLocator.RegisterPasswordVaultAdapter(new PasswordVaultProvider());
                    ResourceLocator.RegisterMessageDialogAdapter(new MessageDialogProvider());
                    ResourceLocator.RegisterHttpContextAdapter(new MalHttpContextProvider());
                    ResourceLocator.RegisterDataCacheAdapter(new Adapters.DataCache(null));
                    Credentials.Init();
                }
            }
            catch (Exception)
            {
                //app is running so we don't check, checks are conducted in runtime manually
                //Defferal?.Complete();
                //return;
            }


            List <MalNotification> notifications = new List <MalNotification>();

            try
            {
                if (
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.FriendRequestAcceptDeny) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.NewRelatedAnime) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.BlogComment) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.ClubMessages) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.ForumQuoute) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.FriendRequest) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.NowAiring) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.ProfileComment) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.Payment) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.UserMentions) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.WatchedTopics))
                {
                    notifications.AddRange(await MalNotificationsQuery.GetNotifications());
                    notifications =
                        notifications.Where(
                            notification =>
                            !notification.IsRead &&
                            (Settings.EnabledNotificationTypes & notification.Type) == notification.Type).ToList();
                }
            }
            catch (Exception)
            {
                //http exec error
            }


            if ((Settings.EnabledNotificationTypes & MalNotificationsTypes.Messages) == MalNotificationsTypes.Messages)
            {
                try
                {
                    var msgs = await AccountMessagesManager.GetMessagesAsync(1);

                    foreach (var malMessageModel in msgs)
                    {
                        if (!malMessageModel.IsRead)
                        {
                            notifications.Add(new MalNotification(malMessageModel)); //I'm assuming that Ids are unique
                        }
                    }
                }
                catch (Exception)
                {
                    //no messages
                }
            }

            bool watchedTopicsUpdated = false;

            foreach (var watchedTopic in ResourceLocator.HandyDataStorage.WatchedTopics.StoredItems)
            {
                if (!watchedTopic.OnCooldown)
                {
                    var count = await new ForumTopicMessageCountQuery(watchedTopic.Id).GetMessageCount(true);
                    if (count == null)
                    {
                        continue;
                    }

                    if (count > watchedTopic.LastCheckedReplyCount)
                    {
                        var notif = new MalNotification(watchedTopic);
                        var diff  = count - watchedTopic.LastCheckedReplyCount;
                        if (diff == 1)
                        {
                            notif.Content += " There is one new reply.";
                        }
                        else
                        {
                            notif.Content += $" There are {diff} new replies.";
                        }

                        notifications.Add(notif);

                        watchedTopic.OnCooldown            = true;
                        watchedTopic.LastCheckedReplyCount = count.Value;
                        watchedTopicsUpdated = true;
                    }
                }
            }
            if (watchedTopicsUpdated)
            {
                ResourceLocator.HandyDataStorage.WatchedTopics.SaveData();
            }

            if (!notifications.Any())
            {
                Defferal?.Complete();
                return;
            }

            var allTriggeredNotifications = (string)(ApplicationData.Current.LocalSettings.Values[nameof(RoamingDataTypes.ReadNotifications)] ?? string.Empty);
            var triggeredNotifications    = allTriggeredNotifications.Split(';').ToList();
            var triggeredAny = false;

            //trigger new notifications
            foreach (var notification in notifications)
            {
                if (triggeredNotifications.Contains(notification.Id))
                {
                    continue;
                }

                triggeredNotifications.Add(notification.Id);
                triggeredAny = true;
                ScheduleToast(notification);
            }
            //remove old triggered entries
            var presentNotifications = new List <string>();

            foreach (var triggeredNotification in triggeredNotifications)
            {
                if (notifications.Any(notif => notif.Id == triggeredNotification))
                {
                    presentNotifications.Add(triggeredNotification);
                }
            }

            ApplicationData.Current.LocalSettings.Values[nameof(RoamingDataTypes.ReadNotifications)] = string.Join(";", presentNotifications);

            if (!triggeredAny)
            {
                Defferal?.Complete();
            }
        }
        public override async void OnReceive(Context context, Intent sourceIntent)
        {
            try
            {
                ResourceLocator.RegisterBase();
                ResourceLocator.RegisterAppDataServiceAdapter(new ApplicationDataServiceService());
                ResourceLocator.RegisterPasswordVaultAdapter(new PasswordVaultProvider());
                ResourceLocator.RegisterMessageDialogAdapter(new MessageDialogProvider());
                ResourceLocator.RegisterHttpContextAdapter(new MalHttpContextProvider());
                ResourceLocator.RegisterDataCacheAdapter(new Adapters.DataCache(null));
                Credentials.Init();
            }
            catch (Exception)
            {
                //may be already registered... voodoo I guess
            }


            List <MalNotification> notifications = new List <MalNotification>();

            try
            {
                if (
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.FriendRequestAcceptDeny) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.NewRelatedAnime) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.BlogComment) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.ClubMessages) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.ForumQuoute) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.FriendRequest) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.NowAiring) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.ProfileComment) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.Payment) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.UserMentions) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.WatchedTopics))
                {
                    List <MalNotification> notifs = null;
                    await Task.Run(async() =>
                    {
                        notifs = await MalNotificationsQuery.GetNotifications();
                    });

                    notifications.AddRange(notifs);
                    notifications =
                        notifications.Where(
                            notification =>
                            !notification.IsRead &&
                            (Settings.EnabledNotificationTypes & notification.Type) == notification.Type).ToList();
                }
            }
            catch (Exception e)
            {
                //http exec error
            }


            if ((Settings.EnabledNotificationTypes & MalNotificationsTypes.Messages) == MalNotificationsTypes.Messages)
            {
                try
                {
                    List <MalMessageModel> msgs = null;
                    await Task.Run(async() =>
                    {
                        msgs = await AccountMessagesManager.GetMessagesAsync(1);
                    });

                    foreach (var malMessageModel in msgs)
                    {
                        if (!malMessageModel.IsRead)
                        {
                            notifications.Add(new MalNotification(malMessageModel)); //I'm assuming that Ids are unique
                        }
                    }
                }
                catch (Exception)
                {
                    //no messages
                }
            }

            bool watchedTopicsUpdated = false;

            foreach (var watchedTopic in ResourceLocator.HandyDataStorage.WatchedTopics.StoredItems)
            {
                if (!watchedTopic.OnCooldown)
                {
                    var count = await new ForumTopicMessageCountQuery(watchedTopic.Id).GetMessageCount(true);
                    if (count == null)
                    {
                        continue;
                    }

                    if (count > watchedTopic.LastCheckedReplyCount)
                    {
                        var notif = new MalNotification(watchedTopic);
                        var diff  = count - watchedTopic.LastCheckedReplyCount;
                        if (diff == 1)
                        {
                            notif.Content += " There is one new reply.";
                        }
                        else
                        {
                            notif.Content += $" There are {diff} new replies.";
                        }

                        notifications.Add(notif);

                        watchedTopic.OnCooldown            = true;
                        watchedTopic.LastCheckedReplyCount = count.Value;
                        watchedTopicsUpdated = true;
                    }
                }
            }
            if (watchedTopicsUpdated)
            {
                ResourceLocator.HandyDataStorage.WatchedTopics.SaveData();
            }


            if (!notifications.Any())
            {
                return;
            }

            var dataService = (ResourceLocator.ApplicationDataService as ApplicationDataServiceService);

            dataService.OverridePreferenceManager(context);

            var allTriggeredNotifications = (ResourceLocator.ApplicationDataService[nameof(RoamingDataTypes.ReadNotifications)] ?? string.Empty) as string;
            var triggeredNotifications    = allTriggeredNotifications?.Split(';').ToList() ?? new List <string>();

            Log.Debug("MALClient",
                      $"Checking notifications: trig: {triggeredNotifications.Count} fetched: {notifications.Count}");
            //trigger new notifications
            foreach (var notification in notifications)
            {
                if (triggeredNotifications.Contains(notification.Id))
                {
                    continue;
                }

                triggeredNotifications.Add(notification.Id);
                ScheduleToast(context, notification);
            }

            //remove old triggered entries
            var presentNotifications = new List <string>();

            foreach (var triggeredNotification in triggeredNotifications)
            {
                if (notifications.Any(notif => notif.Id == triggeredNotification))
                {
                    presentNotifications.Add(triggeredNotification);
                }
            }

            ResourceLocator.ApplicationDataService[nameof(RoamingDataTypes.ReadNotifications)] = string.Join(";",
                                                                                                             presentNotifications);

            dataService.ResetPreferenceManagerOverride();
        }
        protected override async void OnHandleIntent(Intent intent)
        {
            AppWidgetManager manager = AppWidgetManager.GetInstance(this);

            int[] allWidgetIds = intent
                                 .GetIntArrayExtra(AppWidgetManager.ExtraAppwidgetIds);
            var layoutId = intent.GetIntExtra("ResourceId", Resource.Layout.CalendarWidgetLight);
            var views    = new List <Tuple <RemoteViews, int> >();

            try
            {
                ResourceLocator.RegisterBase();
                ResourceLocator.RegisterAppDataServiceAdapter(new ApplicationDataServiceService());
                ResourceLocator.RegisterPasswordVaultAdapter(new PasswordVaultProvider());
                ResourceLocator.RegisterMessageDialogAdapter(new MessageDialogProvider());
                ResourceLocator.RegisterDataCacheAdapter(new Adapters.DataCache(null));
                Credentials.Init();
            }
            catch (Exception e)
            {
            }
            bool running = ResourceLocator.AnimeLibraryDataStorage.AllLoadedAuthAnimeItems?.Any() ?? false;

            foreach (var widgetId in allWidgetIds)
            {
                var view = new RemoteViews(PackageName, layoutId);
                views.Add(new Tuple <RemoteViews, int>(view, widgetId));

                manager.UpdateAppWidget(widgetId, view);
            }

            CalendarPivotPage shows = null;

            if (Credentials.Authenticated)
            {
                if (!running)
                {
                    ViewModelLocator.AnimeList.ListSource = Credentials.UserName;
                    await ViewModelLocator.AnimeList.FetchData(true, AnimeListWorkModes.Anime);
                }

                await ViewModelLocator.CalendarPage.Init(true);

                shows =
                    ViewModelLocator.CalendarPage.CalendarData.FirstOrDefault(
                        page => page.DayOfWeek == DateTime.Now.DayOfWeek);
            }

            if (shows != null && shows.Items.Any())
            {
                foreach (var view in views)
                {
                    view.Item1.SetViewVisibility(Resource.Id.LoadingSpinner, ViewStates.Gone);
                    view.Item1.SetViewVisibility(Resource.Id.EmptyNotice, ViewStates.Gone);
                    view.Item1.SetViewVisibility(Resource.Id.GridView, ViewStates.Visible);
                    view.Item1.SetRemoteAdapter(Resource.Id.GridView, new Intent(ApplicationContext, typeof(CalendarWidgetRemoteViewsService)));

                    var intentTemplate = new Intent(ApplicationContext, typeof(MainActivity));
                    view.Item1.SetPendingIntentTemplate(Resource.Id.GridView, PendingIntent.GetActivity(ApplicationContext, 0, intentTemplate, 0));

                    manager.UpdateAppWidget(view.Item2, view.Item1);
                }
            }
            else
            {
                foreach (var view in views)
                {
                    view.Item1.SetViewVisibility(Resource.Id.LoadingSpinner, ViewStates.Gone);
                    view.Item1.SetViewVisibility(Resource.Id.EmptyNotice, ViewStates.Visible);
                    view.Item1.SetViewVisibility(Resource.Id.GridView, ViewStates.Gone);
                    manager.UpdateAppWidget(view.Item2, view.Item1);
                }
            }
        }
        protected override async void OnHandleIntent(Intent intent)
        {
            var manager = AppWidgetManager.GetInstance(this);

            int[] allWidgetIds = intent
                                 .GetIntArrayExtra(AppWidgetManager.ExtraAppwidgetIds);
            var layoutId = intent.GetIntExtra("ResourceId", Resource.Layout.CalendarWidgetLight);

            _views = new List <Tuple <RemoteViews, int> >();

            try
            {
                ResourceLocator.RegisterBase();
                ResourceLocator.RegisterAppDataServiceAdapter(new ApplicationDataServiceService());
                ResourceLocator.RegisterPasswordVaultAdapter(new PasswordVaultProvider());
                ResourceLocator.RegisterMessageDialogAdapter(new MessageDialogProvider());
                ResourceLocator.RegisterDataCacheAdapter(new Adapters.DataCache(null));

                Credentials.Init();
            }
            catch (Exception e)
            {
            }
            bool running = ResourceLocator.AnimeLibraryDataStorage.AllLoadedAuthAnimeItems?.Any() ?? false;

            foreach (var widgetId in allWidgetIds)
            {
                var view = new RemoteViews(PackageName, layoutId);
                _views.Add(new Tuple <RemoteViews, int>(view, widgetId));

                view.SetViewVisibility(Resource.Id.LoadingSpinner, ViewStates.Visible);
                view.SetViewVisibility(Resource.Id.EmptyNotice, ViewStates.Gone);
                //view.SetViewVisibility(Resource.Id.RefreshButton, ViewStates.Gone);
                view.SetViewVisibility(Resource.Id.GridView, ViewStates.Gone);

                manager.UpdateAppWidget(widgetId, view);
            }

            CalendarPivotPage shows = null;

            try
            {
                if (Credentials.Authenticated)
                {
                    if (!running)
                    {
                        await ResourceLocator.AiringInfoProvider.Init(false);

                        ViewModelLocator.AnimeList.ListSource = Credentials.UserName;
                        await ViewModelLocator.AnimeList.FetchData(true, AnimeListWorkModes.Anime);
                    }
                    if (ResourceLocator.AiringInfoProvider.InitializationSuccess && (ResourceLocator.AnimeLibraryDataStorage.AllLoadedAuthAnimeItems?.Any() ?? false))
                    {
                        await ViewModelLocator.CalendarPage.Init(true);

                        shows =
                            ViewModelLocator.CalendarPage.CalendarData.FirstOrDefault(
                                page => page.DayOfWeek == DateTime.Now.DayOfWeek);
                    }
                }
            }
            catch (Exception e)
            {
                //we have failed very very badly
            }

            await Task.Delay(1000); // give visual feedback


            if (shows != null && shows.Items.Any())
            {
                foreach (var view in _views)
                {
                    view.Item1.SetViewVisibility(Resource.Id.LoadingSpinner, ViewStates.Gone);
                    view.Item1.SetViewVisibility(Resource.Id.EmptyNotice, ViewStates.Gone);
                    view.Item1.SetViewVisibility(Resource.Id.GridView, ViewStates.Visible);
                    view.Item1.SetRemoteAdapter(Resource.Id.GridView, new Intent(ApplicationContext, typeof(CalendarWidgetRemoteViewsService)));

                    var intentTemplate = new Intent(ApplicationContext, typeof(MainActivity));
                    view.Item1.SetPendingIntentTemplate(Resource.Id.GridView, PendingIntent.GetActivity(ApplicationContext, 0, intentTemplate, 0));

                    var refreshIntent = new Intent(ApplicationContext, typeof(CalendarWidgetUpdateService));
                    refreshIntent.PutExtra(AppWidgetManager.ExtraAppwidgetIds, new[] { view.Item2 });
                    refreshIntent.PutExtra("ResourceId", layoutId);
                    view.Item1.SetOnClickPendingIntent(Resource.Id.RefreshButton, PendingIntent.GetService(ApplicationContext, 0, refreshIntent, 0));

                    var preferences = PreferenceManager.GetDefaultSharedPreferences(ApplicationContext);
                    var ids         = preferences.GetStringSet("lastWidgetItems", new List <string>()).Select(int.Parse).ToList();
                    if (!ids.OrderBy(i => i).SequenceEqual(shows.Items.Select(model => model.Id).OrderBy(i => i)))
                    {
                        manager.NotifyAppWidgetViewDataChanged(view.Item2, Resource.Id.GridView);

                        var edit = preferences.Edit();
                        edit.PutStringSet("lastWidgetItems", shows.Items.Select(model => model.Id.ToString()).ToList());
                        edit.Commit();
                    }



                    manager.UpdateAppWidget(view.Item2, view.Item1);
                }
            }
            else
            {
                foreach (var view in _views)
                {
                    view.Item1.SetViewVisibility(Resource.Id.LoadingSpinner, ViewStates.Gone);
                    view.Item1.SetViewVisibility(Resource.Id.EmptyNotice, ViewStates.Visible);
                    view.Item1.SetViewVisibility(Resource.Id.GridView, ViewStates.Gone);


                    var refreshIntent = new Intent(ApplicationContext, typeof(CalendarWidgetUpdateService));
                    refreshIntent.PutExtra(AppWidgetManager.ExtraAppwidgetIds, new[] { view.Item2 });
                    refreshIntent.PutExtra("ResourceId", layoutId);
                    view.Item1.SetOnClickPendingIntent(Resource.Id.RefreshButton, PendingIntent.GetService(ApplicationContext, 0, refreshIntent, 0));


                    manager.UpdateAppWidget(view.Item2, view.Item1);
                }
            }

            await Task.Delay(6000); //let the widget update in peace...
        }