コード例 #1
0
        public void GetProfileInfo(long userId, Action <BackendResult <UserData, ResultCode> > callback)
        {
            Dictionary <string, string> parameters = new Dictionary <string, string>();

            /*
             * parameters["userId"] = userId.ToString();
             * parameters["func_v"] = "3";
             * VKRequestsDispatcher.DispatchRequestToVK<UserData>("execute.getProfileInfo", parameters, callback, (Func<string, UserData>)(jsonStr =>
             * {
             *  jsonStr = VKRequestsDispatcher.FixFalseArray(jsonStr, "relatives", false);
             *  jsonStr = VKRequestsDispatcher.FixFalseArray(jsonStr, "wallData", true);
             *  jsonStr = VKRequestsDispatcher.FixFalseArray(jsonStr, "Groups", false);
             *  jsonStr = VKRequestsDispatcher.FixArrayToObject(jsonStr, "personal");
             *  jsonStr = VKRequestsDispatcher.FixArrayToObject(jsonStr, "occupation");
             *  jsonStr = VKRequestsDispatcher.FixFalseArray(jsonStr, "photos", true);
             *  jsonStr = VKRequestsDispatcher.FixFalseArray(jsonStr, "subscriptions", true);
             *  jsonStr = VKRequestsDispatcher.FixFalseArray(jsonStr, "gifts", true);
             *  int resultCount;
             *  jsonStr = VKRequestsDispatcher.GetArrayCountAndRemove(jsonStr, "wall", out resultCount);
             *  VKRequestsDispatcher.GenericRoot<UserData> genericRoot = JsonConvert.DeserializeObject<VKRequestsDispatcher.GenericRoot<UserData>>(jsonStr);
             *  if (genericRoot.response.user.counters.docs == 0)
             *      genericRoot.response.user.counters.docs = genericRoot.response.docsCount;
             *  return genericRoot.response;
             * }), false, true, new CancellationToken?(), null);*/
            parameters["user_id"]     = userId.ToString();
            parameters["func_v"]      = "2";
            parameters["photo_count"] = "25";
            parameters["gift_count"]  = "25";
            parameters["photo_sizes"] = "1";
            parameters["skip_hidden"] = "1";

            Action <BackendResult <User, ResultCode> > act = (ud) =>
            {
                BackendResult <UserData, ResultCode> res = new BackendResult <UserData, ResultCode>();
                res.ResultData        = new UserData();
                res.ResultData.user   = ud.ResultData;
                res.ResultData.gifts  = ud.ResultData.gifts;
                res.ResultData.photos = ud.ResultData.photos;
                res.ResultCode        = ResultCode.Succeeded;
                callback(res);
            };

            VKRequestsDispatcher.DispatchRequestToVK <User>("execute.getFullProfileNewNew", parameters, act, (Func <string, User>)(jsonStr =>
            {
                //"status":{"text":"На пути достижения цели..."}
                Regex r     = new Regex(".+(\"status\":{\"text\":\"(.*?)\"})");
                Match m     = r.Match(jsonStr);
                string str1 = m.Groups[1].Value;
                string str2 = m.Groups[2].Value;
                jsonStr     = jsonStr.Replace(str1, "\"status\":\"" + str2 + "\"");

                VKRequestsDispatcher.GenericRoot <User> genericRoot = JsonConvert.DeserializeObject <VKRequestsDispatcher.GenericRoot <User> >(jsonStr);
                return(genericRoot.response);
            }), false, true, new CancellationToken?(), null);
        }
