Пример #1
0
        public async Task <ActionResult> UpdateApiFieldsAsync([FromBody] ApiUpdate api)
        {
            var updateApiFields = new UpdateApiFields()
            {
                Name              = api.Name,
                NewBusinessOwner  = api.NewBusinessOwner,
                NewDescription    = api.NewDescription,
                NewName           = api.NewName,
                NewTechnicalOwner = api.NewTechnicalOwner,
                NewTitle          = api.NewTitle,
                NewTags           = api.NewTags
            };

            var response = await _mediator.Send(updateApiFields);

            if (response.Result == UpdateResult.Updated)
            {
                return(Ok());
            }
            else if (response.Result == UpdateResult.NotFound)
            {
                return(NotFound());
            }
            else if (response.Result == UpdateResult.NotUpdated)
            {
                return(StatusCode(500)); // TODO return meaningful result to client
            }
            else
            {
                return(StatusCode(500)); // TODO return meaningful result to client
            }
        }
Пример #2
0
        //Add offline sync item
        //Types: Read, Unread, Star, Unstar
        public static async Task AddOfflineSync(String AddId, String AddType)
        {
            try
            {
                //Wait for busy database
                await ApiUpdate.WaitForBusyDatabase();

                //Add sync item
                TableOffline SyncItem = new TableOffline();
                if (AddType == "Star")
                {
                    SyncItem.item_star_status = AddId;
                }
                else if (AddType == "Unstar")
                {
                    SyncItem.item_unstar_status = AddId;
                }
                else if (AddType == "Read")
                {
                    SyncItem.item_read_status = AddId;
                }
                else if (AddType == "Unread")
                {
                    SyncItem.item_unread_status = AddId;
                }
                await SQLConnection.InsertAsync(SyncItem);

                //Delete opposite
                await DeleteOppositeOfflineSync(AddId, AddType);
            }
            catch { }
        }
Пример #3
0
        static public async Task <bool> ItemsRemoveOld(bool Silent, bool EnableUI)
        {
            try
            {
                if (!Silent)
                {
                    await EventProgressDisableUI("Checking older items...", true);
                }
                Debug.WriteLine("Checking older items...");

                //Wait for busy database
                await ApiUpdate.WaitForBusyDatabase();

                //Date time calculations
                DateTime      RemoveItemsRange = DateTime.UtcNow.AddDays(-Convert.ToDouble(AppVariables.ApplicationSettings["RemoveItemsRange"]));
                List <String> DeleteItems      = (await SQLConnection.Table <TableItems>().Where(x => x.item_star_status == false && x.item_datetime < RemoveItemsRange).ToListAsync()).Select(x => x.item_id).ToList();

                Int32 DeleteCount = DeleteItems.Count();
                if (DeleteCount > 0)
                {
                    if (!Silent)
                    {
                        await EventProgressDisableUI("Removing " + DeleteCount + " older items...", true);
                    }
                    Debug.WriteLine("Removing " + DeleteCount + " older items...");

                    string DeleteString = String.Empty;
                    foreach (String DeleteItem in DeleteItems)
                    {
                        DeleteString += "'" + DeleteItem + "',";
                    }
                    DeleteString = AVFunctions.StringRemoveEnd(DeleteString, ",");

                    Int32 DeletedItems = await SQLConnection.ExecuteAsync("DELETE FROM TableItems WHERE item_id IN (" + DeleteString + ")");

                    Debug.WriteLine("Removed " + DeletedItems + " older items...");
                }

                if (EnableUI)
                {
                    await EventProgressEnableUI();
                }
                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to delete older items: " + ex.Message);
                await EventProgressEnableUI();

                return(false);
            }
        }
Пример #4
0
        public async Task <IApi> Save()
        {
            var data = new ApiUpdate
            {
                Id               = Id,
                Name             = Name,
                PreserveHost     = PreserveHost,
                RequestHost      = RequestHost,
                RequestPath      = RequestPath,
                StripRequestPath = StripRequestPath,
                UpstreamUrl      = UpstreamUrl,
                CreatedAt        = CreatedAt
            };
            var response = await _requestFactory.Parent.Put <Api>(data);

            response.Configure(_requestFactory);
            return(response);
        }
