Esempio n. 1
0
        public void Save_ReturnError()
        {
            const string json =
                @"{
   'error' : {
      'error_code' : 204,
      'error_msg' : 'Access denied: user was banned for this action, cant add video',
      'request_params' : [
         {
            'key' : 'oauth',
            'value' : '1'
         },
         {
            'key' : 'method',
            'value' : 'video.save'
         },
         
         {
            'key' : 'description',
            'value' : '123'
         },
         {
            'key' : 'group_id',
            'value' : '33905270'
         },
         {
            'key' : 'v',
            'value' : '5.64'
         }
      ]
   }
}";

            Assert.That(code: () => VkErrors.IfErrorThrowException(json: json), constraint: Throws.TypeOf <VideoAccessDeniedException>());
        }
Esempio n. 2
0
        public string Invoke(string methodName, IDictionary <string, string> parameters, bool skipAuthorization = false)
        {
            if (!skipAuthorization && !IsAuthorized)
            {
                throw new AccessTokenInvalidException();
            }

            // Защита от превышения кол-ва запросов в секунду
            if (RequestsPerSecond > 0 && LastInvokeTime.HasValue)
            {
                lock (_expireTimer)
                {
                    var span = LastInvokeTimeSpan.Value;
                    LastInvokeTime = DateTimeOffset.Now;
                    if (span.TotalMilliseconds < _minInterval)
                    {
                        Thread.Sleep(_minInterval - (int)span.TotalMilliseconds);
                    }
                }
            }

            var url = GetApiUrl(methodName, parameters);

            var answer = Browser.GetJson(url);

#if DEBUG && !UNIT_TEST
            Trace.WriteLine(Utilities.PreetyPrintApiUrl(url));
            Trace.WriteLine(Utilities.PreetyPrintJson(answer));
#endif
            VkErrors.IfErrorThrowException(answer);

            return(answer);
        }
Esempio n. 3
0
        public void IfErrorThrowException_WrongJson_ThrowVkApiException()
        {
            const string json = "ThisIsNotJson";

            This.Action(() => VkErrors.IfErrorThrowException(json)).Throws <VkApiException>()
            .Message.ShouldEqual("Wrong json data.");
        }
Esempio n. 4
0
        public void IfErrorThrowException_UserAuthorizationFail_ThrowUserAuthorizationFailExcption()
        {
            const string json =
                @"{
                    'error': {
                      'error_code': 5,
                      'error_msg': 'User authorization failed: invalid access_token.',
                      'request_params': [
                        {
                          'key': 'oauth',
                          'value': '1'
                        },
                        {
                          'key': 'method',
                          'value': 'getProfiles'
                        },
                        {
                          'key': 'uid',
                          'value': '1'
                        },
                        {
                          'key': 'access_token',
                          'value': 'sfastybdsjhdg'
                        }
                      ]
                    }
                  }";

            This.Action(() => VkErrors.IfErrorThrowException(json)).Throws <UserAuthorizationFailException>()
            .Message.ShouldEqual("User authorization failed: invalid access_token.");
        }
Esempio n. 5
0
        public void IfErrorThrowException_GroupAccessDenied_ThrowAccessDeniedException()
        {
            const string json =
                @"{
                    'error': {
                      'error_code': 260,
                      'error_msg': 'Access to the groups list is denied due to the user privacy settings.',
                      'request_params': [
                        {
                          'key': 'oauth',
                          'value': '1'
                        },
                        {
                          'key': 'method',
                          'value': 'getGroups'
                        },
                        {
                          'key': 'uid',
                          'value': '1'
                        },
                        {
                          'key': 'access_token',
                          'value': '2f3e43eb608a87632f68d140d82f5a9efa22f772f7765eb2f49f67514987c5e'
                        }
                      ]
                    }
                  }";

            This.Action(() => VkErrors.IfErrorThrowException(json)).Throws <AccessDeniedException>()
            .Message.ShouldEqual("Access to the groups list is denied due to the user privacy settings.");
        }