コード例 #2
0
 private static void DoDispatch <R>(string baseUrl, string methodName, Dictionary <string, string> parameters, Action <BackendResult <R, ResultCode> > callback, Func <string, R> customDeserializationFunc = null, bool lowPriority = false, bool pageDataRequest = true, CancellationToken?cancellationToken = null, Action confirmationRequiredHandler = null)
 {
     parameters["v"] = VKConstants.API_VERSION;
     if (!string.IsNullOrEmpty(VKRequestsDispatcher._autorizationData != null ? VKRequestsDispatcher._autorizationData.access_token : null))
     {
         parameters["access_token"] = VKRequestsDispatcher._autorizationData.access_token;
     }
     VKRequestsDispatcher.AddLangParameter(parameters);
     if (!string.IsNullOrEmpty(VKRequestsDispatcher._autorizationData != null ? VKRequestsDispatcher._autorizationData.secret : null))
     {
         if (parameters.ContainsKey("sig"))
         {
             parameters.Remove("sig");
         }
         string str1 = JsonWebRequest.ConvertDictionaryToQueryString(parameters, false);
         if (str1 != string.Empty)
         {
             str1 = "?" + str1;
         }
         string str2 = VKRequestsDispatcher.HashString("/method/" + methodName + str1 + VKRequestsDispatcher._autorizationData.secret);
         parameters["sig"] = str2.ToLower();
     }
     JsonWebRequest.SendHTTPRequestAsync(!VKRequestsDispatcher.USE_HTTP ? "https://" + baseUrl : "http://" + baseUrl, parameters, (Action <JsonResponseData>)(jsonResp =>
     {
         BackendResult <R, ResultCode> backendResult = new BackendResult <R, ResultCode>(ResultCode.CommunicationFailed);
         if (jsonResp.IsSucceeded)
         {
             VKRequestsDispatcher.ResultData resultFromJson = VKRequestsDispatcher.GetResultFromJson(JObject.Parse(jsonResp.JsonString));
             backendResult.ResultCode = resultFromJson.ResultCode;
             backendResult.Error      = resultFromJson.error;
             if (backendResult.ResultCode == ResultCode.UserAuthorizationFailed)
             {
                 if (!string.IsNullOrEmpty(VKRequestsDispatcher._autorizationData != null ? VKRequestsDispatcher._autorizationData.access_token : null))
                 {
                     Logger.Instance.Error("RECEIVED AUTHORIZATION FAILURE!!! JSON STR = " + jsonResp.JsonString ?? "");
                     LogoutRequestHandler.InvokeLogoutRequest();
                 }
             }
             if (backendResult.ResultCode == ResultCode.CaptchaRequired)
             {
                 CaptchaUserRequestHandler.InvokeCaptchaRequest(new CaptchaUserRequest()
                 {
                     CaptchaSid = resultFromJson.captcha_sid,
                     Url        = resultFromJson.captcha_img
                 }, (Action <CaptchaUserResponse>)(captchaResp =>
                 {
                     if (!captchaResp.IsCancelled)
                     {
                         Dictionary <string, string> parameters1 = parameters;
                         parameters1["captcha_sid"] = captchaResp.Request.CaptchaSid;
                         parameters1["captcha_key"] = captchaResp.EnteredString;
                         VKRequestsDispatcher.DoDispatch <R>(baseUrl, methodName, parameters1, callback, customDeserializationFunc, lowPriority, pageDataRequest, cancellationToken, null);
                     }
                     else
                     {
                         VKRequestsDispatcher.InvokeCallback((Action)(() => callback(new BackendResult <R, ResultCode>(ResultCode.CaptchaControlCancelled))), cancellationToken);
                     }
                 }));
             }
             else if (backendResult.ResultCode == ResultCode.ValidationRequired)
             {
                 if (resultFromJson.validation_type == "2fa_app" || resultFromJson.validation_type == "2fa_sms")
                 {
                     if (parameters.ContainsKey("force_sms") || parameters.ContainsKey("code"))
                     {
                         R r = customDeserializationFunc != null ? customDeserializationFunc("") : default(R);
                         VKRequestsDispatcher.InvokeCallback((Action)(() => callback(new BackendResult <R, ResultCode>(ResultCode.Succeeded, r))), cancellationToken);
                     }
                     else
                     {
                         CaptchaUserRequestHandler.InvokeValidation2FARequest(new Validation2FAUserRequest()
                         {
                             username       = parameters.ContainsKey("username") ? parameters["username"] : "",
                             password       = parameters.ContainsKey("password") ? parameters["password"] : "",
                             phoneMask      = resultFromJson.phone_mask,
                             validationType = resultFromJson.validation_type,
                             validationSid  = resultFromJson.validation_sid
                         }, (Action <ValidationUserResponse>)(valResp => VKRequestsDispatcher.ProcessValidationResponse <R>(valResp, baseUrl, methodName, parameters, callback, customDeserializationFunc, lowPriority, pageDataRequest, cancellationToken)));
                     }
                 }
                 else
                 {
                     CaptchaUserRequestHandler.InvokeValidationRequest(new ValidationUserRequest()
                     {
                         ValidationUri = resultFromJson.redirect_uri
                     }, (Action <ValidationUserResponse>)(valResp => VKRequestsDispatcher.ProcessValidationResponse <R>(valResp, baseUrl, methodName, parameters, callback, customDeserializationFunc, lowPriority, pageDataRequest, cancellationToken)));
                 }
             }
             else if (backendResult.ResultCode == ResultCode.ConfirmationRequired)
             {
                 if (!VKRequestsDispatcher.GetIsResponseCancelled(cancellationToken))
                 {
                     Action action = confirmationRequiredHandler;
                     if (action != null)
                     {
                         action();
                     }
                     IBackendConfirmationHandler confirmationHandler = ServiceLocator.Resolve <IBackendConfirmationHandler>();
                     if (confirmationHandler != null)
                     {
                         confirmationHandler.Confirm(resultFromJson.confirmation_text, (Action <bool>)(confirmed =>
                         {
                             if (confirmed)
                             {
                                 parameters["confirm"] = "1";
                                 VKRequestsDispatcher.DoDispatch <R>(baseUrl, methodName, parameters, callback, customDeserializationFunc, lowPriority, pageDataRequest, cancellationToken, null);
                             }
                             else
                             {
                                 VKRequestsDispatcher.InvokeCallback((Action)(() => callback(new BackendResult <R, ResultCode>(ResultCode.ConfirmationCancelled))), cancellationToken);
                             }
                         }));
                     }
                 }
             }
             else if (backendResult.ResultCode == ResultCode.NotEnoughMoney)
             {
                 if (!VKRequestsDispatcher.GetIsResponseCancelled(cancellationToken))
                 {
                     IBackendNotEnoughMoneyHandler enoughMoneyHandler = ServiceLocator.Resolve <IBackendNotEnoughMoneyHandler>();
                     Action action1 = (() => VKRequestsDispatcher.DoDispatch <R>(baseUrl, methodName, parameters, callback, customDeserializationFunc, lowPriority, pageDataRequest, cancellationToken, null));
                     Action action2 = (Action)(() => VKRequestsDispatcher.InvokeCallback((Action)(() => callback(new BackendResult <R, ResultCode>(ResultCode.BalanceRefillCancelled))), cancellationToken));
                     if (enoughMoneyHandler != null)
                     {
                         Action refilledCallback  = action1;
                         Action cancelledCallback = action2;
                         enoughMoneyHandler.RequestBalanceRefill(refilledCallback, cancelledCallback);
                     }
                 }
             }
             else if (backendResult.ResultCode == ResultCode.Succeeded)
             {
                 try
                 {
                     List <ExecuteError> executeErrorList = null;
                     R r;
                     if (customDeserializationFunc != null)
                     {
                         r = customDeserializationFunc(jsonResp.JsonString);
                     }
                     else if (typeof(R) == typeof(VKClient.Common.Backend.DataObjects.ResponseWithId))
                     {
                         r = JsonConvert.DeserializeObject <R>(jsonResp.JsonString);
                     }
                     else
                     {
                         VKRequestsDispatcher.GenericRoot <R> genericRoot = JsonConvert.DeserializeObject <VKRequestsDispatcher.GenericRoot <R> >(jsonResp.JsonString);
                         r = genericRoot.response;
                         executeErrorList = genericRoot.execute_errors;
                     }
                     backendResult.ResultData    = r;
                     backendResult.ExecuteErrors = executeErrorList;
                 }
                 catch (Exception ex)
                 {
                     Logger.Instance.Error("Error during deserialization", ex);
                     backendResult.ResultCode = ResultCode.DeserializationError;
                 }
             }
         }
         if (backendResult.ResultCode == ResultCode.CaptchaRequired || backendResult.ResultCode == ResultCode.ValidationRequired || (backendResult.ResultCode == ResultCode.ConfirmationRequired || backendResult.ResultCode == ResultCode.NotEnoughMoney))
         {
             return;
         }
         VKRequestsDispatcher.InvokeCallback((Action)(() =>
         {
             Action <BackendResult <R, ResultCode> > action = callback;
             if (action == null)
             {
                 return;
             }
             BackendResult <R, ResultCode> backendResult1 = backendResult;
             action(backendResult1);
         }), cancellationToken);
     }), true, lowPriority, pageDataRequest);
 }
