.net程序自动获取chrome浏览器cookie并检测我的BUG

Posted 真爱无限

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.net程序自动获取chrome浏览器cookie并检测我的BUG相关的知识,希望对你有一定的参考价值。

这边只展示核心代码,其他的循环检测之类的逻辑代码就不贴出来了。
原因是公司新升级了开源的禅道系统,指派BUG的时候没有邮件提醒了,只能自己手动刷,自己写了个桌面程序自动检测,然后桌面弹出提醒,还挺实用的

思路就是:通过sqlite查询chrome存储cookie的文件取出cookie->通过webrequest请求网页获取html->通过xpath解析bug内容->在界面显示或弹出气泡提示

以下贴出关键代码

1、获取chrome的cookie【引用是dapper】

using Dapper;
using JDSpiderClient.DapperRepository;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JDSpiderClient.DapperRepository

    public class CommonRepository : SqLiteBaseRepository
    
        //参考:http://www.voidcn.com/article/p-webxwzqi-btu.html
        public List<CookieModel> GetCookiesByHost(string hostName)
        
            if (hostName == null) throw new ArgumentNullException("hostName");

            var dbPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\\Google\\Chrome\\User Data\\Default\\Cookies";
            if (!System.IO.File.Exists(dbPath)) throw new System.IO.FileNotFoundException("Cant find cookie store", dbPath); // race condition, but i'll risk it

            var connectionString = "Data Source=" + dbPath + ";pooling=false";
            List<CookieModel> result = null;
            using (var cnn = MyDbConnection(connectionString))
            
                cnn.Open();
                result = cnn.Query<CookieModel>(
                    @"SELECT name,encrypted_value FROM cookies WHERE host_key = @hostName", new  hostName ).ToList();
                
            
            if (result != null)
            
                foreach (var item in result)
                
                    //item.decrypted_value = Crypto.decryptAES(item.encrypted_value);
                    var encryptedData = item.encrypted_value;// System.Text.Encoding.UTF8.GetBytes(item.encrypted_value);
                    var decodedData = System.Security.Cryptography.ProtectedData.Unprotect(encryptedData, null, System.Security.Cryptography.DataProtectionScope.CurrentUser);
                    item.decrypted_value = Encoding.ASCII.GetString(decodedData); // Looks like ASCII
                
            
            return result;
        

        /// <summary>
        /// 获取chrome浏览器中的禅道Cookie
        /// </summary>
        /// <returns></returns>
        public string GetZentaoCookie()
        
            var cookieList = GetCookiesByHost("lyzentao.szlanyou.com");
            if (cookieList == null) return string.Empty;
            foreach (var cookie in cookieList)
            
                if (cookie.name == "bugModule" && !string.IsNullOrEmpty(cookie.decrypted_value))
                
                    cookie.decrypted_value = "";//限定模块转为空
                
            
            string ret = string.Join("; ", cookieList.Select(item => string.Format("0=1", item.name, item.decrypted_value)));
            return ret;
        
    

    public class CookieModel
    
        public string name  get; set; 
        public byte[] encrypted_value  get; set; 
        public string decrypted_value  get; set; 
    

数据库连接sqlite

using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JDSpiderClient

    public class SqLiteBaseRepository
    
        public static string DbFile
        
            get  return AppSetting.Instance.Database; 
        

        public static SQLiteConnection SimpleDbConnection()
        
            return new SQLiteConnection("Data Source=" + DbFile);
        

        public static SQLiteConnection MyDbConnection(string connStr)
        
            return new SQLiteConnection(connStr);
        
    


2、使用cookie请求禅道【我的BUG页面】

