示例#1
0
        public async Task RefreshAccessToken(UserAccountEntity account)
        {
            try
            {
                var dic = new Dictionary<String, String>();
                dic["grant_type"] = "refresh_token";
                dic["client_id"] = EndPoints.ConsumerKey;
                dic["client_secret"] = EndPoints.ConsumerSecret;
                dic["refresh_token"] = account.GetRefreshToken();
                dic["scope"] = "psn:sceapp";

                account.SetAccessToken("updating", null);
                account.SetRefreshTime(1000);
                var theAuthClient = new HttpClient();
                HttpContent header = new FormUrlEncodedContent(dic);
                var response = await theAuthClient.PostAsync(EndPoints.OauthToken, header);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var o = JObject.Parse(responseContent);
                    if (string.IsNullOrEmpty(responseContent))
                    {
                        throw new RefreshTokenException("Could not refresh the user token, no response data");
                    }
                    account.SetAccessToken((String)o["access_token"], (String)o["refresh_token"]);
                    account.SetRefreshTime(long.Parse((String)o["expires_in"]));
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Could not refresh the user token", ex);
            }
        }
示例#2
0
 public async Task<Result> DeleteData(Uri uri, StringContent json, UserAccountEntity userAccountEntity)
 {
     var httpClient = new HttpClient();
     try
     {
         var authenticationManager = new AuthenticationManager();
         if (userAccountEntity.GetAccessToken().Equals("refresh"))
         {
             await authenticationManager.RefreshAccessToken(userAccountEntity);
         }
         var user = userAccountEntity.GetUserEntity();
         if (user != null)
         {
             var language = userAccountEntity.GetUserEntity().Language;
             httpClient.DefaultRequestHeaders.Add("Accept-Language", language);
         }
         httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
         var response = await httpClient.DeleteAsync(uri);
         var responseContent = await response.Content.ReadAsStringAsync();
         return response.IsSuccessStatusCode ? new Result(true, string.Empty) : new Result(false, responseContent);
     }
     catch (Exception)
     {
         return new Result(false, string.Empty);
     }
 }
示例#3
0
        public async Task<UstreamEntity> GetUstreamFeed(int pageNumber, int pageSize, string detailLevel,
            Dictionary<string, string> filterList, string sortBy, string query, UserAccountEntity userAccountEntity)
        {
            try
            {
                var url = EndPoints.UstreamBaseUrl;
                url += string.Format("p={0}&", pageNumber);
                url += string.Format("pagesize={0}&", pageSize);

                url += string.Format("detail_level={0}&", detailLevel);
                foreach (var item in filterList)
                {
                    if (item.Key.Equals(EndPoints.UstreamUrlConstants.Interactive))
                    {
                        url += string.Format(EndPoints.UstreamUrlConstants.FilterBase, EndPoints.UstreamUrlConstants.PlatformPs4) +
                                         "[interactive]=" + item.Value + "&";
                    }
                    else
                    {
                        url += string.Concat(string.Format(EndPoints.UstreamUrlConstants.FilterBase, item.Key), "=", item.Value + "&");
                    }
                }
                url += string.Format("sort={0}", sortBy);
                url += "&r=" + Guid.NewGuid();
                var result = await _webManager.GetData(new Uri(url), userAccountEntity);
                var ustream = JsonConvert.DeserializeObject<UstreamEntity>(result.ResultJson);
                return ustream;
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to get Ustream feed", ex);
            }
        }
示例#4
0
 public async Task<FriendsEntity> GetFriendsList(string username, int? offset, bool blockedPlayer,
     bool playedRecently, bool personalDetailSharing, bool friendStatus, bool requesting, bool requested,
     bool onlineFilter, UserAccountEntity userAccountEntity)
 {
     try
     {
         var user = userAccountEntity.GetUserEntity();
         var url = string.Format(EndPoints.FriendList, user.Region, username, offset);
         if (onlineFilter) url += "&filter=online";
         if (friendStatus && !requesting && !requested) url += "&friendStatus=friend&presenceType=primary";
         if (friendStatus && requesting && !requested) url += "&friendStatus=requesting";
         if (friendStatus && !requesting && requested) url += "&friendStatus=requested";
         if (personalDetailSharing && requested) url += "&friendStatus=friend&personalDetailSharing=requested&presenceType=primary";
         if (personalDetailSharing && requesting) url += "&friendStatus=friend&personalDetailSharing=requesting&presenceType=primary";
         if (playedRecently)
             url =
                 string.Format(
                     EndPoints.RecentlyPlayed, username);
         if (blockedPlayer) url = string.Format("https://{0}-prof.np.community.playstation.net/userProfile/v1/users/{1}/blockList?fields=@default,@profile&offset={2}", user.Region, username, offset);
         // TODO: Fix this cheap hack to get around caching issue. For some reason, no-cache is not working...
         url += "&r=" + Guid.NewGuid();
         var result = await _webManager.GetData(new Uri(url), userAccountEntity);
         var friend = JsonConvert.DeserializeObject<FriendsEntity>(result.ResultJson);
         return friend;
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message, ex);
     }
 }
