protected async virtual Task <IEnumerable <ImageItem> > RequestAsync(int pageIndex)
        {
            var cts = CTSFactory.MakeCTS(15000);

            try
            {
                _imageService.Page = pageIndex;
                var result = await _imageService.GetImagesAsync(cts.Token);

                if (result != null)
                {
                    var list = CreateImageItems(result);
                    UpdateHintVisibility(list);
                    return(list);
                }
                else
                {
                    throw new APIException("Request failed");
                }
            }
            catch (TaskCanceledException)
            {
                throw new APIException("Request timeout");
            }
        }
예제 #2
0
        private async Task GetCategoriesAsync()
        {
            if (Categories?.Count > 0)
            {
                return;
            }

            var result = await CloudService.GetCategories(CTSFactory.MakeCTS(20000).Token);

            if (result.IsRequestSuccessful)
            {
                var list = UnsplashCategory.GenerateListFromJson(result.JsonSrc);
                this.Categories = list;
                this.Categories.Insert(0, new UnsplashCategory()
                {
                    Title = "Featured",
                });
                this.Categories.Insert(0, new UnsplashCategory()
                {
                    Title = "New",
                });
                this.Categories.Insert(0, new UnsplashCategory()
                {
                    Title = "Random",
                });
                SelectedIndex = NEW_INDEX;
                await SerializerHelper.SerializerToJson <ObservableCollection <UnsplashCategory> >(list, CachedFileNames.CateListFileName, CacheUtil.GetCachedFileFolder());
            }
        }
예제 #3
0
        public static async Task <IRandomAccessStream> GetIRandomAccessStreamFromUrlAsync(string url,
                                                                                          CancellationToken?token)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new UriFormatException("The url is null or empty.");
            }

            using (var client = new HttpClient())
            {
                if (token == null)
                {
                    token = CTSFactory.MakeCTS().Token;
                }

                var downloadTask = client.GetAsync(new Uri(url), token.Value);

                token?.ThrowIfCancellationRequested();

                var response = await downloadTask;
                response.EnsureSuccessStatusCode();

                var streamTask = response.Content.ReadAsStreamAsync();

                token?.ThrowIfCancellationRequested();

                var stream = await streamTask;

                return(stream.AsRandomAccessStream());
            }
        }
예제 #4
0
        public async Task GetUserPlan()
        {
            CurrentUserPlans = new ObservableCollection <UserPlan>();

            var getResult = await CloudService.GetAllPlans(CTSFactory.MakeCTS().Token);

            getResult.ParseAPIResult();
            if (!getResult.IsSuccessful)
            {
                ToastService.SendToast("获得培养计划失败");
                return;
            }
            var json = getResult.JsonSrc;


            SelectedIndex = 0;

            if (CurrentUserPlans.Count == 0)
            {
                NoItemVisibility = Visibility.Visible;
            }
            else
            {
                NoItemVisibility = Visibility.Collapsed;
            }
        }
예제 #5
0
        public static async Task <bool> GetStreamFromUrlAsync(string url,
                                                              CancellationToken?token, StorageFile file)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new UriFormatException("The url is null or empty.");
            }

            using (var client = new HttpClient())
            {
                if (token == null)
                {
                    token = CTSFactory.MakeCTS().Token;
                }

                using (var fs = await file.OpenStreamForWriteAsync())
                {
                    var resp = await client.GetAsync(new Uri(url), HttpCompletionOption.ResponseHeadersRead, token.Value);

                    var stream = await resp.Content.ReadAsStreamAsync();

                    await stream.CopyToAsync(fs);

                    stream.Dispose();
                }

                return(true);
            }
        }
예제 #6
0
        public async Task TestSearchHasNoResultImages()
        {
            var service = new SearchImageService(new UnsplashImageFactory(false), "dfafefsdfasfsdf");
            var result  = await service.GetImagesAsync(CTSFactory.MakeCTS().Token);

            Assert.IsTrue(result?.Count() == 0);
        }