Esempio n. 6
0
        public void IfErrorThrowException_WrongJson_ThrowVkApiException()
        {
            const string json = "ThisIsNotJson";
            var          ex   = Assert.Throws <VkApiException>(code: () => VkErrors.IfErrorThrowException(json: json));

            Assert.That(actual: ex.Message, expression: Is.EqualTo(expected: "Wrong json data."));
        }
Esempio n. 7
0
        public string Invoke(string methodName, IDictionary <string, string> parameters, bool skipAuthorization = false)
        {
            if (!skipAuthorization)
            {
                IfNotAuthorizedThrowException();
            }

            // проверка на не более 3-х запросов в секунду
            if (_lastInvokeTime != null)
            {
                TimeSpan span = DateTimeOffset.Now - _lastInvokeTime.Value;
                if (span.TotalMilliseconds < MinInterval)
                {
                    System.Threading.Thread.Sleep(MinInterval - (int)span.TotalMilliseconds);
                }
            }

            string url = GetApiUrl(methodName, parameters);

            string answer = Browser.GetJson(url);

            _lastInvokeTime = DateTimeOffset.Now;

#if DEBUG && !UNIT_TEST
            Trace.WriteLine(Utilities.PreetyPrintApiUrl(url));
            Trace.WriteLine(Utilities.PreetyPrintJson(answer));
#endif
            VkErrors.IfErrorThrowException(answer);

            return(answer);
        }
Esempio n. 8
0
        public void IfErrorThrowException_UserAuthorizationFail_ThrowUserAuthorizationFailExcption()
        {
            const string json =
                @"{
                    'error': {
                      'error_code': 5,
                      'error_msg': 'User authorization failed: invalid access_token.',
                      'request_params': [
                        {
                          'key': 'oauth',
                          'value': '1'
                        },
                        {
                          'key': 'method',
                          'value': 'getProfiles'
                        },
                        {
                          'key': 'uid',
                          'value': '1'
                        },
                        {
                          'key': 'access_token',
                          'value': 'sfastybdsjhdg'
                        }
                      ]
                    }
                  }";

            var ex = Assert.Throws <UserAuthorizationFailException>(() => VkErrors.IfErrorThrowException(json));

            Assert.That(ex.Message, Is.EqualTo("User authorization failed: invalid access_token."));
            Assert.That(ex.ErrorCode, Is.EqualTo(5));
        }
Esempio n. 9
0
        public void IfErrorThrowException_WrongJson_ThrowVkApiException()
        {
            const string json = "ThisIsNotJson";
            var          ex   = Assert.Throws <VkApiException>(() => VkErrors.IfErrorThrowException(json));

            Assert.That(ex.Message, Is.EqualTo("Wrong json data."));
        }
Esempio n. 10
0
        public void IfErrorThrowException_GroupAccessDenied_ThrowAccessDeniedException()
        {
            const string json =
                @"{
                    'error': {
                      'error_code': 260,
                      'error_msg': 'Access to the groups list is denied due to the user privacy settings.',
                      'request_params': [
                        {
                          'key': 'oauth',
                          'value': '1'
                        },
                        {
                          'key': 'method',
                          'value': 'getGroups'
                        },
                        {
                          'key': 'uid',
                          'value': '1'
                        },
                        {
                          'key': 'access_token',
                          'value': '2f3e43eb608a87632f68d140d82f5a9efa22f772f7765eb2f49f67514987c5e'
                        }
                      ]
                    }
                  }";

            var ex = Assert.Throws <GroupsListAccessDeniedException>(() => VkErrors.IfErrorThrowException(json));

            StringAssert.AreEqualIgnoringCase("Access to the groups list is denied due to the user privacy settings."
                                              , ex.Message);
        }