示例#5
0
 public async Task<bool> IgnoreFriendRequest(string username, UserAccountEntity userAccountEntity)
 {
     try
     {
         var user = userAccountEntity.GetUserEntity();
         var url = string.Format(EndPoints.DenyAddFriend, user.Region, user.OnlineId, username);
         var result = await _webManager.DeleteData(new Uri(url), null, userAccountEntity);
         return result.IsSuccess;
     }
     catch (Exception ex)
     {
         throw new Exception("Error removing friend", ex);
     }
 }
示例#6
0
 public async Task<SessionInviteEntity> GetSessionInvites(int offset, UserAccountEntity userAccountEntity)
 {
     try
     {
         var user = userAccountEntity.GetUserEntity();
         string url = string.Format(EndPoints.SessionInformation, user.Region, user.OnlineId, user.Language, offset);
         var result = await _webManager.GetData(new Uri(url), userAccountEntity);
         var sessionInvite = JsonConvert.DeserializeObject<SessionInviteEntity>(result.ResultJson);
         return sessionInvite;
     }
     catch (Exception ex)
     {
         throw new Exception("Failed to get session invites", ex);
     }
 }
示例#7
0
 public async Task<NotificationEntity> GetNotifications(string username, UserAccountEntity userAccountEntity)
 {
     try
     {
         var user = userAccountEntity.GetUserEntity();
         var url = string.Format(EndPoints.Notification, user.Region, username, user.Language);
         var result = await _webManager.GetData(new Uri(url), userAccountEntity);
         var notification = JsonConvert.DeserializeObject<NotificationEntity>(result.ResultJson);
         return notification;
     }
     catch (Exception ex)
     {
         throw new Exception("Failed to get notification list", ex);
     }
 }
示例#8
0
 public async Task<SearchResultsEntity> SearchForUsers(int offset, string query, UserAccountEntity userAccountEntity)
 {
     try
     {
         var url = string.Format(EndPoints.Search, offset, query);
         url += "&r=" + Guid.NewGuid();
         var result = await _webManager.GetData(new Uri(url), userAccountEntity);
         var search = JsonConvert.DeserializeObject<SearchResultsEntity>(result.ResultJson);
         return search;
     }
     catch (Exception ex)
     {
        throw new Exception(ex.Message, ex);
     }
 }
示例#9
0
 public async Task<UserEntity> GetUser(string userName, UserAccountEntity userAccountEntity)
 {
     try
     {
         var user = userAccountEntity.GetUserEntity();
         string url = string.Format(EndPoints.User, user.Region, userName);
         url += "&r=" + Guid.NewGuid();
         var result = await _webManager.GetData(new Uri(url), userAccountEntity);
         var userEntity = JsonConvert.DeserializeObject<UserEntity>(result.ResultJson);
         return userEntity;
     }
     catch (Exception ex)
     {
         throw new Exception("Error getting user", ex);
     }
 }
示例#10
0
 public async Task<bool> ClearNotification(NotificationEntity.Notification notification,
     UserAccountEntity userAccountEntity)
 {
     try
     {
         var user = userAccountEntity.GetUserEntity();
         var url = string.Format(EndPoints.ClearNotification, user.Region, user.OnlineId, notification.NotificationGroup, notification.NotificationId);
         var json = new StringContent("{\"seenFlag\":true}", Encoding.UTF8, "application/json");
         var result = await _webManager.PostData(new Uri(url), null, json, userAccountEntity);
         return result.IsSuccess;
     }
     catch (Exception ex)
     {
         throw new Exception("Failed to clear notification", ex);
     }
 }
