public static List <int> TagSearch(string tagName)
        {
            string url = "https://yande.re/post?tags=" + tagName.Replace(" ", "_");

            using (HttpWebClient http = new HttpWebClient()
            {
                TimeOut = 10000,
                Encoding = Encoding.UTF8,
                Proxy = MainSave.Proxy,
                AllowAutoRedirect = true,
            })
            {
                //http.Proxy = new System.Net.WebProxy { Address = new Uri("http://127.0.0.1:1080") };
                string       rawHtml = http.DownloadString(url);
                HtmlDocument doc     = new HtmlDocument();
                doc.LoadHtml(rawHtml);
                var        picNode = doc.DocumentNode.SelectSingleNode(Xpath_List);
                List <int> picID   = new List <int>();
                if (picNode != null && picNode.ChildNodes[1].Name == "ul")
                {
                    foreach (var item in picNode.ChildNodes[1].ChildNodes)
                    {
                        if (item.Name == "li")
                        {
                            picID.Add(Convert.ToInt32(item.Attributes["id"].Value.Replace("p", "")));
                        }
                    }
                }
                else
                {
                    picID.Add(0);
                }
                return(picID);
            }
        }
Beispiel #2
0
        public static string TraceMoe_Call(string picURL)
        {
            string url = $"https://trace.moe/api/search?url={picURL}";

            using (HttpWebClient http = new HttpWebClient()
            {
                TimeOut = 10000,
                Encoding = Encoding.UTF8,
                Proxy = MainSave.Proxy,
                AllowAutoRedirect = true,
            })
            {
                try
                {
                    var json = JsonConvert.DeserializeObject <TraceMoe_Result.Data>(http.DownloadString(url));
                    return(json.ToString());
                }
                catch (Exception e)
                {
                    MainSave.CQLog.Info("解析出错", e.Message, "\n", e.StackTrace);
                    return("解析出错,详情请看日志");
                }
            }
        }
        public static YandeRePicDetail GetYandePic(int id)
        {
            string           url    = $"https://yande.re/post/show/{id}";
            YandeRePicDetail detail = null;

            using (HttpWebClient http = new HttpWebClient()
            {
                TimeOut = 10000,
                Encoding = Encoding.UTF8,
                Proxy = MainSave.Proxy,
                AllowAutoRedirect = true,
            })
            {
                //http.Proxy = new System.Net.WebProxy { Address=new Uri("http://127.0.0.1:1080") };
                string       rawHtml = http.DownloadString(url);
                HtmlDocument doc     = new HtmlDocument();
                doc.LoadHtml(rawHtml);
                var picNode = doc.DocumentNode.SelectSingleNode(XPath_Pic);
                if (picNode == null)
                {
                    var c = doc.DocumentNode.SelectSingleNode("/html/body/div[8]/div[1]/div[3]");
                    c.Remove();
                    picNode = doc.DocumentNode.SelectSingleNode(XPath_Pic);
                }
                if (picNode != null)
                {
                    detail = new YandeRePicDetail
                    {
                        ID             = id,
                        Tags           = picNode.Attributes["alt"].Value.Split(' '),
                        PicWidth       = Convert.ToInt32(picNode.Attributes["width"].Value),
                        PicHeight      = Convert.ToInt32(picNode.Attributes["height"].Value),
                        PicLargeHeight = Convert.ToInt32(picNode.Attributes["large_height"].Value),
                        PicLargeWidth  = Convert.ToInt32(picNode.Attributes["large_width"].Value),
                        PicURL         = picNode.Attributes["src"].Value
                    };
                    picNode = doc.DocumentNode.SelectSingleNode(XPath_Info);
                    if (picNode.Name == "ul")
                    {
                        foreach (var item in picNode.ChildNodes)
                        {
                            int length = item.InnerText.IndexOf(":");
                            if (length < 0)
                            {
                                continue;
                            }
                            string itemName = item.InnerText.Substring(0, length);
                            switch (itemName)
                            {
                            case "Posted":
                                var t = DateTime.TryParseExact(item.SelectSingleNode("a[1]").Attributes["title"].Value
                                                               , "ddd MMM dd HH:mm:ss yyyy"
                                                               , new System.Globalization.CultureInfo("en-US"), System.Globalization.DateTimeStyles.AdjustToUniversal, out DateTime uploadTime);
                                if (t is false)
                                {
                                    uploadTime = DateTime.ParseExact(item.SelectSingleNode("a[1]").Attributes["title"].Value
                                                                     , "ddd MMM  d HH:mm:ss yyyy"
                                                                     , new System.Globalization.CultureInfo("en-US"));
                                }
                                detail.UploadTime   = uploadTime;
                                detail.UpLoaderName = item.SelectSingleNode("a[2]").ChildNodes[0].InnerText;
                                break;

                            case "Source":
                                detail.Source = item.SelectSingleNode("a[1]").Attributes["href"].Value;
                                break;

                            default:
                                break;
                            }
                        }
                        detail.PicLargeURL = doc.DocumentNode.SelectSingleNode(XPath_Large)
                                             .ChildNodes[0].Attributes["href"].Value;
                    }
                }
                else
                {
                    MainSave.CQLog.Info("Yande识别模式错误", "Xpath填写错误,联系作者更正");
                }
            }
            return(detail);
        }
        /// <summary>
        /// 获取图片
        /// </summary>
        /// <param name="ordertext">除指令外的控制文本</param>
        /// <returns></returns>
        public static SendText GetSetuPic(string ordertext, out string objectTostring)
        {
            SendText result = new SendText();

            objectTostring = String.Empty;
            using (HttpWebClient http = new HttpWebClient()
            {
                TimeOut = 10000,
                Encoding = Encoding.UTF8,
                Proxy = MainSave.Proxy,
                AllowAutoRedirect = true,
            })
            {
                try
                {
                    IniConfig ini = MainSave.ConfigMain;
                    string    url = api;
                    //拼接Url
                    if (PublicVariables.Lolicon_ApiSwitch)
                    {
                        url = api + $"apikey={PublicVariables.Lolicon_ApiKey}";
                    }
                    url += GetOrderText(ordertext);

                    if (url.Contains("r18=1") && ini.Object["R18"]["R18PicRevoke"] == "1")
                    {
                        GetLoliconPic.RevokeState = true;//用于后续撤回
                    }
                    string json = "";
                    try
                    {
                        json = http.DownloadString(url);
                    }
                    catch (Exception e)
                    {
                        MainSave.CQLog.Info("Error", e.Message);
                        result.MsgToSend.Add(e.Message);
                        result.HandlingFlag = false;
                        return(result);
                    }
                    //检查路径是否存在
                    if (!Directory.Exists(MainSave.ImageDirectory + @"\LoliconPic\"))
                    {
                        Directory.CreateDirectory(MainSave.ImageDirectory + @"\LoliconPic\");
                    }
                    //反序列化json
                    Setu deserialize = JsonConvert.DeserializeObject <Setu>(json);
                    objectTostring = deserialize.ToString();
                    if (deserialize.code != 0)//非成功调用
                    {
                        MainSave.CQLog.Info("非正常返回", json);
                        result.MsgToSend.Add("非正常返回");
                        result.HandlingFlag = false;
                        return(result);
                    }
                    //获取Data数组信息
                    var    pic  = deserialize.data[0];
                    string path = Path.Combine(MainSave.ImageDirectory, "LoliconPic", $"{pic.pid}.jpg");
                    if (!File.Exists(path))
                    {
                        http.CookieCollection = new CookieCollection();
                        http.DownloadFile(pic.url, path);
                        CommonHelper.AntiHX(path);
                    }
                    result.MsgToSend.Add(CQApi.CQCode_Image(@"\LoliconPic\" + pic.pid + ".jpg").ToSendString());
                    return(result);
                }
                catch (Exception e)
                {
                    MainSave.CQLog.Info("Error", $"发生错误的对象{e.Source} , 发送错误: {e.Message}\n{e.StackTrace}");
                    result.MsgToSend.Add(e.Message);
                    result.HandlingFlag = false;
                    return(result);
                }
            }
        }
        /// <summary>
        /// 获取图片详情及原图
        /// </summary>
        /// <param name="id">图片的Pid</param>
        /// <returns></returns>
        public static IllustInfo GetIllustInfo(int id)
        {
            using (HttpWebClient http = new HttpWebClient()
            {
                TimeOut = 10000,
                Encoding = Encoding.UTF8,
                Proxy = MainSave.Proxy,
                AllowAutoRedirect = true,
            })
            {
                string url       = $"https://pix.ipv4.host/illusts/{id}";
                string returnstr = string.Empty;
                try
                {
                    string authCode = PublicVariables.PixivicAuth;
                    if (string.IsNullOrEmpty(authCode))
                    {
                        MainSave.CQLog.Info("未填写授权码", "搜图需要在数据目录的Config.ini文件内,Config字段的PixivicAuth值内填入获取到的授权码");
                        throw new Exception();
                    }
                    http.Encoding = Encoding.UTF8;
                    http.Headers.Add("authorization", authCode);

                    returnstr = http.DownloadString(url);
                    Pixiv_PID infobase = JsonConvert.DeserializeObject <Pixiv_PID>(returnstr);
                    bool      r18_Flag = infobase.data.tags.Any(x => x.name.Contains("R-18"));
                    if (r18_Flag && !PublicVariables.R18_Flag)
                    {
                        IllustInfo R18Pic = new IllustInfo()
                        {
                            IllustText   = "设置内限制级图片,不予显示",
                            IllustCQCode = new CQCode(CQFunction.Image, new KeyValuePair <string, string>("file", "Error.jpg"))
                        };
                        return(R18Pic);
                    }
                    IllustInfo illustInfo = new IllustInfo()
                    {
                        IllustText   = Pixiv_Illust.GetIllustReturnText(infobase),
                        IllustCQCode = Pixiv_Illust.GetIllustPic(infobase),
                        R18_Flag     = r18_Flag
                    };
                    illustInfo.IllustUrl = infobase.data.imageUrls[0].original.Replace("pximg.net", "pixiv.cat");
                    return(illustInfo);
                }
                catch (Exception e)
                {
                    if (!Directory.Exists(MainSave.AppDirectory + "error\\" + "IllustInfo\\"))
                    {
                        Directory.CreateDirectory(MainSave.AppDirectory + "error\\" + "IllustInfo\\");
                    }
                    IniConfig ini = new IniConfig(MainSave.AppDirectory + "error\\" + "IllustInfo\\" + $"{DateTime.Now:yyyyMMddHHss}.log");
                    ini.Object["Error"]["Message"]    = e.Message;
                    ini.Object["Error"]["StackTrace"] = e.StackTrace;
                    ini.Object["Error"]["Object"]     = returnstr;
                    ini.Save();
                    MainSave.CQLog.Info("图片详情", $"解析失败,错误信息:{e.Message}");
                    IllustInfo illustInfo = new IllustInfo()
                    {
                        IllustText   = "图片解析失败,作品不存在或被删除",
                        IllustCQCode = CQApi.CQCode_Image("Error.jpg")
                    };
                    return(illustInfo);
                }
            }
        }
        public static IllustInfo GetHotSearch(string keyword)
        {
            using (HttpWebClient http = new HttpWebClient()
            {
                TimeOut = 10000,
                Encoding = Encoding.UTF8,
                Proxy = MainSave.Proxy,
                AllowAutoRedirect = true,
                Referer = "https://pixivic.net/"
            })
            {
                string url       = $"https://pix.ipv4.host/illustrations?illustType=illust&searchType=original&maxSanityLevel=6&page={new Random().Next(1, 6)}&keyword={HttpTool.UrlEncode(keyword)}&pageSize=10";
                string returnstr = string.Empty;
                try
                {
                    string authCode = PublicVariables.PixivicAuth;
                    if (string.IsNullOrEmpty(authCode))
                    {
                        MainSave.CQLog.Info("未填写授权码", "搜图需要在数据目录的Config.ini文件内,Config字段的PixivicAuth值内填入获取到的授权码");
                        throw new Exception();
                    }
                    http.Encoding = Encoding.UTF8;
                    http.Headers.Add("authorization", authCode);

                    returnstr = http.DownloadString(url);
                    Pixiv_HotSearch hotSearch  = JsonConvert.DeserializeObject <Pixiv_HotSearch>(returnstr);
                    IllustInfo      illustInfo = new IllustInfo();
                    Datum           info;
                    if (hotSearch.data.Count != 0)
                    {
                        if (PublicVariables.R18_Flag is false)
                        {
                            var result = hotSearch.data.Where(x => !x.tags.Any(y => y.name.Contains("R-18")))
                                         .OrderBy(x => Guid.NewGuid().ToString());
                            info = result.FirstOrDefault();
                            if (info != null)
                            {
                                if (result.Count() != hotSearch.data.Count)
                                {
                                    if (hotSearch.data.Count != 0)
                                    {
                                        MainSave.CQLog.Info("R18拦截", $"拦截了 {hotSearch.data.Count - result.Count()} 个搜索结果");
                                    }
                                }
                                illustInfo = new IllustInfo()
                                {
                                    IllustText   = Pixiv_HotSearch.GetSearchText(info),
                                    IllustCQCode = Pixiv_HotSearch.GetSearchPic(info),
                                    IllustUrl    = info.imageUrls[0].original.Replace("pximg.net", "pixiv.cat")
                                };
                            }
                            else
                            {
                                if (hotSearch.data.Count != 0)
                                {
                                    MainSave.CQLog.Info("R18拦截", $"拦截了 {hotSearch.data.Count} 个搜索结果");
                                }
                                illustInfo = new IllustInfo()
                                {
                                    IllustText   = "设置内限制级图片,不予显示",
                                    IllustCQCode = new CQCode(CQFunction.Image, new KeyValuePair <string, string>("file", "Error.jpg"))
                                };
                                return(illustInfo);
                            }
                        }
                        else
                        {
                            info       = hotSearch.data.OrderBy(x => Guid.NewGuid().ToString()).First();
                            illustInfo = new IllustInfo()
                            {
                                IllustText   = Pixiv_HotSearch.GetSearchText(info),
                                IllustCQCode = Pixiv_HotSearch.GetSearchPic(info),
                                IllustUrl    = info.imageUrls[0].original.Replace("pximg.net", "pixiv.cat"),
                                R18_Flag     = info.tags.Any(x => x.name.Contains("R-18"))
                            };
                        }
                    }
                    else
                    {
                        illustInfo = new IllustInfo()
                        {
                            IllustText   = "搜索结果为空",
                            IllustCQCode = CQApi.CQCode_Image("Error.jpg")
                        };
                    }
                    return(illustInfo);
                }
                catch (Exception e)
                {
                    if (!Directory.Exists(MainSave.AppDirectory + "error\\" + "hotsearch\\"))
                    {
                        Directory.CreateDirectory(MainSave.AppDirectory + "error\\" + "hotsearch\\");
                    }
                    IniConfig ini = new IniConfig(MainSave.AppDirectory + "error\\" + "hotsearch\\" + $"{DateTime.Now:yyyyMMddHHss}.log");
                    ini.Object["Error"]["Message"]    = e.Message;
                    ini.Object["Error"]["StackTrace"] = e.StackTrace;
                    ini.Object["Error"]["Object"]     = returnstr;
                    ini.Save();
                    MainSave.CQLog.Info("搜索详情", $"解析失败,错误信息:{e.Message}");
                    IllustInfo illustInfo = new IllustInfo()
                    {
                        IllustText   = "解析失败,无法获取热门搜索",
                        IllustCQCode = CQApi.CQCode_Image("Error.jpg")
                    };
                    return(illustInfo);
                }
            }
        }
        /// <summary>
        /// SauceNao调用
        /// </summary>
        /// <param name="cqcode">图片CQ码</param>
        /// <param name="e"></param>
        public static void SauceNao_Call(CQCode cqcode, CQGroupMessageEventArgs e)
        {
            string url = "https://saucenao.com/search.php?output_type=2&api_key=56faa0cddf50860330a295e0c331be7c4b4c021f&db=999&numres=3&url=";

            url += CommonHelper.GetImageURL(cqcode.ToSendString());
            using (HttpWebClient http = new HttpWebClient()
            {
                TimeOut = 10000,
                Encoding = Encoding.UTF8,
                Proxy = MainSave.Proxy,
                AllowAutoRedirect = true,
            })
            {
                try
                {
                    Directory.CreateDirectory(MainSave.ImageDirectory + "SauceNaotemp");
                    var result = JsonConvert.DeserializeObject <SauceNao_Result.SauceNAO>(http.DownloadString(url));
                    if (result == null || result.results == null || result.results.Count == 0)
                    {
                        e.CQLog.Info("SauceNao识图", "拉取结果失败,建议重试");
                        e.FromGroup.SendGroupMessage("诶嘿,网络出了点小差~");
                        return;
                    }
                    e.CQLog.Info("SauceNao识图", "结果获取成功,正在拉取缩略图");
                    int count = 1;
                    result.results = result.results.Take(1).ToList();
                    string str = result.ToString();
                    foreach (var item in result.results)
                    {
                        try
                        {
                            string filename = Guid.NewGuid().ToString().ToString();
                            http.DownloadFile(item.header.thumbnail, $@"{MainSave.ImageDirectory}\SauceNaotemp\{filename}.jpg");
                            str = str.Replace($"{{{count}}}", CQApi.CQCode_Image($@"\SauceNaotemp\{filename}.jpg").ToSendString());
                        }
                        catch
                        {
                            str = str.Replace($"{{{count}}}", item.header.thumbnail);
                        }
                        finally { count++; }
                    }
                    e.FromGroup.SendGroupMessage(str);
                    List <int> ls = result.results.Where(x => x.data.pixiv_id.HasValue).Select(x => x.data.pixiv_id.Value).ToList();
                    if (ls.Count != 0)
                    {
                        e.FromGroup.SendGroupMessage("有Pixiv图片信息,尝试拉取原图...");
                        foreach (var item in ls)
                        {
                            try
                            {
                                http.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                                if (!File.Exists($@"{MainSave.ImageDirectory}\LoliconPic\${item}.jpg"))
                                {
                                    dynamic jObject   = JObject.Parse(http.UploadString("https://api.pixiv.cat/v1/generate", $"p={item}"));
                                    string  pixiv_url = string.Empty;
                                    try
                                    {
                                        var urllist = jObject.original_urls_proxy;
                                        pixiv_url = urllist[0];
                                        e.FromGroup.SendGroupMessage("此图为多P图片,选择第一P下载");
                                        MainSave.CQLog.Info("SauceNao识图", "此图为多P图片,选择第一P下载");
                                    }
                                    catch
                                    {
                                        pixiv_url = jObject.Value <string>("original_url_proxy");
                                    }
                                    if (!Directory.Exists($@"{MainSave.ImageDirectory}\LoliconPic"))
                                    {
                                        Directory.CreateDirectory($@"{MainSave.ImageDirectory}\LoliconPic");
                                    }
                                    http.DownloadFile(pixiv_url, $@"{MainSave.ImageDirectory}\LoliconPic\{item}.jpg");
                                    MainSave.CQLog.Info("SauceNao识图", $"pid={item}的图片下载成功,尝试发送");
                                }
                                QQMessage staues = e.FromGroup.SendGroupMessage(CQApi.CQCode_Image($@"\LoliconPic\{item}.jpg"));
                            }
                            catch (Exception exc)
                            {
                                e.FromGroup.SendGroupMessage($"pid={item}的图片拉取失败,错误信息:{exc.Message}");
                            }
                        }
                    }
                }
                catch (Exception exc)
                {
                    e.CQLog.Info("SauceNao搜图", $"搜索失败,错误信息:{exc.Message}在{exc.StackTrace}");
                    e.FromGroup.SendGroupMessage($"拉取失败,错误信息:{exc.Message}");
                }
                try
                {
                    string path = $@"{MainSave.ImageDirectory}\SauceNaotemp";
                    if (Directory.Exists(path))
                    {
                        Directory.Delete(path, true);
                    }
                }
                catch { }
            }
        }