Files
kami_itunes_june/AppleBatch_June.AppleWebServace/AppleWebBase.cs
2024-07-22 00:43:14 +08:00

1128 lines
42 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using AppleBatch_June.ExecuteTasks;
using AppleBatch_June.Model;
using AppleBatch_June.Utils;
using DotNet.Utilities;
namespace AppleBatch_June.AppleWebServace
{
public class AppleWebBase
{
public List<CookieItem> listCookie = new List<CookieItem>();
protected Dictionary<string, string> handelDic = new Dictionary<string, string>();
public Action<string, DisplyType, string> action;
protected Action<string, DisplyType, string> applyAtion;
public ITaskRunState taskState;
protected string loginDomainId = "";
protected string apiKey { get; set; } = "cbf64fd6843ee630b463f358ea0b707b";
protected string userAgent { get; set; }
public bool openVpn { get; set; }
public string ProxyIp { get; set; } = "";
public string noticeKey { get; set; } = "";
protected int MaxRetryCount { get; set; } = 5;
public bool isUpProxyAccountCache { get; set; } = true;
protected bool fristGetProxy { get; set; }
public AppleWebBase(Action<string, DisplyType, string> _action, Action<string, DisplyType, string> _applyAtion, ITaskRunState _taskState)
{
taskState = _taskState ?? throw new Exception("任务运行状态不能是空的");
action = _action;
applyAtion = _applyAtion;
userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36";
userAgent = Tools.GetRandomUserAgent();
}
public void logout(AuthsigninConfig authsignin)
{
WebHeaderCollection webHeaderCollection = new WebHeaderCollection();
webHeaderCollection.AddWebHander("Upgrade-Insecure-Requests", "1");
string postData = "";
string url = "https://buy.apps.apple.com/account/web/logout";
postWebContent(url, postData, authsignin.refererUrl, webHeaderCollection);
}
protected bool authsignin(string appleId, string applePwd, AuthsigninConfig authsignin, ref string errMsg, out HttpResult result, Dictionary<string, string> addHanders = null)
{
errMsg = "未知错误";
string url = "https://idmsa.apple.com/appleauth/auth/authorize/signin?frame_id=" + Tools.ToUrlEncode(authsignin.iframeId) + "&skVersion=7&iframeId=" + Tools.ToUrlEncode(authsignin.iframeId) + "&client_id=" + authsignin.Apple_Widget_Key + "&redirect_uri=" + authsignin.redirectURI + "&response_type=code&response_mode=web_message&state=" + Tools.ToUrlEncode(authsignin.iframeId) + "&authVersion=latest";
WebHeaderCollection webHeaderCollection = new WebHeaderCollection();
webHeaderCollection.AddWebHander("Upgrade-Insecure-Requests", "1");
HttpResult webContent = getWebContent(url, "https://appleid.apple.com/", webHeaderCollection, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", "application/x-www-form-urlencoded");
if (webContent.StatusCode == HttpStatusCode.OK)
{
string text = new Regex("domainId\":([\\s\\S]*?),").Match(webContent.Html).Groups[1].Value.Trim();
loginDomainId = text;
string text2 = "";
string[] allKeys = webContent.Header.AllKeys;
foreach (string text3 in allKeys)
{
if (text3 == "X-Apple-Auth-Attributes" || text3 == "scnt")
{
handelDic.TryAddDic(text3, webContent.Header[text3]);
}
}
if (webContent.Header.AllKeys.Contains("X-Apple-HC-Bits") && webContent.Header.AllKeys.Contains("X-Apple-HC-Challenge"))
{
string text4 = webContent.Header["X-Apple-HC-Bits"];
string text5 = webContent.Header["X-Apple-HC-Challenge"];
string text6 = "1:" + text4 + ":" + DateTime.UtcNow.ToString("yyyyMMddHHmmss") + ":" + text5 + "::";
string text7 = APIUtlis.ApiGetCodeHC(text6);
if (!string.IsNullOrEmpty(text7))
{
text2 = text6 + text7;
}
}
if (!string.IsNullOrEmpty(text2))
{
string refM = "";
string refM2 = "";
string token = "";
bool flag = false;
while (true)
{
action?.Invoke(noticeKey, DisplyType.xinxi, "正在登录.");
if (!signinInit(appleId, applePwd, authsignin, ref refM, ref refM2, ref token, addHanders))
{
break;
}
action?.Invoke(noticeKey, DisplyType.xinxi, "验证登录密码");
string postData = "{\"accountName\":\"" + appleId + "\",\"rememberMe\":false,\"m1\":\"" + refM + "\",\"c\":\"" + token + "\",\"m2\":\"" + refM2 + "\"}";
WebHeaderCollection webHeaderCollection2 = new WebHeaderCollection();
if (handelDic.ContainsKey("scnt"))
{
webHeaderCollection2.AddWebHander("scnt", handelDic["scnt"]);
}
webHeaderCollection2.AddWebHander("X-Apple-Auth-Attributes", handelDic.getDicVal("X-Apple-Auth-Attributes", ""));
webHeaderCollection2.AddWebHander("X-Apple-Widget-Key", authsignin.Apple_Widget_Key);
webHeaderCollection2.AddWebHander("X-Requested-With", "XMLHttpRequest");
addOAuthHanede(webHeaderCollection2, authsignin);
if (addHanders != null)
{
foreach (KeyValuePair<string, string> addHander in addHanders)
{
webHeaderCollection2.AddWebHander(addHander.Key, addHander.Value);
}
}
webHeaderCollection2.AddWebHander("X-APPLE-HC", text2);
string appleIFDClientInfo = FDClientInfoHelp.getAppleIFDClientInfo(userAgent);
webHeaderCollection2.AddWebHander("X-Apple-I-FD-Client-Info", appleIFDClientInfo);
string url2 = "https://idmsa.apple.com/appleauth/auth/signin/complete?isRememberMeEnabled=true";
HttpResult httpResult = postWebContent(url2, postData, authsignin.refererUrl, webHeaderCollection2);
if (httpResult.StatusCode != HttpStatusCode.BadGateway)
{
if (httpResult.StatusCode == HttpStatusCode.Unauthorized || httpResult.StatusCode == HttpStatusCode.Forbidden)
{
result = httpResult;
LoginErrorModel loginErrorModel = Tools.Todejosn<LoginErrorModel>(httpResult.Html);
if (loginErrorModel.serviceErrors != null)
{
if (loginErrorModel.serviceErrors.Length != 0)
{
errMsg = loginErrorModel.serviceErrors[0].message;
action?.Invoke(noticeKey, DisplyType.xinxi, loginErrorModel.serviceErrors[0].message);
if (errMsg.Contains("密码不正确") && !flag)
{
flag = true;
continue;
}
flag = false;
}
else
{
action?.Invoke(noticeKey, DisplyType.xinxi, errMsg);
}
}
else
{
action?.Invoke(noticeKey, DisplyType.xinxi, errMsg);
}
return false;
}
if (httpResult.StatusCode != HttpStatusCode.Conflict && httpResult.StatusCode != HttpStatusCode.OK)
{
if (httpResult.StatusCode == HttpStatusCode.PreconditionFailed)
{
action?.Invoke(noticeKey, DisplyType.xinxi, "密码验证成功");
result = httpResult;
return true;
}
action?.Invoke(noticeKey, DisplyType.xinxi, errMsg + "(" + (int)httpResult.StatusCode + ")");
result = null;
return false;
}
action?.Invoke(noticeKey, DisplyType.xinxi, "密码验证成功");
allKeys = httpResult.Header.AllKeys;
foreach (string text8 in allKeys)
{
switch (text8)
{
case "X-Apple-Auth-Attributes":
case "X-Apple-Repair-Session-Token":
case "X-Apple-ID-Session-Id":
case "scnt":
case "X-Apple-OAuth-Context":
case "X-Apple-ID-Account-Country":
if (text8 == "scnt")
{
handelDic.TryAddDic("scnt2", httpResult.Header[text8]);
}
handelDic.TryAddDic(text8, httpResult.Header[text8]);
break;
}
}
result = httpResult;
return true;
}
errMsg = "服务器拒绝,请使用代理,IP可能已被拉黑";
action?.Invoke(noticeKey, DisplyType.xinxi, errMsg);
result = httpResult;
return false;
}
result = null;
return false;
}
action?.Invoke(noticeKey, DisplyType.xinxi, "登录失败#Hc:AppleService返回:" + (int)webContent.StatusCode);
result = null;
return false;
}
action?.Invoke(noticeKey, DisplyType.xinxi, "登录失败:AppleService返回:" + (int)webContent.StatusCode);
result = null;
return false;
}
protected string getServiceError(ServiceErrorsModel serviceErrors)
{
if (serviceErrors != null)
{
if (serviceErrors.validationErrors != null && serviceErrors.validationErrors.Length != 0)
{
return serviceErrors.validationErrors[0].message;
}
if (serviceErrors.service_errors != null && serviceErrors.service_errors.Length != 0)
{
return serviceErrors.service_errors[0].message;
}
if (serviceErrors.serviceErrors != null && serviceErrors.serviceErrors.Length != 0)
{
return serviceErrors.serviceErrors[0].message;
}
}
return "";
}
protected bool baseRepair(string appleId, AuthsigninConfig authsigninConfig)
{
action?.Invoke(noticeKey, DisplyType.xinxi, "获取阅读协议");
string text = "zh_CN_CHN";
if (handelDic.ContainsKey("X-Apple-Locale"))
{
text = handelDic["X-Apple-Locale"];
}
WebHeaderCollection webHeaderCollection = new WebHeaderCollection();
webHeaderCollection.AddWebHander("Upgrade-Insecure-Requests", "1");
webHeaderCollection.AddWebHander("X-Apple-Widget-Key", authsigninConfig.Apple_Widget_Key);
string uRL = "https://appleid.apple.com/widget/account/repair?widgetKey=" + authsigninConfig.Apple_Widget_Key + "&rv=1&language=" + text;
HttpItem httpItem = new HttpItem
{
URL = uRL,
Method = "get",
Timeout = 120000,
ReadWriteTimeout = 30000,
UserAgent = userAgent,
Cookie = listCookie.toFonmtCookie(),
ContentType = "text/html;charset=UTF-8",
Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
Referer = "https://idmsa.apple.com/",
ResultType = ResultType.String,
ProtocolVersion = HttpVersion.Version11,
WebProxy = WebRequest.DefaultWebProxy
};
httpItem.Header = webHeaderCollection;
addHander(httpItem);
HttpResult httpReuslt = GetHttpReuslt(httpItem);
if (httpReuslt.StatusCode == HttpStatusCode.OK)
{
string value = new Regex(AppSysConfig.getConfig("Regex_repair_sessionId")).Match(httpReuslt.Html).Groups[1].Value.Trim().Replace("\n", "").Replace("\r", "")
.Replace("\"", "")
.TrimStart(':')
.Trim();
string key = "repairSessionId";
if (!handelDic.ContainsKey(key))
{
handelDic.TryAddDic(key, value);
}
else
{
handelDic[key] = value;
}
string[] allKeys = httpReuslt.Header.AllKeys;
foreach (string text2 in allKeys)
{
if (text2 == "scnt")
{
if (!handelDic.ContainsKey(text2))
{
handelDic.TryAddDic(text2, httpReuslt.Header[text2]);
}
else
{
handelDic[text2] = httpReuslt.Header[text2];
}
}
if (text2 == "X-Apple-Repair-Session-Token")
{
if (!handelDic.ContainsKey(text2))
{
handelDic.TryAddDic(text2, httpReuslt.Header[text2]);
}
else
{
handelDic[text2] = httpReuslt.Header[text2];
}
}
}
action?.Invoke(noticeKey, DisplyType.xinxi, "协议获取成功");
return baseOptions(appleId, authsigninConfig);
}
action?.Invoke(noticeKey, DisplyType.xinxi, "协议获取失败");
return false;
}
private bool baseOptions(string appleId, AuthsigninConfig authsigninConfig, bool skieprderPrivacy = false)
{
WebHeaderCollection webHeaderCollection = new WebHeaderCollection();
webHeaderCollection.AddWebHander("X-Requested-With", "XMLHttpRequest");
webHeaderCollection.AddWebHander("scnt", handelDic["scnt"]);
webHeaderCollection.AddWebHander("X-Apple-Skip-Repair-Attributes", "[]");
webHeaderCollection.AddWebHander("X-Apple-OAuth-Context", handelDic.getDicVal("X-Apple-OAuth-Context", ""));
string dicVal = handelDic.getDicVal("X-Apple-Session-Token", "");
if (string.IsNullOrEmpty(dicVal))
{
dicVal = handelDic.getDicVal("X-Apple-Repair-Session-Token", "");
}
webHeaderCollection.AddWebHander("X-Apple-Session-Token", dicVal);
webHeaderCollection.AddWebHander("X-Apple-Locale", authsigninConfig.homeLanguage);
webHeaderCollection.AddWebHander("X-Apple-ID-Session-Id", handelDic.getDicVal("X-Apple-ID-Session-Id", ""));
webHeaderCollection.AddWebHander("X-Apple-Widget-Key", authsigninConfig.Apple_Widget_Key);
string appleIFDClientInfo = FDClientInfoHelp.getAppleIFDClientInfo(userAgent);
webHeaderCollection.AddWebHander("X-Apple-I-FD-Client-Info", appleIFDClientInfo);
string uRL = "https://appleid.apple.com/account/manage/repair/options";
HttpItem httpItem = new HttpItem
{
URL = uRL,
Method = "get",
Timeout = 120000,
ReadWriteTimeout = 30000,
UserAgent = userAgent,
Cookie = listCookie.toFonmtCookie(),
ContentType = "application/json; charset=utf-8",
Accept = "application/json, text/javascript, */*; q=0.01",
Referer = "https://appleid.apple.com/widget/account/repair?widgetKey=" + authsigninConfig.Apple_Widget_Key + "&rv=1&language=zh_CN_CHN",
ResultType = ResultType.String,
ProtocolVersion = HttpVersion.Version11,
WebProxy = WebRequest.DefaultWebProxy
};
httpItem.Header = webHeaderCollection;
addHander(httpItem);
HttpResult httpReuslt = GetHttpReuslt(httpItem);
if (httpReuslt.StatusCode == HttpStatusCode.OK)
{
string[] allKeys = httpReuslt.Header.AllKeys;
foreach (string text in allKeys)
{
if (text == "X-Apple-Session-Token" || text == "scnt")
{
handelDic.TryAddDic(text, httpReuslt.Header[text]);
}
}
Dictionary<string, object> dictionary = Tools.Todejosn<Dictionary<string, object>>(httpReuslt.Html);
if (httpReuslt.Html.Contains("requiredSteps"))
{
foreach (object item in (dynamic)dictionary["requiredSteps"])
{
string text2 = (string)(dynamic)item;
if (!(text2 == "privacy_consent") || baseAccept(appleId, authsigninConfig.Apple_Widget_Key, authsigninConfig.homeLanguage))
{
if (text2 == "crossBorderPrivacyConsent")
{
bool gcbdCrossBorderPrivacyConsentRequired = false;
bool appleCrossBorderPrivacyConsentRequired = false;
try
{
dynamic val = dictionary["repairContext"];
gcbdCrossBorderPrivacyConsentRequired = val["privacyConsentRequirement"]["gcbdCrossBorderPrivacyConsentRequired"];
appleCrossBorderPrivacyConsentRequired = val["privacyConsentRequirement"]["appleCrossBorderPrivacyConsentRequired"];
}
catch (Exception)
{
}
if (CrossBorderPrivacyConsent(appleId, authsigninConfig.Apple_Widget_Key, authsigninConfig.homeLanguage, gcbdCrossBorderPrivacyConsentRequired, appleCrossBorderPrivacyConsentRequired))
{
return false;
}
return baseOptions(appleId, authsigninConfig, skieprderPrivacy: true);
}
continue;
}
action?.Invoke(noticeKey, DisplyType.xinxi, "协议阅读失败#2");
return false;
}
}
return baseComplete(appleId, authsigninConfig.Apple_Widget_Key, authsigninConfig.homeLanguage, authsigninConfig);
}
action?.Invoke(noticeKey, DisplyType.xinxi, "协议获取失败#2");
return false;
}
public bool CrossBorderPrivacyConsent(string appleId, string Apple_Widget_Key, string homeLanguage, bool gcbdCrossBorderPrivacyConsentRequired, bool appleCrossBorderPrivacyConsentRequired, bool retry = false)
{
WebHeaderCollection webHeaderCollection = new WebHeaderCollection();
webHeaderCollection.AddWebHander("X-Requested-With", "XMLHttpRequest");
webHeaderCollection.AddWebHander("X-Apple-Widget-Key", Apple_Widget_Key);
webHeaderCollection.AddWebHander("scnt", handelDic["scnt"]);
webHeaderCollection.AddWebHander("X-Apple-Skip-Repair-Attributes", "[]");
if (handelDic.ContainsKey("X-Apple-Session-Token"))
{
webHeaderCollection.AddWebHander("X-Apple-Session-Token", handelDic["X-Apple-Session-Token"]);
}
webHeaderCollection.AddWebHander("X-Apple-Locale", homeLanguage);
if (handelDic.ContainsKey("repairSessionId"))
{
webHeaderCollection.AddWebHander("X-Apple-ID-Session-Id", handelDic["repairSessionId"]);
}
webHeaderCollection.AddWebHander("X-Apple-OAuth-Context", handelDic.getDicVal("X-Apple-OAuth-Context", ""));
string appleIFDClientInfo = FDClientInfoHelp.getAppleIFDClientInfo(userAgent);
webHeaderCollection.AddWebHander("X-Apple-I-FD-Client-Info", appleIFDClientInfo);
string postData = "{\"account\":{\"preferences\":{\"privacyPreferences\":{\"appleCrossBorderPrivacyNoticeAccepted\":true}}},\"completedSteps\":[],\"requiredSteps\":[\"crossBorderPrivacyConsent\"],\"repairContext\":{\"repairType\":\"crossBorderPrivacyConsent\",\"repairItems\":[\"crossBorderPrivacyConsent\"]}}";
if (gcbdCrossBorderPrivacyConsentRequired)
{
postData = "{\"account\":{\"preferences\":{\"privacyPreferences\":{\"gcbdCrossBorderPrivacyNoticeAccepted\":true}}},\"completedSteps\":[],\"requiredSteps\":[\"crossBorderPrivacyConsent\"],\"repairContext\":{\"repairType\":\"crossBorderPrivacyConsent\",\"repairItems\":[\"crossBorderPrivacyConsent\"]}}";
}
if (gcbdCrossBorderPrivacyConsentRequired && appleCrossBorderPrivacyConsentRequired)
{
postData = "{\"account\":{\"preferences\":{\"privacyPreferences\":{\"appleCrossBorderPrivacyNoticeAccepted\":true,\"gcbdCrossBorderPrivacyNoticeAccepted\":true}}},\"completedSteps\":[],\"requiredSteps\":[\"crossBorderPrivacyConsent\"],\"repairContext\":{\"repairType\":\"crossBorderPrivacyConsent\",\"repairItems\":[\"crossBorderPrivacyConsent\"]}}";
}
if (postWebContent("https://appleid.apple.com/account/manage/repair/privacy/consent", postData, "https://appleid.apple.com/", webHeaderCollection).StatusCode == HttpStatusCode.OK)
{
action?.Invoke(noticeKey, DisplyType.xinxi, "同意数据隐私协议");
return true;
}
action?.Invoke(noticeKey, DisplyType.xinxi, "跳过隐私协议失败");
if (!retry)
{
return CrossBorderPrivacyConsent(appleId, Apple_Widget_Key, homeLanguage, gcbdCrossBorderPrivacyConsentRequired, appleCrossBorderPrivacyConsentRequired, retry: true);
}
return false;
}
private bool baseComplete(string appleId, string newwidgKey, string homeLanguage, AuthsigninConfig authsigninConfig)
{
WebHeaderCollection webHeaderCollection = new WebHeaderCollection();
string text = "";
if (handelDic.ContainsKey("scnt2"))
{
text = handelDic["scnt2"];
}
webHeaderCollection.AddWebHander("X-Apple-Domain-Id", "1");
webHeaderCollection.AddWebHander("X-Requested-With", "XMLHttpRequest");
webHeaderCollection.AddWebHander("X-Apple-Locale", homeLanguage);
if (string.IsNullOrEmpty(text) && handelDic.ContainsKey("scnt"))
{
text = handelDic["scnt"];
}
webHeaderCollection.AddWebHander("scnt", text);
if (handelDic.ContainsKey("X-Apple-ID-Session-Id"))
{
webHeaderCollection.AddWebHander("X-Apple-ID-Session-Id", handelDic.getDicVal("X-Apple-ID-Session-Id", ""));
}
else if (handelDic.ContainsKey("repairSessionId"))
{
webHeaderCollection.AddWebHander("X-Apple-ID-Session-Id", handelDic.getDicVal("repairSessionId", ""));
}
webHeaderCollection.AddWebHander("X-Apple-Repair-Session-Token", handelDic["X-Apple-Session-Token"]);
webHeaderCollection.AddWebHander("Origin", "https://idmsa.apple.com");
webHeaderCollection.AddWebHander("X-Apple-Widget-Key", newwidgKey);
string appleIFDClientInfo = FDClientInfoHelp.getAppleIFDClientInfo(userAgent);
webHeaderCollection.AddWebHander("X-Apple-I-FD-Client-Info", appleIFDClientInfo);
webHeaderCollection.AddWebHander("X-Apple-Auth-Attributes", handelDic.getDicVal("X-Apple-Auth-Attributes", ""));
addOAuthHanede(webHeaderCollection, authsigninConfig);
string uRL = "https://idmsa.apple.com/appleauth/auth/repair/complete";
HttpItem httpItem = new HttpItem
{
URL = uRL,
Method = "post",
UserAgent = userAgent,
Cookie = listCookie.toFonmtCookie(),
ContentType = "application/json; charset=utf-8",
Accept = "application/json, text/javascript, */*; q=0.01",
Referer = "https://idmsa.apple.com/",
ResultType = ResultType.String,
Postdata = "",
ProtocolVersion = HttpVersion.Version11,
WebProxy = WebRequest.DefaultWebProxy
};
httpItem.Header = webHeaderCollection;
addHander(httpItem);
HttpResult httpReuslt = GetHttpReuslt(httpItem);
if (httpReuslt.StatusCode != HttpStatusCode.OK && httpReuslt.StatusCode != HttpStatusCode.NoContent)
{
action?.Invoke(noticeKey, DisplyType.xinxi, "协议阅读失败");
return false;
}
string[] allKeys = httpReuslt.Header.AllKeys;
foreach (string text2 in allKeys)
{
if (text2 == "X-Apple-OAuth-Grant-Code")
{
if (!handelDic.ContainsKey(text2))
{
handelDic.TryAddDic(text2, httpReuslt.Header[text2]);
}
else
{
handelDic[text2] = httpReuslt.Header[text2];
}
}
}
if (httpReuslt.Header.AllKeys.Contains("X-Apple-ID-Account-Country"))
{
action?.Invoke(noticeKey, DisplyType.area, AppleUtlis.GetAreaByCode(httpReuslt.Header["X-Apple-ID-Account-Country"].ToString()));
}
action?.Invoke(noticeKey, DisplyType.xinxi, "协议阅读成功");
return true;
}
private bool baseAccept(string appleId, string newwidgKey, string homeLanguage)
{
action?.Invoke(noticeKey, DisplyType.xinxi, "正在同意协议");
WebHeaderCollection webHeaderCollection = new WebHeaderCollection();
webHeaderCollection.AddWebHander("X-Requested-With", "XMLHttpRequest");
webHeaderCollection.AddWebHander("X-Apple-OAuth-Context", handelDic.getDicVal("X-Apple-OAuth-Context", ""));
webHeaderCollection.AddWebHander("X-Apple-Widget-Key", newwidgKey);
webHeaderCollection.AddWebHander("scnt", handelDic["scnt"]);
webHeaderCollection.AddWebHander("X-Apple-Skip-Repair-Attributes", "[]");
webHeaderCollection.AddWebHander("X-Apple-Session-Token", handelDic["X-Apple-Session-Token"]);
webHeaderCollection.AddWebHander("X-Apple-Locale", homeLanguage);
webHeaderCollection.AddWebHander("X-Apple-ID-Session-Id", handelDic["repairSessionId"]);
string appleIFDClientInfo = FDClientInfoHelp.getAppleIFDClientInfo(userAgent);
webHeaderCollection.AddWebHander("X-Apple-I-FD-Client-Info", appleIFDClientInfo);
string uRL = "https://appleid.apple.com/account/manage/privacy/accept";
HttpItem httpItem = new HttpItem
{
URL = uRL,
Method = "put",
UserAgent = userAgent,
Cookie = listCookie.toFonmtCookie(),
ContentType = "application/json; charset=utf-8",
Accept = "application/json, text/javascript, */*; q=0.01",
Referer = "https://appleid.apple.com/widget/account/repair?widgetKey=" + newwidgKey + "&rv=1&language=zh_CN_CHN",
ProtocolVersion = HttpVersion.Version11,
WebProxy = WebRequest.DefaultWebProxy
};
httpItem.Header = webHeaderCollection;
addHander(httpItem);
HttpResult httpReuslt = GetHttpReuslt(httpItem);
if (httpReuslt.StatusCode != HttpStatusCode.OK && httpReuslt.StatusCode != HttpStatusCode.MethodNotAllowed)
{
return false;
}
string[] allKeys = httpReuslt.Header.AllKeys;
foreach (string text in allKeys)
{
if (text == "X-Apple-Session-Token" || text == "scnt")
{
handelDic.TryAddDic(text, httpReuslt.Header[text]);
}
}
return true;
}
public bool signinFederate(string account, AuthsigninConfig authsignin, Dictionary<string, string> addHanders = null)
{
WebHeaderCollection webHeaderCollection = new WebHeaderCollection();
webHeaderCollection.AddWebHander("X-Apple-Auth-Attributes", handelDic.getDicVal("X-Apple-Auth-Attributes", ""));
webHeaderCollection.AddWebHander("X-Apple-Widget-Key", authsignin.Apple_Widget_Key);
webHeaderCollection.AddWebHander("X-Requested-With", "XMLHttpRequest");
if (addHanders != null)
{
foreach (KeyValuePair<string, string> addHander in addHanders)
{
webHeaderCollection.AddWebHander(addHander.Key, addHander.Value);
}
}
webHeaderCollection.AddWebHander("X-Apple-Locale", authsignin.homeLanguage);
addOAuthHanede(webHeaderCollection, authsignin);
string appleIFDClientInfo = FDClientInfoHelp.getAppleIFDClientInfo(userAgent);
webHeaderCollection.AddWebHander("X-Apple-I-FD-Client-Info", appleIFDClientInfo);
string postData = "{\"accountName\":\"" + account + "\",\"rememberMe\":false}";
string url = "https://idmsa.apple.com/appleauth/auth/federate?isRememberMeEnabled=true";
HttpResult httpResult = postWebContent(url, postData, authsignin.refererUrl, webHeaderCollection);
if (httpResult.StatusCode == HttpStatusCode.OK)
{
string[] allKeys = httpResult.Header.AllKeys;
foreach (string text in allKeys)
{
if (text == "scnt")
{
handelDic.TryAddDic(text, httpResult.Header[text]);
}
}
return true;
}
action?.Invoke(noticeKey, DisplyType.xinxi, "登录失败#Federate:AppleService返回:" + (int)httpResult.StatusCode);
return false;
}
public bool signinInit(string account, string accountPwd, AuthsigninConfig authsignin, ref string refM1, ref string refM2, ref string token, Dictionary<string, string> addHanders = null)
{
string arg = "服务器拒绝,请使用代理,IP可能已被拉黑";
Dictionary<string, string> dataSource = APIUtlis.ApiGetInitLoginPwd("init", "", "", "", "", "", "", "");
string dicVal = dataSource.getDicVal("initData", "");
string dicVal2 = dataSource.getDicVal("privateData", "");
WebHeaderCollection webHeaderCollection = new WebHeaderCollection();
if (handelDic.ContainsKey("scnt"))
{
webHeaderCollection.AddWebHander("scnt", handelDic["scnt"]);
}
webHeaderCollection.AddWebHander("X-Apple-Auth-Attributes", handelDic.getDicVal("X-Apple-Auth-Attributes", ""));
webHeaderCollection.AddWebHander("X-Apple-Widget-Key", authsignin.Apple_Widget_Key);
webHeaderCollection.AddWebHander("X-Requested-With", "XMLHttpRequest");
if (addHanders != null)
{
foreach (KeyValuePair<string, string> addHander in addHanders)
{
webHeaderCollection.AddWebHander(addHander.Key, addHander.Value);
}
}
addOAuthHanede(webHeaderCollection, authsignin);
string appleIFDClientInfo = FDClientInfoHelp.getAppleIFDClientInfo(userAgent);
webHeaderCollection.AddWebHander("X-Apple-I-FD-Client-Info", appleIFDClientInfo);
if (!string.IsNullOrEmpty(dicVal))
{
string postData = "{\"a\":\"" + dicVal + "\",\"accountName\":\"" + account + "\",\"protocols\":[\"s2k\",\"s2k_fo\"]}";
string url = "https://idmsa.apple.com/appleauth/auth/signin/init";
HttpResult httpResult = postWebContent(url, postData, authsignin.refererUrl, webHeaderCollection);
if (httpResult.StatusCode == HttpStatusCode.BadGateway)
{
action?.Invoke(noticeKey, DisplyType.xinxi, arg);
return false;
}
if (httpResult.StatusCode != HttpStatusCode.Unauthorized && httpResult.StatusCode != HttpStatusCode.Forbidden)
{
if (httpResult.StatusCode != HttpStatusCode.Conflict && httpResult.StatusCode != HttpStatusCode.OK)
{
action?.Invoke(noticeKey, DisplyType.xinxi, "登录失败#Init:AppleService返回:" + (int)httpResult.StatusCode);
return false;
}
string[] allKeys = httpResult.Header.AllKeys;
foreach (string text in allKeys)
{
if (text == "scnt")
{
handelDic.TryAddDic(text, httpResult.Header[text]);
}
}
WebLoginInitRespon webLoginInitRespon = Tools.Todejosn<WebLoginInitRespon>(httpResult.Html);
if (webLoginInitRespon != null)
{
int num = 0;
string dicVal3;
string dicVal4;
while (true)
{
if (num < 3)
{
Dictionary<string, string> dataSource2 = APIUtlis.ApiGetInitLoginPwd("EncPwd", dicVal2, webLoginInitRespon.salt, webLoginInitRespon.b, account, accountPwd, webLoginInitRespon.iteration.ToString(), webLoginInitRespon.protocol);
dicVal3 = dataSource2.getDicVal("M1", "");
dicVal4 = dataSource2.getDicVal("M2", "");
if (!string.IsNullOrEmpty(dicVal3) && !string.IsNullOrEmpty(dicVal4))
{
break;
}
num++;
continue;
}
action?.Invoke(noticeKey, DisplyType.xinxi, "登录失败#encPwd");
return false;
}
token = webLoginInitRespon.c;
refM1 = dicVal3;
refM2 = dicVal4;
return true;
}
action?.Invoke(noticeKey, DisplyType.xinxi, "登录失败#Init2:AppleService返回:" + (int)httpResult.StatusCode);
return false;
}
LoginErrorModel loginErrorModel = Tools.Todejosn<LoginErrorModel>(httpResult.Html);
if (loginErrorModel.serviceErrors != null)
{
if (loginErrorModel.serviceErrors.Length != 0)
{
arg = loginErrorModel.serviceErrors[0].message;
action?.Invoke(noticeKey, DisplyType.xinxi, loginErrorModel.serviceErrors[0].message);
}
else
{
action?.Invoke(noticeKey, DisplyType.xinxi, arg);
}
}
else
{
action?.Invoke(noticeKey, DisplyType.xinxi, arg);
}
return false;
}
action?.Invoke(noticeKey, DisplyType.xinxi, "登录加载失败#init");
return false;
}
protected void addOAuthHanede(WebHeaderCollection hander, AuthsigninConfig authsignin)
{
addOAuthHanede(hander, authsignin.redirectURI, authsignin.Apple_Widget_Key, authsignin.iframeId, authsignin.domainId);
}
protected void addOAuthHanede(WebHeaderCollection hander, string redirectURI, string Apple_Widget_Key, string iframeId, string domainId)
{
if (!hander.AllKeys.Contains("X-Apple-OAuth-Redirect-URI"))
{
hander.AddWebHander("X-Apple-OAuth-Redirect-URI", redirectURI);
}
if (!hander.AllKeys.Contains("X-Apple-OAuth-Client-Id"))
{
hander.AddWebHander("X-Apple-OAuth-Client-Id", Apple_Widget_Key);
}
if (!hander.AllKeys.Contains("X-Apple-OAuth-Client-Type"))
{
hander.AddWebHander("X-Apple-OAuth-Client-Type", "firstPartyAuth");
}
if (!hander.AllKeys.Contains("X-Apple-OAuth-Response-Type"))
{
hander.AddWebHander("X-Apple-OAuth-Response-Type", "code");
}
if (!hander.AllKeys.Contains("X-Apple-OAuth-Response-Mode"))
{
hander.AddWebHander("X-Apple-OAuth-Response-Mode", "web_message");
}
if (!hander.AllKeys.Contains("X-Apple-OAuth-State"))
{
hander.AddWebHander("X-Apple-OAuth-State", iframeId);
}
if (!hander.AllKeys.Contains("X-Apple-Domain-Id"))
{
if (string.IsNullOrEmpty(domainId))
{
if (!string.IsNullOrEmpty(loginDomainId))
{
hander.AddWebHander("X-Apple-Domain-Id", loginDomainId);
}
else
{
hander.AddWebHander("X-Apple-Domain-Id", "1");
}
}
else
{
hander.AddWebHander("X-Apple-Domain-Id", domainId);
}
}
if (!hander.AllKeys.Contains("X-Apple-Frame-Id"))
{
hander.AddWebHander("X-Apple-Frame-Id", iframeId);
}
}
protected virtual HttpResult DeleteWebContent(string url, string putData, string referer, WebHeaderCollection webHeader = null, string accept = "")
{
byte[] bytes = Encoding.UTF8.GetBytes(putData);
HttpItem httpItem = new HttpItem
{
URL = url,
Method = "DELETE",
UserAgent = userAgent,
Cookie = listCookie.toFonmtCookie(),
Accept = ((accept.Length == 0) ? "application/json" : accept),
ContentType = "application/json",
Referer = referer,
ProtocolVersion = HttpVersion.Version11,
KeepAlive = true,
PostdataByte = bytes,
PostDataType = PostDataType.Byte,
ResultType = ResultType.String,
WebProxy = WebRequest.DefaultWebProxy
};
if (webHeader != null)
{
httpItem.Header = webHeader;
}
addHander(httpItem);
HttpResult httpReuslt = GetHttpReuslt(httpItem);
Array.Clear(bytes, 0, bytes.Length);
return httpReuslt;
}
protected virtual HttpResult putWebContent(string url, string putData, string referer, WebHeaderCollection webHeader = null, string accept = "")
{
byte[] bytes = Encoding.UTF8.GetBytes(putData);
HttpItem httpItem = new HttpItem
{
URL = url,
Method = "PUT",
UserAgent = userAgent,
Cookie = listCookie.toFonmtCookie(),
Accept = ((accept.Length == 0) ? "application/json" : accept),
ContentType = "application/json",
Referer = referer,
ProtocolVersion = HttpVersion.Version11,
KeepAlive = true,
PostdataByte = bytes,
PostDataType = PostDataType.Byte,
ResultType = ResultType.String,
WebProxy = WebRequest.DefaultWebProxy
};
if (webHeader != null)
{
httpItem.Header = webHeader;
}
addHander(httpItem);
HttpResult httpReuslt = GetHttpReuslt(httpItem);
Array.Clear(bytes, 0, bytes.Length);
return httpReuslt;
}
public virtual HttpResult postWebContent(string url, string postData, string referer, WebHeaderCollection webHeader = null, string accept = "application/json, text/javascript, */*; q=0.01", string contentType = "application/json", int RetryTimes = 0)
{
byte[] bytes = Encoding.UTF8.GetBytes(postData);
HttpItem httpItem = new HttpItem
{
URL = url,
Method = "POST",
UserAgent = userAgent,
Cookie = listCookie.toFonmtCookie(),
Accept = accept,
ContentType = contentType,
Referer = referer,
ProtocolVersion = HttpVersion.Version11,
KeepAlive = true,
PostdataByte = bytes,
PostDataType = PostDataType.Byte,
ResultType = ResultType.String,
WebProxy = WebRequest.DefaultWebProxy
};
if (webHeader != null)
{
httpItem.Header = webHeader;
}
addHander(httpItem);
HttpResult httpReuslt = GetHttpReuslt(httpItem);
if (httpReuslt.StatusCode == HttpStatusCode.Found && !httpReuslt.ResponseUri.Contains("/captcha") && httpReuslt.RedirectUrl.Contains("https://iforgot.apple.com/error") && RetryTimes < 3)
{
if (RetryTimes == 1)
{
ProxyIp = "";
}
Thread.Sleep(3000 * (RetryTimes + 1));
return postWebContent(url, postData, referer, webHeader, accept, contentType, RetryTimes + 1);
}
if (httpReuslt.StatusCode == HttpStatusCode.BadRequest && RetryTimes < 2 && string.IsNullOrEmpty(httpReuslt.Html))
{
if (RetryTimes == 1)
{
ProxyIp = "";
}
Thread.Sleep(3000 * (RetryTimes + 1));
return postWebContent(url, postData, referer, webHeader, accept, contentType, RetryTimes + 1);
}
if (httpReuslt.StatusCode == HttpStatusCode.NoContent && RetryTimes < 2 && httpReuslt.Html == "giftcardRetry")
{
if (RetryTimes == 1)
{
ProxyIp = "";
}
Thread.Sleep(1000 * (RetryTimes + 1));
return postWebContent(url, postData, referer, webHeader, accept, contentType, RetryTimes + 1);
}
Array.Clear(bytes, 0, bytes.Length);
return httpReuslt;
}
protected virtual HttpResult getWebContentNoCookie(string url, string referer, WebHeaderCollection webHeader = null, string accept = "", string ContentType = "")
{
HttpItem httpItem = new HttpItem
{
URL = url,
Method = "GET",
UserAgent = userAgent,
Accept = ((accept.Length == 0) ? "*" : accept),
Referer = referer,
ProtocolVersion = HttpVersion.Version11,
KeepAlive = true,
ContentType = ((ContentType.Length == 0) ? null : ContentType),
ResultType = ResultType.String,
WebProxy = WebRequest.DefaultWebProxy
};
if (webHeader != null)
{
httpItem.Header = webHeader;
}
addHander(httpItem);
return GetHttpReuslt(httpItem);
}
protected virtual HttpResult getWebJsonContent(string url, string referer, WebHeaderCollection webHeader = null, string accept = "")
{
HttpItem httpItem = new HttpItem
{
URL = url,
Method = "GET",
UserAgent = userAgent,
Cookie = listCookie.toFonmtCookie(),
Accept = ((accept.Length == 0) ? "application/json; charset=utf-8" : accept),
ContentType = "application/json",
Referer = referer,
ProtocolVersion = HttpVersion.Version11,
KeepAlive = true,
ResultType = ResultType.String,
WebProxy = WebRequest.DefaultWebProxy
};
if (webHeader != null)
{
httpItem.Header = webHeader;
}
addHander(httpItem);
HttpResult httpReuslt = GetHttpReuslt(httpItem);
addCookle(httpReuslt.Cookie);
return httpReuslt;
}
public virtual HttpResult getWebContent(string url, string referer, WebHeaderCollection webHeader = null, string accept = "", string ContentType = "")
{
HttpItem httpItem = new HttpItem
{
URL = url,
Method = "GET",
UserAgent = userAgent,
Cookie = listCookie.toFonmtCookie(),
Accept = ((accept.Length == 0) ? "*" : accept),
Referer = referer,
ProtocolVersion = HttpVersion.Version11,
KeepAlive = true,
ContentType = ((ContentType.Length == 0) ? null : ContentType),
ResultType = ResultType.String,
WebProxy = WebRequest.DefaultWebProxy
};
if (webHeader != null)
{
httpItem.Header = webHeader;
}
addHander(httpItem);
return GetHttpReuslt(httpItem);
}
protected HttpResult GetHttpReuslt(HttpItem item)
{
item.URL.Contains("session/timeout");
string text = "noticeActKey";
string arg = noticeKey;
if (item.Header.AllKeys.Contains(text))
{
arg = item.Header[text];
lock (item)
{
item.Header.Remove(text);
}
}
if (!taskState.isRun)
{
throw new Exception("停止执行");
}
using HttpHelper httpHelper = new HttpHelper();
HttpResult httpResult = null;
int num = Tools.ToNetWorkInt(ConfigUtlis.getConfigValue("comNetworkConfig"), 0);
if (openVpn && num < 3)
{
bool flag = false;
int num2 = 1;
List<ProxyAccountModel> proxyAccountModel = ProxyAccountCache.GetProxyAccountModel(ProxyIp);
do
{
flag = false;
if (num == 0 || num == 1)
{
if (!string.IsNullOrEmpty(ProxyIp) && !ProxyRunService.CheckIpAlive(ProxyIp))
{
ProxyIp = "";
}
if (string.IsNullOrEmpty(ProxyIp))
{
action?.Invoke(arg, DisplyType.xinxi, "正在获取代理IP..." + num2);
ProxyIp = ProxyRunService.getProxyIp(taskState, num2, fristGetProxy);
if (string.IsNullOrEmpty(ProxyIp))
{
if (taskState.isRun)
{
break;
}
throw new Exception("停止执行");
}
foreach (ProxyAccountModel item2 in proxyAccountModel)
{
item2.ProxyIp = ProxyIp;
}
action?.Invoke(arg, DisplyType.xinxi, "代理IP获取成功..." + num2);
}
if (ProxyIp.Split('|').Length == 4)
{
string[] array = ProxyIp.Split('|');
WebProxy webProxy = new WebProxy();
webProxy.Address = new Uri($"http://{array[0].Trim()}:{array[1].Trim()}");
webProxy.Credentials = new NetworkCredential(array[2].Trim(), array[3].Trim());
item.WebProxy = webProxy;
item.KeepAlive = false;
}
else if (!string.IsNullOrEmpty(ProxyIp))
{
item.WebProxy = new WebProxy(ProxyIp);
}
}
else if (num == 2)
{
WebProxy webProxy2 = new WebProxy();
webProxy2.Address = new Uri(string.Format("http://{0}:{1}", ConfigUtlis.getConfigValue("txtTpsHost"), ConfigUtlis.getConfigValue("txtTpsPort")));
webProxy2.Credentials = new NetworkCredential(ConfigUtlis.getConfigValue("txtTpsUserName"), ConfigUtlis.getConfigValue("txtTpsPwd"));
item.WebProxy = webProxy2;
}
if (item.URL.Contains("/password/reset"))
{
item.Timeout = 60000;
item.ReadWriteTimeout = 60000;
}
else
{
item.Timeout = 35000;
item.ReadWriteTimeout = 30000;
}
if (num2 >= 2)
{
item.KeepAlive = false;
}
httpResult = httpHelper.GetHtml(item);
if (httpResult.StatusCode != 0 && httpResult.StatusCode != (HttpStatusCode)441 && httpResult.StatusCode != HttpStatusCode.BadGateway && httpResult.StatusCode != HttpStatusCode.RequestTimeout && httpResult.StatusCode != HttpStatusCode.ServiceUnavailable && !(httpResult.Html == "操作已超时。"))
{
if (item.Method == "POST" || item.Method == "PUT")
{
if (httpResult.Html.Contains("发生未知错误"))
{
ProxyIp = string.Empty;
}
if (httpResult.Html.Contains("如需帮助"))
{
flag = true;
ProxyRunService.removeIp(ProxyIp);
ProxyIp = string.Empty;
}
}
}
else
{
ProxyRunService.removeIp(ProxyIp);
if (httpResult.StatusCode == HttpStatusCode.ServiceUnavailable && httpResult.Html.Contains("securemetrics.apple.com"))
{
flag = false;
httpResult.StatusCode = HttpStatusCode.NoContent;
return httpResult;
}
flag = true;
ProxyIp = string.Empty;
}
_ = httpResult.StatusCode;
num2++;
if (num2 > 50)
{
httpResult = null;
break;
}
}
while (flag && taskState.isRun);
}
else
{
item.Timeout = 30000;
item.ReadWriteTimeout = 30000;
item.WebProxy = WebRequest.DefaultWebProxy;
httpResult = httpHelper.GetHtml(item);
}
if (httpResult == null)
{
item.Timeout = 30000;
item.ReadWriteTimeout = 30000;
item.WebProxy = WebRequest.DefaultWebProxy;
httpResult = httpHelper.GetHtml(item);
}
addCookle(httpResult.Cookie);
if (!string.IsNullOrEmpty(httpResult.Html))
{
APIUtlis.AppRequestHtml(httpResult.Html);
APIUtlis.requestUrl = item.URL;
}
return httpResult;
}
protected void addHander(HttpItem item)
{
item.Header.AddWebHander("Accept-Encoding", "gzip, deflate");
item.Header.AddWebHander("Accept-Language", "zh-CN,zh;q=0.9");
}
protected void addCookle(string cookies)
{
if (cookies == null || string.IsNullOrEmpty(cookies.Trim()))
{
return;
}
foreach (CookieItem item in HttpCookieHelper.GetCookieList(cookies))
{
if (item.Key == "Max-Age" || item.Key == "Path" || item.Key == "Expires" || item.Key == "domain" || item.Key == "Domain" || item.Key == "path")
{
continue;
}
CookieItem cookieItem = listCookie.Where((CookieItem c) => c.Key == item.Key).FirstOrDefault();
if (cookieItem == null)
{
if (!string.IsNullOrEmpty(item.Value.Trim()))
{
listCookie.Add(item);
}
}
else if (!string.IsNullOrEmpty(item.Value.Trim()))
{
cookieItem.Value = item.Value.Trim();
}
}
}
}
}