Esempio n. 11
0
        public string Invoke(string methodName, IDictionary <string, string> parameters, bool skipAuthorization = false)
        {
            if (!skipAuthorization && !IsAuthorized)
            {
                var message = $"Метод '{methodName}' нельзя вызывать без авторизации";
                _logger?.Error(message: message);

                throw new AccessTokenInvalidException(message: message);
            }

            var url    = $"https://api.vk.com/method/{methodName}";
            var answer = "";

            void SendRequest(string method, IDictionary <string, string> @params)
            {
                LastInvokeTime = DateTimeOffset.Now;

                var response = RestClient.PostAsync(uri: new Uri(uriString: $"https://api.vk.com/method/{method}"), parameters: @params)
                               .Result;

                answer = response.Value ?? response.Message;
            }

            // Защита от превышения количества запросов в секунду
            if (RequestsPerSecond > 0 && LastInvokeTime.HasValue)
            {
                if (_expireTimer == null)
                {
                    SetTimer(expireTime: 0);
                }

                lock (_expireTimerLock)
                {
                    var span = LastInvokeTimeSpan?.TotalMilliseconds;

                    if (span < _minInterval)
                    {
                        var timeout = (int)_minInterval - (int)span;
                                        #if NET40
                        Thread.Sleep(millisecondsTimeout: timeout);
                                        #else
                        Task.Delay(millisecondsDelay: timeout).Wait();
                                        #endif
                    }

                    SendRequest(method: methodName, @params: parameters);
                }
            }
            else if (skipAuthorization)
            {
                SendRequest(method: methodName, @params: parameters);
            }

            _logger?.Trace(message: $"Uri = \"{url}\"");
            _logger?.Trace(message: $"Json ={Environment.NewLine}{Utilities.PreetyPrintJson(json: answer)}");

            VkErrors.IfErrorThrowException(json: answer);

            return(answer);
        }
Esempio n. 12
0
        // todo refactor this shit
        internal async Task <VkResponse> CallAsync(string methodName, VkParameters parameters, bool skipAuthorization = false)
        {
            if (!skipAuthorization)
            {
                IfNotAuthorizedThrowException();
            }

            string url = GetApiUrl(methodName, parameters);

            string answer = await Browser.GetJsonAsync(url);

#if DEBUG
            Trace.WriteLine(Utilities.PreetyPrintApiUrl(url));
            Trace.WriteLine(Utilities.PreetyPrintJson(answer));
#endif
            VkErrors.IfErrorThrowException(answer);

            JObject json = JObject.Parse(answer);

            var rawResponse = json["response"];

            return(new VkResponse(rawResponse)
            {
                RawJson = answer
            });
        }
Esempio n. 13
0
File: VkApi.cs Progetto: gsdu8g9/vk
        public string Invoke(string methodName, IDictionary <string, string> parameters, bool skipAuthorization = false)
        {
            if (!skipAuthorization && !IsAuthorized)
            {
                throw new AccessTokenInvalidException($@"Метод '{methodName}' нельзя вызывать без авторизации");
            }

            var url    = "";
            var answer = "";

            Action sendRequest = delegate
            {
                url            = GetApiUrlAndAddToken(methodName, parameters, skipAuthorization);
                LastInvokeTime = DateTimeOffset.Now;
                answer         = Browser.GetJson(url, parameters);
            };

            // Защита от превышения количества запросов в секунду
            if (RequestsPerSecond > 0 && LastInvokeTime.HasValue)
            {
                if (_expireTimer == null)
                {
                    SetTimer(0);
                }
                lock (_expireTimer)
                {
                    var span = LastInvokeTimeSpan?.TotalMilliseconds;
                    if (span < _minInterval)
                    {
                        var timeout = (int)_minInterval - (int)span;
#if UWP
                        Task.Delay(timeout).Wait();
#else
                        Thread.Sleep(timeout);
#endif
                    }
                    sendRequest();
                }
            }
            else if (skipAuthorization)
            {
                sendRequest();
            }

#if DEBUG && !UNIT_TEST
#if UWP
            Debug.WriteLine(Utilities.PreetyPrintApiUrl(url));
            Debug.WriteLine(Utilities.PreetyPrintJson(answer));
#else
            Trace.WriteLine(Utilities.PreetyPrintApiUrl(url));
            Trace.WriteLine(Utilities.PreetyPrintJson(answer));
#endif
#endif
            VkErrors.IfErrorThrowException(answer);

            return(answer);
        }