using HtmlAgilityPack;
using JDSpiderClient.Tool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JDSpiderClient.Spiders

    public class getMyBugHelper
    
        /// <summary>
        /// 获取禅道-我的BUG
        /// </summary>
        /// <param name="service_item_code"></param>
        /// <returns></returns>
        public static List<ZentaoBugModel> GetZentaoAssignedToMy(string cookie, int timeoutMiniSecond = 10000)
        
            Dictionary<string, string> headers = new Dictionary<string, string>();
            //var contentType = "application/x-www-form-urlencoded; charset=UTF-8";//application/x-www-form-urlencoded; charset=UTF-8
            //contentType = "text/html; charset=utf-8";
            headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
            //headers.Add("Content-Type", contentType);
            headers.Add("Cache-Control", "no-cache");
            headers.Add("Host", "lyzentao.szlanyou.com:81");
            //headers.Add("Origin", "http://zh.voc.com.cn");
            headers.Add("Pragma", "no-cache");
            //headers.Add("Proxy-Connection", "keep-alive");
            //headers.Add("Referer", OppointmentRequestFactory.getAppointmentListUrl);
            headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) CChrome/113.0.3325.4522 Safari/537.36");
            headers.Add("Upgrade-Insecure-Requests", "1");
            headers.Add("Cookie", cookie);
            //headers.Add("", "");
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("ThreadId:0", System.Threading.Thread.CurrentThread.ManagedThreadId).AppendLine();
            //var formdataString = string.Empty;//WebRequestUtil.FromDictToFormDataString(input.toQueryDict());
            var url = "http://lyzentao.szlanyou.com:81/index.php?m=my&f=bug&type=assignedTo";
            var resultHtml = WebRequestUtil.GetAndResponse<string>(url, headers, timeoutMiniSecond);
            //var resultHtml = System.IO.File.ReadAllText(DataHelper.GetAbsolutePath("/pagehtml.txt"));
            var resultList = getZentaoAssignedToMyList(resultHtml);
            return resultList;
        

        private static List<ZentaoBugModel> getZentaoAssignedToMyList(string resultHtml)
        
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(resultHtml);
            HtmlNode rootnode = doc.DocumentNode;
            //xpathstring = "//button[@class='voteBoxRside']/table/tr[not(@class)]";
            var contentNode = rootnode.SelectSingleNode("//*[@id='mainContent']");
            if (contentNode == null) throw new BusinessException("登录失效,请重新登录并输入cookie!");
            var resultList = new List<ZentaoBugModel>();
            string xpathstring = "//*[@id='bugList']/tbody/tr";
            HtmlNodeCollection liNodes = rootnode.SelectNodes(xpathstring);    //所有找到的节点都是一个集合
            if (liNodes == null || liNodes.Count == 0) return resultList;
            foreach (var liNode in liNodes)
            
                var model = new ZentaoBugModel();
                model.BugId = liNode.SelectSingleNode("./td[1]").InnerText;
                model.BugTitle = liNode.SelectSingleNode("./td[5]/a").InnerText;
                model.CreatedName = liNode.SelectSingleNode("./td[6]").InnerText;
                resultList.Add(model);
            
            return resultList;
        
    

    public class ZentaoBugModel
    
        public string BugId  get; set; 
        public string BugTitle  get; set; 
        public string CreatedName  get; set; 
        public string AssignTo  get; set; 
        public string ModuleName  get; set; 
    


请求网络方法

using JDSpiderClient.Spiders;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace JDSpiderClient.Tool

    public static class WebRequestUtil
    


        #region get方法,不输出cookie
        /// <summary>
        /// get方法,不输出cookie
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static T GetAndResponse<T>(string url, IDictionary<string, string> headers = null,int timeout = -1)
        
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            try
            
                if (timeout > 0)
                
                    request.Timeout = timeout;
                    request.ReadWriteTimeout = timeout;
                
                request.Method = "GET";
                request.Headers.Add("Accept-Encoding", "gzip");
                request.AllowAutoRedirect = true;
                request.Proxy = null;
                if (headers != null)
                
                    request.SetRequestHeader(headers);
                
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                

                    T result = default(T);
                    string json = response.GetResponseText();
                    if (typeof(T) == typeof(string)) result = (T)Convert.ChangeType(json, typeof(T), CultureInfo.CurrentCulture);
                    else result = JsonUtility.FromJsonTo<T>(json);
                    return result;
                
            
            finally
            
                TryCatch(() =>
                
                    request.Abort();
                );
            
        
        #endregion
	

json转换方法

        public static T FromJsonTo<T>(string jsonString)
        
            if (string.IsNullOrEmpty(jsonString))
                return default(T);
            var json = new JsonSerializer
            
                NullValueHandling = NullValueHandling.Ignore,
                ObjectCreationHandling = ObjectCreationHandling.Replace,
                MissingMemberHandling = MissingMemberHandling.Ignore,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            ;


            using (var sr = new StringReader(jsonString))
            
                using (var reader = new JsonTextReader(sr))
                
                    var result = json.Deserialize<T>(reader);
                    return result;
                
            

        

3、Form界面逻辑【自己写个循环检测,比如每一分钟检测一次】

                        var bugList = getMyBugHelper.GetZentaoAssignedToMy(cookie);

                        //var cResult = CommonFun.UnicodeToGB(result);
                        //显示在文本框的日志
                        OperationLog.AddLog(new OperationLogModel()
                        
                            CreateTime = DateTime.Now,
                            Remark = string.Format("我的bug:0  1", bugList.Count, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                        );
                        if (bugList.Count > 0)
                        
                            notifyIcon1.Visible = true; //托盘图标可见
                            string tipMsg = "您有待处理BUG,请查看!";
                            this.notifyIcon1.ShowBalloonTip(1000, "消息提示", tipMsg, ToolTipIcon.Info);//显示气泡提示
                        
                        Thread.Sleep(minisecond);

好了,核心代码就是以上,下面看下效果:

右下角提示效果:

以上是关于.net程序自动获取chrome浏览器cookie并检测我的BUG的主要内容,如果未能解决你的问题,请参考以下文章

.net程序自动获取chrome浏览器cookie并检测我的BUG

使用CefSharp在.Net程序中嵌入Chrome浏览器——Cookie

Google Chrome浏览器的Cookies文件找不到问题

复用浏览器, 获取cookie

用C#破解Chrome浏览器cookie值

如何在 ASP.NET 中将 SameSite cookie 属性减少回无?