示例#11
0
 public async Task<UserAccountEntity.User> GetUserEntity(UserAccountEntity userAccountEntity)
 {
     var result = await _webManager.GetData(new Uri(EndPoints.VerifyUser), userAccountEntity);
     if (!result.IsSuccess)
     {
         throw new LoginFailedException("Failed to Log in");
     }
     try
     {
         var user = UserAccountEntity.ParseUser(result.ResultJson);
         return user;
     }
     catch (Exception ex)
     {
         throw new Exception("Failed to parse user", ex);
     }
 }
示例#12
0
        public async Task<MessageGroupEntity> GetMessageGroup(string username, UserAccountEntity userAccountEntity)
        {
            try
            {
                var user = userAccountEntity.GetUserEntity();
                var url = string.Format(EndPoints.MessageGroup, user.Region, username, user.Language);
                url += "&r=" + Guid.NewGuid();
                var result = await _webManager.GetData(new Uri(url), userAccountEntity);
                var messageGroup = JsonConvert.DeserializeObject<MessageGroupEntity>(result.ResultJson);
                return messageGroup;
            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message, ex);
            }
        }
示例#13
0
 public async Task<TrophyEntity> GetTrophyList(string user, int offset, UserAccountEntity userAccountEntity)
 {
     try
     {
         var userAccount = userAccountEntity.GetUserEntity();
         var url = string.Format(EndPoints.TrophyList, userAccount.Region, userAccount.Language, offset, user,
             userAccountEntity.GetUserEntity().OnlineId);
         url += "&r=" + Guid.NewGuid();
         var result = await _webManager.GetData(new Uri(url), userAccountEntity);
         var trophy = JsonConvert.DeserializeObject<TrophyEntity>(result.ResultJson);
         return trophy;
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message, ex);
     }
 }
示例#14
0
 public async Task<TrophyDetailEntity> GetTrophyDetailList(string gameId, string comparedUser, bool includeHidden,
     UserAccountEntity userAccountEntity)
 {
     try
     {
         var user = userAccountEntity.GetUserEntity();
         var url = string.Format(EndPoints.TrophyDetailList, user.Region, gameId, user.Language, comparedUser, user.OnlineId);
         url += "&r=" + Guid.NewGuid();
         var result = await _webManager.GetData(new Uri(url), userAccountEntity);
         var trophyDetailEntity = JsonConvert.DeserializeObject<TrophyDetailEntity>(result.ResultJson);
         return trophyDetailEntity;
     }
     catch (Exception ex)
     {
         throw new Exception("Failed to get trophy detail list", ex);
     }
 }
示例#15
0
        public async Task<RecentActivityEntity> GetActivityFeed(string userName, int? pageNumber, bool storePromo,
            bool isNews, UserAccountEntity userAccountEntity)
        {
            try
            {
                var feedNews = isNews ? "news" : "feed";
                var url = string.Format(EndPoints.RecentActivity, userName, feedNews, pageNumber);
                if (storePromo)
                    url += "&filters=STORE_PROMO";
                url += "&r=" + Guid.NewGuid();
                var result = await _webManager.GetData(new Uri(url), userAccountEntity);
                var recentActivityEntity = JsonConvert.DeserializeObject<RecentActivityEntity>(result.ResultJson);
                return recentActivityEntity;
            }
            catch (Exception exception)
            {

                throw new Exception("Error getting activity feed", exception);
            }
        }
示例#16
0
 public async Task<TwitchEntity> GetTwitchFeed(int offset, int limit, string platform,
     string titlePreset, string query, UserAccountEntity userAccountEntity)
 {
     try
     {
         var url = EndPoints.TwitchBaseUrl;
         // Sony's app hardcodes this value to 0. 
         // This app could, in theory, allow for more polling of data, so these options are left open to new values and limits.
         url += string.Format("offset={0}&", offset);
         url += string.Format("limit={0}&", limit);
         url += string.Format("query={0}&", query);
         var result = await _webManager.GetData(new Uri(url), userAccountEntity);
         var twitch = JsonConvert.DeserializeObject<TwitchEntity>(result.ResultJson);
         return twitch;
     }
     catch (Exception ex)
     {
         throw new Exception("Failed to get Twitch feed", ex);
     }
 }
