1
0
mirror of https://github.com/salexdv/Telemonitor1C.git synced 2025-02-19 19:00:18 +02:00

Новая версия xNet и поддержка цепочки прокси

This commit is contained in:
Alex 2020-02-17 14:21:01 +03:00
parent 7b6354d593
commit 0de437ed43
11 changed files with 168 additions and 152 deletions

82
MainForm.Designer.cs generated
View File

@ -36,47 +36,47 @@ namespace Telemonitor
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.trayIcon = new System.Windows.Forms.NotifyIcon(this.components);
this.trayMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.trayMenuItemExit = new System.Windows.Forms.ToolStripMenuItem();
this.trayMenu.SuspendLayout();
this.SuspendLayout();
//
// trayIcon
//
this.trayIcon.ContextMenuStrip = this.trayMenu;
this.trayIcon.Icon = ((System.Drawing.Icon)(resources.GetObject("trayIcon.Icon")));
this.trayIcon.Text = "Telemonitor";
this.trayIcon.Visible = true;
//
// trayMenu
//
this.trayMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.trayMenuItemExit});
this.trayMenu.Name = "trayMenu";
this.trayMenu.Size = new System.Drawing.Size(109, 26);
//
// trayMenuItemExit
//
this.trayMenuItemExit.Name = "trayMenuItemExit";
this.trayMenuItemExit.Size = new System.Drawing.Size(108, 22);
this.trayMenuItemExit.Text = "Выход";
this.trayMenuItemExit.Click += new System.EventHandler(this.TrayMenuItemExitClick);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(124, 0);
this.Name = "MainForm";
this.Text = "Telemonitor";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainFormFormClosing);
this.Load += new System.EventHandler(this.MainFormLoad);
this.Shown += new System.EventHandler(this.MainFormShown);
this.trayMenu.ResumeLayout(false);
this.ResumeLayout(false);
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.trayIcon = new System.Windows.Forms.NotifyIcon(this.components);
this.trayMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.trayMenuItemExit = new System.Windows.Forms.ToolStripMenuItem();
this.trayMenu.SuspendLayout();
this.SuspendLayout();
//
// trayIcon
//
this.trayIcon.ContextMenuStrip = this.trayMenu;
this.trayIcon.Icon = ((System.Drawing.Icon)(resources.GetObject("trayIcon.Icon")));
this.trayIcon.Text = "Telemonitor";
this.trayIcon.Visible = true;
//
// trayMenu
//
this.trayMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.trayMenuItemExit});
this.trayMenu.Name = "trayMenu";
this.trayMenu.Size = new System.Drawing.Size(109, 26);
//
// trayMenuItemExit
//
this.trayMenuItemExit.Name = "trayMenuItemExit";
this.trayMenuItemExit.Size = new System.Drawing.Size(108, 22);
this.trayMenuItemExit.Text = "Выход";
this.trayMenuItemExit.Click += new System.EventHandler(this.TrayMenuItemExitClick);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(124, 0);
this.Name = "MainForm";
this.Text = "Telemonitor";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainFormFormClosing);
this.Load += new System.EventHandler(this.MainFormLoad);
this.Shown += new System.EventHandler(this.MainFormShown);
this.trayMenu.ResumeLayout(false);
this.ResumeLayout(false);
}
private System.Windows.Forms.ToolStripMenuItem trayMenuItemExit;

View File

@ -117,13 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Drawing" name="System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="trayIcon.TrayLocation" type="System.Drawing.Point, System.Drawing">
<metadata name="trayIcon.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</data>
<data name="trayMenu.TrayLocation" type="System.Drawing.Point, System.Drawing">
</metadata>
<metadata name="trayMenu.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>108, 17</value>
</data>
</metadata>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="trayIcon.Icon" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
AAABAAgAAAAAAAEAIABT3gAAhgAAAICAAAABACAAKAgBANneAABgYAAAAQAgAKiUAAAB5wEAQEAAAAEA

View File