Пример #5
0
        static public async Task <bool> DeleteFeed(string FeedId)
        {
            try
            {
                string[][]          RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };
                HttpStringContent   PostContent   = new HttpStringContent("ac=unsubscribe&s=feed/" + FeedId, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
                HttpResponseMessage PostHttp      = await AVDownloader.SendPostRequestAsync(7500, "News Scroll", RequestHeader, new Uri(ApiConnectionUrl + "subscription/edit"), PostContent);

                if (PostHttp != null && (PostHttp.Content.ToString() == "OK" || PostHttp.Content.ToString().Contains("<error>Not found</error>")))
                {
                    //Wait for busy database
                    await ApiUpdate.WaitForBusyDatabase();

                    //Clear feed from database
                    await SQLConnection.ExecuteAsync("DELETE FROM TableFeeds WHERE feed_id = ('" + FeedId + "')");

                    //Clear items from database
                    await SQLConnection.ExecuteAsync("DELETE FROM TableItems WHERE item_feed_id = ('" + FeedId + "') AND item_star_status = ('0')");

                    //Delete the feed icon
                    IStorageItem LocalFile = await ApplicationData.Current.LocalFolder.TryGetItemAsync(FeedId + ".png");

                    if (LocalFile != null)
                    {
                        try { await LocalFile.DeleteAsync(StorageDeleteOption.PermanentDelete); } catch { }
                    }

                    Debug.WriteLine("Deleted the feed and items off: " + FeedId);
                    return(true);
                }
                else
                {
                    Debug.WriteLine("Failed to delete feed: " + FeedId + " / server error.");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to delete feed: " + FeedId + " / " + ex.Message);
                return(false);
            }
        }
Пример #6
0
        //Database Create
        public static async Task DatabaseCreate()
        {
            try
            {
                //Wait for busy database
                await ApiUpdate.WaitForBusyDatabase();

                await SQLConnection.CreateTableAsync <TableFeeds>();

                await SQLConnection.CreateTableAsync <TableOffline>();

                await SQLConnection.CreateTableAsync <TableItems>();

                await SQLConnection.CreateTableAsync <TableSearchHistory>();

                Debug.WriteLine("Created the database tables.");
            }
            catch
            {
                Debug.WriteLine("Failed creating the database tables.");
            }
        }
Пример #7
0
        //Add offline sync items
        //Types: Read, Unread, Star, Unstar
        public static async Task AddOfflineSync(List <String> AddIds, String AddType)
        {
            try
            {
                //Wait for busy database
                await ApiUpdate.WaitForBusyDatabase();

                //Sync variables
                List <TableOffline> AddSyncItems = new List <TableOffline>();
                foreach (String AddId in AddIds)
                {
                    //Add sync item
                    TableOffline SyncItem = new TableOffline();
                    if (AddType == "Star")
                    {
                        SyncItem.item_star_status = AddId;
                    }
                    else if (AddType == "Unstar")
                    {
                        SyncItem.item_unstar_status = AddId;
                    }
                    else if (AddType == "Read")
                    {
                        SyncItem.item_read_status = AddId;
                    }
                    else if (AddType == "Unread")
                    {
                        SyncItem.item_unread_status = AddId;
                    }
                    AddSyncItems.Add(SyncItem);

                    //Delete opposite
                    await DeleteOppositeOfflineSync(AddId, AddType);
                }

                await SQLConnection.InsertAllAsync(AddSyncItems);
            }
            catch { }
        }
Пример #8
0
        public async Task <IApi> Save()
        {
            var data = new ApiUpdate
            {
                Id                     = Id,
                Name                   = Name,
                PreserveHost           = PreserveHost,
                Hosts                  = Hosts,
                HttpIfTerminated       = HttpIfTerminated,
                HttpsOnly              = HttpsOnly,
                Methods                = Methods,
                Retries                = Retries,
                StripUri               = StripUri,
                UpstreamConnectTimeout = UpstreamConnectTimeout,
                UpstreamSendTimeout    = UpstreamSendTimeout,
                Uris                   = Uris,
                UpstreamUrl            = UpstreamUrl,
                CreatedAt              = CreatedAt
            };
            var response = await _requestFactory.Parent.Put <Api>(data);

            response.Configure(_requestFactory);
            return(response);
        }
Пример #9
0
        private static async Task <bool> MarkReadSingle(ObservableCollection <Items> UpdateList, Items ListItem, string ActionType, bool Silent)
        {
            try
            {
                bool   MarkStatus = false;
                string ItemId     = ListItem.item_id;

                //Check if internet is available
                if (!NetworkInterface.GetIsNetworkAvailable() || ApiMessageError.StartsWith("(Off)"))
                {
                    if (!Silent)
                    {
                        await EventProgressDisableUI("Off marking item as " + ActionType.ToLower() + "...", true);
                    }
                    Debug.WriteLine("Off marking item as " + ActionType.ToLower() + "...");

                    await AddOfflineSync(ItemId, ActionType);

                    MarkStatus = true;
                }
                else
                {
                    if (!Silent)
                    {
                        await EventProgressDisableUI("Marking item as " + ActionType.ToLower() + "...", true);
                    }
                    Debug.WriteLine("Marking item as " + ActionType.ToLower() + "...");

                    string[][] RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };

                    HttpStringContent PostContent;
                    if (ActionType == "Read")
                    {
                        PostContent = new HttpStringContent("i=" + ItemId + "&a=user/-/state/com.google/read", Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
                    }
                    else
                    {
                        PostContent = new HttpStringContent("i=" + ItemId + "&r=user/-/state/com.google/read", Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
                    }

                    HttpResponseMessage PostHttp = await AVDownloader.SendPostRequestAsync(7500, "News Scroll", RequestHeader, new Uri(ApiConnectionUrl + "edit-tag"), PostContent);

                    if (PostHttp != null && (PostHttp.Content.ToString() == "OK" || PostHttp.Content.ToString().Contains("<error>Not found</error>")))
                    {
                        MarkStatus = true;
                    }
                }

                if (MarkStatus)
                {
                    //Wait for busy database
                    await ApiUpdate.WaitForBusyDatabase();

                    //Mark item in database and list
                    TableItems TableEditItems = await SQLConnection.Table <TableItems>().Where(x => x.item_id == ItemId).FirstOrDefaultAsync();

                    if (TableEditItems != null)
                    {
                        if (ActionType == "Read")
                        {
                            TableEditItems.item_read_status = true;
                            ListItem.item_read_status       = Visibility.Visible; //Updates itemviewer
                            if (App.vApplicationFrame.SourcePageType.ToString().EndsWith("NewsPage") && NewsPage.vCurrentLoadingFeedFolder.feed_id != "1" && (bool)AppVariables.ApplicationSettings["HideReadMarkedItem"])
                            {
                                UpdateList.Remove(ListItem);
                            }
                        }
                        else
                        {
                            TableEditItems.item_read_status = false;
                            ListItem.item_read_status       = Visibility.Collapsed; //Updates itemviewer
                            if (App.vApplicationFrame.SourcePageType.ToString().EndsWith("NewsPage") && NewsPage.vCurrentLoadingFeedFolder.feed_id == "1" && (bool)AppVariables.ApplicationSettings["HideReadMarkedItem"])
                            {
                                UpdateList.Remove(ListItem);
                            }
                        }
                    }

                    //Update the items in database
                    await SQLConnection.UpdateAsync(TableEditItems);
                }
                else
                {
                    await AVMessageBox.Popup("Failed to mark item " + ActionType.ToLower(), "Please check your internet connection and try again.", "Ok", "", "", "", "", false);
                    await EventProgressEnableUI();
                }

                return(MarkStatus);
            }
            catch
            {
                Debug.WriteLine("Failed to un/read item.");
                return(false);
            }
        }
Пример #10
0
        //Mark all items as read
        public static async Task <bool> MarkReadAll(ObservableCollection <Items> UpdateList, bool Confirm)
        {
            try
            {
                //Check if user is logged in
                if (!CheckLogin())
                {
                    await AVMessageBox.Popup("Not logged in", "Marking all items read can only be done when you are logged in.", "Ok", "", "", "", "", false);

                    return(false);
                }

                if (Confirm)
                {
                    Int32 MsgBoxResult = await AVMessageBox.Popup("Mark all items read", "Do you want to mark all items for every feed as read?", "Mark all items read", "", "", "", "", true);

                    if (MsgBoxResult == 0)
                    {
                        return(false);
                    }
                }

                bool MarkStatus = false;

                //Check if internet is available
                if (!NetworkInterface.GetIsNetworkAvailable() || ApiMessageError.StartsWith("(Off)"))
                {
                    await EventProgressDisableUI("Off marking all items as read...", true);

                    Debug.WriteLine("Off marking all items as read...");

                    //Wait for busy database
                    await ApiUpdate.WaitForBusyDatabase();

                    List <String> UnreadItemList = (await SQLConnection.Table <TableItems>().Where(x => !x.item_read_status).ToListAsync()).Select(x => x.item_id).ToList();
                    await AddOfflineSync(UnreadItemList, "Read");

                    MarkStatus = true;
                }
                else
                {
                    await EventProgressDisableUI("Marking all items as read...", true);

                    Debug.WriteLine("Marking all items as read...");

                    //Date time variables
                    Int64 UnixTimeTicks = 0;
                    if (AppVariables.ApplicationSettings["LastItemsUpdate"].ToString() != "Never")
                    {
                        UnixTimeTicks = (Convert.ToDateTime(AppVariables.ApplicationSettings["LastItemsUpdate"], AppVariables.CultureInfoEnglish).Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks) / 10; //Nanoseconds
                    }

                    //Mark all items as read on api server
                    string[][]        RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };
                    HttpStringContent PostContent   = new HttpStringContent("s=user/-/state/com.google/reading-list&ts=" + UnixTimeTicks, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");

                    HttpResponseMessage PostHttp = await AVDownloader.SendPostRequestAsync(7500, "News Scroll", RequestHeader, new Uri(ApiConnectionUrl + "mark-all-as-read"), PostContent);

                    if (PostHttp != null && (PostHttp.Content.ToString() == "OK" || PostHttp.Content.ToString().Contains("<error>Not found</error>")))
                    {
                        MarkStatus = true;
                    }
                }

                if (MarkStatus)
                {
                    Debug.WriteLine("Marked all items as read on the server or offline sync list.");

                    //Wait for busy database
                    await ApiUpdate.WaitForBusyDatabase();

                    //Update items in database
                    await SQLConnection.ExecuteAsync("UPDATE TableItems SET item_read_status = ('1') WHERE item_read_status = ('0')");

                    //Update current items list
                    List <Items> ListItems = UpdateList.Where(x => x.item_read_status == Visibility.Collapsed).ToList();
                    foreach (Items NewsItem in ListItems)
                    {
                        if ((bool)AppVariables.ApplicationSettings["HideReadMarkedItem"])
                        {
                            UpdateList.Remove(NewsItem);
                        }
                        else
                        {
                            NewsItem.item_read_status = Visibility.Visible;
                        }
                    }

                    await EventProgressEnableUI();
                }
                else
                {
                    await AVMessageBox.Popup("Failed to mark all items read", "Please check your internet connection and try again.", "Ok", "", "", "", "", false);
                    await EventProgressEnableUI();
                }

                return(MarkStatus);
            }
            catch
            {
                await AVMessageBox.Popup("Failed to mark all items read", "Please check your internet connection and try again.", "Ok", "", "", "", "", false);
                await EventProgressEnableUI();

                return(false);
            }
        }
Пример #11
0
        //Mark items till as read
        public static async Task <bool> MarkReadTill(ObservableCollection <Items> UpdateList, Items EndItem, bool Confirm, bool Silent, bool EnableUI)
        {
            try
            {
                if (Confirm)
                {
                    Int32 MsgBoxResult = await AVMessageBox.Popup("Mark items read till item", "Do you want to mark all items for the selected feed till this item as read?", "Mark read till item", "", "", "", "", true);

                    if (MsgBoxResult == 0)
                    {
                        return(false);
                    }
                }

                bool   MarkStatus = false;
                string EndItemId  = EndItem.item_id;

                //Check the selected items
                List <Items> TableEditItems = UpdateList.Where(x => x.item_id == EndItemId || x.item_read_status == Visibility.Collapsed).ToList();

                //Check if internet is available
                if (!NetworkInterface.GetIsNetworkAvailable() || ApiMessageError.StartsWith("(Off)"))
                {
                    if (!Silent)
                    {
                        await EventProgressDisableUI("Off marking read till item...", true);
                    }
                    Debug.WriteLine("Off marking read till item...");

                    //Add items to string list
                    List <String> ReadItemIds = new List <String>();
                    foreach (Items NewsItem in TableEditItems)
                    {
                        string NewsItemId = NewsItem.item_id;
                        ReadItemIds.Add(NewsItemId);

                        //Check if the end item has been reached
                        if (EndItemId == NewsItemId)
                        {
                            Debug.WriteLine("Added all news items to the string list.");
                            break;
                        }
                    }

                    await AddOfflineSync(ReadItemIds, "Read");

                    MarkStatus = true;
                }
                else
                {
                    if (!Silent)
                    {
                        await EventProgressDisableUI("Marking read till item...", true);
                    }
                    Debug.WriteLine("Marking read till item...");

                    //Add items to post string
                    string PostStringItemIds = String.Empty;
                    foreach (Items NewsItem in TableEditItems)
                    {
                        string NewsItemId = NewsItem.item_id;
                        PostStringItemIds += "&i=" + NewsItemId;

                        //Check if the end item has been reached
                        if (EndItemId == NewsItemId)
                        {
                            Debug.WriteLine("Added all news items to the post string.");
                            break;
                        }
                    }

                    string[][]        RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };
                    HttpStringContent PostContent   = new HttpStringContent("a=user/-/state/com.google/read" + PostStringItemIds, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");

                    HttpResponseMessage PostHttp = await AVDownloader.SendPostRequestAsync(10000, "News Scroll", RequestHeader, new Uri(ApiConnectionUrl + "edit-tag"), PostContent);

                    if (PostHttp != null && (PostHttp.Content.ToString() == "OK" || PostHttp.Content.ToString().Contains("<error>Not found</error>")))
                    {
                        MarkStatus = true;
                    }
                }

                if (MarkStatus)
                {
                    Debug.WriteLine("Marked items till this item as read on the server or offline sync list.");

                    //Add items to post string
                    string SqlStringItemIds = String.Empty;
                    foreach (Items NewsItem in TableEditItems)
                    {
                        string NewsItemId = NewsItem.item_id;
                        SqlStringItemIds += "'" + NewsItemId + "',";

                        //Check if the end item has been reached
                        if (EndItemId == NewsItemId)
                        {
                            Debug.WriteLine("Added all news items to the sql string.");
                            break;
                        }
                    }

                    //Wait for busy database
                    await ApiUpdate.WaitForBusyDatabase();

                    SqlStringItemIds = AVFunctions.StringRemoveEnd(SqlStringItemIds, ",");
                    await SQLConnection.ExecuteAsync("UPDATE TableItems SET item_read_status = ('1') WHERE item_id IN (" + SqlStringItemIds + ") AND item_read_status = ('0')");

                    //Update current items list
                    foreach (Items NewsItem in UpdateList.ToList())
                    {
                        //Mark the item as read or remove it from list
                        if ((bool)AppVariables.ApplicationSettings["HideReadMarkedItem"])
                        {
                            UpdateList.Remove(NewsItem);
                        }
                        else
                        {
                            NewsItem.item_read_status = Visibility.Visible;
                        }

                        //Check if the end item has been reached
                        if (EndItemId == NewsItem.item_id)
                        {
                            Debug.WriteLine("Marked items till this item as read in the list and database.");
                            break;
                        }
                    }

                    if (EnableUI)
                    {
                        await EventProgressEnableUI();
                    }
                }
                else
                {
                    await AVMessageBox.Popup("Failed to mark items read", "Please check your internet connection and try again.", "Ok", "", "", "", "", false);
                    await EventProgressEnableUI();
                }

                return(MarkStatus);
            }
            catch
            {
                await AVMessageBox.Popup("Failed to mark items read", "Please check your internet connection and try again.", "Ok", "", "", "", "", false);
                await EventProgressEnableUI();

                return(false);
            }
        }
Пример #12
0
        static public async Task <bool> ItemsRead(ObservableCollection <Items> UpdateList, bool Silent, bool EnableUI)
        {
            try
            {
                if (!Silent)
                {
                    await EventProgressDisableUI("Downloading read status...", true);
                }
                Debug.WriteLine("Downloading read status...");

                //Wait for busy database
                await ApiUpdate.WaitForBusyDatabase();

                //Get all stored items from the database
                List <TableItems> CurrentItems = await SQLConnection.Table <TableItems>().ToListAsync();

                if (CurrentItems.Any())
                {
                    //Get last stored item date minus starred items
                    TableItems LastStoredItem = CurrentItems.Where(x => x.item_star_status == false).OrderByDescending(x => x.item_datetime).LastOrDefault();
                    if (LastStoredItem != null)
                    {
                        //Date time calculations
                        DateTime RemoveItemsRange = LastStoredItem.item_datetime.AddHours(-1);
                        //Debug.WriteLine("Downloading read items till: " + LastStoredItem.item_title + "/" + RemoveItemsRange);
                        Int64 UnixTimeTicks = (RemoveItemsRange.Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks) / 10000000; //Second

                        string[][] RequestHeader  = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };
                        Uri        DownloadUri    = new Uri(ApiConnectionUrl + "stream/items/ids?output=json&s=user/-/state/com.google/read&n=" + AppVariables.ItemsMaximumLoad + "&ot=" + UnixTimeTicks);
                        string     DownloadString = await AVDownloader.DownloadStringAsync(10000, "News Scroll", RequestHeader, DownloadUri);

                        if (!String.IsNullOrWhiteSpace(DownloadString))
                        {
                            JObject WebJObject = JObject.Parse(DownloadString);
                            if (WebJObject["itemRefs"] != null && WebJObject["itemRefs"].HasValues)
                            {
                                if (!Silent)
                                {
                                    await EventProgressDisableUI("Updating " + WebJObject["itemRefs"].Count() + " read status...", true);
                                }
                                Debug.WriteLine("Updating " + WebJObject["itemRefs"].Count() + " read status...");

                                //Check and set the received read item ids
                                string        ReadUpdateString = String.Empty;
                                List <String> ReadItemsList    = new List <String>();
                                foreach (JToken JTokenRoot in WebJObject["itemRefs"])
                                {
                                    string FoundItemId = JTokenRoot["id"].ToString().Replace(" ", String.Empty).Replace("tag:google.com,2005:reader/item/", String.Empty);
                                    ReadUpdateString += "'" + FoundItemId + "',";
                                    ReadItemsList.Add(FoundItemId);
                                }

                                //Update the read status in database
                                if (ReadItemsList.Any())
                                {
                                    ReadUpdateString = AVFunctions.StringRemoveEnd(ReadUpdateString, ",");
                                    Int32 UpdatedItems = await SQLConnection.ExecuteAsync("UPDATE TableItems SET item_read_status = ('1') WHERE item_id IN (" + ReadUpdateString + ") AND item_read_status = ('0')");

                                    Debug.WriteLine("Updated read items: " + UpdatedItems);
                                }

                                //Update the read status in list
                                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                {
                                    try
                                    {
                                        List <Items> ReadItemsIDList = UpdateList.Where(x => x.item_read_status == Visibility.Collapsed && ReadItemsList.Any(y => y == x.item_id)).ToList();
                                        foreach (Items ReadItem in ReadItemsIDList)
                                        {
                                            ReadItem.item_read_status = Visibility.Visible;
                                        }
                                    }
                                    catch { }
                                });

                                //Update the unread status in database
                                string        UnreadUpdateString = String.Empty;
                                List <String> UnreadItemsList    = (await SQLConnection.Table <TableItems>().ToListAsync()).Where(x => x.item_read_status == true && x.item_datetime > RemoveItemsRange).Select(x => x.item_id).Except(ReadItemsList).ToList();
                                foreach (String UnreadItem in UnreadItemsList)
                                {
                                    UnreadUpdateString += "'" + UnreadItem + "',";
                                }
                                if (UnreadItemsList.Any())
                                {
                                    UnreadUpdateString = AVFunctions.StringRemoveEnd(UnreadUpdateString, ",");
                                    Int32 UpdatedItems = await SQLConnection.ExecuteAsync("UPDATE TableItems SET item_read_status = ('0') WHERE item_id IN (" + UnreadUpdateString + ") AND item_read_status = ('1')");

                                    Debug.WriteLine("Updated unread items: " + UpdatedItems);
                                }

                                //Update the unread status in list
                                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                {
                                    try
                                    {
                                        List <Items> UnreadItemsIDList = UpdateList.Where(x => x.item_read_status == Visibility.Visible && UnreadItemsList.Any(y => y == x.item_id)).ToList();
                                        foreach (Items UnreadItem in UnreadItemsIDList)
                                        {
                                            UnreadItem.item_read_status = Visibility.Collapsed;
                                        }
                                    }
                                    catch { }
                                });
                            }
                        }
                    }
                }

                if (EnableUI)
                {
                    await EventProgressEnableUI();
                }
                return(true);
            }
            catch
            {
                await EventProgressEnableUI();

                return(false);
            }
        }