示例#17
0
        public async Task<Stream> GetImageMessageContent(string id, MessageEntity.Message message,
            UserAccountEntity userAccountEntity)
        {
            try
            {
                var user = userAccountEntity.GetUserEntity();
                const string content = "image-data-0";
                var url = string.Format(EndPoints.MessageContent, user.Region, id, message.messageUid, content, user.Language);
                url += "&r=" + Guid.NewGuid();
                var theAuthClient = new HttpClient();
                var request = new HttpRequestMessage(HttpMethod.Get, url);
                request.Headers.CacheControl = new CacheControlHeaderValue { NoCache = true };
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
                var response = await theAuthClient.SendAsync(request);
                var responseContent = await response.Content.ReadAsStreamAsync();
                return responseContent;
            }
            catch (Exception ex)
            {

                throw new Exception("Failed to get image message content", ex);
            }
        }
示例#18
0
        public async Task<bool> ClearMessages(MessageEntity messageEntity, UserAccountEntity userAccountEntity)
        {
            try
            {
                if (messageEntity.messages == null)
                {
                    return false;
                }
                var user = userAccountEntity.GetUserEntity();
                var messageUids = new List<int>();
                messageUids.AddRange(messageEntity.messages.Where(o => o.seenFlag == false).Select(message => message.messageUid));
                if (messageUids.Count == 0) return false;
                var url = string.Format(EndPoints.ClearMessages, user.Region, messageEntity.messageGroup.messageGroupId, string.Join(",", messageUids));
                var json = new StringContent("{\"seenFlag\":true}", Encoding.UTF8, "application/json");
                var result = await _webManager.PutData(new Uri(url), json, userAccountEntity);
                return result.IsSuccess;
            }
            catch (Exception ex)
            {

                throw new Exception("Failed to clear messages", ex);
            }
        }
示例#19
0
 public async Task<NicoNicoEntity> GetNicoFeed(string status, string platform, int offset, int limit, string sort,
     UserAccountEntity userAccountEntity)
 {
     try
     {
         var url = EndPoints.NicoNicoBaseUrl;
         // Sony's app hardcodes this value to 0. 
         // This app could, in theory, allow for more polling of data, so these options are left open to new values and limits.
         url += string.Format("offset={0}&", offset);
         url += string.Format("limit={0}&", limit);
         url += string.Format("status={0}&", status);
         url += string.Format("sce_platform={0}&", platform);
         url += string.Format("sort={0}", sort);
         // TODO: Fix this cheap hack to get around caching issue. For some reason, no-cache is not working...
         url += "&r=" + Guid.NewGuid();
         var result = await _webManager.GetData(new Uri(url), userAccountEntity);
         var nico = JsonConvert.DeserializeObject<NicoNicoEntity>(result.ResultJson);
         return nico;
     }
     catch (Exception ex)
     {
         throw new Exception("Failed to get Nico Nico Douga feed", ex);
     }
 }
示例#20
0
        public async Task<Result> PostData(Uri uri, MultipartContent header, StringContent content, UserAccountEntity userAccountEntity)
        {
            var httpClient = new HttpClient();
            try
            {
                var authenticationManager = new AuthenticationManager();
                if (userAccountEntity.GetAccessToken().Equals("refresh"))
                {
                    await authenticationManager.RefreshAccessToken(userAccountEntity);
                }
                var user = userAccountEntity.GetUserEntity();
                if (user != null)
                {
                    var language = userAccountEntity.GetUserEntity().Language;
                    httpClient.DefaultRequestHeaders.Add("Accept-Language", language);
                }

                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
                HttpResponseMessage response;
                if (header == null)
                {
                    response = await httpClient.PostAsync(uri, content);
                }
                else
                {
                    response = await httpClient.PostAsync(uri, header);
                }
                var responseContent = await response.Content.ReadAsStringAsync();
                return new Result(true, responseContent);
            }
            catch
            {
                // TODO: Add detail error result to json object.
                return new Result(false, string.Empty);
            }
        }
示例#21
0
        public async Task<MessageEntity> GetGroupConversation(string messageGroupId, UserAccountEntity userAccountEntity)
        {
            try
            {
                var user = userAccountEntity.GetUserEntity();
                var url = string.Format(EndPoints.MessageGroup2, user.Region, messageGroupId, user.Language);
                url += "&r=" + Guid.NewGuid();
                var result = await _webManager.GetData(new Uri(url), userAccountEntity);
                var messageGroup = JsonConvert.DeserializeObject<MessageEntity>(result.ResultJson);
                return messageGroup;
            }
            catch (Exception ex)
            {

                throw new Exception("Failed to get the group conversation", ex);
            }
        }