@ -10,6 +10,7 @@ using System;
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json;
using xNet;
namespace Telemonitor
{
@ -21,15 +22,10 @@ namespace Telemonitor
{
private bool settingsExists;
private string botToken;
private int interval;
private bool useProxy;
private string proxyServer;
private int proxyPort;
private string proxyUser;
private string proxyPass;
private int proxyType;
private int interval;
private List<DBStruct> bases;
private Dictionary<string, Command> commands;
private List<ProxyClient> proxies;
private Dictionary<string, Command> commands;
private Dictionary<string, bool> allowUsers;
private Dictionary<string, bool> screenOwners;
private bool debug;
@ -136,26 +132,68 @@ namespace Telemonitor
try
{
this.botToken = (string)IniReadValue(iniSettings, "Main", "BotToken", typeof(string));
this.interval = (int)IniReadValue(iniSettings, "Main", "Interval", typeof(int));
this.useProxy = (bool)IniReadValue(iniSettings, "Proxy", "UseProxy", typeof(bool));
this.proxyServer = (string)IniReadValue(iniSettings, "Proxy", "Server", typeof(string));
this.proxyPort = (int)IniReadValue(iniSettings, "Proxy", "Port", typeof(int));
this.proxyUser = (string)IniReadValue(iniSettings, "Proxy", "Username", typeof(string));
this.proxyPass = (string)IniReadValue(iniSettings, "Proxy", "Password", typeof(string));
this.proxyType = (int)IniReadValue(iniSettings, "Proxy", "Type", typeof(int));
this.interval = (int)IniReadValue(iniSettings, "Main", "Interval", typeof(int));
this.debug = (bool)IniReadValue(iniSettings, "Debug", "Enabled", typeof(bool));
this.safeMode1C = (bool)GetAdditionalParamFromINI(iniSettings, "SafeMode1C", "Enabled", typeof(bool), "1");
this.buttonsShowStart = (bool)GetAdditionalParamFromINI(iniSettings, "Buttons", "ShowStartButton", typeof(bool), "0");
this.buttonsHideKeyboard = (bool)GetAdditionalParamFromINI(iniSettings, "Buttons", "HideButtonsAfterMessage", typeof(bool), "1");
this.buttonsNumRows = (int)GetAdditionalParamFromINI(iniSettings, "Buttons", "NumRowsOfButtons", typeof(int), "2");
this.buttonsUsePic = (bool)GetAdditionalParamFromINI(iniSettings, "Buttons", "UsePictures", typeof(bool), "1");
this.buttonsUsePic = (bool)GetAdditionalParamFromINI(iniSettings, "Buttons", "UsePictures", typeof(bool), "1");
this.allowUsers = GetWhiteListOfUsers((string)GetAdditionalParamFromINI(iniSettings, "WhiteList", "Users", typeof(string), ""));
this.screenOwners = GetWhiteListOfUsers((string)GetAdditionalParamFromINI(iniSettings, "WhiteList", "ScreenOwners", typeof(string), ""));
this.oscriptPath = (string)GetAdditionalParamFromINI(iniSettings, "Environment", "OneScriptPath", typeof(string), "");
if (!String.IsNullOrEmpty(botToken)) {
try
{
// Старая версия ini-файла с одним прокси
string host = (string)IniReadValue(iniSettings, "Proxy", "Server", typeof(string), true);
if ((bool)GetAdditionalParamFromINI(iniSettings, "Proxy", "UseProxy", typeof(bool), "1"))
{
ProxyClient proxy = null;
if ((int)GetAdditionalParamFromINI(iniSettings, "Proxy", "Type", typeof(int), "0") == 0)
proxy = new HttpProxyClient();
else
proxy = new Socks5ProxyClient();
proxy.Host = host;
proxy.Port = (int)GetAdditionalParamFromINI(iniSettings, "Proxy", "Port", typeof(int), "0");
proxy.Username = (string)GetAdditionalParamFromINI(iniSettings, "Proxy", "Username", typeof(string), "");
proxy.Password = (string)GetAdditionalParamFromINI(iniSettings, "Proxy", "Password", typeof(string), "");
this.proxies.Add(proxy);
}
}
catch
{
// Новая версия, где может быть несколько прокси
int countProxies = (int)GetAdditionalParamFromINI(iniSettings, "Proxy", "CountProxy", typeof(int), "0");
int idxProxy = 0;
while (idxProxy < countProxies)
{
ProxyClient proxy = null;
if ((int)GetAdditionalParamFromINI(iniSettings, "Proxy", "Type" + (idxProxy + 1), typeof(int), "0") == 0)
proxy = new HttpProxyClient();
else
proxy = new Socks5ProxyClient();
proxy.Host = (string)GetAdditionalParamFromINI(iniSettings, "Proxy", "Server" + (idxProxy + 1), typeof(string), "");
proxy.Port = (int)GetAdditionalParamFromINI(iniSettings, "Proxy", "Port" + (idxProxy + 1), typeof(int), "0");
proxy.Username = (string)GetAdditionalParamFromINI(iniSettings, "Proxy", "Username" + (idxProxy + 1), typeof(string), "");
proxy.Password = (string)GetAdditionalParamFromINI(iniSettings, "Proxy", "Password" + (idxProxy + 1), typeof(string), "");
this.proxies.Add(proxy);
idxProxy++;
}
}
if (!String.IsNullOrEmpty(botToken)) {
if (this.interval == 0)
this.interval = 1;
iniOK = true;
@ -510,6 +548,7 @@ namespace Telemonitor
{
string runPath = Service.CheckPath(System.Windows.Forms.Application.StartupPath);
this.commands = new Dictionary<string, Command>();
this.proxies = new List<ProxyClient>();
bool iniOK = CheckMainINI(runPath);
bool dbOK = CheckDbSettings(runPath);
@ -554,69 +593,14 @@ namespace Telemonitor
/// <summary>
/// Использовать/не использовать прокси-сервер
/// </summary>
public bool UseProxy
public List<ProxyClient> Proxies
{
get
{
return this.useProxy;
return this.proxies;
}
}
/// <summary>
/// Имя прокси-сервера
/// </summary>
public string ProxyServer
{
get
{
return this.proxyServer;
}
}
/// <summary>
/// Порт прокси-сервера
/// </summary>
public int ProxyPort
{
get
{
return this.proxyPort;
}
}
/// <summary>
/// Имя пользователя прокси-сервера
/// </summary>
public string ProxyUser
{
get
{
return this.proxyUser;
}
}
/// <summary>
/// Пароль пользователя прокси-сервера
/// </summary>
public string ProxyPass
{
get
{
return this.proxyPass;
}
}
/// <summary>
/// Тип прокси-сервера (0 - HTTP, 1 - SOCKS5)
/// </summary>
public int ProxyType
{
get
{
return this.proxyType;
}
}
/// <summary>
/// Признак отладки
/// </summary>

View File

@ -24,7 +24,7 @@ namespace Telemonitor
/// Уникальный идентификатор группового чата
/// </summary>
[JsonProperty("id")]
public int id { get; set; }
public Int64 id { get; set; }
/// <summary>
/// Заголовок чата

View File

@ -24,7 +24,7 @@ namespace Telemonitor
/// Уникальный идентификатор сообщения
/// </summary>
[JsonProperty("message_id")]
public int message_id { get; set; }
public Int64 message_id { get; set; }
/// <summary>
/// Отправитель сообщения

View File

@ -24,7 +24,7 @@ namespace Telemonitor
/// Уникальный идентификатор пользователя или бота
/// </summary>
[JsonProperty("id")]
public int id { get; set; }
public Int64 id { get; set; }
/// <summary>
/// Имя пользователя

View File

@ -80,7 +80,7 @@ namespace Telemonitor
/// <summary>
/// Очередь необработанных сообщений
/// </summary>
private Dictionary<int, TelegramCommand> messageOrder;
private Dictionary<Int64, TelegramCommand> messageOrder;
/// <summary>
/// Соединение с базой sqlite
@ -173,7 +173,7 @@ namespace Telemonitor
/// <param name="user_id">Идентификатор пользователя</param>
/// <param name="chat_id">Идентификатор чата</param>
/// <returns></returns>
private MessageTDB GetMessageFromDB(int message_id, int user_id, int chat_id)
private MessageTDB GetMessageFromDB(Int64 message_id, Int64 user_id, Int64 chat_id)
{
if (sqlConnection != null) {
SQLiteCommand cmd = sqlConnection.CreateCommand();
@ -216,7 +216,7 @@ namespace Telemonitor
commandParams.Add(message.text);
MessageTDB msg = null;
int parent_id = message.reply_to_message.message_id;
Int64 parent_id = message.reply_to_message.message_id;
while (parent_id > 0) {
msg = GetMessageFromDB(parent_id, message.from.id, message.chat.id);
@ -261,7 +261,7 @@ namespace Telemonitor
this.botToken = settings.BotToken;
this.mutLogger = new Mutex();
this.mutAPI = new Mutex();
this.messageOrder = new Dictionary<int, TelegramCommand>();
this.messageOrder = new Dictionary<Int64, TelegramCommand>();
this.sqlConnection = GetSQLConnection();
}
@ -272,6 +272,7 @@ namespace Telemonitor
}
else if (e.Error != null) {
Logger.Debug(tmSettings, "worker error: " + e.Error.Message, true, mutLogger);
Logger.Debug(tmSettings, "worker error: " + e.Error.ToString(), true, mutLogger);
}
else if (e.Result == null) {
Logger.Debug(tmSettings, "worker stopped", true, mutLogger);
@ -367,7 +368,9 @@ namespace Telemonitor
Logger.Debug(tmSettings, "mt wait", false, mutLogger);
mutAPI.WaitOne();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
HttpRequest request = CreateRequest();
Logger.Debug(tmSettings, "request created", false, mutLogger);
@ -375,7 +378,8 @@ namespace Telemonitor
TelegramAnswer answer = null;
try {
//HttpResponse response = request.Send(HttpMethod .GET, new Uri(String.Format(url, botToken)));
HttpResponse response = request.Get(String.Format(url, botToken));
string jsonText = response.ToString();
@ -392,7 +396,10 @@ namespace Telemonitor
}
catch (Exception respExc) {
Logger.Debug(tmSettings, "response err: " + respExc.Message, true, mutLogger);
string err = respExc.Message;
if (respExc.InnerException != null)
err += " --> " + respExc.InnerException.Message;
Logger.Debug(tmSettings, "response err: " + err, true, mutLogger);
}
request.Close();
@ -434,6 +441,7 @@ namespace Telemonitor
Logger.Debug(tmSettings, "smfd post request", false, mutLogger);
//HttpResponse response = request.Send(HttpMethod.POST, new Uri(String.Format(url, botToken)));
HttpResponse response = request.Post(String.Format(url, botToken));
string jsonText = response.ToString();
@ -465,7 +473,7 @@ namespace Telemonitor
/// <PARAM name="chat_id">Идентификатор чата</PARAM>
/// <PARAM name="fileName">Имя отправляемого файла</PARAM>
/// </summary>
private void SendPhoto(int chat_id, string fileName, int reply_to_message_id = 0)
private void SendPhoto(Int64 chat_id, string fileName, Int64 reply_to_message_id = 0)
{
string url = "https://api.telegram.org/bot{0}/sendPhoto";
@ -513,7 +521,7 @@ namespace Telemonitor
/// <PARAM name="chat_id">Идентификатор чата</PARAM>
/// <PARAM name="message">Текст сообщения</PARAM>
/// </summary>
private void SendMessage(int chat_id, string message, string keyboard = "", int reply_to_message_id = 0)
private void SendMessage(Int64 chat_id, string message, string keyboard = "", Int64 reply_to_message_id = 0)
{
string url = "https://api.telegram.org/bot{0}/sendMessage";
@ -555,7 +563,7 @@ namespace Telemonitor
/// <PARAM name="chat_id">Идентификатор чата</PARAM>
/// <PARAM name="fName">Имя файла</PARAM>
/// </summary>
private void SendDocument(int chat_id, string fileName, int reply_to_message_id = 0)
private void SendDocument(Int64 chat_id, string fileName, Int64 reply_to_message_id = 0)
{
if (File.Exists(fileName)) {
@ -592,13 +600,23 @@ namespace Telemonitor
var request = new HttpRequest();
request.KeepAlive = true;
request.ConnectTimeout = 30000;
if (tmSettings.UseProxy) {
if (tmSettings.ProxyType == 0)
request.Proxy = HttpProxyClient.Parse(tmSettings.ProxyServer.ToString() + ':' + tmSettings.ProxyPort.ToString());
else
request.Proxy = Socks5ProxyClient.Parse(tmSettings.ProxyServer.ToString() + ':' + tmSettings.ProxyPort.ToString());
request.Proxy.Username = tmSettings.ProxyUser;
request.Proxy.Password = tmSettings.ProxyPass;
if (0 < tmSettings.Proxies.Count) {
if (1 == tmSettings.Proxies.Count)
{
request.Proxy = tmSettings.Proxies[0];
}
else
{
ChainProxyClient chain = new ChainProxyClient();
foreach (ProxyClient proxy in tmSettings.Proxies)
{
chain.AddProxy(proxy);
}
request.Proxy = chain;
}
}
return request;
@ -651,7 +669,7 @@ namespace Telemonitor
if (connector.Success) {
int reply_to_message_id = (result.Dialog) ? tCommand.Message.message_id : 0;
Int64 reply_to_message_id = (result.Dialog) ? tCommand.Message.message_id : 0;
if (!String.IsNullOrEmpty(result.Text))
SendMessage(tCommand.Message.chat.id, result.Text, "", reply_to_message_id);
@ -733,7 +751,7 @@ namespace Telemonitor
output.AppendLine(curString);
}
int reply_to_message_id = (dialog) ? tCommand.Message.message_id : 0;
Int64 reply_to_message_id = (dialog) ? tCommand.Message.message_id : 0;
if (0 < output.Length || !String.IsNullOrEmpty(resFile)) {
if (0 < output.Length)

View File

@ -7,9 +7,10 @@
<OutputType>WinExe</OutputType>
<RootNamespace>Telemonitor</RootNamespace>
<AssemblyName>Telemonitor</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<AppDesignerFolder>Properties</AppDesignerFolder>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<ApplicationIcon>pic\Telemonitor_logo.ico</ApplicationIcon>
<NoWin32Manifest>False</NoWin32Manifest>
<SignAssembly>False</SignAssembly>
@ -39,6 +40,8 @@
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<BaseIntermediateOutputPath>obj\</BaseIntermediateOutputPath>
<StartAction>Project</StartAction>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<OutputPath>bin\Release\</OutputPath>
@ -74,9 +77,6 @@
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="xNet">
<HintPath>xNet.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Const.cs" />
@ -116,5 +116,11 @@
<ItemGroup>
<None Include="app.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\xNet-master\xNet.csproj">
<Project>{5d25d06e-0d35-42ef-bba2-d5de6e06cd04}</Project>
<Name>xNet</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -1,9 +1,13 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
# SharpDevelop 5.1
VisualStudioVersion = 12.0.20827.3
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Telemonitor", "Telemonitor.csproj", "{0A4153D9-1029-4131-9D43-F4734D97F2AB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "xNet", "..\xNet-master\xNet.csproj", "{5D25D06E-0D35-42EF-BBA2-D5DE6E06CD04}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -14,5 +18,9 @@ Global
{0A4153D9-1029-4131-9D43-F4734D97F2AB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0A4153D9-1029-4131-9D43-F4734D97F2AB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0A4153D9-1029-4131-9D43-F4734D97F2AB}.Release|Any CPU.Build.0 = Release|Any CPU
{5D25D06E-0D35-42EF-BBA2-D5DE6E06CD04}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5D25D06E-0D35-42EF-BBA2-D5DE6E06CD04}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5D25D06E-0D35-42EF-BBA2-D5DE6E06CD04}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5D25D06E-0D35-42EF-BBA2-D5DE6E06CD04}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client" />
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

BIN
xNet.dll

Binary file not shown.