Пример #13
0
        static public async Task <bool> ItemsStarred(bool Preload, bool Silent, bool EnableUI)
        {
            try
            {
                if (!Silent)
                {
                    await EventProgressDisableUI("Downloading starred status...", true);
                }
                Debug.WriteLine("Downloading starred status...");

                string[][] RequestHeader  = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };
                string     DownloadString = await AVDownloader.DownloadStringAsync(15000, "News Scroll", RequestHeader, new Uri(ApiConnectionUrl + "stream/items/ids?output=json&s=user/-/state/com.google/starred&n=" + AppVariables.StarredMaximumLoad));

                if (!String.IsNullOrWhiteSpace(DownloadString))
                {
                    JObject WebJObject = JObject.Parse(DownloadString);
                    if (WebJObject["itemRefs"] != null && WebJObject["itemRefs"].HasValues)
                    {
                        if (!Silent)
                        {
                            await EventProgressDisableUI("Updating " + WebJObject["itemRefs"].Count() + " star status...", true);
                        }
                        Debug.WriteLine("Updating " + WebJObject["itemRefs"].Count() + " star status...");

                        //Wait for busy database
                        await ApiUpdate.WaitForBusyDatabase();

                        //Check and set the received star item ids
                        List <TableItems> TableEditItems = await SQLConnection.Table <TableItems>().ToListAsync();

                        string        DownloadItemIds = String.Empty;
                        List <String> StarItemsID     = new List <String>();
                        foreach (JToken JTokenRoot in WebJObject["itemRefs"])
                        {
                            string FoundItemId = JTokenRoot["id"].ToString().Replace(" ", String.Empty).Replace("tag:google.com,2005:reader/item/", String.Empty);
                            StarItemsID.Add(FoundItemId);

                            //Check if star item exists
                            if (!TableEditItems.Any(x => x.item_id == FoundItemId))
                            {
                                DownloadItemIds += "&i=" + FoundItemId;
                            }
                        }

                        //Update the star status in database
                        string StarUpdateString = String.Empty;
                        foreach (String StarItem in StarItemsID)
                        {
                            StarUpdateString += "'" + StarItem + "',";
                        }
                        StarUpdateString = AVFunctions.StringRemoveEnd(StarUpdateString, ",");
                        if (StarItemsID.Any())
                        {
                            Int32 UpdatedItems = await SQLConnection.ExecuteAsync("UPDATE TableItems SET item_star_status = ('1'), item_read_status = ('1') WHERE item_id IN (" + StarUpdateString + ") AND item_star_status = ('0')");

                            Debug.WriteLine("Updated star items: " + UpdatedItems);
                        }

                        //Update the unstar status in database
                        List <String> UnstarItemsID      = TableEditItems.Where(x => x.item_star_status == true).Select(x => x.item_id).Except(StarItemsID).ToList();
                        string        UnstarUpdateString = String.Empty;
                        foreach (String UnstarItem in UnstarItemsID)
                        {
                            UnstarUpdateString += "'" + UnstarItem + "',";
                        }
                        UnstarUpdateString = AVFunctions.StringRemoveEnd(UnstarUpdateString, ",");
                        if (UnstarItemsID.Any())
                        {
                            Int32 UpdatedItems = await SQLConnection.ExecuteAsync("UPDATE TableItems SET item_star_status = ('0') WHERE item_id IN (" + UnstarUpdateString + ") AND item_star_status = ('1')");

                            Debug.WriteLine("Updated unstar items: " + UpdatedItems);
                        }

                        //Download all missing starred items
                        if (!String.IsNullOrWhiteSpace(DownloadItemIds))
                        {
                            if (!Silent)
                            {
                                await EventProgressDisableUI("Downloading starred items...", true);
                            }
                            Debug.WriteLine("Downloading starred items...");

                            bool UpdatedItems = await MultiItems(DownloadItemIds, true, true, Silent, EnableUI);

                            if (!UpdatedItems)
                            {
                                await EventProgressEnableUI();

                                return(false);
                            }
                        }
                    }

                    if (EnableUI)
                    {
                        await EventProgressEnableUI();
                    }
                    return(true);
                }
                else
                {
                    await EventProgressEnableUI();

                    return(false);
                }
            }
            catch
            {
                await EventProgressEnableUI();

                return(false);
            }
        }