示例#22
0
 public async Task<bool> SendNameRequest(string username, UserAccountEntity userAccountEntity)
 {
     try
     {
         var user = userAccountEntity.GetUserEntity();
         var param = new Dictionary<String, String>();
         var jsonObject = JsonConvert.SerializeObject(param);
         var stringContent = new StringContent(jsonObject, Encoding.UTF8, "application/json");
         var url = string.Format(EndPoints.SendNameRequest, user.Region, user.OnlineId, username);
         var result = await _webManager.PostData(new Uri(url), null, stringContent, userAccountEntity);
         return result.IsSuccess;
     }
     catch (Exception ex)
     {
         throw new Exception("Error sending name request", ex);
     }
 }
示例#23
0
 public async Task<string> GetFriendRequestMessage(string username, UserAccountEntity userAccountEntity)
 {
     try
     {
         var user = userAccountEntity.GetUserEntity();
         var url = string.Format(EndPoints.RequestMessage, user.Region, user.OnlineId, username);
         var result = await _webManager.GetData(new Uri(url), userAccountEntity);
         var o = JObject.Parse(result.ResultJson);
         return o["requestMessage"] != null ? (string)o["requestMessage"] : string.Empty;
     }
     catch (Exception ex)
     {
         throw new Exception("Error getting friend request message", ex);
     }
 }
示例#24
0
        public async Task<bool> CreatePostWithMedia(string messageUserId, string post, String path, byte[] fileStream,
            UserAccountEntity userAccountEntity)
        {
            try
            {
                var user = userAccountEntity.GetUserEntity();
                var url = string.Format(EndPoints.CreatePost, user.Region, messageUserId);
                const string boundary = "abcdefghijklmnopqrstuvwxyz";
                var messageJson = new SendMessage
                {
                    message = new Message()
                    {
                        body = post,
                        fakeMessageUid = 1384958573288,
                        messageKind = 1
                    }
                };

                var json = JsonConvert.SerializeObject(messageJson);
                var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
                stringContent.Headers.Add("Content-Description", "message");
                var form = new MultipartContent("mixed", boundary) { stringContent };

                Stream stream = new MemoryStream(fileStream);
                var t = new StreamContent(stream);
                var s = Path.GetExtension(path);
                if (s != null && s.Equals(".png"))
                {
                    t.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                }
                else
                {
                    var extension = Path.GetExtension(path);
                    if (extension != null && (extension.Equals(".jpg") || extension.Equals(".jpeg")))
                    {
                        t.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                    }
                    else
                    {
                        t.Headers.ContentType = new MediaTypeHeaderValue("image/gif");
                    }
                }
                t.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                t.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                t.Headers.Add("Content-Description", "image-data-0");
                t.Headers.Add("Content-Transfer-Encoding", "binary");
                t.Headers.ContentLength = stream.Length;
                form.Add(t);

                var result = await _webManager.PostData(new Uri(url), form, null, userAccountEntity);
                return result.IsSuccess;
            }
            catch (Exception ex)
            {

                throw new Exception("Failed to send post (with media)", ex);
            }
        }
示例#25
0
 public async Task<FriendTokenEntity> GetFriendLink(UserAccountEntity userAccountEntity)
 {
     try
     {
         var param = new Dictionary<string, string> { { "type", "ONE" } };
         var jsonObject = JsonConvert.SerializeObject(param);
         var stringContent = new StringContent(jsonObject, Encoding.UTF8, "application/json");
         var result = await _webManager.PostData(new Uri(EndPoints.FriendMeUrl), null, stringContent, userAccountEntity);
         var friend = JsonConvert.DeserializeObject<FriendTokenEntity>(result.ResultJson);
         return friend;
     }
     catch (Exception ex)
     {
         throw new Exception("Error getting friends link", ex);
     }
 }
示例#26
0
        public async Task<bool> CreatePost(string messageUserId, string post,
            UserAccountEntity userAccountEntity)
        {
            try
            {
                var user = userAccountEntity.GetUserEntity();
                var url = string.Format(EndPoints.CreatePost, user.Region, messageUserId);
                const string boundary = "abcdefghijklmnopqrstuvwxyz";
                var messageJson = new SendMessage
                {
                    message = new Message()
                    {
                        body = post,
                        fakeMessageUid = 1384958573288,
                        messageKind = 1
                    }
                };

                var json = JsonConvert.SerializeObject(messageJson);
                var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
                stringContent.Headers.Add("Content-Description", "message");
                var form = new MultipartContent("mixed", boundary) { stringContent };
                var result = await _webManager.PostData(new Uri(url), form, null, userAccountEntity);
                return result.IsSuccess;
            }
            catch (Exception ex)
            {

                throw new Exception("Failed to send post", ex);
            }
        }
