using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Windows.ApplicationModel.Background; using Windows.Storage; using Windows.Storage.Search; using Windows.System.UserProfile; namespace XboxBackgroundTask { public sealed class XboxSlideshowTask : IBackgroundTask { #region Variables string UserId = ""; WallpaperCollection RoamingCollectionLockScreen = null; WallpaperCollection RoamingCollectionWallpaper = null; WallpaperCollection LocalCollectionLockScreen = null; WallpaperCollection LocalCollectionWallpaper = null; WallpaperCollection CollectionToSetAsLockScreen = null; WallpaperCollection CollectionToSetAsWallpaper = null; bool IsRoamingLockScreenStronger = false; bool IsRoamingWallpaperStronger = false; BackgroundTaskDeferral deferral; ApiUtil Api; PersistenceHelper PersistenceHelper; InteractiveSlideHelper InteractiveHelper; #endregion public async void Run(IBackgroundTaskInstance taskInstance) { deferral = taskInstance.GetDeferral(); taskInstance.Canceled += TaskInstance_Canceled; try { Api = new ApiUtil(); InteractiveHelper = new InteractiveSlideHelper(); PersistenceHelper = new PersistenceHelper(); if (!Api.IsInternetAccessAvailable()) { deferral.Complete(); return; } UserId = PersistenceHelper.GetSettings(SettingKey.LoggedInUserId); await GetRemoteCollections(); GetLocalCollections(); if (RoamingCollectionLockScreen == null && RoamingCollectionWallpaper == null && LocalCollectionLockScreen == null && LocalCollectionWallpaper == null) { deferral.Complete(); return; } if (PersistenceHelper.GetSettings(SettingKey.IsLockscreenSlideEnabled) == "on") SelectCollectionToBeSet("lock"); if (PersistenceHelper.GetSettings(SettingKey.IsWallpaperSlideEnabled) == "on") SelectCollectionToBeSet("wall"); if (CollectionToSetAsLockScreen == null && CollectionToSetAsWallpaper == null) { deferral.Complete(); return; } if (CollectionToSetAsLockScreen != null) { await SetCurrentCollection(CollectionToSetAsLockScreen, true); PersistenceHelper.SetSettings(SettingKey.LastSlideShowChangedDateTimeLock, JsonConvert.SerializeObject(DateTime.Now)); } if (CollectionToSetAsWallpaper != null) { await SetCurrentCollection(CollectionToSetAsWallpaper, false); PersistenceHelper.SetSettings(SettingKey.LastSlideShowChangedDateTimeDesktop, JsonConvert.SerializeObject(DateTime.Now)); } } catch (Exception ex) { Console.WriteLine(ex.Message); } deferral.Complete(); } private async Task GetRemoteCollections() { if (IsUserLoggedIn()) { IList collections = await Api.GetRemoteWallpaperCollections(UserId); if (collections != null) { foreach (var item in collections) { if (item.IsLockScreen == 1) RoamingCollectionLockScreen = item; if (item.IsLockScreen == 0) RoamingCollectionWallpaper = item; } } } } private void GetLocalCollections() { string lockScreenJson = PersistenceHelper.GetSettings(SettingKey.LockScreenCollection); if (!string.IsNullOrEmpty(lockScreenJson)) { try { LocalCollectionLockScreen = JsonConvert.DeserializeObject(lockScreenJson); } catch (Exception) { } } string wallpaperJson = PersistenceHelper.GetSettings(SettingKey.WallpaperCollection); if (!string.IsNullOrEmpty(wallpaperJson)) { try { LocalCollectionWallpaper = JsonConvert.DeserializeObject(wallpaperJson); } catch (Exception) { } } } private void SelectCollectionToBeSet(string wallpaperType) { switch (wallpaperType) { case "lock": if (RoamingCollectionLockScreen != null && LocalCollectionLockScreen != null) // Local and roaming info exists. { if (RoamingCollectionLockScreen.CollectionDate > LocalCollectionLockScreen.CollectionDate) { CollectionToSetAsLockScreen = RoamingCollectionLockScreen; IsRoamingLockScreenStronger = true; } else CollectionToSetAsLockScreen = LocalCollectionLockScreen; } else if (LocalCollectionLockScreen != null) // Only local info exists. { CollectionToSetAsLockScreen = LocalCollectionLockScreen; } else if (RoamingCollectionLockScreen != null) //Only roaming info exists. { CollectionToSetAsLockScreen = RoamingCollectionLockScreen; IsRoamingLockScreenStronger = true; } else { return; } break; case "wall": if (RoamingCollectionWallpaper != null && LocalCollectionWallpaper != null) // Local and roaming info exists. { if (RoamingCollectionWallpaper.CollectionDate > LocalCollectionWallpaper.CollectionDate) { CollectionToSetAsWallpaper = RoamingCollectionWallpaper; IsRoamingWallpaperStronger = true; } else CollectionToSetAsWallpaper = LocalCollectionWallpaper; } else if (LocalCollectionWallpaper != null) // Only local info exists. { CollectionToSetAsWallpaper = LocalCollectionWallpaper; } else if (RoamingCollectionWallpaper != null) //Only roaming info exists. { CollectionToSetAsWallpaper = RoamingCollectionWallpaper; IsRoamingWallpaperStronger = true; } else { return; } break; } } private async Task SetCurrentCollection(WallpaperCollection collection, bool isLockScreen) { if (collection.CollectionType == "weather") { var point = await InteractiveHelper.GetCurrentLocation(); if (point != null) { var weather = await InteractiveHelper.GetWeatherData(point); if (weather != null) { int code = weather.Weather[0].Id; collection.CollectionSubType = InteractiveHelper.GetWeatherTagByCode(code); if (weather.Sys.SunriseTime < DateTime.Now && weather.Sys.SunsetTime > DateTime.Now) { collection.PublisherId = "0"; } else { collection.PublisherId = "1"; } } } } if (collection.CollectionType == "timeofday") { var point = await InteractiveHelper.GetCurrentLocation(); if (point != null) { var weather = await InteractiveHelper.GetWeatherData(point); if (weather != null) { collection.CollectionSubType = InteractiveHelper.GetTimeOfDay(weather); } } } if (collection.CollectionType == "seasonal") { var point = await InteractiveHelper.GetCurrentLocation(); if (point != null) { string season = InteractiveHelper.GetSeason(point); collection.CollectionSubType = season; } } if (collection.CollectionType == "favorite" || collection.CollectionType == "history" || collection.CollectionType == "folder") { await SetWallpaperLocal(collection, isLockScreen); } else if (collection.CollectionType == "wallpaper") { string fileName = GetFileName(collection.PreviousWallpaperPhotoUrl); if (string.IsNullOrEmpty(fileName)) return; if (isLockScreen) fileName = "lock-" + fileName; else fileName = "desktop-" + fileName; try { StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName); } catch (Exception) { if (collection == null || collection.CollectionSubType == null) return; await FinalProcess(collection.CollectionSubType, collection, isLockScreen); } } else if (collection.CollectionType == "bingwallpaper") { string bingFileName = GetFileName(collection.PreviousWallpaperPhotoUrl); if (string.IsNullOrEmpty(bingFileName)) return; if (isLockScreen) bingFileName = "lock-" + bingFileName; else bingFileName = "desktop-" + bingFileName; try { StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(bingFileName); } catch (Exception) { if (collection == null || collection.CollectionSubType == null) return; await BingFinalProcess(collection.CollectionSubType, collection, isLockScreen); } } else if (collection.CollectionType == "bingslide") { await SetBingWallpaper(collection, isLockScreen); } else { await SetWallpaperRemote(collection, isLockScreen); } } private async Task SetWallpaperLocal(WallpaperCollection collection, bool isLockScreen) { if (collection == null || collection.CollectionSubType == null) return; string idJson = null; string folderJson = null; string finalJson = null; if (IsUserLoggedIn()) { if (collection.CollectionType == "folder") { finalJson = await Api.GetFolderWallpapersJson(collection.CollectionSubType, UserId); } else { finalJson = await Api.GetPublisherDataCollectionJson(collection.CollectionType, UserId); } } else { switch (collection.CollectionType) { case "favorite": idJson = await PersistenceHelper.ReadStringFromFile(PersistenceHelper.FavoritesFileKey, true); break; case "history": idJson = await PersistenceHelper.ReadStringFromFile(PersistenceHelper.HistoryFileKey, true); break; case "folder": folderJson = await PersistenceHelper.ReadStringFromFile(PersistenceHelper.FoldersFileKey, true); break; } if (collection.CollectionType == "folder") { if (!string.IsNullOrEmpty(folderJson)) { IList folderWithIds = null; try { folderWithIds = JsonConvert.DeserializeObject>(folderJson); } catch (Exception) { } if (folderWithIds != null && folderWithIds.Count != 0) { var ids = new List(); foreach (var folder in folderWithIds) { if (folder.FolderName == collection.CollectionSubType) { if (folder.WallpaperIds != null && folder.WallpaperIds.Count != 0) { foreach (var item in folder.WallpaperIds) { ids.Add(item); } } } } if (ids != null && ids.Count > 0) { idJson = JsonConvert.SerializeObject(ids); } } if (string.IsNullOrEmpty(idJson)) return; var result = await Api.GetWallpapersByIds(idJson); if (result != null && result.Count > 0) { finalJson = JsonConvert.SerializeObject(result); } } } } if (string.IsNullOrEmpty(finalJson)) return; IList wallpapers = null; try { wallpapers = JsonConvert.DeserializeObject>(finalJson); } catch (Exception) { } if (wallpapers == null || wallpapers.Count == 0) return; await ProcessWallpaper(wallpapers, collection, isLockScreen); } private async Task SetWallpaperRemote(WallpaperCollection collection, bool isLockScreen) { _ = int.TryParse(collection.PublisherId, out int publisherId); IList wallpapers = await Api.ProcessSlideshow(collection, publisherId); if (wallpapers != null) { await ProcessWallpaper(wallpapers, collection, isLockScreen); } } private async Task ProcessWallpaper(IList wallpapers, WallpaperCollection collection, bool isLockScreen) { if (wallpapers == null || wallpapers.Count == 0) return; WallpaperData wallpaperData = new WallpaperData(); if (collection.PreviousWallpaperPhotoUrl == null || collection.PreviousWallpaperPhotoUrl == "") { Random rnd = new Random(); int index = rnd.Next(0, wallpapers.Count - 1); wallpaperData.ID = wallpapers[index].ID; wallpaperData.FullPhotoUrl = wallpapers[index].FullPhotoUrl; } else { Random rnd = new Random(); int index = rnd.Next(0, wallpapers.Count - 1); wallpaperData.ID = wallpapers[index].ID; wallpaperData.FullPhotoUrl = wallpapers[index].FullPhotoUrl; if (wallpapers.Count > 1) { while (wallpaperData.FullPhotoUrl == collection.PreviousWallpaperPhotoUrl) { rnd = new Random(); index = rnd.Next(0, wallpapers.Count); wallpaperData.ID = wallpapers[index].ID; wallpaperData.FullPhotoUrl = wallpapers[index].FullPhotoUrl; } } else { if (wallpaperData.FullPhotoUrl == collection.PreviousWallpaperPhotoUrl) return; } } await FinalProcess(wallpaperData.FullPhotoUrl, collection, isLockScreen); } private async Task SetBingWallpaper(WallpaperCollection collection, bool isLockScreen) { var url = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=" + collection.CollectionSubType; string json = await Api.GetStringFromUrl(url); if (string.IsNullOrEmpty(json)) return; BingWallpaperGroup bingGroup; try { bingGroup = JsonConvert.DeserializeObject(json); } catch (Exception) { return; } if (bingGroup == null) return; if (collection.PreviousWallpaperPhotoUrl != bingGroup.Images[0].FullUrl) { await BingFinalProcess(bingGroup.Images[0].FullUrl, collection, isLockScreen); } } private async Task FinalProcess(string photoUrl, WallpaperCollection currentCollection, bool isLockScreen) { byte[] fileBytes; try { using (var client = new HttpClient()) { fileBytes = await client.GetByteArrayAsync(photoUrl); } } catch (HttpRequestException) { return; } catch (Exception) { return; } if (fileBytes == null) return; await DeleteFile(isLockScreen); var file = await SaveFile(photoUrl, isLockScreen, fileBytes, false); if (file != null) { await SetWallpaper(isLockScreen, file, currentCollection, photoUrl); } } private async Task BingFinalProcess(string photoUrl, WallpaperCollection collection, bool isLockScreen) { byte[] fileBytes; try { using (var client = new HttpClient()) { fileBytes = await client.GetByteArrayAsync(photoUrl); } } catch (HttpRequestException) { return; } catch (Exception) { return; } await DeleteFile(isLockScreen); var file = await SaveFile(photoUrl, isLockScreen, fileBytes, true); if (file != null) { await SetWallpaper(isLockScreen, file, collection, photoUrl); } } private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) { deferral.Complete(); } private bool IsUserLoggedIn() { if (string.IsNullOrEmpty(UserId) || string.IsNullOrWhiteSpace(UserId)) return false; string userid = UserId.Replace(" ", string.Empty); if (userid.Length < 3) return false; else return true; } private string GetFileName(string photoUrl) { string[] photoUrlArray = photoUrl.Split('/'); return photoUrlArray[photoUrlArray.Count() - 1]; } private async Task DeleteFile(bool isLockScreen) { try { List fileTypeFilter = new List { "*" }; QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderBySearchRank, fileTypeFilter); { if (isLockScreen) queryOptions.UserSearchFilter = "lock-"; else queryOptions.UserSearchFilter = "desktop-"; } queryOptions.FolderDepth = FolderDepth.Shallow; var queryResult = ApplicationData.Current.LocalFolder.CreateFileQueryWithOptions(queryOptions); var files = await queryResult.GetFilesAsync(); if (files != null) { if (files.Count > 0) { foreach (StorageFile file1 in files) { await file1.DeleteAsync(StorageDeleteOption.PermanentDelete); } } } } catch (Exception) { ; } } private async Task SaveFile(string photoUrl, bool isLockScreen, byte[] bytes, bool isBing) { string fileName; if (isBing) { fileName = "bing-" + DateTime.Now.ToString("MM-dd-yyyy"); } else { fileName = GetFileName(photoUrl); } if (fileName == null) return null; if (isLockScreen) fileName = "lock-" + fileName; else fileName = "desktop-" + fileName; StorageFile file; try { file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); if (file == null) return null; await FileIO.WriteBytesAsync(file, bytes); } catch (Exception) { return null; } return file; } private async Task SetWallpaper(bool isLockScreen, StorageFile file, WallpaperCollection collection, string photoUrl) { if (UserProfilePersonalizationSettings.IsSupported()) { UserProfilePersonalizationSettings profileSettings = UserProfilePersonalizationSettings.Current; bool isSuccess; if (isLockScreen) { isSuccess = await profileSettings.TrySetLockScreenImageAsync(file); } else { isSuccess = await profileSettings.TrySetWallpaperImageAsync(file); } if (isSuccess) { collection.PreviousWallpaperPhotoUrl = photoUrl; if (isLockScreen) { if (IsRoamingLockScreenStronger) { await Api.CreateSlideshow(JsonConvert.SerializeObject(collection)); } else { PersistenceHelper.SetSettings(SettingKey.LockScreenCollection, JsonConvert.SerializeObject(collection)); } } else { if (IsRoamingWallpaperStronger) { await Api.CreateSlideshow(JsonConvert.SerializeObject(collection)); } else { PersistenceHelper.SetSettings(SettingKey.WallpaperCollection, JsonConvert.SerializeObject(collection)); } } } } } } }