Пример #14
0
        private static async Task <bool> DownloadToTableItemList(bool Preload, bool IgnoreDate, string DownloadString, bool Silent, bool EnableUI)
        {
            try
            {
                JObject WebJObject = JObject.Parse(DownloadString);
                if (WebJObject["items"] != null && WebJObject["items"].HasValues)
                {
                    Int32 TotalItemsCount = WebJObject["items"].Count();
                    if (!Silent)
                    {
                        await EventProgressDisableUI("Processing " + TotalItemsCount + " items...", true);
                    }
                    Debug.WriteLine("Processing " + TotalItemsCount + " items...");

                    //Check the received item ids
                    Int32 ProcessedItems = 0;
                    Int32 PreloadedItems = AppVariables.ItemsToPreloadBatch;

                    //Wait for busy database
                    await ApiUpdate.WaitForBusyDatabase();

                    List <TableItems> TableUpdatedItems = new List <TableItems>();
                    List <TableItems> TableCurrentItems = await SQLConnection.Table <TableItems>().ToListAsync();

                    //Filter un/ignored feeds
                    List <String> IgnoredFeedList = (await SQLConnection.Table <TableFeeds>().Where(x => x.feed_ignore_status == true).ToListAsync()).Select(x => x.feed_id).ToList();

                    foreach (JToken JTokenRoot in WebJObject["items"]) //.OrderByDescending(obj => (string)obj["crawlTimeMsec"])
                    {
                        string     FoundItemId = JTokenRoot["id"].ToString().Replace(" ", String.Empty).Replace("tag:google.com,2005:reader/item/", String.Empty);
                        TableItems TableResult = TableCurrentItems.Where(x => x.item_id == FoundItemId).FirstOrDefault();
                        if (TableResult == null)
                        {
                            //Debug.WriteLine("Adding item: " + FoundItemId);

                            TableResult = JSonToTableItem(FoundItemId, JTokenRoot, IgnoreDate, AppVariables.LoadStarred);
                            if (TableResult != null)
                            {
                                TableUpdatedItems.Add(TableResult);
                                TableCurrentItems.Add(TableResult);
                            }
                        }
                        else
                        {
                            //Debug.WriteLine("Updating item: " + FoundItemId);

                            //Check item status
                            string Categories = String.Empty;
                            try { Categories = JTokenRoot["categories"].ToString(); } catch { }

                            //Read the item
                            if (Categories.Contains("\"user/-/state/com.google/read\""))
                            {
                                TableResult.item_read_status = true;
                            }
                            else
                            {
                                TableResult.item_read_status = false;
                            }

                            //Star the item
                            if (AppVariables.LoadStarred || Categories.Contains("\"user/-/state/com.google/starred\""))
                            {
                                TableResult.item_star_status = true;
                            }
                            else
                            {
                                TableResult.item_star_status = false;
                            }

                            TableUpdatedItems.Add(TableResult);
                        }

                        //Check if items need to be preloaded
                        if (Preload && TableResult != null && PreloadedItems <= AppVariables.ItemsToPreloadMax)
                        {
                            //Validate the processed item
                            if (ProcessItemLoad.ValidateTableItems(IgnoredFeedList, TableResult))
                            {
                                ProcessedItems++;
                            }

                            //Preload items to the list
                            if (ProcessedItems == PreloadedItems || ProcessedItems == TotalItemsCount)
                            {
                                Debug.WriteLine("Preloading " + AppVariables.ItemsToPreloadBatch + " new items...");
                                await ProcessItemLoad.DatabaseToList(null, TableCurrentItems, AppVariables.CurrentItemsLoaded, AppVariables.ItemsToPreloadBatch, true, false);

                                PreloadedItems += AppVariables.ItemsToPreloadBatch;
                            }
                        }
                    }

                    //Update the items in database
                    if (TableUpdatedItems.Any())
                    {
                        if (!Silent)
                        {
                            await EventProgressDisableUI("Updating " + TableUpdatedItems.Count() + " items...", true);
                        }
                        Debug.WriteLine("Updating " + TableUpdatedItems.Count() + " items...");

                        await SQLConnection.InsertOrReplaceAllAsync(TableUpdatedItems);
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed DownloadToTableItemList: " + ex.Message);
                return(false);
            }
        }
Пример #15
0
        //Sync offline changes
        public static async Task SyncOfflineChanges(bool Silent, bool EnableUI)
        {
            try
            {
                if (!Silent)
                {
                    await EventProgressDisableUI("Syncing offline changes...", true);
                }
                Debug.WriteLine("Syncing offline changes...");

                //Wait for busy database
                await ApiUpdate.WaitForBusyDatabase();

                //Get current offline sync items
                List <TableOffline> OfflineSyncItemList = await SQLConnection.Table <TableOffline>().ToListAsync();

                //Sync read items
                List <String> ReadStringList = OfflineSyncItemList.Where(x => !String.IsNullOrWhiteSpace(x.item_read_status)).Select(x => x.item_read_status).ToList();
                if (ReadStringList.Any())
                {
                    bool Result = await MarkItemReadStringList(ReadStringList, true);

                    //Remove from list when succeeded
                    if (Result)
                    {
                        Int32 DeletedItems = await SQLConnection.ExecuteAsync("DELETE FROM TableOffline WHERE item_read_status");

                        Debug.WriteLine("Removed " + DeletedItems + " Read offline synced items...");
                    }
                    else
                    {
                        Debug.WriteLine("Failed to sync offline read items.");
                    }
                }

                //Sync unread items
                List <String> UnreadStringList = OfflineSyncItemList.Where(x => !String.IsNullOrWhiteSpace(x.item_unread_status)).Select(x => x.item_unread_status).ToList();
                if (UnreadStringList.Any())
                {
                    bool Result = await MarkItemReadStringList(UnreadStringList, false);

                    //Remove from list when succeeded
                    if (Result)
                    {
                        Int32 DeletedItems = await SQLConnection.ExecuteAsync("DELETE FROM TableOffline WHERE item_unread_status");

                        Debug.WriteLine("Removed " + DeletedItems + " Unread offline synced items...");
                    }
                    else
                    {
                        Debug.WriteLine("Failed to sync offline unread items.");
                    }
                }

                //Sync starred items
                List <String> StarStringList = OfflineSyncItemList.Where(x => !String.IsNullOrWhiteSpace(x.item_star_status)).Select(x => x.item_star_status).ToList();
                if (StarStringList.Any())
                {
                    bool Result = await MarkItemStarStringList(StarStringList, true);

                    //Remove from list when succeeded
                    if (Result)
                    {
                        Int32 DeletedItems = await SQLConnection.ExecuteAsync("DELETE FROM TableOffline WHERE item_star_status");

                        Debug.WriteLine("Removed " + DeletedItems + " Star offline synced items...");
                    }
                    else
                    {
                        Debug.WriteLine("Failed to sync offline star items.");
                    }
                }

                //Sync Unstarred items
                List <String> UnstarStringList = OfflineSyncItemList.Where(x => !String.IsNullOrWhiteSpace(x.item_unstar_status)).Select(x => x.item_unstar_status).ToList();
                if (UnstarStringList.Any())
                {
                    bool Result = await MarkItemStarStringList(UnstarStringList, false);

                    //Remove from list when succeeded
                    if (Result)
                    {
                        Int32 DeletedItems = await SQLConnection.ExecuteAsync("DELETE FROM TableOffline WHERE item_unstar_status");

                        Debug.WriteLine("Removed " + DeletedItems + " unstar offline synced items...");
                    }
                    else
                    {
                        Debug.WriteLine("Failed to sync offline unstar items.");
                    }
                }

                if (EnableUI)
                {
                    await EventProgressEnableUI();
                }
            }
            catch { await EventProgressEnableUI(); }
        }
Пример #16
0
        static public async Task <bool> Feeds(bool Silent, bool EnableUI)
        {
            try
            {
                if (!Silent)
                {
                    await EventProgressDisableUI("Downloading latest feeds...", true);
                }
                Debug.WriteLine("Downloading latest feeds...");

                string[][] RequestHeader  = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };
                string     DownloadString = await AVDownloader.DownloadStringAsync(10000, "News Scroll", RequestHeader, new Uri(ApiConnectionUrl + "subscription/list?output=json"));

                JObject WebJObject = JObject.Parse(DownloadString);
                if (WebJObject["subscriptions"] != null && WebJObject["subscriptions"].HasValues)
                {
                    if (!Silent)
                    {
                        await EventProgressDisableUI("Processing " + WebJObject["subscriptions"].Count() + " feeds...", true);
                    }
                    Debug.WriteLine("Processing " + WebJObject["subscriptions"].Count() + " feeds...");

                    List <String> ApiFeedIdList = new List <String>();
                    IReadOnlyList <IStorageItem> LocalFileList = await ApplicationData.Current.LocalFolder.GetItemsAsync();

                    //Wait for busy database
                    await ApiUpdate.WaitForBusyDatabase();

                    List <TableFeeds> TableUpdatedFeeds = new List <TableFeeds>();
                    List <TableFeeds> TableCurrentFeeds = await SQLConnection.Table <TableFeeds>().ToListAsync();

                    foreach (JToken JTokenRoot in WebJObject["subscriptions"])
                    {
                        string FeedId    = JTokenRoot["sortid"].ToString();
                        string FeedTitle = JTokenRoot["title"].ToString();

                        string HtmlUrl = WebUtility.HtmlDecode(JTokenRoot["htmlUrl"].ToString());
                        HtmlUrl = WebUtility.UrlDecode(HtmlUrl);

                        Uri FullUrl = new Uri(HtmlUrl);
                        ApiFeedIdList.Add(FeedId);

                        TableFeeds TableResult = TableCurrentFeeds.Where(x => x.feed_id == FeedId).FirstOrDefault();
                        if (TableResult == null)
                        {
                            //Debug.WriteLine("Adding feed: " + FeedTitle);

                            TableFeeds AddFeed = new TableFeeds();
                            AddFeed.feed_id    = FeedId;
                            AddFeed.feed_title = FeedTitle;
                            AddFeed.feed_link  = FullUrl.Scheme + "://" + FullUrl.Host;

                            AddFeed.feed_ignore_status = false;
                            if (JTokenRoot["categories"] != null && JTokenRoot["categories"].HasValues)
                            {
                                AddFeed.feed_folder = JTokenRoot["categories"][0]["label"].ToString();
                            }

                            TableUpdatedFeeds.Add(AddFeed);
                        }
                        else
                        {
                            //Debug.WriteLine("Updating feed: " + FeedTitle);

                            TableResult.feed_title = FeedTitle;
                            TableResult.feed_link  = FullUrl.Scheme + "://" + FullUrl.Host;

                            if (JTokenRoot["categories"] != null && JTokenRoot["categories"].HasValues)
                            {
                                TableResult.feed_folder = JTokenRoot["categories"][0]["label"].ToString();
                            }

                            TableUpdatedFeeds.Add(TableResult);
                        }

                        //Check and download feed logo
                        if (!LocalFileList.Any(x => x.Name == FeedId + ".png"))
                        {
                            try
                            {
                                if (!Silent)
                                {
                                    await EventProgressDisableUI("Downloading " + FeedTitle + " icon...", true);
                                }

                                Uri     IconUrl      = new Uri("https://s2.googleusercontent.com/s2/favicons?domain=" + FullUrl.Host);
                                IBuffer HttpFeedIcon = await AVDownloader.DownloadBufferAsync(3000, "News Scroll", IconUrl);

                                if (HttpFeedIcon != null && HttpFeedIcon.Length > 75)
                                {
                                    await AVFile.SaveBuffer(FeedId + ".png", HttpFeedIcon);

                                    Debug.WriteLine("Downloaded transparent logo: " + HttpFeedIcon.Length + "bytes/" + IconUrl);
                                }
                                else
                                {
                                    Debug.WriteLine("No logo found for: " + IconUrl);
                                }
                            }
                            catch { }
                        }
                    }

                    //Update the feeds in database
                    if (TableUpdatedFeeds.Any())
                    {
                        await SQLConnection.InsertOrReplaceAllAsync(TableUpdatedFeeds);
                    }

                    //Delete removed feeds from the database
                    List <String> DeletedFeeds = TableCurrentFeeds.Select(x => x.feed_id).Except(ApiFeedIdList).ToList();
                    Debug.WriteLine("Found deleted feeds: " + DeletedFeeds.Count());
                    foreach (String DeleteFeedId in DeletedFeeds)
                    {
                        await DeleteFeed(DeleteFeedId);
                    }
                }

                if (EnableUI)
                {
                    await EventProgressEnableUI();
                }
                return(true);
            }
            catch
            {
                await EventProgressEnableUI();

                return(false);
            }
        }