예제 #7
0
        private async Task Login()
        {
            try
            {
                var saltResult = await CloudService.GetSalt(Email, CTSFactory.MakeCTS(100000).Token);

                saltResult.ParseAPIResult();
                if (!saltResult.IsSuccessful)
                {
                    throw new APIException(saltResult.ErrorMsg);
                }
                var saltObj = JsonObject.Parse(saltResult.JsonSrc);
                var salt    = JsonParser.GetStringFromJsonObj(saltObj, "Salt");
                if (string.IsNullOrEmpty(salt))
                {
                    throw new APIException("User does not exist.");
                }

                var newPwd       = MD5.GetMd5String(Password);
                var newPwdInSalt = MD5.GetMd5String(newPwd + salt);
                var loginResult  = await CloudService.Login(Email, newPwdInSalt, CTSFactory.MakeCTS(100000).Token);

                loginResult.ParseAPIResult();
                if (!loginResult.IsSuccessful)
                {
                    throw new APIException(loginResult.ErrorMsg);
                }
                var loginObj    = JsonObject.Parse(loginResult.JsonSrc);
                var userObj     = loginObj["UserInfo"];
                var uid         = JsonParser.GetStringFromJsonObj(userObj, "uid");
                var accessToken = JsonParser.GetStringFromJsonObj(userObj, "access_token");
                if (uid.IsNotNullOrEmpty() && accessToken.IsNotNullOrEmpty())
                {
                    LocalSettingHelper.AddValue("uid", uid);
                    LocalSettingHelper.AddValue("access_token", accessToken);
                    NavigationService.NavigateViaRootFrame(typeof(MainPage));
                }
            }
            catch (TaskCanceledException)
            {
                ToastService.SendToast("Connection time out");
            }
            catch (APIException e)
            {
                ToastService.SendToast(e.ErrorMessage.IsNotNullOrEmpty() ? e.Message : "Fail to login");
            }
            catch (Exception e)
            {
                ToastService.SendToast("Fail to login");
                var task = ExceptionHelper.WriteRecordAsync(e, nameof(LoginViewModel), nameof(Login));
            }
            finally
            {
                ShowLoading = Visibility.Collapsed;
            }
        }
        protected async override Task <IEnumerable <UnsplashImageBase> > RequestAsync(int pageIndex)
        {
            var result = await CloudService.GetRandomImages((int)DEFAULT_PER_PAGE, CTSFactory.MakeCTS(5000).Token);

            if (result.IsRequestSuccessful)
            {
                var list = UnsplashImage.ParseListFromJson(result.JsonSrc);
                UpdateHintVisibility(list);
                return(list);
            }
            else
            {
                throw new APIException();
            }
        }
        protected async override Task <IEnumerable <UnsplashImageBase> > RequestAsync(int pageIndex)
        {
            var result = await CloudService.SearchImages(pageIndex, (int)20, CTSFactory.MakeCTS(10000).Token, _keyword);

            if (result.IsRequestSuccessful)
            {
                var rootObj     = JsonObject.Parse(result.JsonSrc);
                var resultArray = JsonParser.GetJsonArrayFromJsonObj(rootObj, "results");
                var list        = UnsplashImage.ParseListFromJson(resultArray.ToString());
                UpdateHintVisibility(list);
                return(list);
            }
            else
            {
                throw new APIException();
            }
        }
예제 #10
0
        public async Task TestGetAllPlans()
        {
            Helper.AddAuthInfo();
            var result = await CloudService.GetAllPlans(CTSFactory.MakeCTS().Token);

            Assert.IsTrue(result.IsSuccessful);
            var json   = result.JsonSrc;
            var obj    = JsonObject.Parse(json);
            var plants = JsonParser.GetJsonArrayFromJsonObj(obj, "Plans");

            Assert.IsNotNull(plants);
            Assert.IsTrue(plants.Count > 0);
            foreach (var plant in plants)
            {
                var plantObj = plant.GetObject();
                Assert.IsNotNull(plantObj);
            }
        }
예제 #11
0
        private async Task Register()
        {
            try
            {
                var isUserExist = await CloudService.CheckUserExist(Email, CTSFactory.MakeCTS(10000).Token);

                isUserExist.ParseAPIResult();
                if (!isUserExist.IsSuccessful)
                {
                    throw new ArgumentException();
                }
                var json    = JsonObject.Parse(isUserExist.JsonSrc);
                var isExist = JsonParser.GetBooleanFromJsonObj(json, "isExist", false);
                if (isExist)
                {
                    throw new ArgumentException("The email has been used.");
                }

                var registerResult = await CloudService.Register(Email, MD5.GetMd5String(Password), CTSFactory.MakeCTS(100000).Token);

                registerResult.ParseAPIResult();
                if (!registerResult.IsSuccessful)
                {
                    throw new ArgumentException();
                }
                await Login();
            }
            catch (ArgumentException e)
            {
                ToastService.SendToast(e.Message.IsNotNullOrEmpty() ? e.Message : "Fail to register");
            }
            catch (TaskCanceledException e)
            {
            }
            catch (Exception e)
            {
            }
            finally
            {
                ShowLoading = Visibility.Collapsed;
            }
        }
예제 #12
0
        protected async virtual Task <IEnumerable <UnsplashImageBase> > RequestAsync(int pageIndex)
        {
#if DEBUG
            var cts = CTSFactory.MakeCTS();
#else
            var cts = CTSFactory.MakeCTS(15000);
#endif
            try
            {
                var result = await CloudService.GetImages(pageIndex, (int)20u, cts.Token, RequestUrl);

                if (result.IsRequestSuccessful)
                {
                    IEnumerable <UnsplashImageBase> list = null;
                    if (Featured)
                    {
                        list = UnsplashFeaturedImage.ParseListFromJson(result.JsonSrc);
                    }
                    else
                    {
                        list = UnsplashImage.ParseListFromJson(result.JsonSrc);
                    }
                    await CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        UpdateHintVisibility(list);
                    });

                    return(list);
                }
                else
                {
                    throw new ArgumentNullException();
                }
            }
            catch (Exception e)
            {
                await Logger.LogAsync(e);

                return(new List <UnsplashImage>());
            }
        }