Esempio n. 14
0
        internal async Task <string> InvokeAsyncInternal(Uri uri, IDictionary <string, string> parameters, CancellationToken cancellationToken = default)
        {
            var response = await _restClient.PostAsync(uri, parameters).ConfigureAwait(false);

            var answer = response.Value ?? response.Message;

            VkAuthErrors.IfErrorThrowException(answer);
            VkErrors.IfErrorThrowException(answer);

            return(answer);
        }
Esempio n. 15
0
        private string Invoke(string url, VkParameters parameters)
        {
            var response = _restClient.GetAsync(new Uri(url), parameters)
                           .ConfigureAwait(false)
                           .GetAwaiter()
                           .GetResult();

            var answer = response.Value ?? response.Message;

            VkErrors.IfErrorThrowException(answer);
            return(answer);
        }
Esempio n. 16
0
        public string Invoke(string methodName, IDictionary <string, string> parameters, bool skipAuthorization = false)
        {
            if (!skipAuthorization && !IsAuthorized)
            {
                throw new AccessTokenInvalidException();
            }

            var url    = "";
            var answer = "";

            // Защита от превышения количества запросов в секунду
            if (RequestsPerSecond > 0 && LastInvokeTime.HasValue)
            {
                if (_expireTimer == null)
                {
                    SetTimer(0);
                }
                lock (_expireTimer)
                {
                    var span = LastInvokeTimeSpan?.TotalMilliseconds;
                    if (span < _minInterval)
                    {
                        Thread.Sleep((int)_minInterval - (int)span);
                    }
                    url            = GetApiUrl(methodName, parameters, skipAuthorization);
                    LastInvokeTime = DateTimeOffset.Now;
                    answer         = Browser.GetJson(url.Replace("\'", "%27"));
                }
            }
            else if (skipAuthorization)
            {
                url            = GetApiUrl(methodName, parameters, skipAuthorization: true);
                LastInvokeTime = DateTimeOffset.Now;
                answer         = Browser.GetJson(url.Replace("\'", "%27"));
            }


#if DEBUG && !UNIT_TEST
            Trace.WriteLine(Utilities.PreetyPrintApiUrl(url));
            Trace.WriteLine(Utilities.PreetyPrintJson(answer));
#endif
            VkErrors.IfErrorThrowException(answer);

            return(answer);
        }
Esempio n. 17
0
        public void Post_ReturnValidateNeeded()
        {
            Url = "https://api.vk.com/method/wall.post";

            Json =
                @"
                {
                    'error' : {
                    'error_code' : 17,
                    'error_msg' : 'Validation required: please open redirect_uri in browser',
                    'redirect_uri' : 'https://m.vk.com/activation?act=validate&api_hash=****&hash=***',
                    'request_params' : [
                        {
                        'key' : 'oauth',
                        'value' : '1'
                        },
                        {
                        'key' : 'method',
                        'value' : 'wall.post'
                        },
                        {
                        'key' : 'owner_id',
                        'value' : '-153877099'
                        },
                        {
                        'key' : 'from_group',
                        'value' : '1'
                        },
                        {
                        'key' : 'message',
                        'value' : 'Test'
                        },
                        {
                        'key' : 'v',
                        'value' : '5.64'
                        }
                    ]
                    }
                 }
                 ";

            Assert.That(() => VkErrors.IfErrorThrowException(Json), Throws.TypeOf <NeedValidationException>());
        }
Esempio n. 18
0
        public void IfErrorThrowException_NormalCase_NothingExceptions()
        {
            const string json =
                @"{
                    'response': [
                      {
                        'uid': 1,
                        'first_name': 'Павел',
                        'last_name': 'Дуров',
                        'university': '1',
                        'university_name': 'СПбГУ',
                        'faculty': '0',
                        'faculty_name': '',
                        'graduation': '0'
                      }
                    ]
                  }";

            VkErrors.IfErrorThrowException(json);
        }
Esempio n. 19
0
        public void IfErrorThrowException_WrongJson_ThrowVkApiException()
        {
            const string json = "ThisIsNotJson";

            VkErrors.IfErrorThrowException(json);
        }