コード例 #3
0
 public void GetUsers(List <long> userIds, Action <BackendResult <List <User>, ResultCode> > callback)
 {
     if (userIds == null || userIds.Count == 0)
     {
         callback(new BackendResult <List <User>, ResultCode>()
         {
             ResultCode = ResultCode.Succeeded,
             ResultData = new List <User>()
         });
     }
     else
     {
         List <User> resultData = new List <User>();
         bool        flag       = true;
         foreach (long userId in userIds)
         {
             DateTime now = DateTime.Now;
             if (this.GetCachedUser(userId) != null)
             {
                 resultData.Add(this._usersCache[userId]);
             }
             else
             {
                 flag = false;
                 break;
             }
         }
         if (flag)
         {
             Logger.Instance.Info("Returning {0} users from cache", resultData.Count);
             callback(new BackendResult <List <User>, ResultCode>(ResultCode.Succeeded, resultData));
         }
         else
         {
             string allUserIds = userIds.GetCommaSeparated();
             if (this._callbacksToExecute.ContainsKey(allUserIds))
             {
                 this._callbacksToExecute[allUserIds].Add(callback);
             }
             else
             {
                 this._callbacksToExecute.Add(allUserIds, new List <Action <BackendResult <List <User>, ResultCode> > >()
                 {
                     callback
                 });
                 Dictionary <string, string> dictionary = new Dictionary <string, string>()
                 {
                     {
                         "user_ids",
                         allUserIds
                     },
                     {
                         "fields",
                         "uid,first_name,last_name,online,online_mobile,photo_max,sex,photo_medium,friend_status"
                     }
                 };
                 VKRequestsDispatcher.Execute <UsersAndGroups>(string.Format("\r\nvar userIds = \"{0}\";\r\nvar groupIds = \"{1}\";\r\n\r\nvar users = [];\r\nvar groups = [];\r\n\r\nif (userIds.length > 0)\r\n{{\r\n   users = API.users.get({{\"user_ids\":userIds, \"fields\":\"uid,first_name,last_name,online,online_mobile,photo_max,sex,photo_medium,friend_status,first_name_dat\" }});\r\n}}\r\n\r\nif (groupIds.length > 0)\r\n{{\r\n   groups = API.groups.getById({{\"group_ids\":groupIds, \"fields\":\"photo_200,is_messages_blocked\"}});\r\n}}\r\n\r\nreturn {{\"users\":users, \"groups\":groups}};", userIds.Where <long>((Func <long, bool>)(uid => uid > 0L)).ToList <long>().GetCommaSeparated(), userIds.Where <long>((Func <long, bool>)(uid =>
                 {
                     if (uid < 0L)
                     {
                         return(uid > -2000000000L);
                     }
                     return(false);
                 })).Select <long, long>((Func <long, long>)(uid => - uid)).ToList <long>().GetCommaSeparated()), (Action <BackendResult <UsersAndGroups, ResultCode> >)(res =>
                 {
                     if (res.ResultCode == ResultCode.Succeeded)
                     {
                         foreach (VKClient.Common.Backend.DataObjects.Group group in res.ResultData.groups)
                         {
                             User user = new User();
                             user.InitFromGroup(group);
                             res.ResultData.users.Add(user);
                         }
                         foreach (User user in res.ResultData.users)
                         {
                             this.SetCachedUser(user);
                         }
                     }
                     BackendResult <List <User>, ResultCode> backendResult = new BackendResult <List <User>, ResultCode>();
                     backendResult.ResultCode = res.ResultCode;
                     if (res.ResultData != null)
                     {
                         backendResult.ResultData = res.ResultData.users;
                     }
                     foreach (Action <BackendResult <List <User>, ResultCode> > action in this._callbacksToExecute[allUserIds])
                     {
                         action(backendResult);
                     }
                     this._callbacksToExecute.Remove(allUserIds);
                 }), null, false, true, new CancellationToken?());
             }
         }
     }
 }