12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744 |
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using SufeiUtil;
- using SXLibrary;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data.SQLite;
- using System.Globalization;
- using System.IO;
- using System.Management;
- using System.Net;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Windows.Forms;
- using System.Xml;
- using WHC.OrderWater.Commons;
- using HttpHelper = SufeiUtil.HttpHelper;
- using System.Web;
- using System.Security.Cryptography.X509Certificates;
- using System.Net.Security;
- using System.Runtime.InteropServices;
- using System.Diagnostics;
- using System.Linq;
- namespace MOKA_Factory_Tools
- {
- class CommonMethod
- {
- [DllImport("kernel32")]
- public static extern bool GetProfileString(string lpApplicationName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize);
- [DllImport("kernel32")]
- public static extern bool WriteProfileString(string lpApplicationName, string lpKeyName, string lpString);
- public static string FactoryName = "Unknown";
- private static string lastOrder = "";
- private static List<string> ListACASSN = new List<string>();
- private static Dictionary<string,string> SN_ACAS_MAP = new Dictionary<string,string>();
- private static LoginInput loginInput = new LoginInput();
- private static FunctionSetting functionSetting = null;
- private static MidList midList = null;
- public static void SetCommonsData(FunctionSetting function, MidList mid)
- {
- if ( function != null )
- functionSetting = function;
- if ( mid != null)
- midList = mid;
- }
- /// <summary>
- /// 保存登录信息;
- /// </summary>
- /// <param name="strAccount"></param>
- /// <param name="strPssword"></param>
- public static void SaveLoginInfo(string strAccount, string strPssword)
- {
- loginInput.account = strAccount;
- loginInput.password = strPssword;
- }
- /// <summary>
- /// 获取登录账号;
- /// </summary>
- /// <returns></returns>
- public static string GetLoginAccout()
- {
- return loginInput.account;
- }
- public static string ReadProfileString(string lpApplicationName, string lpKeyName, string lpDefault)
- {
- StringBuilder MyString = new StringBuilder(256);
- GetProfileString(lpApplicationName, lpKeyName, lpDefault, MyString, 256);
- if ( MyString.Length > 0)
- return MyString.ToString();
- return lpDefault;
- }
- /// <summary>
- /// 更新G客户抄写状态;
- /// </summary>
- /// <param name="SN">当前SN</param>
- /// <param name="bResult">当前SN的抄写结果,true=pass, false=fail</param>
- public static void UpdateGSNProfile( string SN, bool bResult = false )
- {
- string strLastSN = ReadProfileString("MOKAFactoryTools", "LastGSN", "");
- if (!strLastSN.Equals(SN, StringComparison.OrdinalIgnoreCase))
- {
- WriteProfileString("MOKAFactoryTools", "LastGSN", SN);
- // 清空连续次数值;
- WriteProfileString("MOKAFactoryTools", "GFailCount", "0");
- // 清空上次测试状态;
- WriteProfileString("MOKAFactoryTools", "LastGResult", "0");
- }
- else
- {
- if (bResult == false)
- {
- int nGSNCount = Convert.ToInt32(ReadProfileString("MOKAFactoryTools", "GFailCount", "0")) + 1;
- // 更新连续测试中累计失败的次数;
- WriteProfileString("MOKAFactoryTools", "GFailCount", nGSNCount.ToString());
- }
- // 更新抄写状态;
- WriteProfileString("MOKAFactoryTools", "LastGResult", bResult ? "1" : "0");
- }
- }
- //public static string LocalMacAddress = GetMacAddress();
- /// <summary>
- /// 获取活动网卡硬件地址
- /// </summary>
- /// <returns></returns>
- public static string GetMacAddress()
- {
- string mac = "";
- using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
- {
- ManagementObjectCollection moc = mc.GetInstances();
- int i = 0;
- int j = 0;
- foreach (ManagementObject mo in moc)
- {
- if (mo["MacAddress"] != null)
- {
- if (Convert.ToBoolean(mo["IPEnabled"]))
- {
- if (j < 2)
- {
- mac = mo["MacAddress"].ToString() + "&" + mac;
- j++;
- }
- }
- else
- {
- if (i < 1)
- {
- mac += mo["MacAddress"].ToString() + "&";
- i++;
- }
- }
- }
- }
- }
- return mac.Replace(":", "-");
- //return "C0-B6-F9-44-D7-BB";
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="runFilePath"></param>
- /// <param name="args"></param>
- /// <returns></returns>
- public static bool StartProcess(string runFilePath, string args)
- {
- try
- {
- Process process = new Process();//创建进程对象
- ProcessStartInfo startInfo = new ProcessStartInfo(runFilePath, args);
- startInfo.UseShellExecute = false;
- startInfo.CreateNoWindow = true;
- process.StartInfo = startInfo;
- return process.Start();
- //process.WaitForExit();
- }
- catch (Exception ex)
- {
- Log.WriteErrorLog(string.Format("打开进程{0}失败:{1}", runFilePath, ex.Message));
- }
-
- return false;
- }
- public static bool StartProcess(string runFilePath, string args, out string outPutMsg)
- {
- try
- {
- outPutMsg = null;
- Process process = new Process();
- ProcessStartInfo startInfo = new ProcessStartInfo(runFilePath, args);
- startInfo.UseShellExecute = false;
- process.StartInfo = startInfo;
- process.StartInfo.RedirectStandardError = true;
- process.StartInfo.RedirectStandardInput = true;
- process.StartInfo.RedirectStandardOutput = true;
- process.StartInfo.CreateNoWindow= true;
- process.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "replace_tv_projects";
- process.Start();
- outPutMsg = process.StandardOutput.ReadToEnd();
- process.WaitForExit();
- process.Close();
- }
- catch(Exception ex)
- {
- outPutMsg = null;
- Log.WriteErrorLog(string.Format("打开进程{0}失败:{1}", runFilePath, ex.Message));
- return false;
- }
- Log.WriteInfoLog(string.Format("adb push结果={0}",outPutMsg));
- return true;
- }
- /// <summary>
- /// 获取订单信息
- /// </summary>
- /// <param name="url"></param>
- /// <param name="order"></param>
- /// <param name="pcmac"></param>
- /// <param name="iptvip"></param>
- /// <param name="version"></param>
- /// <param name="sqliteConn"></param>
- /// <param name="mid"></param>
- /// <returns></returns>
- [Obsolete]
- public static bool GetMidInfo(string url, string order, string pcmac, string iptvip, string version, SQLiteConnection sqliteConn, out MidList mid)
- {
- mid = new MidList();
- OrderInput orderInput1 = new OrderInput { bid = order, mac = pcmac, version = "", clientType = "" };//"74-27-EA-6E-DA-9F"
- string jsonorder = JsonConvert.SerializeObject(orderInput1, Newtonsoft.Json.Formatting.Indented);
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- URL = url,//URL这里都是测试URl 必需项
- Encoding = Encoding.UTF8,//编码格式(utf-8,gb2312,gbk) 可选项 默认类会自动识别
- //Encoding = Encoding.Default,
- Method = "post",//URL 可选项 默认为Get
- Postdata = jsonorder,
- PostEncoding = Encoding.UTF8,
- KeepAlive = false
- };
- item.ContentType = "application/json;charset=utf-8";
- System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
- stopwatch.Start();
- HttpResult result = http.GetHtml(item);
- stopwatch.Stop();
- string usingtime = stopwatch.ElapsedMilliseconds.ToString();
- stopwatch.Reset();
- string ParseText = result.Html;
- if (result.StatusCode == System.Net.HttpStatusCode.OK)
- {
- Log.WriteGetKeyLog("\r\nGet MID info\r\nUsing time:" + usingtime + "ms\r\n" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
- }
- else
- {
- Log.WriteErrorLog("\r\nFail to GetMidInfo:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
- ReportErrormsg("Fail to GetMidInfo", result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
- return false;
- }
- try
- {
- JObject jObject = JObject.Parse(ParseText);
- mid.message = jObject["message"].Value<string>();
- mid.code = jObject["code"].Value<string>();
- mid.factoryname = jObject["factoryName"].Value<string>();
- mid.factoryNum = jObject["factoryNum"].Value<string>();
- mid.version = jObject["version"].Value<string>();
- mid.quantity = jObject["quantity"].Value<string>();
- mid.projectid = jObject["projectId"].Value<string>();
- mid.clienttype = jObject["clientType"].Value<string>();
- mid.host = jObject["host"].Value<string>();
- mid.whiteType = jObject["whiteType"].Value<string>();
- object a = jObject["rokuCustomer"];
- if (jObject["rokuCustomer"].ToString().Length > 0)
- {
- mid.rokuCustomer = new RokuCustomer()
- {
- id = JSON_SeleteNode(jObject["rokuCustomer"], "id").Trim(),
- ordernum = JSON_SeleteNode(jObject["rokuCustomer"], "ordernum").Trim(),
- brand = JSON_SeleteNode(jObject["rokuCustomer"], "brand").Trim(),
- //region = JSON_SeleteNode(jObject["rokuCustomer"], "region").Trim(),
- oemmodel = JSON_SeleteNode(jObject["rokuCustomer"], "oemmodel").Trim(),
- //supporturl = JSON_SeleteNode(jObject["rokuCustomer"], "supporturl").Trim(),
- //supportphone = JSON_SeleteNode(jObject["rokuCustomer"], "supportphone").Trim(),
- productiondate = JSON_SeleteNode(jObject["rokuCustomer"], "productiondate").Trim(),
- remotetype = JSON_SeleteNode(jObject["rokuCustomer"], "remotetype").Trim(),
- updatetime = JSON_SeleteNode(jObject["rokuCustomer"], "updatetime").Trim(),
- createtime = JSON_SeleteNode(jObject["rokuCustomer"], "createtime").Trim(),
- isdelete = JSON_SeleteNode(jObject["rokuCustomer"], "isdelete").Trim()
- };
- }
- mid.keytype = new Dictionary<string, string>();
- foreach (var ss in jObject["obj"]) //查找某个字段与值
- {
- mid.keytype.Add(ss["name"].Value<string>(), ss["type"].Value<string>());
- }
- if (mid.code == "1000")
- return true;
- else
- return false;
- }
- catch (Exception ex)
- {
- Log.WriteErrorLog("\r\nFail to parse MID info," + ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
- ReportErrormsg("Fail to parse MID info", ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
- MessageBox.Show("Fail to parse MID info\r\n " + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 检验抄写类型
- /// </summary>
- /// <param name="keyTypes"></param>
- /// 服务器返回的key types
- /// <param name="cfg_write"></param>
- /// 配置文件配置的key to write
- /// <param name="resultKeyType"></param>
- /// <returns></returns>
- public static bool CheckKeyType(Dictionary<string, string> keyTypes, Config_WriteDone cfg_write, out List<KeyType> resultKeyType)
- {
- resultKeyType = new List<KeyType>();
- foreach (var item in keyTypes)
- {
- resultKeyType.Add(new KeyType { name = item.Key , type = item.Value});
- }
- Action<string, List <KeyType>, bool> check_key_type = (keyname, listType, writeYesNo) =>
- {
- if (keyTypes.ContainsKey(keyname))
- {
- if (!writeYesNo)
- {
- KeyType kt = listType.Find(x=>x.name == keyname);
- if ( kt != null)
- listType.Remove(kt);
- }
- }
- };
- // 共22个key需要抄写;
- check_key_type("DeviceID", resultKeyType, cfg_write.DIDWrite_YesNo);
- check_key_type("MAC", resultKeyType, cfg_write.MacWrite_YesNo);
- check_key_type("HDCP_KEY", resultKeyType, cfg_write.HDCPWrite_YesNo);
- check_key_type("HDCP2.2_KEY", resultKeyType, cfg_write.HDCP22Write_YesNo);
- check_key_type("NETFILX_ESN", resultKeyType, cfg_write.ESNWrite_YesNo);
- check_key_type("Widevine_KEY", resultKeyType, cfg_write.WidevineWrite_YesNo);
- check_key_type("CI_PLUS_KEY", resultKeyType, cfg_write.CI_plusWrite_YesNo);
- check_key_type("Attestation_key", resultKeyType, cfg_write.AttestationWrite_YesNo);
- check_key_type("MGK_KEY", resultKeyType, cfg_write.MGKWrite_YesNo);
- check_key_type("Fairplay_KEY", resultKeyType, cfg_write.FairplayWrite_YesNo);
- check_key_type("ECP_KEY", resultKeyType, cfg_write.ECPWrite_YesNo);
- check_key_type("WiFi_MAC", resultKeyType, cfg_write.WifiMacWrite_YesNo);
- check_key_type("BT_MAC", resultKeyType, cfg_write.BTMacWrite_YesNo);
- check_key_type("LEK", resultKeyType, cfg_write.LEKWrite_YesNo);
- check_key_type("PEK", resultKeyType, cfg_write.PEKWrite_YesNo);
- check_key_type("PlayReady_key", resultKeyType, cfg_write.PlayreadyWrite_YesNo);
- check_key_type("Hashkey", resultKeyType, cfg_write.HashWrite_YesNo);
- check_key_type("DSN", resultKeyType, cfg_write.DSNWrite_YesNo);
- check_key_type("YouTube_KEY", resultKeyType, cfg_write.YouTubeWrite_YesNo);
- check_key_type("ACAS_KEY", resultKeyType, cfg_write.ACASKeyWrite_YesNo);
- check_key_type("DAK", resultKeyType, cfg_write.DAKWrite_YesNo);
- check_key_type("KFP_KEY", resultKeyType, cfg_write.KFPWrite_YesNo);
- check_key_type("RMCA_Key", resultKeyType, cfg_write.RMCAWrite_YesNo);
- return resultKeyType.Count == 0 ? false : true;
- }
- /// <summary>
- /// 获取预绑定模式下的key包地址
- /// </summary>
- /// <param name="midInfo"></param>
- /// <param name="order"></param>
- /// <param name="sqliteConn"></param>
- /// <param name="midAddress"></param>
- /// <returns></returns>
- [Obsolete]
- public static bool GetMidAddress(MidList midInfo, string order, SQLiteConnection sqliteConn, out MidAddress midAddress)
- {
- midAddress = new MidAddress();
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- Encoding = null,//编码格式(utf-8,gb2312,gbk) 可选项 默认类会自动识别
- //Encoding = Encoding.Default,
- Method = "post",//URL 可选项 默认为Get
- Postdata = ("orderNumber=" + order + "&mac=" + HttpUtility.UrlEncode(TestMode.MAC)),
- KeepAlive = false
- };
- #region 新接口统一返回带/v1,getofflinelist.do依旧采用旧host地址;
- string url = midInfo.host;
- if (url.EndsWith("/v1"))
- {
- url = url.Replace("/v1", "");
- }
- item.URL = url + "/getofflinelist.do?";
- #endregion
- item.ContentType = "application/x-www-form-urlencoded";
- HttpResult result = http.GetHtml(item);
- string ParseText = result.Html;
- if (result.StatusCode == System.Net.HttpStatusCode.OK)
- {
- }
- else
- {
- Log.WriteErrorLog("\r\nFail to get Mid address:" + result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata);
- CommonMethod.ReportErrormsg("Fail to get Mid address", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata, sqliteConn);
- return false;
- }
- try
- {
- JObject jObject = JObject.Parse(ParseText);
- midAddress.des = JSON_SeleteNode(jObject, "des");
- midAddress.code = JSON_SeleteNode(jObject, "code");
- midAddress.order = JSON_SeleteNode(jObject, "order_number");
- midAddress.number = JSON_SeleteNode(jObject, "order_quantity");
- midAddress.pid = JSON_SeleteNode(jObject, "project_id");
- midAddress.ctype = JSON_SeleteNode(jObject, "client_type");
- midAddress.purl = JSON_SeleteNode(jObject, "packet_url");
- midAddress.psize = JSON_SeleteNode(jObject, "packet_size");
- midAddress.pmd5 = JSON_SeleteNode(jObject, "packet_md5");
- midAddress.version = JSON_SeleteNode(jObject, "soft_version");
- midAddress.host = midInfo.host;
- Log.WriteGetKeyLog("\r\nGet Mid address success:" + "\r\n" + result.Html + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata);
- return true;
- }
- catch (Exception ex)
- {
- Log.WriteErrorLog("\r\nFail to parse MID address," + ex.Message + ":" + ParseText + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata);
- CommonMethod.ReportErrormsg("Fail to parse MID address", ex.Message + "\r\n" + ParseText + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata, sqliteConn);
- MessageBox.Show("Fail to parse MIDAddress info\r\n " + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 获取预绑定模式下的key包地址
- /// </summary>
- /// <param name="midInfo"></param>
- /// <param name="order"></param>
- /// <param name="sqliteConn"></param>
- /// <param name="midAddress"></param>
- /// <returns></returns>
- [Obsolete]
- public static bool GetMidAddress2(MidList midInfo, string order, SQLiteConnection sqliteConn, out List<MidAddress> midAddressList)
- {
- midAddressList = new List<MidAddress>();
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- Encoding = null,//编码格式(utf-8,gb2312,gbk) 可选项 默认类会自动识别
- //Encoding = Encoding.Default,
- Method = "post",//URL 可选项 默认为Get
- Postdata = ("orderNumber=" + order + "&mac=" + HttpUtility.UrlEncode(TestMode.MAC)),
- KeepAlive = false
- };
- #region 新接口统一返回带/v1,getofflinelist.do依旧采用旧host地址;
- string url = midInfo.host;
- if (url.EndsWith("/v1"))
- {
- url = url.Replace("/v1", "");
- }
- item.URL = url + "/getofflinelist.do?";
- #endregion
- item.ContentType = "application/x-www-form-urlencoded";
- HttpResult result = http.GetHtml(item);
- string ParseText = result.Html;
- if (result.StatusCode == System.Net.HttpStatusCode.OK)
- {
- }
- else
- {
- Log.WriteErrorLog("\r\nFail to get Mid address:" + result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata);
- CommonMethod.ReportErrormsg("Fail to get Mid address", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata, sqliteConn);
- return false;
- }
- try
- {
- JObject jObject = JObject.Parse(ParseText);
- if (jObject["data"] != null)
- {
- foreach (var data in jObject["data"])
- {
- midAddressList.Add(new MidAddress()
- {
- des = JSON_SeleteNode(jObject, "des"),
- code = JSON_SeleteNode(jObject, "code"),
- order = data["order_number"].ToObject<string>(),
- number = data["order_quantity"].ToObject<string>(),
- pid = data["project_id"].ToObject<string>(),
- ctype = data["client_type"].ToObject<string>(),
- purl = data["packet_url"].ToObject<string>(),
- psize = data["packet_size"].ToObject<string>(),
- pmd5 = data["packet_md5"].ToObject<string>(),
- version = data["soft_version"].ToObject<string>(),
- host = midInfo.host
- });
- }
- }
- Log.WriteGetKeyLog("\r\nGet Mid address success:" + "\r\n" + result.Html + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata);
- return true;
- }
- catch (Exception ex)
- {
- Log.WriteErrorLog("\r\nFail to parse MID address," + ex.Message + ":" + ParseText + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata);
- CommonMethod.ReportErrormsg("Fail to parse MID address", ex.Message + "\r\n" + ParseText + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata, sqliteConn);
- MessageBox.Show("Fail to parse MIDAddress info\r\n " + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 解析XML格式的DID
- /// </summary>
- /// <param name="str"></param>
- /// <param name="node"></param>
- /// <param name="node2"></param>
- /// <param name="code"></param>
- /// <param name="desc"></param>
- /// <param name="value"></param>
- /// <returns></returns>
- public static bool GetDIDKeyXml(string str, string node, string node2, out string code, out string desc, out string value)
- {
- code = "";
- value = "";
- try
- {
- XmlDocument xml = new XmlDocument();
- //xml.Load(path);
- xml.LoadXml(str);
- code = xml.SelectSingleNode(node).Attributes.GetNamedItem("code").InnerText;
- desc = xml.SelectSingleNode(node).Attributes.GetNamedItem("desc").InnerText;
- if (code == "200")
- {
- value = xml.SelectSingleNode(node + "//" + node2).Attributes.GetNamedItem("deviceid").InnerText;
- string CRC32 = xml.SelectSingleNode(node + "//" + node2).Attributes.GetNamedItem("crc32").InnerText;
- if (CrcUtils.CRC32(value) == Convert.ToUInt32(CRC32))
- {
- return true;
- }
- else
- {
- desc = "CRC32 error";
- return false;
- }
- }
- return false;
- }
- catch (Exception ex)
- {
- desc = ex.Message;
- return false;
- }
- }
- /// <summary>
- /// 在线获取Key:最新接口;
- /// </summary>
- /// <param name="url"></param>
- /// <param name="sn"></param>
- /// <param name="order"></param>
- /// <param name="psn"></param>
- /// <param name="firetv_device_code"></param>
- /// <param name="connection"></param>
- /// <param name="key"></param>
- /// <param name="error"></param>
- /// <param name="md5"></param>
- /// <returns></returns>
- [Obsolete]
- public static bool GetIDMKeys(string url, string sn, string order, string psn, string firetv_device_code, List<KeyType> key2Write, SQLiteConnection connection, ref KeyInfo keys, out string msg)
- {
- msg = "";
- string code;
- bool result = false;
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- Encoding = Encoding.UTF8,
- Method = "post",
- ContentType = "application/json",
- KeepAlive = false
- };
- // 计算函数耗时;
- Stopwatch watch = new Stopwatch();
- watch.Start();
- item.URL = url + "/bind/order";
- item.Postdata = string.Format("{{\"orderNum\":\"{0}\",\"sn\":\"{1}\",\"psn\":\"{2}\",\"orderCode\":\"{3}\",\"skipKey\":{4}}}", order, sn, psn, firetv_device_code, key2Write == null ? "[]" : JsonConvert.SerializeObject(key2Write).ToString());
- HttpResult httpResult = http.GetHtml(item);
- if (httpResult.StatusCode == System.Net.HttpStatusCode.OK)
- {
- try {
- JObject jObject = JObject.Parse(httpResult.Html);
- msg = JSON_SeleteNode(jObject, "msg");
- code = JSON_SeleteNode(jObject, "code");
- if (code == "0")
- {
- Dictionary<string, string> data = JsonConvert.DeserializeObject<Dictionary<string, string>>(jObject["data"].ToString());
- if (data != null)
- {
- Func<string, string, bool> CheckMD5 = (data, md5) =>
- {
- if (data == null)
- return true;
- if (!GetMD5.GetStrMd5(data).Equals(md5, StringComparison.OrdinalIgnoreCase))
- return false;
- return true;
- };
- if (data.ContainsKey("mac") && data.ContainsKey("mac_md5"))
- {
- keys.Mac.data = data["mac"];
- keys.Mac.md5 = data["mac_md5"];
- if (!CheckMD5(keys.Mac.data, keys.Mac.md5))
- {
- msg = string.Format("Mac Key Value md5 Is Incorrect: data={0}, md5={1}", keys.Mac.data, keys.Mac.md5);
- goto end;
- }
- }
- if (data.ContainsKey("btMac") && data.ContainsKey("btMac_md5"))
- {
- keys.BT_MAC.data = data["btMac"];
- keys.BT_MAC.md5 = data["btMac_md5"];
- if (!CheckMD5(keys.BT_MAC.data, keys.BT_MAC.md5))
- {
- msg = string.Format("BT_MAC Key Value md5 Is Incorrect: data={0}, md5={1}", keys.BT_MAC.data, keys.BT_MAC.md5);
- goto end;
- }
- }
- if (data.ContainsKey("wifiMac") && data.ContainsKey("wifiMac_md5"))
- {
- keys.WiFi_MAC.data = data["wifiMac"];
- keys.WiFi_MAC.md5 = data["wifiMac_md5"];
- if (!CheckMD5(keys.WiFi_MAC.data, keys.WiFi_MAC.md5))
- {
- msg = string.Format("WiFi_MAC Key Value md5 Is Incorrect: data={0}, md5={1}", keys.WiFi_MAC.data, keys.WiFi_MAC.md5);
- goto end;
- }
- }
- if (data.ContainsKey("deviceid") && data.ContainsKey("deviceid_md5"))
- {
- keys.DID.data = data["deviceid"];
- keys.DID.md5 = data["deviceid_md5"];
- if (!CheckMD5(keys.DID.data, keys.DID.md5))
- {
- msg = string.Format("DID Key Value md5 Is Incorrect: data={0}, md5={1}", keys.DID.data, keys.DID.md5);
- goto end;
- }
- }
- if (data.ContainsKey("hdcp") && data.ContainsKey("hdcp_md5"))
- {
- keys.HDCP.data = data["hdcp"];
- keys.HDCP.md5 = data["hdcp_md5"];
- if (!CheckMD5(keys.HDCP.data, keys.HDCP.md5))
- {
- msg = string.Format("HDCP Key Value md5 Is Incorrect: data={0}, md5={1}", keys.HDCP.data, keys.HDCP.md5);
- goto end;
- }
- }
- if (data.ContainsKey("hdcp2") && data.ContainsKey("hdcp2_md5"))
- {
- keys.HDCP22.data = data["hdcp2"];
- keys.HDCP22.md5 = data["hdcp2_md5"];
- if (!CheckMD5(keys.HDCP22.data, keys.HDCP22.md5))
- {
- msg = string.Format("HDCP22 Key Value md5 Is Incorrect: data={0}, md5={1}", keys.HDCP22.data, keys.HDCP22.md5);
- goto end;
- }
- }
- if (data.ContainsKey("ci") && data.ContainsKey("ci_md5"))
- {
- keys.CI_plus.data = data["ci"];
- keys.CI_plus.md5 = data["ci_md5"];
- if (!CheckMD5(keys.CI_plus.data, keys.CI_plus.md5))
- {
- msg = string.Format("CI_plus Key Value md5 Is Incorrect: data={0}, md5={1}", keys.CI_plus.data, keys.CI_plus.md5);
- goto end;
- }
- }
- if (data.ContainsKey("ecp") && data.ContainsKey("ecp_md5"))
- {
- keys.ECP.data = data["ecp"];
- keys.ECP.md5 = data["ecp_md5"];
- if (!CheckMD5(keys.ECP.data, keys.ECP.md5))
- {
- msg = string.Format("ECP Key Value md5 Is Incorrect: data={0}, md5={1}", keys.ECP.data, keys.ECP.md5);
- goto end;
- }
- }
- if (data.ContainsKey("acas") && data.ContainsKey("acas_md5"))
- {
- keys.ACASKey_Data.data = data["acas"];
- keys.ACASKey_Data.md5 = data["acas_md5"];
- if (!CheckMD5(keys.ACASKey_Data.data, keys.ACASKey_Data.md5))
- {
- msg = string.Format("ACASKey_Data Key Value md5 Is Incorrect: data={0}, md5={1}", keys.ACASKey_Data.data, keys.ACASKey_Data.md5);
- goto end;
- }
- }
- if (data.ContainsKey("lek") && data.ContainsKey("lek_md5"))
- {
- keys.LEK.data = data["lek"];
- keys.LEK.md5 = data["lek_md5"];
- if (!CheckMD5(keys.LEK.data, keys.LEK.md5))
- {
- msg = string.Format("LEK Key Value md5 Is Incorrect: data={0}, md5={1}", keys.LEK.data, keys.LEK.md5);
- goto end;
- }
- }
- if (data.ContainsKey("pek") && data.ContainsKey("pek_md5"))
- {
- keys.PEK.data = data["pek"];
- keys.PEK.md5 = data["pek_md5"];
- if (!CheckMD5(keys.PEK.data, keys.PEK.md5))
- {
- msg = string.Format("PEK Key Value md5 Is Incorrect: data={0}, md5={1}", keys.PEK.data, keys.PEK.md5);
- goto end;
- }
- }
- if (data.ContainsKey("playready") && data.ContainsKey("playready_md5"))
- {
- keys.Playready.data = data["playready"];
- keys.Playready.md5 = data["playready_md5"];
- if (!CheckMD5(keys.Playready.data, keys.Playready.md5))
- {
- msg = string.Format("Playready Key Value md5 Is Incorrect: data={0}, md5={1}", keys.Playready.data, keys.Playready.md5);
- goto end;
- }
- }
- if (data.ContainsKey("netfilx") && data.ContainsKey("netfilx_md5"))
- {
- keys.ESN.data = data["netfilx"];
- keys.ESN.md5 = data["netfilx_md5"];
- if (!CheckMD5(keys.ESN.data, keys.ESN.md5))
- {
- msg = string.Format("ESN Key Value md5 Is Incorrect: data={0}, md5={1}", keys.ESN.data, keys.ESN.md5);
- goto end;
- }
- }
- if (data.ContainsKey("hash") && data.ContainsKey("hash_md5"))
- {
- keys.Hashkey.data = data["hash"];
- keys.Hashkey.md5 = data["hash_md5"];
- if (!CheckMD5(keys.Hashkey.data, keys.Hashkey.md5))
- {
- msg = string.Format("Hashkey Key Value md5 Is Incorrect: data={0}, md5={1}", keys.Hashkey.data, keys.Hashkey.md5);
- goto end;
- }
- }
- if (data.ContainsKey("mgk") && data.ContainsKey("mgk_md5"))
- {
- keys.MGK.data = data["mgk"];
- keys.MGK.md5 = data["mgk_md5"];
- if (!CheckMD5(keys.MGK.data, keys.MGK.md5))
- {
- msg = string.Format("MGK Key Value md5 Is Incorrect: data={0}, md5={1}", keys.MGK.data, keys.MGK.md5);
- goto end;
- }
- }
- if (data.ContainsKey("youtube") && data.ContainsKey("youtube_md5"))
- {
- keys.YouTube_KEY.data = data["youtube"];
- keys.YouTube_KEY.md5 = data["youtube_md5"];
- if (!CheckMD5(keys.YouTube_KEY.data, keys.YouTube_KEY.md5))
- {
- msg = string.Format("YouTube_KEY Key Value md5 Is Incorrect: data={0}, md5={1}", keys.YouTube_KEY.data, keys.YouTube_KEY.md5);
- goto end;
- }
- }
- if (data.ContainsKey("fairplay") && data.ContainsKey("fairplay_md5"))
- {
- keys.Fairplay.data = data["fairplay"];
- keys.Fairplay.md5 = data["fairplay_md5"];
- if (!CheckMD5(keys.Fairplay.data, keys.Fairplay.md5))
- {
- msg = string.Format("Fairplay Key Value md5 Is Incorrect: data={0}, md5={1}", keys.Fairplay.data, keys.Fairplay.md5);
- goto end;
- }
- }
- if (data.ContainsKey("widevine") && data.ContainsKey("widevine_md5"))
- {
- keys.Widevine.data = data["widevine"];
- keys.Widevine.md5 = data["widevine_md5"];
- if (!CheckMD5(keys.Widevine.data, keys.Widevine.md5))
- {
- msg = string.Format("Widevine Key Value md5 Is Incorrect: data={0}, md5={1}", keys.Widevine.data, keys.Widevine.md5);
- goto end;
- }
- }
- if (data.ContainsKey("attention") && data.ContainsKey("attention_md5"))
- {
- keys.Attestation.data = data["attention"];
- keys.Attestation.md5 = data["attention_md5"];
- if (!CheckMD5(keys.Attestation.data, keys.Attestation.md5))
- {
- msg = string.Format("Attestation Key Value md5 Is Incorrect: data={0}, md5={1}", keys.Attestation.data, keys.Attestation.md5);
- goto end;
- }
- }
- if (data.ContainsKey("dsn") && data.ContainsKey("dsn_md5"))
- {
- keys.DSN.data = data["dsn"];
- keys.DSN.md5 = data["dsn_md5"];
- if (!CheckMD5(keys.DSN.data, keys.DSN.md5))
- {
- msg = string.Format("DSN Key Value md5 Is Incorrect: data={0}, md5={1}", keys.DSN.data, keys.DSN.md5);
- goto end;
- }
- }
- if (data.ContainsKey("dak") && data.ContainsKey("dak_md5"))
- {
- keys.DAK.data = data["dak"];
- keys.DAK.md5 = data["dak_md5"];
- if (!CheckMD5(keys.DAK.data, keys.DAK.md5))
- {
- msg = string.Format("DAK Key Value md5 Is Incorrect: data={0}, md5={1}", keys.DAK.data, keys.DAK.md5);
- goto end;
- }
- }
- result = true;
- }
- }
- }
- catch {
- msg = "解决Json失败";
- }
- }
- end:
- watch.Stop();
- Log.WriteInfoLog(string.Format("[GetIDMKeys] order={0},sn={1},Elapsed={2} GetKeys={3}", order, sn, watch.Elapsed.TotalMilliseconds, result ? "成功" : "失败"));
- if ( !result )
- ReportErrormsg("Fail to GetIDMKeys ", msg + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + httpResult.Html, connection);
- return result;
- }
- /// <summary>
- /// 异常上报
- /// </summary>
- /// <param name="reportType"></param>
- /// <param name="reportData"></param>
- /// <param name="sqliteConn"></param>
- /// <returns></returns>
- public static bool ReportErrormsg(string reportType, string reportData, SQLiteConnection sqliteConn)
- {
- // 计算函数耗时;
- Stopwatch watch = new Stopwatch();
- watch.Start();
- ErrorInfo ErrorInfo1 = new ErrorInfo { reportType = reportType, reportData = reportData.Replace("'", ""), version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(), factory = FactoryName, mac = TestMode.MAC, reportTime = System.DateTime.Now.ToString(("yyyy-MM-dd HH:mm:ss")) };
- string jsonError = Newtonsoft.Json.JsonConvert.SerializeObject(ErrorInfo1, Newtonsoft.Json.Formatting.Indented);
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- URL = TestMode.errorreportServerurl,//URL这里都是测试URl 必需项
- Encoding = Encoding.UTF8,//编码格式(utf-8,gb2312,gbk) 可选项 默认类会自动识别
- //Encoding = Encoding.Default,
- Method = "post",//URL 可选项 默认为Get
- Postdata = jsonError,
- PostEncoding = Encoding.UTF8,
- KeepAlive = false
- };
- item.ContentType = "application/json;charset=utf-8";
- HttpResult result = http.GetHtml(item);
- string ParseText = result.Html;
- if (result.StatusCode == System.Net.HttpStatusCode.OK)
- {
- Log.WriteGetKeyLog("\r\nReportErrormsg:\r\n" + result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + TestMode.errorreportServerurl + "\r\nPostdata:" + jsonError);
- }
- else
- {
- Log.WriteErrorLog("\r\nFail to ReportErrormsg:\r\n" + result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + TestMode.errorreportServerurl + "\r\nPostdata:" + jsonError);
- return false;
- }
- try
- {
- JObject jObject = JObject.Parse(ParseText);
- string message = jObject["message"].Value<string>();
- string code = jObject["code"].Value<string>();
- if (code != "1000")
- {
- Log.WriteErrorLog("\r\nError report return error:\r\n" + ParseText + "\r\nAddress:" + TestMode.errorreportServerurl + "\r\nPostdata:" + jsonError);
- return false;
- }
- watch.Stop();
- Log.WriteInfoLog(string.Format("[ReportErrormsg] Elapsed={0}", watch.Elapsed.TotalMilliseconds));
- return true;
- }
- catch (Exception ex)
- {
- Log.WriteErrorLog("\r\nFail to parse Error report return info," + ex.Message + ":" + ParseText + "\r\nAddress:" + TestMode.errorreportServerurl + "\r\nPostdata:" + jsonError);
- return false;
- }
- }
- /// <summary>
- /// 上报预绑定包下载结果
- /// </summary>
- /// <param name="url"></param>
- /// <param name="order"></param>
- /// <param name="sqliteConn"></param>
- /// <returns></returns>
- [Obsolete]
- public static bool ReportDownloadStatus(string url, string order, SQLiteConnection sqliteConn)
- {
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- Encoding = null,//编码格式(utf-8,gb2312,gbk) 可选项 默认类会自动识别
- //Encoding = Encoding.Default,
- Method = "post",//URL 可选项 默认为Get
- Postdata = ("orderNumber =" + order),
- KeepAlive = false
- };
- #region 新接口统一返回带/v1,getreportofflinesn.do依旧采用旧host地址;
- if (url.EndsWith("/v1"))
- {
- url = url.Replace("/v1", "");
- }
- url += "/getreportofflinesn.do?";
- item.URL = url;
- #endregion
- item.ContentType = "application/x-www-form-urlencoded";
- HttpResult result = http.GetHtml(item);
- string ParseText = result.Html;
- if (result.StatusCode == System.Net.HttpStatusCode.OK)
- {
- //
- }
- else
- {
- Log.WriteErrorLog("\r\nFail to report download status:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "/getreportofflinesn.do?" + "\r\nPostdata:" + ("orderNumber =" + order));
- CommonMethod.ReportErrormsg("Fail to report download status", result.StatusDescription + result.Html + "\r\nAddress:" + url + "/getreportofflinesn.do?" + "\r\nPostdata:" + ("orderNumber =" + order), sqliteConn);
- return false;
- }
- try
- {
- JObject jObject = JObject.Parse(ParseText);
- string des = JSON_SeleteNode(jObject, "des");
- string code = JSON_SeleteNode(jObject, "code");
- string data = JSON_SeleteNode(jObject, "data");
- if (code == "1000")
- return true;
- else
- {
- Log.WriteErrorLog("\r\nError report download status,should be 1000:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "/getreportofflinesn.do?" + "\r\nPostdata:" + ("orderNumber =" + order));
- CommonMethod.ReportErrormsg("Error download status code return", result.StatusDescription + result.Html + "\r\nAddress:" + url + "/getreportofflinesn.do?" + "\r\nPostdata:" + ("orderNumber =" + order), sqliteConn);
- return false;
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- Log.WriteErrorLog("\r\n" + ex.Message + ":" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "/getreportofflinesn.do?" + "\r\nPostdata:" + ("orderNumber =" + order));
- CommonMethod.ReportErrormsg("Error parse download status return", result.StatusDescription + result.Html + "\r\nAddress:" + url + "/getreportofflinesn.do?" + "\r\nPostdata:" + ("orderNumber =" + order), sqliteConn);
- return false;
- }
- }
- /// <summary>
- /// 生成DB格式key json字符串
- /// </summary>
- /// <param name="keyInfo"></param>
- /// <param name="keydata"></param>
- /// <param name="error"></param>
- /// <returns></returns>
- public static bool CreateDBkeyString(KeyInfo keyInfo, out string keydata, out string error)
- {
- keydata = "";
- error = "";
- try
- {
- DBKeysStringFormat DBKeysStringFormat1 = new DBKeysStringFormat { cikey = keyInfo.CI_plus == null ? "" : keyInfo.CI_plus, esn = keyInfo.ESN == null ? "" : keyInfo.ESN, hdcp = keyInfo.HDCP == null ? "" : keyInfo.HDCP, widevine = keyInfo.Widevine == null ? "" : keyInfo.Widevine, hdcp22 = keyInfo.HDCP22 == null ? "" : keyInfo.HDCP22, did = keyInfo.DID == null ? "" : keyInfo.DID, mac = keyInfo.Mac == null ? "" : keyInfo.Mac, attestation = keyInfo.Attestation == null ? "" : keyInfo.Attestation, mgk = keyInfo.MGK == null ? "" : keyInfo.MGK };
- keydata = Newtonsoft.Json.JsonConvert.SerializeObject(DBKeysStringFormat1, Newtonsoft.Json.Formatting.Indented);
- return true;
- }
- catch (Exception ex)
- {
- error = ex.Message;
- return false;
- }
- }
- /// <summary>
- /// 获取相应json子节点的值
- /// </summary>
- /// <param name="childnodelist"></param>
- public static string JSON_SeleteNode(JToken json, string ReName)
- {
- try
- {
- string result = "";
- //这里6.0版块可以用正则匹配
- var node = json.SelectToken("$.." + ReName);
- if (node != null)
- {
- //判断节点类型
- if (node.Type == JTokenType.String || node.Type == JTokenType.Integer || node.Type == JTokenType.Float)
- {
- //返回string值
- result = node.Value<object>().ToString();
- }
- }
- return result;
- }
- catch (Exception ex)
- {
- return "";
- }
- }
- /// <summary>
- /// 确认是否为有效的url(检测开头是否为http://或者https://)
- /// </summary>
- /// <param name="Value"></param>
- /// <returns></returns>
- public static bool HTTPChecker(string Value)
- {
- try
- {
- if ((Value.Substring(0, 7) == "http://") || (Value.Substring(0, 8) == "https://"))
- {
- return true;
- }
- else
- return false;
- }
- catch (Exception ex)
- {
- return false;
- }
- }
- /// <summary>
- /// 检查是否能正常访问网络
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static bool CheckUrlConnection(string url)
- {
- try
- {
- HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
- myRequest.Method = "HEAD"; //设置提交方式可以为"get","head"等
- myRequest.Timeout = 10000; //设置网页响应时间长度
- myRequest.AllowAutoRedirect = false;//是否允许自动重定向
- myRequest.UseDefaultCredentials = true;
- HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
- myRequest.UseDefaultCredentials = true;//权限设置
- return (myResponse.StatusCode == HttpStatusCode.OK);//返回响应的状态
- }
- catch (Exception ex)
- {
- return false;
- }
- }
- /// <summary>
- /// 指定目录创建文件夹
- /// </summary>
- /// <param name="path"></param>
- public static void CreateDirectory(string path)
- {
- if (!Directory.Exists(path))//如果不存在就创建file文件夹
- {
- Directory.CreateDirectory(path);
- }
- }
- /// <summary>
- /// 在线下载抄写模式抄写的上报
- /// </summary>
- /// <param name="content"></param>
- /// <returns></returns>
- [Obsolete]
- public static bool UploadCopyResult(string content, string url, SQLiteConnection sqliteConn, string order, bool repeatupload, string id, int timeout)
- {
- if (timeout < 5000)
- timeout = 5000;
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- Encoding = Encoding.UTF8,
- Method = "post",
- ContentType = "application/x-www-form-urlencoded",
- Timeout = timeout,
- KeepAlive = false
- };
- item.PostEncoding = Encoding.UTF8;
- #region 新接口统一返回带/v1,report.do依旧采用旧host地址;
- if ( url.EndsWith("/v1") )
- {
- url = url.Replace("/v1", "");
- }
- item.URL = url + "/report.do?";
- #endregion
- item.Postdata = content;
- System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
- stopwatch.Start();
- HttpResult result = http.GetHtml(item);
- stopwatch.Stop();
- string usingtime = stopwatch.ElapsedMilliseconds.ToString();
- stopwatch.Reset();
- if (result.StatusCode == System.Net.HttpStatusCode.OK)
- {
- if (Xmlconfig.ReportXml(result.Html, "response", out string code, out string desc))
- {
- Log.WriteGetKeyLog("\r\nUpload copy status success:\r\nUsing time:" + usingtime + "ms\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
- return true;
- }
- else
- {
- CommonMethod.ReportErrormsg("Fail to parse copy result return", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, sqliteConn);
- Log.WriteErrorLog(code + "Error");
- if (repeatupload)
- {
- SQLiteHelper.DeleteDelayCopyReport(sqliteConn, id);
- }
- return false;
- }
- }
- else
- {
- if (repeatupload)
- return false;
- if (CommonMethod.HTTPChecker(item.URL))
- SQLiteHelper.InsertDelayCopyReport(sqliteConn, new object[] { order, item.URL, item.Postdata });
- CommonMethod.ReportErrormsg("Fail to upload copy result", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, sqliteConn);
- return true;
- }
- }
- /// <summary>
- /// 本地DB存储的异常重新上报
- /// </summary>
- /// <param name="reportType"></param>
- /// <param name="reportData"></param>
- /// <param name="sqliteConn"></param>
- /// <returns></returns>
- public static bool ReportErrormsg2(string url, string content, out bool mark)
- {
- mark = false;
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- URL = url,//URL这里都是测试URl 必需项
- Encoding = Encoding.UTF8,//编码格式(utf-8,gb2312,gbk) 可选项 默认类会自动识别
- //Encoding = Encoding.Default,
- Method = "post",//URL 可选项 默认为Get
- Postdata = content,
- PostEncoding = Encoding.UTF8,
- KeepAlive = false
- };
- item.ContentType = "application/json;charset=utf-8";
- HttpResult result = http.GetHtml(item);
- string ParseText = result.Html;
- if (result.StatusCode == System.Net.HttpStatusCode.OK)
- {
- mark = true;
- Log.WriteGetKeyLog("\r\nReportErrormsg:\r\n" + result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + TestMode.errorreportServerurl + "\r\nPostdata:" + content);
- }
- else
- {
- Log.WriteErrorLog("\r\nFail to ReportErrormsg:\r\n" + result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + TestMode.errorreportServerurl + "\r\nPostdata:" + content);
- return false;
- }
- try
- {
- JObject jObject = JObject.Parse(ParseText);
- string message = jObject["message"].Value<string>();
- string code = jObject["code"].Value<string>();
- if (code == "1000")
- return true;
- else
- {
- Log.WriteErrorLog("\r\nError report return error:\r\n" + ParseText + "\r\nAddress:" + TestMode.errorreportServerurl + "\r\nPostdata:" + content);
- return false;
- }
- }
- catch (Exception ex)
- {
- Log.WriteErrorLog("\r\nFail to parse Error report return info," + ex.Message + ":" + ParseText + "\r\nAddress:" + TestMode.errorreportServerurl + "\r\nPostdata:" + content);
- return false;
- }
- }
- /// <summary>
- /// 判断目标字符串是否只有数字和字母
- /// </summary>
- /// <param name="value">目标字符串</param>
- /// <returns></returns>
- public static bool IsNumberAndWord(string value)
- {
- if (value is null)
- return false;
- try
- {
- Regex r = new Regex(@"^[a-zA-Z0-9]+$");
- return r.Match(value).Success;
- }
- catch(Exception ex)
- {
- Log.WriteErrorLog(string.Format("Regex Match Error. {0} -> {1} ", value, ex.Message));
- }
- return false;
- }
- public static bool InsertJsonConfig(string node, string key, bool value = false)
- {
- JObject jObject;
- using (StreamReader file = new StreamReader(LocalPath.localpath + "\\Config.json"))
- {
- using (JsonTextReader reader = new JsonTextReader(file))
- {
- jObject = (JObject)JToken.ReadFrom(reader);
- jObject[node][key] = value;
- }
- }
- using (StreamWriter writer = new StreamWriter(LocalPath.localpath + "\\Config.json"))
- {
- writer.Write(jObject.ToString());
- }
- return true;
- }
- public static bool AddJsonConfig(string key, object value)
- {
- JObject jObject;
- using (StreamReader file = new StreamReader(LocalPath.localpath + "\\Config.json"))
- {
- using (JsonTextReader reader = new JsonTextReader(file))
- {
- jObject = (JObject)JToken.ReadFrom(reader);
- jObject.Add(key, (JToken)value);
- }
- }
- using (StreamWriter writer = new StreamWriter(LocalPath.localpath + "\\Config.json"))
- {
- writer.Write(jObject.ToString());
- }
- return false;
- }
- /// <summary>
- /// 预下载模式抄写的上报
- /// </summary>
- /// <param name="copydate">烧录时间</param>
- /// <returns></returns>
- [Obsolete]
- public static bool UploadPreloadCopyResult(string host, string copydate, string SN, SQLiteConnection localDBNow, SQLiteConnection sqliteConn, bool repeatupload, string id, int timeout)
- {
- string ParseText = "";
- bool status;
- try
- {
- List<PostDateClass> postList = new List<PostDateClass>();
- postList.Add(new PostDateClass("sn", SN));
- postList.Add(new PostDateClass("date", copydate));
- #region 新接口统一返回带/v1,reportlist.do依旧采用旧host地址;
- if (host.EndsWith("/v1"))
- {
- host = host.Replace("/v1", "");
- }
- #endregion
- ParseText = FormPost.postFileMessage(host + "/reportlist.do?", postList, out status, timeout);
- if (status)
- {
- JObject jObject = JObject.Parse(ParseText);
- string des = CommonMethod.JSON_SeleteNode(jObject, "des");
- string code = CommonMethod.JSON_SeleteNode(jObject, "code");
- string data = JSON_SeleteNode(jObject, "data");
- if (code == "1000")
- {
- //更新上报内容
- if (SQLiteHelper.UpdateReportStatus(localDBNow, SN))
- {
- //更新成功
- Log.WriteGetKeyLog("\r\nUpdateReportStatus success:\r\n" + host + "/reportlist.do?\r\n" + "sn=" + SN + "\r\ndate=" + copydate + "\r\n" + ParseText);
- return true;
- }
- else
- {
- Log.WriteErrorLog("\r\nFail to UpdateReportStatus: " + SN);
- return false;
- }
- }
- else
- {
- CommonMethod.ReportErrormsg("Fail to UploadPreloadCopyResult", "Address: " + host + "/reportlist.do?" + "\r\nPostdata: " + "sn=" + SN + "\r\ndate=" + copydate + "\r\n" + ParseText, sqliteConn);
- Log.WriteErrorLog("\r\nUpdateReportStatus code return error,should be 1000 " + "\r\n" + SN + ":" + ParseText + "\r\nAddress:" + host + "/reportlist.do?" + "\r\nPostdata: " + "sn=" + SN + "\r\ndate=" + copydate);
- if (repeatupload)
- {
- SQLiteHelper.DeleteDelayCopyReport(sqliteConn, id);
- }
- return false;
- }
- }
- else
- {
- if (repeatupload)
- return false;
- if (CommonMethod.HTTPChecker(host))
- SQLiteHelper.InsertDelayCopyReport(sqliteConn, new object[] { "preload_mode", host, SN + "@" + copydate });
- return false;
- }
- }
- catch (Exception ex)
- {
- Log.WriteErrorLog("\r\nFail to parse UpdateReportStatus return: " + ex.Message + "\r\n" + SN + ":" + ParseText);
- return false;
- }
- }
- /// <summary>
- /// 预下载模式抄写的批量上报
- /// </summary>
- /// <param name="host"></param>
- /// <param name="postList"></param>
- /// <param name="localDBNow"></param>
- /// <param name="sqliteConn"></param>
- /// <param name="repeatupload"></param>
- /// <param name="id"></param>
- /// <returns></returns>
- [Obsolete]
- public static bool UploadPreloadCopyResultList(string host, List<PostDateClass> postList, SQLiteConnection localDBNow, SQLiteConnection sqliteConn, bool repeatupload, string id)
- {
- string ParseText = "";
- bool status;
- try
- {
- #region 新接口统一返回带/v1,reportlist.do依旧采用旧host地址;
- if (host.EndsWith("/v1"))
- {
- host = host.Replace("/v1", "");
- }
- #endregion
- ParseText = FormPost.postFileMessage(host + "/reportlist.do?", postList, out status, 30000);
- if (status)
- {
- JObject jObject = JObject.Parse(ParseText);
- string des = CommonMethod.JSON_SeleteNode(jObject, "des");
- string code = CommonMethod.JSON_SeleteNode(jObject, "code");
- string data = JSON_SeleteNode(jObject, "data");
- if (code == "1000")
- {
- Log.WriteGetKeyLog("UploadPreloadCopyResult successful\r\nAddress: " + host + "/reportlist.do?" + ParseText);
- return true;
- }
- else
- {
- CommonMethod.ReportErrormsg("Fail to UploadPreloadCopyResult", "Address: " + host + "/reportlist.do?" + ParseText, sqliteConn);
- Log.WriteErrorLog("\r\nUpdateReportStatus code return error,should be 1000 " + "\r\n" + ParseText + "\r\nAddress:" + host + "/reportlist.do?");
- if (repeatupload)
- {
- SQLiteHelper.DeleteDelayCopyReport(sqliteConn, id);
- }
- return false;
- }
- }
- else
- {
- Log.WriteErrorLog("Fail to UploadPreloadCopyResult\r\nAddress: " + host + "/reportlist.do?" + ParseText);
- return false;
- }
- }
- catch (Exception ex)
- {
- Log.WriteErrorLog("\r\nFail to parse UpdateReportStatus return: " + ex.Message + "\r\n" + ParseText);
- return false;
- }
- }
- /// <summary>
- /// byte[]数组到int转换
- /// </summary>
- /// <param name="value"></param>
- /// <returns></returns>
- public static int BytelisttoInt(byte[] value)
- {
- Array.Reverse(value);
- int result = 0;
- for (int i = 0; i < value.Length; i++)
- {
- result += value[i] << i * 8;
- }
- return result;
- }
- /// <summary>
- /// int类型到byte[]数组转换
- /// </summary>
- /// <param name="value"></param>
- /// <returns></returns>
- public static byte[] InttoBytelist(int value)
- {
- byte[] bytes = BitConverter.GetBytes(value);
- Array.Reverse(bytes);
- if (value == 0)
- return bytes;
- List<byte> list = new List<byte>();
- list.AddRange(bytes);
- while (true)
- {
- if (list[0] != 0)
- break;
- else
- list.RemoveAt(0);
- }
- bytes = list.ToArray();
- return bytes;
- }
- /// <summary>
- /// 升级检查
- /// </summary>
- /// <param name="url"></param>
- /// <param name="FactoryNum"></param>
- /// <param name="sqliteConn"></param>
- /// <param name="upmid"></param>
- /// <returns></returns>
- public static bool UpgradeCheck(string url, string FactoryNum, SQLiteConnection sqliteConn, out UpgradeMsgList upmid)
- {
- upmid = new UpgradeMsgList();
- UpgradeCheckInput UpgradeCheckInput1 = new UpgradeCheckInput { appid = "SCBC_Factory_Tools", devicemodel = "SCBC_Factory_Tools", dnum = FactoryNum, ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(), type = "pc" };//System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()
- string jsonorder = Newtonsoft.Json.JsonConvert.SerializeObject(UpgradeCheckInput1, Newtonsoft.Json.Formatting.Indented);
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- URL = url,//URL这里都是测试URl 必需项
- Encoding = Encoding.UTF8,//编码格式(utf-8,gb2312,gbk) 可选项 默认类会自动识别
- //Encoding = Encoding.Default,
- Method = "post",//URL 可选项 默认为Get
- Postdata = jsonorder,
- PostEncoding = Encoding.UTF8,
- KeepAlive = false
- };
- item.ContentType = "application/json;charset=utf-8";
- ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
- | SecurityProtocolType.Tls
- | SecurityProtocolType.Tls11//(SecurityProtocolType)0x300 //Tls11
- | SecurityProtocolType.Tls12;//(SecurityProtocolType)0xC00; //Tls12
- HttpResult result = http.GetHtml(item);
- string ParseText = result.Html;
- if (result.StatusCode == System.Net.HttpStatusCode.OK)
- {
- Log.WriteGetKeyLog("\r\nUpgrade check," + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
- }
- else
- {
- Log.WriteErrorLog("\r\nFail to upgrade check:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
- ReportErrormsg("Fail to upgrade check", result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
- return false;
- }
- try
- {
- JObject jObject = JObject.Parse(ParseText);
- upmid.servertime = jObject["servertime"].Value<string>();
- upmid.callid = jObject["callid"].Value<string>();
- upmid.state = jObject["state"].Value<string>();
- upmid.note = jObject["note"].Value<string>();
- upmid.language = jObject["language"].Value<string>();
- upmid.apiversion = jObject["apiversion"].Value<string>();
- upmid.upgrade = new UpgradeMsgList2()
- {
- type = JSON_SeleteNode(jObject, "type"),
- appid = JSON_SeleteNode(jObject, "appid"),
- apptype = JSON_SeleteNode(jObject, "apptype"),
- version = JSON_SeleteNode(jObject, "version"),
- verid = JSON_SeleteNode(jObject, "verid"),
- md5 = JSON_SeleteNode(jObject, "md5"),
- size = JSON_SeleteNode(jObject, "size"),
- minicon = JSON_SeleteNode(jObject, "minicon"),
- midicon = JSON_SeleteNode(jObject, "midicon"),
- fileurl = JSON_SeleteNode(jObject, "fileurl"),
- increment = JSON_SeleteNode(jObject, "increment"),
- appendver = JSON_SeleteNode(jObject, "appendver"),
- updatetime = JSON_SeleteNode(jObject, "updatetime")
- };
- if (upmid.state == "0000")
- return true;
- else
- {
- return false;
- }
- }
- catch (Exception ex)
- {
- Log.WriteErrorLog("\r\nFail to parse upgrade check info," + ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
- ReportErrormsg("Fail to parse upgrade check info", ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
- MessageBox.Show("Fail to parse upgrade check info\r\n " + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 升级上报
- /// </summary>
- /// <param name="url"></param>
- /// <param name="FactoryNum"></param>
- /// <param name="Result"></param>
- /// <param name="sqliteConn"></param>
- /// <returns></returns>
- public static bool UpgradeReport(string url, string FactoryNum, string Result, SQLiteConnection sqliteConn)
- {
- UpgradeReportInput UpgradeCheckInput1 = new UpgradeReportInput { appid = "SCBC_Factory_Tools", devmodel = "SCBC_Factory_Tools", dnum = FactoryNum, ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(), type = "pc", result = Result };
- string jsonorder = Newtonsoft.Json.JsonConvert.SerializeObject(UpgradeCheckInput1, Newtonsoft.Json.Formatting.Indented);
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- URL = url,//URL这里都是测试URl 必需项
- Encoding = Encoding.UTF8,//编码格式(utf-8,gb2312,gbk) 可选项 默认类会自动识别
- //Encoding = Encoding.Default,
- Method = "post",//URL 可选项 默认为Get
- Postdata = jsonorder,
- PostEncoding = Encoding.UTF8,
- KeepAlive = false
- };
- item.ContentType = "application/json;charset=utf-8";
- ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
- | SecurityProtocolType.Tls
- | (SecurityProtocolType)0x300 //Tls11
- | (SecurityProtocolType)0xC00; //Tls12
- HttpResult result = http.GetHtml(item);
- string ParseText = result.Html;
- if (result.StatusCode == System.Net.HttpStatusCode.OK)
- {
- Log.WriteGetKeyLog("\r\nUpgrade report," + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
- }
- else
- {
- Log.WriteErrorLog("\r\nFail to upgrade report:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
- ReportErrormsg("Fail to upgrade report", result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
- return false;
- }
- try
- {
- JObject jObject = JObject.Parse(ParseText);
- return true;
- }
- catch (Exception ex)
- {
- Log.WriteErrorLog("\r\nFail to parse upgrade report info," + ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
- ReportErrormsg("Fail to parse upgrade report info", ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
- MessageBox.Show("Fail to parse upgrade report info\r\n " + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 比较本地文件的MD5值
- /// </summary>
- /// <param name="filename"></param>
- /// <param name="filetype"></param>
- /// <param name="filemd5"></param>
- /// <param name="error"></param>
- /// <returns></returns>
- public static bool CompareLocalkey(string filename, string filetype, string filemd5, out string error, out string filefullname)
- {
- error = "";
- filefullname = "";
- try
- {
- string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Keys\\" + filename + "\\" + filetype;
- if (!Directory.Exists(filepath))
- {
- Directory.CreateDirectory(filepath);
- }
- DirectoryInfo Getkeyfile = new DirectoryInfo(filepath);
- foreach (FileInfo keyfile in Getkeyfile.GetFiles())
- {
- string FileMD5 = GetMD5.GetMD5HashFromFile(keyfile.Name);
- if (FileMD5 == filemd5)
- {
- Log.WriteGetKeyLog("Check md5file success,file md5:" + FileMD5 + "\r\nfile:" + keyfile.FullName);
- filefullname = keyfile.FullName;
- return true;
- }
- else
- {
- Log.WriteErrorLog("Check md5file error,delete file:" + keyfile.FullName + "\r\nfile md5" + FileMD5);
- File.Delete(keyfile.FullName);
- }
- }
- return false;
- }
- catch (Exception ex)
- {
- error = ex.Message;
- return false;
- }
- }
- /// <summary>
- /// 数据MD5核对。当数据头为"MD5="时,key内容比对改为key内容MD5比对
- /// </summary>
- /// <param name="key"></param>
- /// <param name="data"></param>
- /// <param name="md5"></param>
- /// <returns></returns>
- public static bool CompareMD5(byte[] key, byte[] data)
- {
- string strdata = Encoding.ASCII.GetString(data);
- Console.WriteLine(strdata);
- if (strdata.StartsWith("MD5="))
- {
- string md5 = GetMD5.GetMD5Hash(key);
- Console.WriteLine(md5);
- return strdata.Remove(0, 4).Equals(md5);
- }
- return false;
- }
- /// <summary>
- /// 将16进制字符串转为对应字节流写入生成key文件
- /// </summary>
- /// <param name="path"></param>
- /// <param name="data"></param>
- /// <param name="error"></param>
- /// <returns></returns>
- public static bool GetCreateHexkey(string path, string data, out string error)
- {
- error = "";
- try
- {
- string filepath = path + ".bin";
- byte[] bytedata = SerialInit.HexToByte(data);
- //创建一个文件流
- FileStream fs = new FileStream(filepath, FileMode.Create);
- fs.Write(bytedata, 0, bytedata.Length);
- fs.Close();
- Log.WriteGetKeyLog("save key:" + filepath);
- return true;
- }
- catch (Exception ex)
- {
- error = ex.Message;
- Log.WriteErrorLog("save key error:" + error);
- return false;
- }
- }
- /// <summary>
- /// 读取key文件内容转换为16进制字符串
- /// </summary>
- /// <param name="filepath"></param>
- /// <param name="data"></param>
- /// <param name="error"></param>
- /// <returns></returns>
- public static bool ReadHexFile(string filepath, out string data, out string error)
- {
- data = "";
- error = "";
- try
- {
- using FileStream fskey = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.None);
- {
- using BinaryReader brkey = new BinaryReader(fskey);
- {
- data = SerialInit.ByteToHex(brkey.ReadBytes((int)fskey.Length));
- data = data.Replace(" ", "");
- return true;
- }
- }
- }
- catch (Exception ex)
- {
- error = ex.Message;
- return false;
- }
- }
- /// <summary>
- /// 账号登录
- /// </summary>
- /// <param name="url"></param>
- /// <param name="account"></param>
- /// <param name="password"></param>
- /// <param name="pcmac"></param>
- /// <param name="sqliteConn"></param>
- /// <param name="loginOutput1"></param>
- /// <returns></returns>
- public static bool UserLogin(string url, string account, string password, string pcmac, SQLiteConnection sqliteConn, out LoginOutput loginOutput1)
- {
- loginOutput1 = new LoginOutput();
- LoginInput LoginInput1 = new LoginInput { account = account, password = password, mac = pcmac, toolVersion = Utils.FileUtils.GetAssemblyVersion() };
- string jsonorder = Newtonsoft.Json.JsonConvert.SerializeObject(LoginInput1, Newtonsoft.Json.Formatting.Indented);
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- URL = url,//URL这里都是测试URl 必需项
- Encoding = Encoding.UTF8,//编码格式(utf-8,gb2312,gbk) 可选项 默认类会自动识别
- //Encoding = Encoding.Default,
- Method = "post",//URL 可选项 默认为Get
- Postdata = jsonorder,
- PostEncoding = Encoding.UTF8,
- KeepAlive = false
- };
- item.ContentType = "application/json;charset=utf-8";
- ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;//
- HttpResult result = http.GetHtml(item);
- string ParseText = result.Html;
- if (result.StatusCode == HttpStatusCode.OK)
- {
- Log.WriteGetKeyLog("\r\nLogin," + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
- }
- else
- {
- Log.WriteErrorLog("\r\nFail to login:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
- ReportErrormsg("Fail to login", result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
- return false;
- }
- try
- {
- JObject jObject = JObject.Parse(ParseText);
- loginOutput1.msg = jObject["msg"].Value<string>();
- loginOutput1.code = jObject["code"].Value<string>();
- loginOutput1.factoryname = JSON_SeleteNode(jObject, "factoryName");
- loginOutput1.factorynum = JSON_SeleteNode(jObject, "factoryNum");
- if (loginOutput1.code == "1000")
- return true;
- else
- return false;
- }
- catch (Exception ex)
- {
- Log.WriteErrorLog("\r\nFail to login," + ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
- ReportErrormsg("Fail to login", ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
- MessageBox.Show("Fail to parse login return\r\n " + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 获取指定日期,在为一年中为第几周
- /// </summary>
- /// <param name="dt">指定时间</param>
- /// <reutrn>返回第几周</reutrn>
- public static int GetWeekOfYear(DateTime dt)
- {
- GregorianCalendar gc = new GregorianCalendar();
- int weekOfYear = gc.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
- return weekOfYear;
- }
- /// <summary>
- /// 版本号比较:new_version>=old_version
- /// </summary>
- /// <param name="new_version">8.4.0</param>
- /// <param name="old_version">8.3.10</param>
- /// <returns></returns>
- public static bool CompareVersion(string new_version, string old_version)
- {
- try
- {
- if (string.IsNullOrEmpty(new_version) || string.IsNullOrEmpty(old_version))
- return false;
- Version v_new = new Version(new_version);
- Version v_old = new Version(old_version);
- if (v_new >= v_old)
- return true;
- return false;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- /// <summary>
- /// 获取白平衡信息
- /// </summary>
- /// <param name="url"></param>
- /// <param name="order"></param>
- /// <param name="pcmac"></param>
- /// <param name="sqliteConn"></param>
- /// <param name="WBList"></param>
- /// <returns></returns>
- public static bool GetWhiteBalanceInfo(string url, string order, string pcmac, SQLiteConnection sqliteConn, out WhiteBalanceList WBList)
- {
- WBList = new WhiteBalanceList();
- WhiteBalanceInput WBInput1 = new WhiteBalanceInput { bid = order, mac = pcmac };//"74-27-EA-6E-DA-9F"
- string jsonorder = Newtonsoft.Json.JsonConvert.SerializeObject(WBInput1, Newtonsoft.Json.Formatting.Indented);
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- URL = url,//URL这里都是测试URl 必需项
- Encoding = Encoding.UTF8,//编码格式(utf-8,gb2312,gbk) 可选项 默认类会自动识别
- //Encoding = Encoding.Default,
- Method = "post",//URL 可选项 默认为Get
- Postdata = jsonorder,
- PostEncoding = Encoding.UTF8,
- KeepAlive = false
- };
- // 如果是墨西哥和印度工厂,白平衡地址为本地;
- if (functionSetting != null && (functionSetting.Mexican_IDM || functionSetting.IndiaMITVEnable))
- item.URL = midList.host + "/order/getBalanceMessage";
- item.ContentType = "application/json;charset=utf-8";
- System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
- stopwatch.Start();
- HttpResult result = http.GetHtml(item);
- stopwatch.Stop();
- string usingtime = stopwatch.ElapsedMilliseconds.ToString();
- stopwatch.Reset();
- string ParseText = result.Html;
- if (result.StatusCode == System.Net.HttpStatusCode.OK)
- {
- Log.WriteGetKeyLog("\r\nGet WB info\r\nUsing time:" + usingtime + "ms\r\n" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
- }
- else
- {
- Log.WriteErrorLog("\r\nFail to WBinfo:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
- ReportErrormsg("Fail to WBinfo", result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
- return false;
- }
- try
- {
- JObject jObject = JObject.Parse(ParseText);
- WBList.message = jObject["message"].Value<string>();
- WBList.code = jObject["code"].Value<string>();
- object a = jObject["obj"];
- if (jObject["obj"].ToString().Length > 0)
- WBList.whiteBalanceInfo = new WhiteBalanceInfo()
- {
- id = JSON_SeleteNode(jObject["obj"], "id"),
- ordernum = JSON_SeleteNode(jObject["obj"], "ordernum"),
- hdmirgain = JSON_SeleteNode(jObject["obj"], "hdmirgain"),
- hdmiggain = JSON_SeleteNode(jObject["obj"], "hdmiggain"),
- hdmibgain = JSON_SeleteNode(jObject["obj"], "hdmibgain"),
- nrgain = JSON_SeleteNode(jObject["obj"], "nrgain"),
- nggain = JSON_SeleteNode(jObject["obj"], "nggain"),
- nbgain = JSON_SeleteNode(jObject["obj"], "nbgain"),
- lrgain = JSON_SeleteNode(jObject["obj"], "lrgain"),
- lggain = JSON_SeleteNode(jObject["obj"], "lggain"),
- lbgain = JSON_SeleteNode(jObject["obj"], "lbgain"),
- updatetime = JSON_SeleteNode(jObject["obj"], "updatetime"),
- createtime = JSON_SeleteNode(jObject["obj"], "createtime"),
- isdelete = JSON_SeleteNode(jObject["obj"], "isdelete"),
- isExemption = JSON_SeleteNode(jObject["obj"], "isExemption")
- };
- if (WBList.code == "1000")
- return true;
- else
- return false;
- }
- catch (Exception ex)
- {
- Log.WriteErrorLog("\r\nFail to parse WB info," + ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
- ReportErrormsg("Fail to parse WB info", ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
- MessageBox.Show("Fail to parse WB info\r\n " + ex.Message);
- return false;
- }
- }
- private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
- {
- return true;
- }
- /// <summary>
- /// 读取指定订单号的文件内容;
- /// </summary>
- /// <param name="order"></param>
- public static void ReadSNACASID(string order)
- {
- string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\SN-ACAS";
- if (!Directory.Exists(path))
- return;
- string fileName = path + "\\" + order + ".txt";
- if (!File.Exists(fileName))
- return;
- try
- {
- IEnumerable<string> lines = File.ReadLines(fileName);
- foreach (string line in lines)
- {// key=SN val=ACAS
- SN_ACAS_MAP.Add(line.Split(';')[0], line.Split(';')[1]);
- }
- }
- catch(Exception ex) { }
- }
- /// <summary>
- /// 判断SN和ACAS是否已存在;
- /// </summary>
- /// <param name="sn"></param>
- /// <param name="acas"></param>
- /// <returns></returns>
- public static bool IsSNAndACASExist(string sn, string acas)
- {
- if ( SN_ACAS_MAP.Keys.Contains(sn) || SN_ACAS_MAP.Values.Contains(acas))
- return true;
- return false;
- }
- /// <summary>
- /// 导出日本的SN与ACASID到文本中;
- /// </summary>
- /// <param name="ordernum"></param>
- /// <param name="sn"></param>
- /// <param name="acasid"></param>
- public static void ExportSNACASID(string ordernum, string sn, string acasid)
- {
- string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\SN-ACAS";
- if (!Directory.Exists(path))
- {
- Directory.CreateDirectory(path);
- }
- if (!lastOrder.Equals(ordernum))
- {
- lastOrder = ordernum;
- ReadSNACASID(ordernum);
- ListACASSN.Clear();
- }
- string msg = string.Format("{0};{1}", sn, acasid);
- if (ListACASSN.Contains(msg))
- {
- return;
- }
- ListACASSN.Add(msg);
- SN_ACAS_MAP.Add(sn, acasid);
- string fileName = path + "\\" + ordernum + ".txt";
- var stream = new StreamWriter(fileName, true);
- stream.WriteLine(msg);
- stream.Close();
- stream.Dispose();
- }
- /// <summary>
- /// 是否抄写EDID;
- /// </summary>
- /// <param name="midInfo"></param>
- /// <returns></returns>
- public static bool IsEDIDCopy(MidList midInfo)
- {
- if (midInfo == null || midInfo.keytype == null)
- return false;
- if (!midInfo.keytype.ContainsKey("edid_pid") && !midInfo.keytype.ContainsKey("edid_model_name"))
- return false;
- return true;
- }
- #region 小米FireTV功能模块相关接口;
- public static bool GetMIKey(string url, string sn, out MIKey mikey, out string msg)
- {
- msg = "";
- mikey = new MIKey();
- string strPost = String.Format("{{\"TVSN\":\"{0}\"}}", sn);
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- Encoding = Encoding.UTF8,
- Method = "post",
- ContentType = "application/json",
- KeepAlive = false
- };
- item.URL = url;
- item.Postdata = strPost;
- HttpResult hResult = http.GetHtml(item);
- if (hResult.StatusCode == System.Net.HttpStatusCode.OK)
- {
- try
- {
- using (JsonTextReader reader = new JsonTextReader(new StringReader(hResult.Html)))
- {
- JObject jObject = (JObject)JToken.ReadFrom(reader);
- reader.Close();
- bool bResult = jObject["Result"].Value<bool>();
- msg = jObject["Error"].Value<string>();
- JArray jAry = (JArray)JsonConvert.DeserializeObject(jObject["Data"].ToString());
- if (jAry == null)
- {
- Log.WriteErrorLog("GetMIKey Json-null:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
- return false;
- }
- if ( jAry.Count > 0 )
- {
- mikey = JsonConvert.DeserializeObject<MIKey>(jAry[0].ToString());
- }
- if (bResult)
- {
- Log.WriteInfoLog("GetMIKey Info:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
- return true;
- }
- Log.WriteInfoLog("GetMIKey error:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
- }
- }
- catch (Exception e)
- {
- msg = e.Message;
- Log.WriteErrorLog("GetMIKey Json-error:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
- }
- }
- else
- {
- msg = hResult.StatusDescription;
- Log.WriteInfoLog("GetMIKey Http-error:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
- }
- return false;
- }
- public static bool ReportMIKey(string url, ReportMIKey mikey, out string msg)
- {
- msg = "";
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- Encoding = Encoding.UTF8,
- Method = "post",
- ContentType = "application/json",
- KeepAlive = false
- };
- item.URL = url;
- item.Postdata = JsonConvert.SerializeObject(mikey); ;
- HttpResult hResult = http.GetHtml(item);
- if (hResult.StatusCode == System.Net.HttpStatusCode.OK)
- {
- try
- {
- using (JsonTextReader reader = new JsonTextReader(new StringReader(hResult.Html)))
- {
- JObject jObject = (JObject)JToken.ReadFrom(reader);
- reader.Close();
- bool bResult = jObject["Result"].Value<bool>();
- msg = jObject["Error"].Value<string>();
- string data = jObject["Data"].ToString();
- if (bResult)
- {
- Log.WriteInfoLog("ReportMIKey info:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
- return true;
- }
- Log.WriteInfoLog("ReportMIKey error:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
- }
- }
- catch (Exception e)
- {
- msg = e.Message;
- Log.WriteErrorLog("ReportMIKey Json-error:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
- }
- }
- else
- {
- msg = hResult.StatusDescription;
- Log.WriteInfoLog("ReportMIKey Http-error:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
- }
- return false;
- }
- #endregion
- }
- /// <summary>
- /// CRC32
- /// </summary>
- class CRC32
- {
- //生成CRC32码表
- static uint[] Crc32Table;
- private static void GetCRC32Table()
- {
- uint Crc;
- Crc32Table = new uint[256];
- int i, j;
- for (i = 0; i < 256; i++)
- {
- Crc = (uint)i;
- for (j = 8; j > 0; j--)
- {
- if ((Crc & 1) == 1)
- Crc = (Crc >> 1) ^ 0xEDB88320;
- else
- Crc >>= 1;
- }
- Crc32Table[i] = Crc;
- }
- }
- public static uint GetCRC32(byte[] bytes)
- {
- GetCRC32Table();
- uint value = 0xffffffff;
- int len = bytes.Length;
- for (int i = 0; i < len; i++)
- {
- value = (value >> 8) ^ Crc32Table[(value & 0xFF) ^ bytes[i]];
- }
- return value ^ 0xffffffff;
- }
- }
- /// <summary>
- /// 本地抄写模式方法
- /// </summary>
- public class GetLocalKeyCount
- {
- static string LocalKeyPath = AppDomain.CurrentDomain.BaseDirectory + "\\Keys\\";
- public static bool GetLocalDidCount(string order, out int num, ref MidList localmidList, SQLiteConnection errorDBNow)
- {
- num = 0;
- try
- {
- string DIDpath = LocalKeyPath + order + "\\DeviceID";
- if (Directory.Exists(DIDpath) == false)
- return false;
- else
- {
- DirectoryInfo GetDIDfile = new DirectoryInfo(DIDpath);
- foreach (FileInfo keyfile in GetDIDfile.GetFiles())
- {
- string filename = keyfile.FullName;
- //if (keyfile.Name.Contains("Online"))
- if (false)
- {
- if (localmidList.host == null)
- {
- //if (CommonMethod.GetMidInfo(TestMode.serverurl, order, TestMode.MAC, "", "", errorDBNow, out localmidList))
- if (V2Method.GetMidInfo(order, TestMode.MAC, errorDBNow, out localmidList))
- {
- ;
- }
- else
- {
- num = -1;
- return true;
- }
- }
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- Encoding = Encoding.Default,
- Method = "post",
- ContentType = "application/x-www-form-urlencoded"
- };
- string url1 = localmidList.host + "/statdeviceid.do?";
- item.URL = url1;
- item.Postdata = "devicetype=tcl_unknown_model";
- HttpResult result = http.GetHtml(item);
- if (result.StatusCode == System.Net.HttpStatusCode.OK)
- {
- Log.WriteGetKeyLog("\r\nGetDeviceID count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
- if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out string code, out string desc, out string count))
- {
- num = Convert.ToInt32(count.Replace(",", ""));
- return true;
- }
- else
- {
- num = -1;
- return true;
- }
- }
- else
- {
- num = -1;
- return true;
- }
- }
- else
- {
- num = GetDIDfile.GetFiles().Length;
- return true;
- }
- }
- return true;
- }
- }
- catch (Exception ex)
- {
- num = -1;
- return true;
- }
- }
- public static bool GetLocalMacCount(string order, out int num, ref MidList localmidList, SQLiteConnection errorDBNow)
- {
- num = 0;
- try
- {
- string MACpath = LocalKeyPath + order + "\\MAC";
- if (Directory.Exists(MACpath) == false)
- return false;
- else
- {
- DirectoryInfo GetMACfile = new DirectoryInfo(MACpath);
- foreach (FileInfo keyfile in GetMACfile.GetFiles())
- {
- string filename = keyfile.FullName;
- //if (keyfile.Name.Contains("Online"))
- if (false)
- {
- if (localmidList.host == null)
- {
- //if (CommonMethod.GetMidInfo(TestMode.serverurl, order, TestMode.MAC, "", "", errorDBNow, out localmidList))
- if (V2Method.GetMidInfo(order, TestMode.MAC, errorDBNow, out localmidList))
- {
- ;
- }
- else
- {
- num = -1;
- return true;
- }
- }
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- Encoding = Encoding.Default,
- Method = "post",
- ContentType = "application/x-www-form-urlencoded"
- };
- string url1 = localmidList.host + "/statmac.do?";
- item.URL = url1;
- item.Postdata = "typeString=" + localmidList.keytype["MAC"];
- HttpResult result = http.GetHtml(item);
- if (result.StatusCode == System.Net.HttpStatusCode.OK)
- {
- Log.WriteGetKeyLog("\r\nGetMac count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
- if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out string code, out string desc, out string count))
- {
- num = Convert.ToInt32(count.Replace(",", ""));
- return true;
- }
- else
- {
- num = -1;
- return true;
- }
- }
- else
- {
- num = -1;
- return true;
- }
- }
- else
- {
- num = GetMACfile.GetFiles().Length;
- return true;
- }
- }
- return true;
- }
- }
- catch (Exception ex)
- {
- num = -1;
- return true;
- }
- }
- public static bool GetLocalHDCPKEYCount(string order, out int num)
- {
- num = 0;
- try
- {
- string HDCPKEYpath = LocalKeyPath + order + "\\HDCPKEY";
- if (Directory.Exists(HDCPKEYpath) == false)
- return false;
- else
- {
- DirectoryInfo GetHDCPKEYfile = new DirectoryInfo(HDCPKEYpath);
- num = GetHDCPKEYfile.GetFiles().Length;
- return true;
- }
- }
- catch (Exception ex)
- {
- num = -1;
- return true;
- }
- }
- public static bool GetLocalHDCPKEY22Count(string order, out int num)
- {
- num = 0;
- try
- {
- string HDCPKEY22path = LocalKeyPath + order + "\\HDCPKEY22";
- if (Directory.Exists(HDCPKEY22path) == false)
- return false;
- else
- {
- DirectoryInfo GetHDCPKEY22file = new DirectoryInfo(HDCPKEY22path);
- num = GetHDCPKEY22file.GetFiles().Length;
- return true;
- }
- }
- catch (Exception ex)
- {
- num = -1;
- return true;
- }
- }
- public static bool GetLocalWiDiCount(string order, out int num)
- {
- num = 0;
- try
- {
- string WiDipath = LocalKeyPath + order + "\\WiDi";
- if (Directory.Exists(WiDipath) == false)
- return false;
- else
- {
- DirectoryInfo GetWiDifile = new DirectoryInfo(WiDipath);
- num = GetWiDifile.GetFiles().Length;
- return true;
- }
- }
- catch (Exception ex)
- {
- num = -1;
- return true;
- }
- }
- public static bool GetLocalWidevineCount(string order, out int num)
- {
- num = 0;
- try
- {
- string Widevinepath = LocalKeyPath + order + "\\Widevine";
- if (Directory.Exists(Widevinepath) == false)
- return false;
- else
- {
- DirectoryInfo GetWidevinefile = new DirectoryInfo(Widevinepath);
- num = GetWidevinefile.GetFiles().Length;
- return true;
- }
- }
- catch (Exception ex)
- {
- num = -1;
- return true;
- }
- }
- public static bool GetLocalESNCount(string order, out int num)
- {
- num = 0;
- try
- {
- string ESNpath = LocalKeyPath + order + "\\ESN";
- if (Directory.Exists(ESNpath) == false)
- return false;
- else
- {
- DirectoryInfo GetESNfile = new DirectoryInfo(ESNpath);
- num = GetESNfile.GetFiles().Length;
- return true;
- }
- }
- catch (Exception ex)
- {
- num = -1;
- return true;
- }
- }
- public static bool GetLocalMGKCount(string order, out int num)
- {
- num = 0;
- try
- {
- string MGKpath = LocalKeyPath + order + "\\MGK";
- if (Directory.Exists(MGKpath) == false)
- return false;
- else
- {
- DirectoryInfo GetMGKfile = new DirectoryInfo(MGKpath);
- num = GetMGKfile.GetFiles().Length;
- return true;
- }
- }
- catch (Exception ex)
- {
- num = -1;
- return true;
- }
- }
- public static bool GetLocalFairplayCount(string order, out int num)
- {
- num = 0;
- try
- {
- string Fairplaypath = LocalKeyPath + order + "\\Fairplay";
- if (Directory.Exists(Fairplaypath) == false)
- return false;
- else
- {
- DirectoryInfo GetFairplayfile = new DirectoryInfo(Fairplaypath);
- num = GetFairplayfile.GetFiles().Length;
- return true;
- }
- }
- catch (Exception ex)
- {
- num = -1;
- return true;
- }
- }
- public static bool GetLocalFolderKeyCount(string order, string keyname, out int num)
- {
- num = 0;
- try
- {
- string Fairplaypath = LocalKeyPath + order + "\\" + keyname;
- if (Directory.Exists(Fairplaypath) == false)
- return false;
- else
- {
- DirectoryInfo GetFairplayfile = new DirectoryInfo(Fairplaypath);
- num = GetFairplayfile.GetFiles().Length;
- return true;
- }
- }
- catch (Exception ex)
- {
- num = -1;
- return true;
- }
- }
- public static bool GetLocalAttestationCount(string order, out int num)
- {
- num = 0;
- try
- {
- string Attestationpath = LocalKeyPath + order + "\\Attestation";
- if (Directory.Exists(Attestationpath) == false)
- return false;
- else
- {
- DirectoryInfo GetAttestationfile = new DirectoryInfo(Attestationpath);
- num = GetAttestationfile.GetFiles().Length;
- return true;
- }
- }
- catch (Exception ex)
- {
- num = -1;
- return true;
- }
- }
- public static bool GetLocalCIKEYCount(string order, out int num)
- {
- num = 0;
- try
- {
- string CIKEYpath = LocalKeyPath + order + "\\CIKEY";
- if (Directory.Exists(CIKEYpath) == false)
- return false;
- else
- {
- DirectoryInfo GetCIKEYfile = new DirectoryInfo(CIKEYpath);
- num = GetCIKEYfile.GetFiles().Length;
- return true;
- }
- }
- catch (Exception ex)
- {
- num = -1;
- return true;
- }
- }
- public static bool GetLocalStringKeys(string order, string keytype, int filesize, out FileStream fskey, out StreamReader brkey, out string data, out string filename, out string error, SQLiteConnection errorDBNow, ref MidList localmidList, string SN)
- {
- data = "";
- filename = "";
- error = "";
- brkey = null;
- fskey = null;
- try
- {
- string keypath = LocalKeyPath + order + "\\" + keytype;
- if (Directory.Exists(keypath) == false)
- {
- error = "File not exist";
- return false;
- }
- else
- {
- DirectoryInfo Getkeyfile = new DirectoryInfo(keypath);
- foreach (FileInfo keyfile in Getkeyfile.GetFiles())
- {
- filename = keyfile.FullName;
- try
- {
- fskey = new FileStream(keyfile.FullName.ToString(), FileMode.Open, FileAccess.ReadWrite, FileShare.None);
- {
- brkey = new StreamReader(fskey);
- {
- if (fskey.Length == filesize || filesize == -1)
- {
- data = brkey.ReadToEnd();
- return true;
- }
- else
- {
- error = "File size error.\r\nFilename:" + keyfile.Name + "\r\nFilesize:" + fskey.Length.ToString();
- return false;
- }
- }
- }
- }
- catch
- {
- ;
- }
- }
- return false;
- }
- }
- catch (Exception ex)
- {
- error = ex.Message;
- return false;
- }
- }
- public static bool GetLocalHexKeys(string order, string keytype, int filesize, out FileStream fskey, out BinaryReader brkey, out string data, out string filename, out string error, SQLiteConnection errorDBNow, ref MidList localmidList, string SN)
- {
- data = "";
- filename = "";
- error = "";
- brkey = null;
- fskey = null;
- try
- {
- string keypath = LocalKeyPath + order + "\\" + keytype;
- if (Directory.Exists(keypath) == false)
- {
- error = "File not exist";
- return false;
- }
- else
- {
- DirectoryInfo Getkeyfile = new DirectoryInfo(keypath);
- foreach (FileInfo keyfile in Getkeyfile.GetFiles())
- {
- filename = keyfile.FullName;
- try
- {
- fskey = new FileStream(keyfile.FullName.ToString(), FileMode.Open, FileAccess.Read, FileShare.None);
- {
- brkey = new BinaryReader(fskey);
- {
- if (fskey.Length == filesize || filesize == -1)
- {
- data = SerialInit.ByteToHex(brkey.ReadBytes((int)fskey.Length));
- data = data.Replace(" ", "");
- return true;
- }
- else
- {
- error = "File size error.\r\nFilename: " + keyfile.Name + "\r\nFilesize: " + fskey.Length.ToString();
- return false;
- }
- }
- }
- }
- catch
- {
- ;
- }
- }
- return false;
- }
- }
- catch (Exception ex)
- {
- error = ex.Message;
- return false;
- }
- }
- public static bool DeleteLocalKeys(ArrayList filelist, ArrayList Stream, ArrayList Reader)
- {
- try
- {
- if (filelist.Count == Reader.Count)
- {
- for (int i = 0; i < filelist.Count; i++)
- {
- if (filelist[i].ToString().Contains("DeviceID"))
- ((StreamReader)Reader[i]).Dispose();
- else
- ((BinaryReader)Reader[i]).Dispose();
- ((FileStream)Stream[i]).Dispose();
- File.Delete(filelist[i].ToString());
- }
- return true;
- }
- else
- return false;
- }
- catch (Exception ex)
- {
- for (int i = 0; i < Reader.Count; i++)
- {
- if (filelist[i].ToString().Contains("DeviceID"))
- ((StreamReader)Reader[i]).Dispose();
- else
- ((BinaryReader)Reader[i]).Dispose();
- ((FileStream)Stream[i]).Dispose();
- }
- return false;
- }
- }
- public static bool UnlockLocalKeys(ArrayList filelist, ArrayList Stream, ArrayList Reader)
- {
- for (int i = 0; i < Reader.Count; i++)
- {
- if (filelist[i].ToString().Contains("DeviceID"))
- ((StreamReader)Reader[i]).Dispose();
- else
- ((BinaryReader)Reader[i]).Dispose();
- ((FileStream)Stream[i]).Dispose();
- }
- return true;
- }
- }
- /// <summary>
- /// 本地缓存记录
- /// </summary>
- public class LocalTxtRecord
- {
- public static bool LocalRecord(string record, string name)
- {
- try
- {
- string order = name + ".txt";
- if (File.Exists(@order))
- {
- FileStream fs = new FileStream(@order, FileMode.Append);
- byte[] data = System.Text.Encoding.Default.GetBytes("\r\n" + record);
- fs.Write(data, 0, data.Length);
- fs.Flush();
- fs.Close();
- }
- else
- {
- FileStream fs = new FileStream(@order, FileMode.Create);
- byte[] data = System.Text.Encoding.Default.GetBytes(record);
- fs.Write(data, 0, data.Length);
- fs.Flush();
- fs.Close();
- }
- return true;
- }
- catch (Exception ex)
- {
- return false;
- }
- }
- }
- }
|