示例#27
0
 public async Task<bool> DeleteMessageThread(string messageUserId, UserAccountEntity userAccountEntity)
 {
     try
     {
         var user = userAccountEntity.GetUserEntity();
         var url = string.Format(EndPoints.DeleteThread, user.Region, messageUserId, user.OnlineId);
         var result = await _webManager.DeleteData(new Uri(url), null, userAccountEntity);
         return result.IsSuccess;
     }
     catch (Exception ex)
     {
         throw new Exception("Failed to remove message thread", ex);
     }
 }
示例#28
0
        private async Task<UserAccountEntity> SendLoginData(string userName, string password)
        {
            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 8_1_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B440 Safari/600.1.4");
            httpClient.DefaultRequestHeaders.Add("Accept-Language", "ja-jp");
            httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
            var ohNoTest = await httpClient.GetAsync(new Uri(EndPoints.Login));

            httpClient.DefaultRequestHeaders.Referrer = new Uri("https://auth.api.sonyentertainmentnetwork.com/login.jsp?service_entity=psn&request_theme=liquid");
            httpClient.DefaultRequestHeaders.Add("Origin", "https://auth.api.sonyentertainmentnetwork.com");
            var nameValueCollection = new Dictionary<string, string>
                {
                { "params", "c2VydmljZV9lbnRpdHk9cHNuJnJlcXVlc3RfdGhlbWU9bGlxdWlk" },
                { "rememberSignIn", "On" },
                { "j_username", userName },
                { "j_password", password },
            };

            var form = new FormUrlEncodedContent(nameValueCollection);
            var response = await httpClient.PostAsync(EndPoints.LoginPost, form);
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to log in: " + response.StatusCode);
            }

            var codeUrl = response.RequestMessage.RequestUri;
            var queryString = UriExtensions.ParseQueryString(codeUrl.ToString());
            if (queryString.ContainsKey("authentication_error"))
            {
                throw new LoginFailedException("Wrong Username/Password");
            }
            if (!queryString.ContainsKey("targetUrl")) return null;
            queryString = UriExtensions.ParseQueryString(WebUtility.UrlDecode(queryString["targetUrl"]));
            if (!queryString.ContainsKey("code")) return null;

            var authManager = new AuthenticationManager();
            var authEntity = await authManager.RequestAccessToken(queryString["code"]);
            if (authEntity == null) return null;
             var userAccountEntity = new UserAccountEntity(authEntity.AccessToken, authEntity.RefreshToken);
             userAccountEntity = await LoginTest(userAccountEntity);

            return userAccountEntity;
        }
示例#29
0
 public async Task<Result> GetData(Uri uri, UserAccountEntity userAccountEntity)
 {
     var httpClient = new HttpClient();
     try
     {
         var authenticationManager = new AuthenticationManager();
         if (userAccountEntity.GetAccessToken().Equals("refresh"))
         {
             await authenticationManager.RefreshAccessToken(userAccountEntity);
         }
         var user = userAccountEntity.GetUserEntity();
         if (user != null)
         {
             var language = userAccountEntity.GetUserEntity().Language;
             httpClient.DefaultRequestHeaders.Add("Accept-Language", language);
         }
         httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
         var response = await httpClient.GetAsync(uri);
         if (response.StatusCode == HttpStatusCode.NotFound)
         {
             throw new WebException("PSN API Error: Service not found.");
         }
         var responseContent = await response.Content.ReadAsStringAsync();
         return string.IsNullOrEmpty(responseContent) ? new Result(false, string.Empty) : new Result(true, responseContent);
     }
     catch
     {
         throw new WebException("PSN API Error: Service not found.");
     }
 }
示例#30
0
 public async Task<UserAccountEntity> LoginTest(UserAccountEntity userAccountEntity)
 {
     var authManager = new AuthenticationManager();
     UserAccountEntity.User user = await authManager.GetUserEntity(userAccountEntity);
     if (user == null) return null;
     userAccountEntity.SetUserEntity(user);
     return userAccountEntity;
 }