예제 #13
0
        private async Task GetCategoriesAsync()
        {
            if (Categories?.Count > 0)
            {
                return;
            }

            var result = await CloudService.GetCategories(CTSFactory.MakeCTS(20000).Token);

            if (result.IsRequestSuccessful)
            {
                var list = UnsplashCategory.GenerateListFromJson(result.JsonSrc);
                this.Categories = list;
                this.Categories.Insert(0, new UnsplashCategory()
                {
                    Title = "Featured",
                });

                SelectedIndex = 0;
            }
        }
        protected async virtual Task <IEnumerable <UnsplashImageBase> > RequestAsync(int pageIndex)
        {
            var result = await CloudService.GetImages(pageIndex, (int)DEFAULT_PER_PAGE, CTSFactory.MakeCTS(10000).Token, RequestUrl);

            if (result.IsRequestSuccessful)
            {
                if (Featured)
                {
                    var list = UnsplashFeaturedImage.ParseListFromJson(result.JsonSrc);
                    UpdateHintVisibility(list);
                    return(list);
                }
                else
                {
                    var list = UnsplashImage.ParseListFromJson(result.JsonSrc);
                    UpdateHintVisibility(list);
                    return(list);
                }
            }
            else
            {
                throw new APIException();
            }
        }
예제 #15
0
 private async Task ReportDownloadAsync(string url)
 {
     await _service.ReportPhotoDownload(url, CTSFactory.MakeCTS(5000).Token);
 }
예제 #16
0
        private async Task DownloadFromRemoteUrlAsync()
        {
            var cachedFolder = ApplicationData.Current.TemporaryFolder;

            if (!string.IsNullOrEmpty(ExpectedFileName))
            {
                var file = await cachedFolder.TryGetFileAsync(ExpectedFileName);

                if (file != null)
                {
                    LocalPath = file.Path;
                    await SetImageSourceAsync(file);

                    return;
                }
            }
            else
            {
                ExpectedFileName = GenerateRandomFileName();
            }
            using (var stream = await FileDownloadUtil.GetIRandomAccessStreamFromUrlAsync(this.RemoteUrl, CTSFactory.MakeCTS().Token))
            {
                var file = await SaveStreamIntoFileAsync(stream.AsStream(), ExpectedFileName, cachedFolder);

                if (file != null)
                {
                    LocalPath = file.Path;
                }
                stream.Seek(0);
                if (stream != null)
                {
                    await SetImageSourceAsync(stream);
                }
            }
        }
예제 #17
0
        public async Task TestSearchCase1()
        {
            var result = await CloudService.SearchImages(1, 10, "cat", CTSFactory.MakeCTS(20000).Token);

            Assert.IsTrue(result.IsRequestSuccessful);
        }
예제 #18
0
        public async Task TestGetCagetories()
        {
            var result = await CloudService.GetCategories(CTSFactory.MakeCTS().Token);

            Assert.IsTrue(result.IsRequestSuccessful);
        }
예제 #19
0
        public async Task TestGetRandomImages()
        {
            var result = await _randomImageService.GetImagesAsync(CTSFactory.MakeCTS().Token);

            Assert.IsTrue(result?.Count() > 0);
        }
예제 #20
0
        protected async override Task <IEnumerable <UnsplashImage> > GetList(int pageIndex)
        {
            try
            {
                if (pageIndex >= 2)
                {
                    MainVM.ShowFooterLoading = Visibility.Visible;
                }

                var result = await CloudService.GetImages(pageIndex, (int)DEFAULT_PER_PAGE, CTSFactory.MakeCTS(10000).Token, RequestUrl);

                if (result.IsRequestSuccessful)
                {
                    var list = UnsplashImage.ParseListFromJson(result.JsonSrc);
                    return(list);
                }
                else
                {
                    throw new APIException();
                }
            }
            catch (APIException)
            {
                await CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    MainVM.ShowFooterLoading    = Visibility.Collapsed;
                    MainVM.ShowFooterReloadGrid = Visibility.Visible;
                    MainVM.IsRefreshing         = false;

                    if (MainVM.MainList?.Count == 0)
                    {
                        MainVM.ShowNoItemHint = Visibility.Visible;
                    }
                    else
                    {
                        MainVM.ShowNoItemHint = Visibility.Collapsed;
                    }

                    ToastService.SendToast("Request failed.");
                });

                return(new List <UnsplashImage>());
            }
            catch (TaskCanceledException)
            {
                await CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    MainVM.ShowFooterLoading    = Visibility.Collapsed;
                    MainVM.ShowFooterReloadGrid = Visibility.Visible;
                    MainVM.IsRefreshing         = false;

                    if (MainVM.MainList.Count == 0)
                    {
                        MainVM.ShowNoItemHint = Visibility.Visible;
                    }
                    else
                    {
                        MainVM.ShowNoItemHint = Visibility.Collapsed;
                    }

                    ToastService.SendToast("Request timeout.");
                });

                return(new List <UnsplashImage>());
            }
            catch (Exception e)
            {
                var task = ExceptionHelper.WriteRecordAsync(e, nameof(ImageDataViewModel), nameof(GetList));
                return(new List <UnsplashImage>());
            }
        }