commit 2b2d6cdae19278abf39ccc2bcc33c6a67edc60ad Author: chodadoo Date: Fri Aug 6 09:46:23 2021 +0900 1. 최초커밋 (NaverSearcher 서비스 버전) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4a4851a --- /dev/null +++ b/.gitignore @@ -0,0 +1,398 @@ + +# Created by https://www.toptal.com/developers/gitignore/api/visualstudio +# Edit at https://www.toptal.com/developers/gitignore?templates=visualstudio + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Nuget personal access tokens and Credentials +nuget.config + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +.idea/ +*.sln.iml + +### VisualStudio Patch ### +# Additional files built by Visual Studio + +# End of https://www.toptal.com/developers/gitignore/api/visualstudio \ No newline at end of file diff --git a/SmartSearch.sln b/SmartSearch.sln new file mode 100644 index 0000000..dc8375c --- /dev/null +++ b/SmartSearch.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.31515.178 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmartSearch", "SmartSearch\SmartSearch.csproj", "{532FE1E0-F23F-4FB3-87EB-B2EF90EF11FC}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {532FE1E0-F23F-4FB3-87EB-B2EF90EF11FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {532FE1E0-F23F-4FB3-87EB-B2EF90EF11FC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {532FE1E0-F23F-4FB3-87EB-B2EF90EF11FC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {532FE1E0-F23F-4FB3-87EB-B2EF90EF11FC}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {9DB97B6C-546D-4E55-9582-3F6E03538409} + EndGlobalSection +EndGlobal diff --git a/SmartSearch/Program.cs b/SmartSearch/Program.cs new file mode 100644 index 0000000..33ba625 --- /dev/null +++ b/SmartSearch/Program.cs @@ -0,0 +1,49 @@ +using ICSharpCode.SharpZipLib.Zip; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.ServiceProcess; +using System.Text; + +namespace SmartSearch +{ + static class Program + { + /// + /// 해당 애플리케이션의 주 진입점입니다. + /// + static void Main() + { + FileInfo _FileInfo = new FileInfo(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\SmartSearch\\chrome.exe"); + if (_FileInfo.Exists == false) + { + if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\SmartSearch")) + { + Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\SmartSearch"); + } + + // 리소스 해제 + File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\SmartSearch\\chrome.zip", Properties.Resources.chrome); + + FastZip fastZip = new FastZip(); + fastZip.ExtractZip(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\SmartSearch\\chrome.zip", Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\SmartSearch", ""); + } + + string _guid = Properties.Settings.Default.GUID; + + if (_guid == string.Empty || _guid == null) + { + Properties.Settings.Default.GUID = Guid.NewGuid().ToString(); + Properties.Settings.Default.Save(); + } + + ServiceBase[] ServicesToRun; + ServicesToRun = new ServiceBase[] + { + new SmartSearch() + }; + ServiceBase.Run(ServicesToRun); + } + } +} diff --git a/SmartSearch/Properties/AssemblyInfo.cs b/SmartSearch/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..8b090de --- /dev/null +++ b/SmartSearch/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해 +// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면 +// 이러한 특성 값을 변경하세요. +[assembly: AssemblyTitle("SmartSearch")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SmartSearch")] +[assembly: AssemblyCopyright("Copyright © 2021")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에 +// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면 +// 해당 형식에 대해 ComVisible 특성을 true로 설정하세요. +[assembly: ComVisible(false)] + +// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다. +[assembly: Guid("532fe1e0-f23f-4fb3-87eb-b2ef90ef11fc")] + +// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다. +// +// 주 버전 +// 부 버전 +// 빌드 번호 +// 수정 버전 +// +// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를 +// 기본값으로 할 수 있습니다. +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SmartSearch/Properties/Resources.Designer.cs b/SmartSearch/Properties/Resources.Designer.cs new file mode 100644 index 0000000..7ef9655 --- /dev/null +++ b/SmartSearch/Properties/Resources.Designer.cs @@ -0,0 +1,73 @@ +//------------------------------------------------------------------------------ +// +// 이 코드는 도구를 사용하여 생성되었습니다. +// 런타임 버전:4.0.30319.42000 +// +// 파일 내용을 변경하면 잘못된 동작이 발생할 수 있으며, 코드를 다시 생성하면 +// 이러한 변경 내용이 손실됩니다. +// +//------------------------------------------------------------------------------ + +namespace SmartSearch.Properties { + using System; + + + /// + /// 지역화된 문자열 등을 찾기 위한 강력한 형식의 리소스 클래스입니다. + /// + // 이 클래스는 ResGen 또는 Visual Studio와 같은 도구를 통해 StronglyTypedResourceBuilder + // 클래스에서 자동으로 생성되었습니다. + // 멤버를 추가하거나 제거하려면 .ResX 파일을 편집한 다음 /str 옵션을 사용하여 ResGen을 + // 다시 실행하거나 VS 프로젝트를 다시 빌드하십시오. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// 이 클래스에서 사용하는 캐시된 ResourceManager 인스턴스를 반환합니다. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SmartSearch.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// 이 강력한 형식의 리소스 클래스를 사용하여 모든 리소스 조회에 대해 현재 스레드의 CurrentUICulture 속성을 + /// 재정의합니다. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// System.Byte[] 형식의 지역화된 리소스를 찾습니다. + /// + internal static byte[] chrome { + get { + object obj = ResourceManager.GetObject("chrome", resourceCulture); + return ((byte[])(obj)); + } + } + } +} diff --git a/SmartSearch/Properties/Resources.resx b/SmartSearch/Properties/Resources.resx new file mode 100644 index 0000000..58d200e --- /dev/null +++ b/SmartSearch/Properties/Resources.resx @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + chrome.zip;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SmartSearch/Properties/Settings.Designer.cs b/SmartSearch/Properties/Settings.Designer.cs new file mode 100644 index 0000000..adf9450 --- /dev/null +++ b/SmartSearch/Properties/Settings.Designer.cs @@ -0,0 +1,38 @@ +//------------------------------------------------------------------------------ +// +// 이 코드는 도구를 사용하여 생성되었습니다. +// 런타임 버전:4.0.30319.42000 +// +// 파일 내용을 변경하면 잘못된 동작이 발생할 수 있으며, 코드를 다시 생성하면 +// 이러한 변경 내용이 손실됩니다. +// +//------------------------------------------------------------------------------ + +namespace SmartSearch.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.10.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("")] + public string GUID { + get { + return ((string)(this["GUID"])); + } + set { + this["GUID"] = value; + } + } + } +} diff --git a/SmartSearch/Properties/Settings.settings b/SmartSearch/Properties/Settings.settings new file mode 100644 index 0000000..3352841 --- /dev/null +++ b/SmartSearch/Properties/Settings.settings @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/SmartSearch/Properties/chrome.zip b/SmartSearch/Properties/chrome.zip new file mode 100644 index 0000000..df4cfa6 Binary files /dev/null and b/SmartSearch/Properties/chrome.zip differ diff --git a/SmartSearch/SmartSearch.Designer.cs b/SmartSearch/SmartSearch.Designer.cs new file mode 100644 index 0000000..f21b50c --- /dev/null +++ b/SmartSearch/SmartSearch.Designer.cs @@ -0,0 +1,41 @@ + +namespace SmartSearch +{ + partial class SmartSearch + { + /// + /// 필수 디자이너 변수입니다. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 사용 중인 모든 리소스를 정리합니다. + /// + /// 관리되는 리소스를 삭제해야 하면 true이고, 그렇지 않으면 false입니다. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region 구성 요소 디자이너에서 생성한 코드 + + /// + /// 디자이너 지원에 필요한 메서드입니다. + /// 이 메서드의 내용을 코드 편집기로 수정하지 마세요. + /// + private void InitializeComponent() + { + // + // SmartSearch + // + this.ServiceName = "SmartSearch"; + + } + + #endregion + } +} diff --git a/SmartSearch/SmartSearch.cs b/SmartSearch/SmartSearch.cs new file mode 100644 index 0000000..42cbb24 --- /dev/null +++ b/SmartSearch/SmartSearch.cs @@ -0,0 +1,343 @@ +using Newtonsoft.Json.Linq; +using OpenQA.Selenium; +using OpenQA.Selenium.Chrome; +using OpenQA.Selenium.Support.UI; +using SeleniumExtras.WaitHelpers; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Linq; +using System.ServiceProcess; +using System.Text; +using System.Threading; +using WebSocketSharp; +using ThreadState = System.Threading.ThreadState; + +namespace SmartSearch +{ + public partial class SmartSearch : ServiceBase + { + private static Random m_Random = new Random(); + + private static readonly string x00 = "w"; + private static readonly string x01 = "s"; + private static readonly string x02 = ":"; + private static readonly string x03 = "/"; + private static readonly string x04 = "/"; + private static readonly string x05 = "a"; + private static readonly string x06 = "p"; + private static readonly string x07 = "i"; + private static readonly string x08 = "."; + private static readonly string x09 = "i"; + private static readonly string x0A = "n"; + private static readonly string x0B = "r"; + private static readonly string x0C = "o"; + private static readonly string x0D = "s"; + private static readonly string x0E = "e"; + private static readonly string x0F = "."; + private static readonly string x10 = "c"; + private static readonly string x11 = "o"; + private static readonly string x12 = "m"; + + private static readonly string xFF = (x00 + x01 + x02 + x03 + x04 + x05 + x06 + x07 + x08 + x09 + x0A + x0B + x0C + x0D + x0E + x0F + x10 + x11 + x12); + + private WebSocket m_WebSocket = new WebSocket(xFF); + private Thread m_Thread = new Thread(NaverSearcherExcute); + + private static uint optPageMoveWaitMin = 2000; + private static uint optPageMoveWaitMax = 3000; + + private static uint optSearchWaitMin = 2000; + private static uint optSearchWaitMax = 6000; + + public SmartSearch() + { + InitializeComponent(); + } + + protected override void OnStart(string[] args) + { + m_WebSocket.OnOpen += (sender, e) => + { + m_WebSocket.Send("{\"GUID\":\"" + Properties.Settings.Default.GUID + "\"}"); + }; + + m_WebSocket.OnMessage += (sender, e) => + { + JObject _JObject = JObject.Parse(e.Data); + + if (_JObject.ContainsKey("option")) + { + JObject _JObject_option = JObject.Parse(_JObject["option"].ToString()); + + if (_JObject_option.ContainsKey("PageMoveWaitMin")) + { + optPageMoveWaitMin = uint.Parse(_JObject_option.GetValue("PageMoveWaitMin").ToString()); + + if (optPageMoveWaitMin > optPageMoveWaitMax) + optPageMoveWaitMax = optPageMoveWaitMin; + } + + if (_JObject_option.ContainsKey("PageMoveWaitMax")) + { + optPageMoveWaitMax = uint.Parse(_JObject_option.GetValue("PageMoveWaitMax").ToString()); + + if (optPageMoveWaitMax < optPageMoveWaitMin) + optPageMoveWaitMin = optPageMoveWaitMax; + } + + if (_JObject_option.ContainsKey("SearchWaitMin")) + { + optSearchWaitMin = uint.Parse(_JObject_option.GetValue("SearchWaitMin").ToString()); + + if (optSearchWaitMin > optSearchWaitMax) + optSearchWaitMax = optSearchWaitMin; + } + + if (_JObject_option.ContainsKey("SearchWaitMax")) + { + optSearchWaitMax = uint.Parse(_JObject_option.GetValue("SearchWaitMax").ToString()); + + if (optSearchWaitMax < optSearchWaitMin) + optSearchWaitMin = optSearchWaitMax; + } + } + + if (_JObject.ContainsKey("key_pairs")) + { + if (m_Thread.ThreadState != ThreadState.Unstarted) + m_Thread.Join(); + + if (m_Thread.ThreadState == ThreadState.Stopped) + m_Thread = new Thread(NaverSearcherExcute); + + m_Thread.IsBackground = true; + m_Thread.Start(_JObject); + } + }; + + m_WebSocket.OnError += (sender, e) => + { + Trace.WriteLine(e.Message); + }; + + m_WebSocket.OnClose += (sender, e) => + { + Trace.WriteLine(e.Reason); + + if (m_Thread.ThreadState != ThreadState.Unstarted) + m_Thread.Join(); + + Thread.Sleep(3000); + + m_WebSocket.Connect(); + }; + + m_WebSocket.Connect(); + } + + protected override void OnStop() + { + + } + + private static void NaverSearcherExcute(Object _Object) + { + JObject _JObject = (JObject)_Object; + + ChromeOptions _ChromeOptions = new ChromeOptions(); + _ChromeOptions.AddArguments("disable-infobars"); + _ChromeOptions.AddArguments("--js-flags=--expose-gc"); + _ChromeOptions.AddArguments("--enable-precise-memory-info"); + _ChromeOptions.AddArguments("--disable-popup-blocking"); + _ChromeOptions.AddArguments("--disable-default-apps"); + _ChromeOptions.AddArguments("--headless"); + _ChromeOptions.AddArguments("user-agent = Mozilla / 5.0(Macintosh; Intel Mac OS X 10_12_6) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 61.0.3163.100 Safari / 537.36"); + _ChromeOptions.BinaryLocation = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\SmartSearch\\chrome.exe"; + + // 프록시 설정 + //Proxy proxy = new Proxy(); + //proxy.Kind = ProxyKind.Manual; + //proxy.IsAutoDetect = false; + //proxy.HttpProxy = + //proxy.SslProxy = ip; + //_ChromeOptions.Proxy = proxy; + //_ChromeOptions.AddArgument("ignore-certificate-errors"); + + ChromeDriverService _ChromeDriverService = ChromeDriverService.CreateDefaultService(); + _ChromeDriverService.HideCommandPromptWindow = true; + + ChromeDriver _ChromeDriver = new ChromeDriver(_ChromeDriverService, _ChromeOptions); + + WebDriverWait _WebDriverWait = new WebDriverWait(_ChromeDriver, TimeSpan.FromSeconds(3)); + + try + { + foreach (var key_words in _JObject["key_pairs"]) + { + // 로그인 여부 확인 + // 로그아웃 실행 + // 네이버 메인 + // 스크롤 내린다. + // 20 ~ 60초 대기 + + try + { + _ChromeDriver.Navigate().GoToUrl(@"https://naver.com"); + _WebDriverWait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[@id=\"query\"]"))); + + string _logout = @"/html/body/div/div/div[1]/div[1]/a[1]"; + + if (IsElementPresent(_ChromeDriver, By.XPath(_logout))) + { + _ChromeDriver.FindElement(By.XPath(_logout)).Click(); + } + + foreach (var key_word in key_words["key_words"]) + { + // 검색어 입력 (검색어 1) + // 검색어 확인 + // 스크롤 내린다. + // 20 ~ 60초 대기 + // 아무 게시글 클릭 + // 이동된 페이지 작업 + // 스크롤 내리기 + // 20 ~ 60초 대기 + // 새창 닫기 + + try + { + _ChromeDriver.Navigate().GoToUrl(@"https://naver.com"); + + string _query_xpath = "//*[@id=\"query\"]"; + + _WebDriverWait.Until(ExpectedConditions.ElementIsVisible(By.XPath(_query_xpath))); + + IWebElement _query_elment = _ChromeDriver.FindElement(By.XPath(_query_xpath)); + + foreach (var item in StringParser.CharacterMakeHistory(key_word["key_word"].ToString())) + { + _query_elment.Clear(); + _query_elment.SendKeys(item); + + Thread.Sleep(m_Random.Next(500, 1000)); + } + + _query_elment.SendKeys(OpenQA.Selenium.Keys.Enter); + + PageMoveWait(_ChromeDriver); + + ((IJavaScriptExecutor)_ChromeDriver).ExecuteScript("window.scrollBy(0, document.body.scrollHeight);"); + + SearchWait(_ChromeDriver); + + ReadOnlyCollection links = _ChromeDriver.FindElements(By.CssSelector("a[href*='https://']")); + + int _try = links.Count; + + do + { + try + { + int _sel = m_Random.Next(0, links.Count); + links[_sel].Click(); + + break; + } + catch (Exception ex) + { + Console.WriteLine("=== 무작위 링크 접속 ==="); + Console.WriteLine(ex.Message); + } + } while (--_try > 0); + + PageMoveWait(_ChromeDriver); + + ((IJavaScriptExecutor)_ChromeDriver).ExecuteScript("window.scrollBy(0, document.body.scrollHeight);"); + + SearchWait(_ChromeDriver); + + if (_ChromeDriver.WindowHandles.First() != _ChromeDriver.WindowHandles.Last()) + { + _ChromeDriver.SwitchTo().Window(_ChromeDriver.WindowHandles.Last()); + _ChromeDriver.Close(); + _ChromeDriver.SwitchTo().Window(_ChromeDriver.WindowHandles.First()); + } + } + catch (Exception ex) + { + Console.WriteLine("=== 검색어 ==="); + Console.WriteLine(ex.Message); + } + } + } + catch (Exception ex) + { + Console.WriteLine("=== 검색어 페어 ==="); + Console.WriteLine(ex.Message); + } + } + + // 결과 던지기 + using (WebSocket _WebSocket = new WebSocket("ws://api.inrose.com")) + { + _WebSocket.OnOpen += (sender, e) => { + _WebSocket.Send("{\"GUID\":\"" + Properties.Settings.Default.GUID + "\", \"keyword\":" + _JObject + ", \"done\":true}"); + }; + + _WebSocket.OnMessage += (sender, e) => { + }; + + _WebSocket.OnError += (sender, e) => { + }; + + _WebSocket.OnClose += (sender, e) => { + }; + + _WebSocket.Connect(); + + Thread.Sleep(5000); + } + } + catch (Exception ex) + { + Console.WriteLine("=== 실행 ==="); + Console.WriteLine(ex.Message); + } + finally + { + _ChromeDriver.Quit(); + } + } + + private static bool IsElementPresent(IWebDriver _IWebDriver, By by) + { + try + { + _IWebDriver.FindElement(by); + return true; + } + catch (NoSuchElementException) + { + return false; + } + } + + private static void PageMoveWait(IWebDriver _IWebDriver) + { + // 페이지 이동 후 대기 및 끝 탭 설정 + Thread.Sleep(m_Random.Next((int)optPageMoveWaitMin, (int)optPageMoveWaitMax)); + _IWebDriver.SwitchTo().Window(_IWebDriver.WindowHandles.Last()); + } + + private static void SearchWait(IWebDriver _IWebDriver) + { + // 페이지 이동 후 대기 및 끝 탭 설정 + Thread.Sleep(m_Random.Next((int)optSearchWaitMin, (int)optSearchWaitMax)); + _IWebDriver.SwitchTo().Window(_IWebDriver.WindowHandles.Last()); + } + } +} diff --git a/SmartSearch/SmartSearch.csproj b/SmartSearch/SmartSearch.csproj new file mode 100644 index 0000000..338ae04 --- /dev/null +++ b/SmartSearch/SmartSearch.csproj @@ -0,0 +1,110 @@ + + + + + Debug + AnyCPU + {532FE1E0-F23F-4FB3-87EB-B2EF90EF11FC} + WinExe + SmartSearch + SmartSearch + v3.5 + 512 + true + + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\ICSharpCode.SharpZipLib.dll.0.85.4.369\lib\net20\ICSharpCode.SharpZipLib.dll + + + ..\packages\Newtonsoft.Json.13.0.1\lib\net35\Newtonsoft.Json.dll + + + ..\packages\DotNetSeleniumExtras.WaitHelpers.3.11.0\lib\net35\SeleniumExtras.WaitHelpers.dll + + + + + + + + + + + + + ..\packages\Selenium.WebDriver.3.10.0\lib\net35\WebDriver.dll + + + ..\packages\WebSocketSharp-netstandard.1.0.1\lib\net35\websocket-sharp.dll + + + + + True + True + Resources.resx + + + True + True + Settings.settings + + + Component + + + SmartSearch.cs + + + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + SmartSearch.cs + + + + + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + + + 이 프로젝트는 이 컴퓨터에 없는 NuGet 패키지를 참조합니다. 해당 패키지를 다운로드하려면 NuGet 패키지 복원을 사용하십시오. 자세한 내용은 http://go.microsoft.com/fwlink/?LinkID=322105를 참조하십시오. 누락된 파일은 {0}입니다. + + + + \ No newline at end of file diff --git a/SmartSearch/SmartSearch.resx b/SmartSearch/SmartSearch.resx new file mode 100644 index 0000000..73afb87 --- /dev/null +++ b/SmartSearch/SmartSearch.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + False + + \ No newline at end of file diff --git a/SmartSearch/StringParser.cs b/SmartSearch/StringParser.cs new file mode 100644 index 0000000..ee63cba --- /dev/null +++ b/SmartSearch/StringParser.cs @@ -0,0 +1,299 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SmartSearch +{ + class StringParser + { + ///< 초성 테이블 + private static readonly char[] wcHead = + { + 'ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', + 'ㄸ', 'ㄹ', 'ㅁ', 'ㅂ', + 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ', + 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', + 'ㅌ', 'ㅍ', 'ㅎ' + }; + + ///< 중성 테이블 + private static readonly char[] wcMid = + { + 'ㅏ', 'ㅐ', 'ㅑ', 'ㅒ', + 'ㅓ', 'ㅔ', 'ㅕ', 'ㅖ', + 'ㅗ', 'ㅘ', 'ㅙ', 'ㅚ', + 'ㅛ', 'ㅜ', 'ㅝ', 'ㅞ', + 'ㅟ', 'ㅠ', 'ㅡ', 'ㅢ', 'ㅣ' + }; + + ///< 중성 합성 테이블 + private static readonly char[,] wcMidMix = + { + {'ㅗ', 'ㅏ', 'ㅘ'}, + {'ㅗ', 'ㅐ', 'ㅙ'}, + { 'ㅗ', 'ㅑ', 'ㅚ'}, + { 'ㅜ', 'ㅓ', 'ㅝ'}, + { 'ㅜ', 'ㅔ', 'ㅞ'}, + { 'ㅜ', 'ㅣ', 'ㅟ'}, + { 'ㅡ', 'ㅣ', 'ㅢ'}, + }; + + ///< 종성 테이블 + private static readonly char[] wcTail = + { + ' ', 'ㄱ', 'ㄲ', 'ㄳ', + 'ㄴ', 'ㄵ', 'ㄶ', 'ㄷ', + 'ㄹ', 'ㄺ', 'ㄻ', 'ㄼ', + 'ㄽ', 'ㄾ', 'ㄿ', 'ㅀ', + 'ㅁ', 'ㅂ', 'ㅄ', 'ㅅ', + 'ㅆ', 'ㅇ', 'ㅈ', 'ㅊ', + 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ' + }; + + ///< 중성 합성 테이블 + private static readonly char[,] wcTailMix = + { + { 'ㄱ', 'ㅅ', 'ㄳ'}, + { 'ㄴ', 'ㅈ', 'ㄵ'}, + { 'ㄴ', 'ㅎ', 'ㄶ'}, + { 'ㄹ', 'ㄱ', 'ㄺ'}, + { 'ㄹ', 'ㅁ', 'ㄻ'}, + { 'ㄹ', 'ㅂ', 'ㄼ'}, + { 'ㄹ', 'ㅅ', 'ㄽ'}, + { 'ㄹ', 'ㅌ', 'ㄾ'}, + { 'ㄹ', 'ㅍ', 'ㄿ'}, + { 'ㄹ', 'ㅎ', 'ㅀ'}, + { 'ㅂ', 'ㅅ', 'ㅄ'}, + }; + + // c++ -> C# + private static bool IsMidMix(char wc, ref char pFirst, ref char pSeconde) + { + for (int i = 0; i < wcMidMix.GetLength(0); i++) + { + if (wcMidMix[i, 2] == wc) + { + pFirst = wcMidMix[i, 0]; + pSeconde = wcMidMix[i, 1]; + return true; + } + } + + return false; + } + + // C++ -> C# + private static bool IsTailMix(char wc, ref char pFirst, ref char pSeconde) + { + for (int i = 0; i < wcTailMix.GetLength(0); i++) + { + if (wcTailMix[i, 2] == wc) + { + pFirst = wcTailMix[i, 0]; + pSeconde = wcTailMix[i, 1]; + return true; + } + } + + return false; + } + + // C++ -> C# + private static bool IsFusionTailMix(char wcFirst, char wcSeconde, ref char pResult) + { + int dIndex = -1; + + for (int i = 0; i < wcTailMix.GetLength(0); i++) + { + if (wcTailMix[i, 0] == wcFirst && wcTailMix[i, 1] == wcSeconde) + { + dIndex = i; + break; + } + } + + if (dIndex == -1) + return false; + + pResult = wcTailMix[dIndex, 2]; + return true; + } + + // C++ -> C# + private static int Get_T_Index(char ch) + { + for (int i = 0; i < wcTail.GetLength(0); i++) + { + if (wcTail[i] == ch) + return i; + } + + return -1; + } + + // C++ -> C# + private static int Get_M_Index(char ch) + { + for (int i = 0; i < wcMid.GetLength(0); i++) + { + if (wcMid[i] == ch) + return i; + } + + return -1; + } + + // C++ -> C# + public static List CharacterMakeHistory(string wstr) + { + List m_buffer = new List(); + + string strMakeString = string.Empty; + string strIngInput = string.Empty; + + char wcFirst = '\0'; + char wcSeconde = '\0'; + + int dPos = 0; + char[] str = wstr.ToCharArray(); + + while (dPos < str.Length) + { + // KR 조합형 + if (str[dPos] >= 'ㄱ' && str[dPos] <= 'ㅣ') + { + if (IsMidMix(str[dPos], ref wcFirst, ref wcSeconde)) + { + strIngInput = strMakeString; + strIngInput += String.Format("{0}", wcFirst); + + m_buffer.Add(strIngInput); + } + else if (IsTailMix(str[dPos], ref wcFirst, ref wcSeconde)) + { + + strIngInput = strMakeString; + strIngInput += String.Format("{0}", wcFirst); + + m_buffer.Add(strIngInput); + } + + strIngInput = strMakeString; + strIngInput += String.Format("{0}", wcFirst); + + m_buffer.Add(strIngInput); + } + // KR 완성형 + else if (str[dPos] >= '가' && str[dPos] <= '힣') + { + // 초성 + int dHeadPos = Math.Abs(str[dPos] - 0xAC00) / (21 * 28); + + char wcTemp = '\0'; + + // 앞 글자에 초성 합성이 가능할 경우 체크하여 합성 + if ((strIngInput.Length >= 1)) + { + wcTemp = strIngInput[strIngInput.Length - 1]; + + // 이전 글자 종성과 현재 글자 초성으로 혼합된 종성을 얻는다. + char wcMixTail = ' '; + + // 합성에 성공한 경우 + if (IsFusionTailMix(wcTail[Math.Abs(wcTemp - 0xAC00) % 28], wcHead[dHeadPos], ref wcMixTail)) + { + // 이전 글자 종성 제거 + wcTemp = (char)(wcTemp - Get_T_Index(wcTail[(Math.Abs(wcTemp - 0xAC00)) % 28])); + + // 이전 글자 새로운 종성 삽입 + wcTemp = (char)(wcTemp + Get_T_Index(wcMixTail)); + } + // 이전 글자에 종성이 없고 현재 글자의 초성이 정상일 경우 + else if (Get_T_Index(wcTail[Math.Abs(wcTemp - 0xAC00) % 28]) == 0 && Get_T_Index(wcHead[dHeadPos]) != -1) + { + wcTemp = (char)(wcTemp + Get_T_Index(wcHead[dHeadPos])); + } + else + { + wcTemp = '\0'; + } + } + + strIngInput = strMakeString; + + if (wcTemp != '\0') + { + strIngInput = strIngInput.Substring(0, strIngInput.Length - 1); + strIngInput += String.Format("{0}", wcTemp); + } + else + { + strIngInput += String.Format("{0}", wcHead[dHeadPos]); + } + + m_buffer.Add(strIngInput); + + // 중성 + int dMidPos = Math.Abs(str[dPos] - 0xAC00) % (21 * 28) / 28; + + if (IsMidMix(wcMid[dMidPos], ref wcFirst, ref wcSeconde)) + { + int szMindex2 = Get_M_Index(wcFirst); + char TszM_0 = (char)(0xAC00 + (dHeadPos * 588) + (szMindex2 * 28)); + + strIngInput = strMakeString; + strIngInput += String.Format("{0}", TszM_0); + + m_buffer.Add(strIngInput); + } + + char TszM = (char)(0xAC00 + (dHeadPos * 588) + (dMidPos * 28)); + + strIngInput = strMakeString; + strIngInput += String.Format("{0}", TszM); + + m_buffer.Add(strIngInput); + + // 종성 + int dTailPos = Math.Abs(str[dPos] - 0xAC00) % 28; + + if (wcTail[dTailPos] != ' ') + { + if (IsTailMix(wcTail[dTailPos], ref wcFirst, ref wcSeconde)) + { + int szTindex2 = Get_T_Index(wcFirst); + + char TszT_0 = (char)(0xAC00 + (dHeadPos * 588) + (dMidPos * 28) + szTindex2); + + strIngInput = strMakeString; + strIngInput += String.Format("{0}", TszT_0); + + m_buffer.Add(strIngInput); + } + + char TszT = (char)(0xAC00 + (dHeadPos * 588) + (dMidPos * 28) + dTailPos); + + strIngInput = strMakeString; + strIngInput += String.Format("{0}", TszT); + + m_buffer.Add(strIngInput); + } + } + else + { + strIngInput = strMakeString; + strIngInput += String.Format("{0}", str[dPos]); + + m_buffer.Add(strIngInput); + } + + strMakeString = strIngInput; + + dPos++; + } + + return m_buffer; + } + } +} diff --git a/SmartSearch/app.config b/SmartSearch/app.config new file mode 100644 index 0000000..3a68e30 --- /dev/null +++ b/SmartSearch/app.config @@ -0,0 +1,15 @@ + + + + +
+ + + + + + + + + + \ No newline at end of file diff --git a/SmartSearch/packages.config b/SmartSearch/packages.config new file mode 100644 index 0000000..b705024 --- /dev/null +++ b/SmartSearch/packages.config @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file