old_flsystem/类库/Api.Framework/ApiClient - 复制.cs

3273 lines
171 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Api.Framework.Config;
using Api.Framework.Config;
using Api.Framework.Enums;
using Api.Framework.Model;
using Api.Framework.SDK;
using Api.Framework.Timers;
using Api.Framework.Tools;
using Api.Framework.UIForm;
using Chat.Framework;
using CsharpHttpHelper;
using Api.Framework.Tools;
using SqlSugar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using ZXing;
using ZXing.Common;
using System.Reflection;
using Chat.Framework.WXSdk;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using SuperSocket.SocketBase;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using Chat.Framework.PCRobotSDK.WechatEvents;
using PCRobot.Pack;
using SuperSocket.SocketEngine;
using Chat.Framework.PCRobotSDK;
using Chat.Framework.WXSdk.Events;
using Chat.Framework.WXSdk.Implement;
using Chat.Framework.PCRobotSDK.WorkWechatEvents;
using Grant.Framework;
using Newtonsoft.Json.Linq;
using System.Web.Configuration;
using System.Web.Security;
using static Api.Framework.Cps.AlimamaApi;
using Robot.Framework.Entities;
using Chat.Framework.QQSdk.QPlus;
namespace Api.Framework
{
public class ApiClient
{
private static Version _version;
/// <summary>
/// 当前版本
/// </summary>
public static Version CurVersion
{
get
{
if (_version == null)
{
string file = Util.MapFile("VersionUpdate.xml");
if (!File.Exists(file)) file = Util.MapFile("OnlineUpdate.xml");
if (!File.Exists(file)) throw new Exception("文件丢失[VersionUpdate.xml],不存在!");
var xml = File.ReadAllText(file).Trim();
if (!string.IsNullOrWhiteSpace(xml))
{
var reg = Regex.Match(xml, @"File\s+?Name=""核心组件""\s+?Version=""(?<版本号>([^""]*?))""");
if (reg.Success)
{
var version = reg.Groups["版本号"].Value.Trim();
_version = Version.Parse(version);
}
}
}
return _version;
}
}
public static SoperSocketServer Server { get; private set; }
public static void StopSocketServer()
{
try
{
if (Server != null)
{
Server.Stop();
Server.NewSessionConnected -= appServer_NewSessionConnected;
Server.SessionClosed -= appServer_NewSessionClosed;
}
}
catch (Exception)
{ }
}
public static bool StartSocketServer(int port, string password)
{
try
{
StopSocketServer();
Server = new SoperSocketServer();
var serconfig = new SuperSocket.SocketBase.Config.ServerConfig();
serconfig.TextEncoding = "UTF-8";
serconfig.Ip = "Any";
serconfig.Port = port;
serconfig.SendBufferSize = 1024 * 40;
serconfig.ReceiveBufferSize = 10240 * 40;
serconfig.MaxRequestLength = 10240 * 40;
serconfig.SendingQueueSize = 50;
Console.WriteLine(serconfig.MaxConnectionNumber);
// serconfig.MaxConnectionNumber = 5000;
//SuperSocket.SocketBase. appServer = new AppServer();
if (!Server.Setup(serconfig)) throw new Exception("监听端口失败,请检查是否关闭防火墙或端口被占用!");
//var cfg = new SuperSocket.SocketBase.Config.ServerConfig();
//cfg.ReceiveBufferSize = int.MaxValue;
//var rfg = new SuperSocket.SocketBase.Config.RootConfig();
////Try to start the appServer
if (!Server.Start()) throw new Exception("初始化端口失败,请检查是否关闭防火墙或端口被占用!");
ApiClient.Setting.ServerConfig.SocketPassword = password;
ApiClient.Setting.ServerConfig.SocketPort = port;
ApiClient.Setting.ServerConfig.SocketIsOpen = true;
//var cfg = Server.Config;
////var rfg = Server.RootConfig;
//Server.Config.ReceiveBufferSize = int.MaxValue;
ChatClient.SocketPassword = password;
Server.NewSessionConnected += appServer_NewSessionConnected;
Server.SessionClosed += appServer_NewSessionClosed;
////SocketCMD 是KEY
Server.NewRequestReceived += Server_NewRequestReceived;
//Server.r
Util.Save(Setting.ServerConfig);
return true;
//return true;
}
catch (Exception ex)
{
ApiClient.Setting.ServerConfig.SocketIsOpen = false;
Util.Save(Setting.ServerConfig);
throw ex;
}
return false;
}
/// <summary>
/// HOOK机器人消息事件
/// </summary>
/// <param name="session"></param>
/// <param name="requestInfo"></param>
private static void Server_NewRequestReceived(SupperSocketSession _session, SuperSocket.SocketBase.Protocol.StringRequestInfo _requestInfo)
{
var session = _session;
var requestInfo = _requestInfo;
var action = new Action(delegate ()
{
try
{
int key;
//var cmd = (PCRobot.Pack.PCRobotCMD)Enum.Parse(typeof(PCRobot.Pack.PCRobotCMD), requestInfo.Key);
PCRobot.Pack.PCRobotCMD cmd;
if (!Enum.TryParse<PCRobot.Pack.PCRobotCMD>(requestInfo.Key, out cmd)) return;
var data = PackTool.DecompressString(requestInfo.Body);
var dic = CsharpHttpHelper.HttpExtend.JsonToDictionary(data);
if (dic.ContainsKey("Key") && dic["Key"].ToString() != Setting.ServerConfig.SocketPassword)
{
var RobotUsernick = string.Empty;
if (dic.ContainsKey("RobotUsernick"))
RobotUsernick = dic["RobotUsernick"].ToString();
var RobotUsername = string.Empty;
if (dic.ContainsKey("RobotUsername"))
RobotUsername = dic["RobotUsername"].ToString();
RobotType robotType;
if (dic.ContainsKey("RobotType"))
{
var type = dic["RobotType"].ToString();
if (Enum.TryParse<RobotType>(type, out robotType))
throw new Exception($"{(robotType == RobotType.客户端微信 ? ChatType.微信 : robotType == RobotType.客户端企业微信 ? ChatType.企业微信 : robotType == RobotType.客户端扣扣 ? ChatType.QQ : ChatType.微信公众号)}{RobotUsernick}({RobotUsername}) 易转发与软件秘钥不匹配,无法通讯!");
}
}
var cmd_int = (int)cmd;
var events = ChatClient.Events;
//心跳包处理
//if (cmd == PCRobotCMD.heartBreak)
//{
// var json = HttpHelper.JsonToObject<WechatStatus>(data) as WechatStatus;
// var evt = new Chat.Framework.PCRobotSDK.WechatEvents.WechatStatusEvents(json);
// if (evt == null) return;
// if (evt.Key != Setting.ServerConfig.SocketPassword) throw new Exception("秘钥不匹配,无法连接!");
// //var robot = GetRobotInfo(evt.RobotUsername, evt.RobotUsernick, evt.RobotType == RobotType.客户端企业微信 ? ChatType.企业微信 : ChatType.微信, evt.Uin);
// //Chat.Framework.ChatClient.PCRobotPool.Update(evt.RobotUsername, session);
// //var hook = FindHookRobot(robot, evt.RobotType);
// //if (hook != null)
// //{
// // hook.Receive(evt);
// //}
// //EventClient.OnEvent(null,$"收到{robot.name}({robot.nick})的心跳包!");
// session.Send("heartBreak $");
//}
if (cmd.ToString().StartsWith("offline"))
{
var json = HttpHelper.JsonToObject<WechatStatus>(data) as WechatStatus;
var evt = new Chat.Framework.PCRobotSDK.WechatEvents.WechatStatusEvents(json);
if (evt == null)
{
EventClient.OnEvent(null, $"{json.RobotUsername}({json.Uin})心跳发送失败");
return;
}
if (evt.Key == Setting.ServerConfig.SocketPassword)
session.TrySend(data);
else
EventClient.OnEvent(null, $"{json.RobotUsername}({json.Uin})心跳发送失败,秘钥不一致");
}
//个人微信消息
if (cmd_int >= 2000 && cmd_int <= 2999)
{
switch (cmd)
{
case PCRobot.Pack.PCRobotCMD.rcvTxt:
case PCRobot.Pack.PCRobotCMD.rcvFile:
case PCRobot.Pack.PCRobotCMD.rcvImg:
{
var json = HttpHelper.JsonToObject<WechatReceiveMsg>(data) as WechatReceiveMsg;
var evt = new Chat.Framework.PCRobotSDK.WechatEvents.WechatReceiveMsgEvents(json);
if (evt == null) return;
var robot = GetRobotInfo(evt.Data.RobotUsername, evt.Data.RobotUsernick, ChatType.);
Chat.Framework.ChatClient.PCRobotPool.Update(evt.Data.RobotUsername, session);
//EventClient.OnEvent(evt, evt);
var hook = FindHookRobot(robot, evt.Data.RobotType);
if (hook != null)
{
hook.Receive(evt);
}
}
break;
case PCRobotCMD.applyFriend:
{
var json = HttpHelper.JsonToObject<WechatApplyFriend>(data) as WechatApplyFriend;
var evt = new Chat.Framework.PCRobotSDK.WechatEvents.WechatApplyFriendEvents(json);
if (evt == null) return;
var robot = GetRobotInfo(evt.Data.RobotUsername, evt.Data.RobotUsernick, ChatType.);
Chat.Framework.ChatClient.PCRobotPool.Update(evt.Data.RobotUsername, session);
var hook = FindHookRobot(robot, evt.Data.RobotType);
if (hook != null)
hook.Receive(evt);
}
break;
case PCRobot.Pack.PCRobotCMD.receivePay:
{
var json = HttpHelper.JsonToObject<WechatReicevePay>(data) as WechatReicevePay;
var evt = new Chat.Framework.PCRobotSDK.WechatEvents.WechatReicevePayEvents(json);
if (evt == null) return;
var robot = GetRobotInfo(evt.Data.RobotUsername, evt.Data.RobotUsernick, ChatType.);
Chat.Framework.ChatClient.PCRobotPool.Update(evt.Data.RobotUsername, session);
var hook = FindHookRobot(robot, evt.Data.RobotType);
if (hook != null)
hook.Receive(evt);
}
break;
case PCRobotCMD.applyGroup:
{ }
break;
case PCRobotCMD.newfriend:
{
var json = HttpHelper.JsonToObject<WechatNewFriend>(data) as WechatNewFriend;
var evt = new Chat.Framework.PCRobotSDK.WechatEvents.WechatNewFriendEvents(json);
if (evt == null) return;
var robot = GetRobotInfo(evt.Data.RobotUsername, evt.Data.RobotUsernick, ChatType.);
Chat.Framework.ChatClient.PCRobotPool.Update(evt.Data.RobotUsername, session);
var hook = FindHookRobot(robot, evt.Data.RobotType);
if (hook != null)
hook.Receive(evt);
}
break;
case PCRobotCMD.offline:
{
var json = HttpHelper.JsonToObject<WechatStatus>(data) as WechatStatus;
var evt = new Chat.Framework.PCRobotSDK.WechatEvents.WechatStatusEvents(json);
if (evt == null)
{
EventClient.OnEvent(null, $"{json.RobotUsername}({json.Uin})心跳发送失败,秘钥不一致");
return;
}
var robot = GetRobotInfo(evt.RobotUsername, evt.RobotUsernick, ChatType., json.Uin);
robot.is_login = evt.Status == Status.线;
Chat.Framework.ChatClient.PCRobotPool.Update(evt.RobotUsername, session);
var hook = FindHookRobot(robot, evt.RobotType);
if (hook != null)
{
hook.Receive(evt);
if (string.IsNullOrWhiteSpace(robot.end_time))
{
var softId = (robot.type == Api.Framework.SDK.ChatType.QQ) ? 1002 : 1001;
var custm = GrantClient.Get().Refresh(robot.uin.ToString(), softId);
if (custm != null)
{
robot.end_time = custm.endTime;
ApiClient.GetSession().SaveOrUpdate(robot);
ApiClient.GetSession().FindRobots(true);
}
}
}
}
break;
case PCRobotCMD.newMember:
{
var json = HttpHelper.JsonToObject<WechatNewMemer>(data) as WechatNewMemer;
var evt = new WechatNewMemerEvents(json);
if (evt == null) return;
var robot = GetRobotInfo(evt.Data.RobotUsername, evt.Data.RobotUsernick, ChatType.);
Chat.Framework.ChatClient.PCRobotPool.Update(evt.Data.RobotUsername, session);
var hook = FindHookRobot(robot, evt.Data.RobotType);
if (hook != null)
hook.Receive(evt);
}
break;
case PCRobotCMD.rcvContactList:
{
var json = HttpHelper.JsonToObject<WechatContact>(data) as WechatContact;
var evt = new WechatContactListEvents(json);
if (evt == null) return;
var robot = GetRobotInfo(evt.Data.RobotUsername, evt.Data.RobotUsernick, ChatType.);
Chat.Framework.ChatClient.PCRobotPool.Update(evt.Data.RobotUsername, session);
Chat.Framework.ChatClient.PCRobotPool.PackHist.SetResult(json);
var hook = FindHookRobot(robot, evt.Data.RobotType);
if (hook != null)
hook.Receive(evt);
}
break;
case PCRobotCMD.rcvContact:
{
var json = HttpHelper.JsonToObject<WechatContact>(data) as WechatContact;
var evt = new WechatContactListEvents(json);
if (evt == null) return;
var robot = GetRobotInfo(evt.Data.RobotUsername, evt.Data.RobotUsernick, ChatType.);
Chat.Framework.ChatClient.PCRobotPool.Update(evt.Data.RobotUsername, session);
Chat.Framework.ChatClient.PCRobotPool.PackHist.SetResult(json);
}
break;
case PCRobotCMD.rcvCheckUrl:
{
var json = HttpHelper.JsonToObject<CheckUrl>(data) as CheckUrl;
Chat.Framework.ChatClient.PCRobotPool.PackHist.SetResult(json);
}
break;
case PCRobotCMD.rcvCreateRoom:
{
var json = HttpHelper.JsonToObject<CreateRoom>(data) as CreateRoom;
Chat.Framework.ChatClient.PCRobotPool.PackHist.SetResult(json);
}
break;
case PCRobotCMD.rcvGroupMember:
{
var json = HttpHelper.JsonToObject<WechatGroupMember>(data) as WechatGroupMember;
var evt = new WechatGroupMemberEvents(json);
if (evt == null) return;
var robot = GetRobotInfo(evt.Data.RobotUsername, evt.Data.RobotUsernick, ChatType.);
Chat.Framework.ChatClient.PCRobotPool.Update(evt.Data.RobotUsername, session);
var hook = FindHookRobot(robot, evt.Data.RobotType);
if (hook != null)
hook.Receive(evt);
}
break;
}
}
//企业微信消息处理
else if (cmd_int >= 3000 && cmd_int <= 3999)
{
switch (cmd)
{
case PCRobotCMD.rcvTxt_workWeChat:
case PCRobotCMD.rcvFile_workWeChat:
case PCRobotCMD.rcvImg_workWeChat:
{
var json = HttpHelper.JsonToObject<WorkWechatReceiveMsg>(data) as WorkWechatReceiveMsg;
var evt = new Chat.Framework.PCRobotSDK.WorkWechatEvents.WorkWechatReceiveMsgEvents(json);
if (evt == null) return;
var robot = GetRobotInfo(evt.Data.RobotUsername, evt.Data.RobotUsernick, ChatType.);
Chat.Framework.ChatClient.PCRobotPool.Update(evt.Data.RobotUsername, session);
//EventClient.OnEvent(evt, evt);
var hook = FindHookRobot(robot, evt.Data.RobotType);
if (hook != null)
hook.Receive(evt);
else
{ }
}
break;
case PCRobotCMD.applyFriend_workWeChat:
{
var json = HttpHelper.JsonToObject<WorkWechatApplyFriend>(data) as WorkWechatApplyFriend;
var evt = new Chat.Framework.PCRobotSDK.WorkWechatEvents.WorkWechatApplyFriendEvents(json);
if (evt == null) return;
var robot = GetRobotInfo(evt.Data.RobotUsername, evt.Data.RobotUsernick, ChatType.);
Chat.Framework.ChatClient.PCRobotPool.Update(evt.Data.RobotUsername, session);
var hook = FindHookRobot(robot, evt.Data.RobotType);
if (hook != null)
hook.Receive(evt);
else
{ }
}
break;
case PCRobotCMD.receivePay_workWeChat:
{
var json = HttpHelper.JsonToObject<WorkWechatReicevePay>(data) as WorkWechatReicevePay;
var evt = new Chat.Framework.PCRobotSDK.WorkWechatEvents.WorkWechatReicevePayEvents(json);
if (evt == null) return;
var robot = GetRobotInfo(evt.Data.RobotUsername, evt.Data.RobotUsernick, ChatType.);
Chat.Framework.ChatClient.PCRobotPool.Update(evt.Data.RobotUsername, session);
var hook = FindHookRobot(robot, evt.Data.RobotType);
if (hook != null)
hook.Receive(evt);
else
{ }
}
break;
case PCRobotCMD.applyGroup_workWeChat:
{ }
break;
case PCRobotCMD.newfriend_workWeChat:
{
var json = HttpHelper.JsonToObject<WorkWechatNewFriend>(data) as WorkWechatNewFriend;
var evt = new Chat.Framework.PCRobotSDK.WorkWechatEvents.WorkWechatNewFriendEvents(json);
if (evt == null) return;
var robot = GetRobotInfo(evt.Data.RobotUsername, evt.Data.RobotUsernick, ChatType.);
Chat.Framework.ChatClient.PCRobotPool.Update(evt.Data.RobotUsername, session);
var hook = FindHookRobot(robot, evt.Data.RobotType);
if (hook != null)
hook.Receive(evt);
else
{ }
}
break;
case PCRobotCMD.offline_workWeChat:
{
var json = HttpHelper.JsonToObject<WechatStatus>(data) as WechatStatus;
var evt = new Chat.Framework.PCRobotSDK.WechatEvents.WechatStatusEvents(json);
if (evt == null)
{
EventClient.OnEvent(null, $"{json.RobotUsername}({json.Uin})心跳发送失败,秘钥不一致");
return;
}
var robot = GetRobotInfo(evt.RobotUsername, evt.RobotUsernick, ChatType., json.Uin);
robot.is_login = evt.Status == Status.线;
Chat.Framework.ChatClient.PCRobotPool.Update(evt.RobotUsername, session);
var hook = FindHookRobot(robot, evt.RobotType);
if (hook != null)
{
hook.Receive(evt);
if (string.IsNullOrWhiteSpace(robot.end_time))
{
var softId = (robot.type == Api.Framework.SDK.ChatType.QQ) ? 1002 : 1001;
var custm = GrantClient.Get().Refresh(robot.uin.ToString(), softId);
if (custm != null)
{
robot.end_time = custm.endTime;
ApiClient.GetSession().SaveOrUpdate(robot);
ApiClient.GetSession().FindRobots(true);
}
}
}
else
{ }
}
break;
case PCRobotCMD.newMember_workWeChat:
{
var json = HttpHelper.JsonToObject<WorkWechatNewMemer>(data) as WorkWechatNewMemer;
var evt = new WorkWechatNewMemerEvents(json);
if (evt == null) return;
var robot = GetRobotInfo(evt.Data.RobotUsername, evt.Data.RobotUsernick, ChatType.);
Chat.Framework.ChatClient.PCRobotPool.Update(evt.Data.RobotUsername, session);
var hook = FindHookRobot(robot, evt.Data.RobotType);
if (hook != null)
hook.Receive(evt);
else
{ }
}
break;
case PCRobotCMD.rcvContact_workWeChat:
{
var json = HttpHelper.JsonToObject<WorkWechatContact>(data) as WorkWechatContact;
var evt = new WorkWechatContactListEvents(json);
if (evt == null) return;
var robot = GetRobotInfo(evt.Data.RobotUsername, evt.Data.RobotUsernick, ChatType.);
Chat.Framework.ChatClient.PCRobotPool.Update(evt.Data.RobotUsername, session);
Chat.Framework.ChatClient.PCRobotPool.PackHist.SetResult(json);
}
break;
case PCRobotCMD.rcvContactList_workWeChat:
{
var json = HttpHelper.JsonToObject<WorkWechatContact>(data) as WorkWechatContact;
var evt = new WorkWechatContactListEvents(json);
if (evt == null) return;
var robot = GetRobotInfo(evt.Data.RobotUsername, evt.Data.RobotUsernick, ChatType.);
Chat.Framework.ChatClient.PCRobotPool.Update(evt.Data.RobotUsername, session);
var hook = FindHookRobot(robot, evt.Data.RobotType);
if (hook != null)
hook.Receive(evt);
else
{ }
}
break;
case PCRobotCMD.rcvGroupMember_workWeChat:
{
var json = HttpHelper.JsonToObject<WorkWechatGroupMember>(data) as WorkWechatGroupMember;
var evt = new WorkWechatGroupMemberEvents(json);
if (evt == null) return;
var robot = GetRobotInfo(evt.Data.RobotUsername, evt.Data.RobotUsernick, ChatType.);
Chat.Framework.ChatClient.PCRobotPool.Update(evt.Data.RobotUsername, session);
var hook = FindHookRobot(robot, evt.Data.RobotType);
if (hook != null)
hook.Receive(evt);
else
{ }
}
break;
}
}
}
catch (Exception ex)
{
EventClient.OnEvent(null, $"{ex.Message}.");
}
});
action.BeginInvoke(null, null);
}
/// <summary>
/// 锁获取机器人对象,确保唯一
/// </summary>
private static readonly object GetRobotLock = new object();
/// <summary>
/// 获取机器人对象
/// </summary>
/// <param name="weixinhao"></param>
/// <returns></returns>
private static WeixinBase FindHookRobot(fl_robot_info robot, RobotType robotType)
{
lock (GetRobotLock)
{
var v = ChatClient.WXClient.FirstOrDefault(f => f.Key == robot.name).Value;
if (!robot.is_login && v == null)
return null;
switch (robotType)
{
case RobotType.:
break;
case RobotType.:
if (v == null)
v = new WXClientImpl_HOOK(robot.name, robot.nick, long.Parse(robot.uin));
break;
case RobotType.:
if (v == null)
v = new WXClientImpl_QYHOOK(robot.name, robot.nick, long.Parse(robot.uin));
break;
case RobotType.:
break;
}
return v;
}
}
/// <summary>
/// 获取机器人对象
/// </summary>
/// <param name="username"></param>
/// <param name="usernick"></param>
/// <param name="robotType"></param>
/// <returns></returns>
[Obsolete("这个函数已经过时了", true)]
private static WeixinBase FindHookRobot(string username, string usernick, RobotType robotType)
{
lock (GetRobotLock)
{
var v = ChatClient.WXClient.FirstOrDefault(f => f.Key == username).Value;
switch (robotType)
{
case RobotType.:
break;
case RobotType.:
if (v == null)
v = new WXClientImpl_HOOK(username, usernick);
break;
case RobotType.:
if (v == null)
v = new WXClientImpl_QYHOOK(username, usernick);
break;
case RobotType.:
break;
}
return v;
}
}
/// <summary>
/// 删除机器人对象
/// </summary>
/// <param name="weixinhao"></param>
//private static void RemoveHookRobot(string weixinhao)
//{
// lock (GetRobotLock)
// {
// if (ChatClient.WXClient.ContainsKey(weixinhao))
// ChatClient.WXClient.Remove(weixinhao);
// }
//}
private readonly static object robot_lock = new object();
private static fl_robot_info GetRobotInfo(string robotUsername, string robotUsernick, ChatType chatType, string uin = "")
{
var s = ApiClient.GetSession();
fl_robot_info robot = null;
if (string.IsNullOrWhiteSpace(robotUsername))
return null;
lock (robot_lock)
{
robot = s.FindRobotInfo(robotUsername, chatType);
if (robot == null)
{
robot = new fl_robot_info()
{
name = robotUsername,
nick = Util.RemoveEmoji(robotUsernick),
uin = uin,
type = chatType,
remark = "PCWechat HOOK"
};
s.Insertable<fl_robot_info>(robot).ExecuteCommandIdentityIntoEntity();
s.FindRobots(true);
}
else
{
if (!string.IsNullOrWhiteSpace(uin))
{
robot.nick = Util.RemoveEmoji(robotUsernick);
robot.uin = uin;
robot.remark = "PCWechat HOOK";
s.Updateable<fl_robot_info>(robot).ExecuteCommand();
s.FindRobots(true);
}
else
{ }
}
robot.is_login = true;
}
return robot;
}
private static void appServer_NewSessionClosed(SupperSocketSession session, SuperSocket.SocketBase.CloseReason value)
{
try
{
EventClient.OnEvent(session, $"{session.RemoteEndPoint.Address}-{session.RemoteEndPoint.Port}--> 已关闭!");
var con = ApiClient.GetSession();
var name = Chat.Framework.ChatClient.PCRobotPool.Remove(session);
var r = con.FindRobots().FirstOrDefault(f => f.name == name);
if (r != null)
{
r.is_login = false;
con.Updateable<fl_robot_info>(r).ExecuteCommand();
}
}
catch (Exception)
{
}
}
private static void appServer_NewSessionConnected(SupperSocketSession session)
{
EventClient.OnEvent(session, $"{session.RemoteEndPoint.Address}-{session.RemoteEndPoint.Port} --> 连接成功!");
}
public static Setting Setting { get; set; }
/// <summary>
/// 清理垃圾
/// </summary>
private static ClearGarbageTimer _ClearGarbage;
public static bool SelectDbbase()
{
Setting = new Setting();
//选择数据库
if (string.IsNullOrEmpty(Setting.DbConfig.ConnectionString))
{
SetConnectionConfig connection = new SetConnectionConfig();
connection.ShowDialog();
if (!connection.IsOk) return false;
return true;
}
return true;
}
/// <summary>
/// 初始化
/// </summary>
public static bool Initialization()
{
try
{
Cache = CacheTool.GetSingleObj();
//初始化
var session = GetSession();
try
{
bool first = CreateTables(session);
Setting.Iniconfig();
Setting.SystemConfig.cps_server_api = "http://cps.api.52cmg.cn/";
if (first)
{
Setting.Plugins.Add("PointManage.Class1");
Setting.Plugins.Add("TBRebate.Class1");
Setting.Plugins.Add("PDDRebate.Class1");
Setting.Plugins.Add("UserFission.Class1");
Setting.Plugins.Add("AutoAnswer.Class1");
}
string key = "<RSAKeyValue><Modulus>2lThVzrziUuYbxfzgQ9CpivZANcSOVzUaV9Uacw8gCaudDjT6Vn6Mv+HyMKUnZB4zCwBOYkFuMjS8gfoog3Dk26TkHxAp7izE3RK8ptL7vzqozaMioqak05binUrZxLiy4X/5D9+Ny+lueuQjCIjn6eXL0D595NbAlTw/uOHodE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
CpsClient.SetEnckey(10003, ApiClient.Setting.SystemConfig.cps_server_api, key);
//var ip = (CpsClient.SendServer("find_config", "webtool.asmx", new { name = "Grpc微信服务器" }) as string).Split(',');
ChatClient.GetServerDataMethod = GetServerConfig;
// var ip = "193.112.217.56:81".Split(','); ;
//var ip = "193.112.217.56:81".Split(','); ;
// ip = new string[] { "118.25.53.240:9888" };
ChatClient.SetWeixinCore(null, new string[] { "1001", "13101A4D25A0C46B97BB58799C0D5CC7" });
ChatClient.Events.WXGetDeviceEvent += Events_WXGetDeviceEvent;
ChatClient.GetDBWechatFriend = GetDBWechatFriend;
PluginClient.LodingPlugin();//加载插件
ResetTimer();
if (Setting.ServerConfig.IsOpen)
{
WebClient.Start(Setting.ServerConfig.Host, ApiClient.Setting.ServerConfig.Port, false);
}
if (Setting.ServerConfig.SocketIsOpen)
{
StartSocketServer(Setting.ServerConfig.SocketPort, Setting.ServerConfig.SocketPassword);
}
return true;
}
catch (Exception ex)
{
throw ex;
return false;
// session.Rollback();
}
}
catch (Exception ex)
{
throw ex;
//MessageBox.Show(ex.Message + ex.StackTrace != null ? "\r\n" + ex.StackTrace : "", "初始化失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
private static Chat.Framework.WXSdk.Friend GetDBWechatFriend(string username)
{
try
{
var session = GetSession();
var member = session.FindSingle<fl_member_info>("select * from fl_member_info where (robot_type = @robot_type1 or robot_type = @robot_type2) and username = @username", new { username = username, robot_type1 = ChatType., robot_type2 = ChatType. });
if (member != null)
return new Chat.Framework.WXSdk.Friend() { UserName = member.username, NickName = member.usernick, Alias = member.wechatid };
}
catch (Exception)
{ }
return new Chat.Framework.WXSdk.Friend() { UserName = username };
}
private static void Events_WXGetDeviceEvent(object sender, Chat.Framework.WXSdk.Events.WXGetDevice e)
{
try
{
var session = GetSession();
//var device = session.Queryable<fl_wechat_device>().Where(f => f.weixinhao == e.Client.WeixinHao).Single();
var device = session.FindSingle<fl_wechat_device>("select * from fl_wechat_device where weixinhao = @weixinhao", new { weixinhao = e.Client.WeixinHao });
if (device != null)
{
e.DeviceInfo = string.IsNullOrEmpty(device.device_info) ? string.Empty : device.device_info;
}
}
catch (Exception)
{ }
}
public static string GetServerConfig(string key)
{
return CpsClient.SendServer("find_config", "webtool.asmx", new { name = key }) as string;
}
#region ,false不用管,true表示已经删除了(,)
private static bool checkIndex(SqlSugarClient session, string tableName, params object[] values)
{
try
{
if (session.CurrentConnectionConfig.DbType == DbType.MySql)
{
if (session.IndexExist(tableName, values[0].ToString()))
return session.DeleteIndex(tableName, values[0].ToString());
}
else if (session.CurrentConnectionConfig.DbType == DbType.Sqlite)
{
if (session.IndexExist(tableName, tableName + "_" + string.Join("_", values)))
return session.DeleteIndex(tableName, tableName + "_" + string.Join("_", values));
}
}
catch (Exception)
{ }
return false;
}
#endregion
/// <summary>
/// 创建表,没有表则创建
/// </summary>
/// <param name="session"></param>
/// <returns></returns>
public static bool CreateTables(SqlSugarClient session)
{
try
{
//全额免单
if (!session.TableExist<fl_plugin_allrebatesactivity_info>())
{
session.CreateTable<fl_plugin_allrebatesactivity_info>();
session.AddIndex<fl_plugin_allrebatesactivity_info>("name");//增加索引.以后数据多了.查询速度会比较快
session.AddUnique<fl_plugin_allrebatesactivity_info>("name");//增加唯一约束
}
//全额免单订单
if (!session.TableExist<fl_plugin_allrebatesactivity_orderlist>())
{
session.CreateTable<fl_plugin_allrebatesactivity_orderlist>();
}
if (!session.TableExist<fl_prevent_theft_cache>())
{
session.CreateTable<fl_prevent_theft_cache>();
session.AddIndex<fl_prevent_theft_cache>("order_id");
session.AddUnique<fl_prevent_theft_cache>("order_id");
}
//推广位组
if (!session.TableExist<fl_adzone_group>())
{
session.CreateTable<fl_adzone_group>();
session.AddIndex<fl_adzone_group>("cps_type");
session.AddUnique<fl_adzone_group>("name");
}
else
{
if (!session.ColumnExist("fl_adzone_group", "remark"))
{
session.AddColumn("fl_adzone_group", "remark", "varchar(255) default ''");
}
}
//推广位
if (!session.TableExist<fl_adzone_info>())
{
session.CreateTable<fl_adzone_info>();
}
else
{
if (!session.ColumnExist("fl_adzone_info", "is_auto_bind"))
{
session.AddColumn("fl_adzone_info", "is_auto_bind", "boolean default 0");
}
if (!session.ColumnExist("fl_adzone_info", "adzone_group"))
{
session.AddColumn("fl_adzone_info", "adzone_group", "integer default 0");
}
}
//用户自定义变量
if (!session.TableExist<fl_uservariate_info>())
{
session.CreateTable<fl_uservariate_info>();
session.AddUnique<fl_uservariate_info>("variate");
}
if (!session.TableExist<fl_wechat_contacts>())
{
session.CreateTable<fl_wechat_contacts>();
session.AddUnique<fl_wechat_contacts>("user_name");
}
if (!session.TableExist<fl_noticeapi_info>())
{
session.CreateTable<fl_noticeapi_info>();
session.AddUnique<fl_noticeapi_info>("name");
}
//dubug日志
if (!session.TableExist<fl_debug_log>())
{
session.CreateTable<fl_debug_log>();
}
//群负责人
if (!session.TableExist<fl_group_person>())
{
session.CreateTable<fl_group_person>();
session.AddIndex<fl_group_person>("groupid");
}
//私人pid
if (!session.TableExist<fl_private_pid>())
{
session.CreateTable<fl_private_pid>();
}
//阿里妈妈维权表
if (!session.TableExist<fl_order_refund_alimama>())
{
session.CreateTable<fl_order_refund_alimama>();
session.AddIndex<fl_order_refund_alimama>("tbtradeparentid", "tbtradeid");
}
else
{
#region
try
{
if (session.CurrentConnectionConfig.DbType == DbType.Sqlite)
{
session.ExcuteSQL("drop index fl_order_refund_alimama_tbTradeParentId_", new { });
}
else if (session.CurrentConnectionConfig.DbType == DbType.MySql)
{
session.ExcuteSQL("ALTER TABLE fl_order_refund_alimama DROP INDEX tbTradeParentId", new { });
}
}
catch (Exception ex)
{
}
#endregion
}
//微信设备信息
if (!session.TableExist<fl_wechat_device>())
{
session.CreateTable<fl_wechat_device>();
session.AddUnique("fl_wechat_device", "weixinhao");
}
else
{
#region mysql中varchar类型,text的类型
if (session.CurrentConnectionConfig.DbType == DbType.MySql)
{
try
{
PropertyInfo[] Propertys = typeof(fl_wechat_device).GetProperties();
foreach (var item in Propertys)
{
string _name = item.Name;
if (_name.ToLower() == "device_info".ToLower())
{
if (item.PropertyType.FullName == typeof(string).ToString())
session.ExcuteSQL("ALTER TABLE fl_wechat_device MODIFY COLUMN " + _name + " Text", new { });
}
}
}
catch (Exception ex)
{ }
}
#endregion
}
//用户信息表
if (!session.TableExist<fl_member_info>())
{
session.CreateTable<fl_member_info>();
session.AddUnique<fl_member_info>("robot_type", "username");
//session.AddIndex<fl_member_info>("inviter_id", "robot_type", "username");
//session.AddIndex<fl_member_info>("status", "robot_name");
session.AddIndex<fl_member_info>("robot_type", "username");
session.AddIndex<fl_member_info>("crt_time", "robot_name");
session.AddIndex<fl_member_info>("status");
session.AddIndex<fl_member_info>("inviter_id");
session.AddIndex<fl_member_info>("usernick");
}
else
{
//if (!session.IndexExist<fl_member_info>("inviter_id"))
//{
// session.AddIndex<fl_member_info>("inviter_id", "status", "robot_name");
//}
var flag1 = checkIndex(session, "fl_member_info", "inviter_id", "robot_type", "username");
var flag2 = checkIndex(session, "fl_member_info", "status", "robot_name");
var flag3 = checkIndex(session, "fl_member_info", "inviter_id", "status", "robot_name");
if (flag1 || flag2 || flag3)
{
session.AddIndex<fl_member_info>("robot_type", "username");
session.AddIndex<fl_member_info>("crt_time", "robot_name");
session.AddIndex<fl_member_info>("status");
session.AddIndex<fl_member_info>("inviter_id");
session.AddIndex<fl_member_info>("usernick");
}
if (!session.ColumnExist("fl_member_info", "ignore_group_update"))
{
session.AddColumn("fl_member_info", "ignore_group_update", "integer default 0");
}
if (!session.ColumnExist("fl_member_info", "chat_count"))
{
session.AddColumn("fl_member_info", "chat_count", "integer default 0");
session.AddColumn("fl_member_info", "blackout_time", "datetime default '2000-01-01 00:00:00'");
}
if (!session.ColumnExist("fl_member_info", "identity_card"))
{
session.AddColumn("fl_member_info", "identity_card", "varchar(255)");
}
if (!session.ColumnExist("fl_member_info", "identity_name"))
{
session.AddColumn("fl_member_info", "identity_name", "varchar(255)");
}
if (!session.ColumnExist("fl_member_info", "ban_exchange_time"))
{
session.AddColumn("fl_member_info", "ban_exchange_time", "datetime default '2000-01-01 00:00:00'");
}
if (!session.ColumnExist("fl_member_info", "private_ratio"))
{
session.AddColumn("fl_member_info", "private_ratio", "double default 0");
}
if (!session.ColumnExist("fl_member_info", "realnick"))
{
session.AddColumn("fl_member_info", "realnick", "varchar(255) default ''");
session.AddColumn("fl_member_info", "wechatid", "varchar(255) default ''");
}
if (!session.ColumnExist("fl_member_info", "check_cloud_black_time"))
{
session.AddColumn("fl_member_info", "check_cloud_black_time", "datetime default '2000-01-01 00:00:00'");
session.AddColumn("fl_member_info", "is_cloud_black", "boolean default 0");
}
if (!session.ColumnExist("fl_member_info", "bind_order"))
{
session.AddColumn("fl_member_info", "bind_order", "integer default 0");
var members = session.Find<fl_member_info>("select * from fl_member_info").Where(f => f.finish_order != 0).ToList();
for (int i = 0; i < members.Count; i++)
{
members[i].bind_order = members[i].finish_order;
}
var _num = (int)Math.Ceiling((decimal)members.Count / 500m);
for (int o = 1; o <= _num; o++)
{
var _list = members.Skip((o - 1) * 500).Take(500).ToList();
session.Updateable(_list.ToArray()).ExecuteCommand();
}
}
}
//云黑名单
if (!session.TableExist<fl_cloud_black>())
{
session.CreateTable<fl_cloud_black>();
session.AddUnique<fl_cloud_black>("memberid");
}
//用户其他信息记录表
if (!session.TableExist<fl_statistics_record>())
{
session.CreateTable<fl_statistics_record>();
session.AddIndex<fl_statistics_record>("uid");
session.AddUnique<fl_statistics_record>("uid");
}
else
{
try
{
var result = session.FindTable("select uid from fl_statistics_record group by uid having count(uid) > 1 order by uid");
if (result.Rows.Count != 0)
{
for (int i = 0; i < result.Rows.Count; i++)
{
var uid = result.Rows[i]["uid"].ToString();
var records = session.Find<fl_statistics_record>("uid = @uid", new { uid = uid });
fl_statistics_record _record = null;
foreach (var record in records)
{
if (_record == null)
_record = record;
else
{
if (_record.ex1 == 0)
_record.ex1 += record.ex1;
if (_record.ex2 == 0)
_record.ex2 += record.ex2;
_record.ex3 += record.ex3;
_record.ex4 += record.ex4;
_record.ex5 += record.ex5;
_record.ex6 += record.ex6;
_record.ex7 += record.ex7;
_record.ex8 += record.ex8;
_record.ex9 += record.ex9;
_record.ex10 += record.ex10;
_record.ex11 += record.ex11;
_record.ex12 += record.ex12;
_record.querynum += record.querynum;
session.Deleteable<fl_statistics_record>().In(record.id).ExecuteCommand();
}
}
if (_record != null)
session.Updateable(_record).ExecuteCommand();
}
}
if (!session.ExistUnique("fl_statistics_record", "uid"))
session.AddUnique<fl_statistics_record>("uid");
}
catch (Exception ex)
{ }
}
if (!session.TableExist<fl_member_level>())
{
session.CreateTable<fl_member_level>();
}
if (!session.TableExist<fl_alimama_tlj_create_record>())
{
session.CreateTable<fl_alimama_tlj_create_record>();
session.AddUnique<fl_alimama_tlj_create_record>("cpsname");
}
if (!session.TableExist<fl_alimama_tlj_get_record>())
{
session.CreateTable<fl_alimama_tlj_get_record>();
session.AddUnique<fl_alimama_tlj_get_record>("itemid");
session.AddIndex<fl_alimama_tlj_get_record>("itemid", "expiredate");
}
if (!session.TableExist<fl_plugin_info>())
{
session.CreateTable<fl_plugin_info>();
}
if (!session.TableExist<fl_robot_info>())
{
session.CreateTable<fl_robot_info>();
session.AddUnique<fl_robot_info>("name", "type");
}
else
{
if (!session.ColumnExist("fl_robot_info", "is_receives"))
{
session.AddColumn("fl_robot_info", "is_receives", "integer default 1");
}
if (!session.ColumnExist("fl_robot_info", "off_line_tip"))
{
session.AddColumn("fl_robot_info", "off_line_tip", "integer default 1");
}
if (!session.ColumnExist("fl_robot_info", "off_line_auto_login"))
{
session.AddColumn("fl_robot_info", "off_line_auto_login", "integer default 1");
}
}
if (session.TableExist("fl_member_private_config"))
{
session.DropTable("fl_member_private_config");
}
if (!session.TableExist<fl_weixin_password>())
{
session.CreateTable<fl_weixin_password>();
session.AddUnique<fl_weixin_password>("robot_id");
}
else
{
//这个字段没有什么用,最早之前不知道为什么要给fl_weixin_password继承base_model
if (!session.ColumnExist("fl_weixin_password", "db_status_time"))
{
session.AddColumn("fl_weixin_password", "db_status_time", "varchar(25)");
}
}
if (!session.TableExist<fl_cps_member>())
{
session.CreateTable<fl_cps_member>();
session.AddUnique<fl_cps_member>("username", "cpstype");
}
else
{
if (!session.ColumnExist("fl_cps_member", "abnormal_tip"))
{
session.AddColumn("fl_cps_member", "abnormal_tip", "integer default 1");
}
if (!session.ColumnExist("fl_cps_member", "is_download"))
{
session.AddColumn("fl_cps_member", "is_download", "integer default 1");
}
if (!session.ColumnExist("fl_cps_member", "is_valid"))
{
session.AddColumn("fl_cps_member", "is_valid", "boolean default 1");
}
}
try
{
session.UpdateColumnType("fl_cps_member", "cookies", "longText");
}
catch (Exception)
{ }
if (!session.TableExist<fl_point_hist>())
{
session.CreateTable<fl_point_hist>();
session.AddIndex<fl_point_hist>("crt_time", "type", "rid", "uid");
session.AddIndex<fl_point_hist>("uid", "type");
}
else
{
if (!session.ColumnExist("fl_point_hist", "after_point"))
{
session.AddColumn("fl_point_hist", "after_point", "double default 0");
session.AddColumn("fl_point_hist", "before_point", "double default 0");
}
if (!session.ColumnExist("fl_point_hist", "rid"))
{
session.AddColumn("fl_point_hist", "rid", "integer default 0");
}
//if (!session.IndexExist<fl_point_hist>("crt_time"))
//{
// session.AddIndex<fl_point_hist>("crt_time", "type", "rid", "uid");
//}
}
if (!session.TableExist<fl_create_info>())
{
session.CreateTable<fl_create_info>();
session.AddUnique<fl_create_info>("groupid", "chat_type");
}
if (!session.TableExist<fl_alimama_order_lastnum>())
{
session.CreateTable<fl_alimama_order_lastnum>();
session.AddUnique<fl_alimama_order_lastnum>("lastnumber", "userid");
session.AddIndex<fl_alimama_order_lastnum>("lastnumber");
}
if (!session.TableExist<fl_alimama_tlj_info>())
{
session.CreateTable<fl_alimama_tlj_info>();
session.AddUnique<fl_alimama_tlj_info>("username");
}
//添加淘宝比例
if (!session.TableExist<fl_ratio_info>())
{
session.CreateTable<fl_ratio_info>();
session.AddUnique<fl_ratio_info>("comm", "cps_type");
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 10.00, subsidy_num = 50.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 30.00, subsidy_num = 40.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 99999.00, subsidy_num = 30.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 10.00, subsidy_num = 50.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 30.00, subsidy_num = 40.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 99999.00, subsidy_num = 30.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 10.00, subsidy_num = 50.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 30.00, subsidy_num = 40.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 99999.00, subsidy_num = 30.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 10.00, subsidy_num = 50.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 30.00, subsidy_num = 40.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 99999.00, subsidy_num = 30.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 10.00, subsidy_num = 50.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 30.00, subsidy_num = 40.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 99999.00, subsidy_num = 30.00, subsidy_type = SubsidyType. }).ExecuteCommand();
}
else
{
try
{
var tmps = session.Queryable<fl_ratio_info>().Where(f => f.cps_type == CpsType.).ToList();
if (tmps == null || tmps.Count == 0)
{
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 10.00, subsidy_num = 50.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 30.00, subsidy_num = 40.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 99999.00, subsidy_num = 30.00, subsidy_type = SubsidyType. }).ExecuteCommand();
}
}
catch (Exception)
{ }
try
{
var tmps = session.Queryable<fl_ratio_info>().Where(f => f.cps_type == CpsType.).ToList();
if (tmps == null || tmps.Count == 0)
{
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 10.00, subsidy_num = 50.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 30.00, subsidy_num = 40.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_ratio_info>(new fl_ratio_info() { cps_type = CpsType., comm = 99999.00, subsidy_num = 30.00, subsidy_type = SubsidyType. }).ExecuteCommand();
}
}
catch (Exception)
{ }
}
if (!session.TableExist<fl_member_group>())
{
session.CreateTable<fl_member_group>();
session.AddUnique<fl_member_group>("name");
session.AddUnique<fl_member_group>("terms", "terms_ordersum");
session.Insertable<fl_member_group>(new fl_member_group() { name = "大众会员", terms = 0, terms_ordersum = 0, subsidy = 0.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_member_group>(new fl_member_group() { name = "黄金会员", terms = 20, terms_ordersum = 5, subsidy = 0.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_member_group>(new fl_member_group() { name = "铂金会员", terms = 100, terms_ordersum = 15, subsidy = 0.00, subsidy_type = SubsidyType. }).ExecuteCommand();
session.Insertable<fl_member_group>(new fl_member_group() { name = "钻石会员", terms = 500, terms_ordersum = 50, subsidy = 0.00, subsidy_type = SubsidyType. }).ExecuteCommand();
}
else
{
if (!session.ColumnExist("fl_member_group", "terms_ordersum"))
{
session.AddColumn("fl_member_group", "terms_ordersum", "integer default 0");
try
{
session.AddUnique<fl_member_group>("terms", "terms_ordersum");
if (session.CurrentConnectionConfig.DbType == DbType.Sqlite)
{
session.ExcuteSQL("drop INDEX fl_member_group_terms_", new { });
}
else if (session.CurrentConnectionConfig.DbType == DbType.MySql)
{
session.ExcuteSQL("ALTER TABLE fl_member_group DROP INDEX terms", new { });
}
}
catch (Exception ex)
{
}
}
}
if (!session.TableExist<fl_order_sleep>())
{
session.CreateTable<fl_order_sleep>();
session.AddUnique<fl_order_sleep>("money", "cps_type");
session.Insertable<fl_order_sleep>(new fl_order_sleep() { money = 30.00, sleep = 24, cps_type = CpsType. }).ExecuteCommand();
session.Insertable<fl_order_sleep>(new fl_order_sleep() { money = 999999.00, sleep = 48, cps_type = CpsType. }).ExecuteCommand();
session.Insertable<fl_order_sleep>(new fl_order_sleep() { money = 30.00, sleep = 24, cps_type = CpsType. }).ExecuteCommand();
session.Insertable<fl_order_sleep>(new fl_order_sleep() { money = 999999.00, sleep = 48, cps_type = CpsType. }).ExecuteCommand();
session.Insertable<fl_order_sleep>(new fl_order_sleep() { money = 30.00, sleep = 24, cps_type = CpsType. }).ExecuteCommand();
session.Insertable<fl_order_sleep>(new fl_order_sleep() { money = 999999.00, sleep = 48, cps_type = CpsType. }).ExecuteCommand();
session.Insertable<fl_order_sleep>(new fl_order_sleep() { money = 30.00, sleep = 24, cps_type = CpsType. }).ExecuteCommand();
session.Insertable<fl_order_sleep>(new fl_order_sleep() { money = 999999.00, sleep = 48, cps_type = CpsType. }).ExecuteCommand();
}
else
{
try
{
var tmps = session.Queryable<fl_order_sleep>().Where(f => f.cps_type == CpsType.).ToList();
if (tmps == null || tmps.Count == 0)
{
session.Insertable<fl_order_sleep>(new fl_order_sleep() { money = 30.00, sleep = 24, cps_type = CpsType. }).ExecuteCommand();
session.Insertable<fl_order_sleep>(new fl_order_sleep() { money = 999999.00, sleep = 48, cps_type = CpsType. }).ExecuteCommand();
}
}
catch (Exception)
{ }
}
if (!session.TableExist<fl_query_hist>())
{
session.CreateTable<fl_query_hist>();
session.AddIndex<fl_query_hist>("userid", "itemid", "adzoneid", "crt_time");
}
else
{
if (!session.ColumnExist("fl_query_hist", "adzoneid"))
{
session.AddColumn("fl_query_hist", "adzoneid", "varchar(255)");
}
if (!session.ColumnExist("fl_query_hist", "mallid"))
{
session.Deleteable<fl_query_hist>().Where(f => f.crt_time < DateTime.Now.AddMonths(-2)).ExecuteCommand();
session.AddColumn("fl_query_hist", "mallid", "varchar(30)");
}
//if (!session.IndexExist<fl_query_hist>("userid"))
//{
// session.AddIndex<fl_query_hist>("userid", "itemid", "adzoneid", "crt_time");
//}
}
if (!session.TableExist<fl_order_alimama>())
{
session.CreateTable<fl_order_alimama>();
session.AddUnique<fl_order_alimama>("trade_id", "trade_parent_id");
session.AddIndex<fl_order_alimama>("create_time", "db_status");
session.AddIndex<fl_order_alimama>("db_userid", "db_status");
session.AddIndex<fl_order_alimama>("create_time", "db_userid");
session.AddIndex<fl_order_alimama>("trade_parent_id");
session.AddIndex<fl_order_alimama>("paid_time", "db_status");
session.AddIndex<fl_order_alimama>("db_robotname", "db_robottype");
session.AddIndex<fl_order_alimama>("earning_time", "db_status");
//session.AddIndex<fl_order_alimama>("trade_parent_id", "db_userid", "adzone_id", "create_time");
//session.AddIndex<fl_order_alimama>("num_iid", "item_title", "db_cpsnick", "db_cpsname");
//session.AddIndex<fl_order_alimama>("db_status", "db_userid");
}
else
{
//if (!session.IndexExist<fl_order_alimama>("db_status"))
//{
// session.AddIndex<fl_order_alimama>("db_status", "db_userid");
//}
if (!session.IndexExist<fl_order_alimama>("db_status", "db_endtime"))
{
session.AddIndex<fl_order_alimama>("db_status", "db_endtime");
}
if (!session.IndexExist<fl_order_alimama>("db_status", "create_time"))
{
session.AddIndex<fl_order_alimama>("db_status", "create_time");
}
var flag1 = checkIndex(session, "fl_order_alimama", "db_status", "db_userid");
var flag2 = checkIndex(session, "fl_order_alimama", "item_title", "db_cpsnick", "db_cpsname");
var flag3 = checkIndex(session, "fl_order_alimama", "trade_parent_id", "db_userid", "adzone_id", "create_time");
var flag4 = checkIndex(session, "fl_order_alimama", "num_iid", "item_title", "db_cpsnick", "db_cpsname");
var flag5 = checkIndex(session, "fl_order_alimama", "db_status", "db_userid");
var flag6 = checkIndex(session, "fl_order_alimama", "db_userid", "adzone_id", "num_iid", "create_time");
if (flag1 || flag2 || flag3 || flag4 || flag5 || flag6)
{
session.AddIndex<fl_order_alimama>("create_time", "db_status");
session.AddIndex<fl_order_alimama>("db_userid", "db_status");
session.AddIndex<fl_order_alimama>("create_time", "db_userid");
session.AddIndex<fl_order_alimama>("trade_parent_id");
session.AddIndex<fl_order_alimama>("paid_time", "db_status");
session.AddIndex<fl_order_alimama>("db_robotname", "db_robottype");
session.AddIndex<fl_order_alimama>("earning_time", "db_status");
}
if (!session.ColumnExist("fl_order_alimama", "seller_id"))
{
session.AddColumn("fl_order_alimama", "seller_id", "varchar(30)");
}
if (!session.ColumnExist("fl_order_alimama", "paid_time"))
{
session.AddColumn("fl_order_alimama", "paid_time", "datetime");
}
if (!session.ColumnExist("fl_order_alimama", "deposit_price"))
{
session.AddColumn("fl_order_alimama", "deposit_price", "varchar(30)");
}
if (!session.ColumnExist("fl_order_alimama", "tb_deposit_time"))
{
session.AddColumn("fl_order_alimama", "tb_deposit_time", "varchar(25)");
}
if (!session.ColumnExist("fl_order_alimama", "db_status_time"))
{
session.AddColumn("fl_order_alimama", "db_status_time", "varchar(25)");
}
if (!session.ColumnExist("fl_order_alimama", "alimama_rate"))
{
session.AddColumn("fl_order_alimama", "alimama_rate", "double default 0");
}
if (!session.ColumnExist("fl_order_alimama", "alimama_share_fee"))
{
session.AddColumn("fl_order_alimama", "alimama_share_fee", "double default 0");
}
}
if (!session.TableExist<fl_order_pinduoduo>())
{
session.CreateTable<fl_order_pinduoduo>();
session.AddUnique<fl_order_pinduoduo>("order_sn");
//session.AddIndex<fl_order_pinduoduo>("order_sn", "db_userid", "db_cpsnick", "order_create_time");
//session.AddIndex<fl_order_pinduoduo>("db_cpsname", "p_id", "goods_name", "goods_id");
//session.AddIndex<fl_order_pinduoduo>("db_status", "db_userid");
session.AddIndex<fl_order_pinduoduo>("db_userid", "db_status");
session.AddIndex<fl_order_pinduoduo>("order_create_time", "db_status");
session.AddIndex<fl_order_pinduoduo>("order_create_time", "db_userid");
session.AddIndex<fl_order_pinduoduo>("db_status", "db_endtime");
session.AddIndex<fl_order_pinduoduo>("db_robotname", "db_robottype");
}
else
{
//if (!session.IndexExist<fl_order_pinduoduo>("db_status"))
//{
// session.AddIndex<fl_order_pinduoduo>("db_status", "db_userid");
//}
//if (!session.IndexExist<fl_order_pinduoduo>("db_userid"))
//{
// session.AddIndex<fl_order_pinduoduo>("db_userid", "db_cpsnick", "db_cpsname");
// session.AddIndex<fl_order_pinduoduo>("p_id", "goods_name", "goods_id", "order_create_time");
//}
var flag1 = checkIndex(session, "fl_order_pinduoduo", "order_sn", "db_userid", "db_cpsnick", "order_create_time");
var flag2 = checkIndex(session, "fl_order_pinduoduo", "db_cpsname", "p_id", "goods_name", "goods_id");
var flag3 = checkIndex(session, "fl_order_pinduoduo", "db_status", "db_userid");
var flag4 = checkIndex(session, "fl_order_pinduoduo", "db_userid", "db_cpsnick", "db_cpsname");
var flag5 = checkIndex(session, "fl_order_pinduoduo", "p_id", "goods_name", "goods_id", "order_create_time");
if (flag1 || flag2 || flag3 || flag4 || flag5)
{
session.AddIndex<fl_order_pinduoduo>("db_userid", "db_status");
session.AddIndex<fl_order_pinduoduo>("order_create_time", "db_status");
session.AddIndex<fl_order_pinduoduo>("order_create_time", "db_userid");
session.AddIndex<fl_order_pinduoduo>("db_status", "db_endtime");
session.AddIndex<fl_order_pinduoduo>("db_robotname", "db_robottype");
}
if (!session.ColumnExist("fl_order_pinduoduo", "mall_id"))
{
session.AddColumn("fl_order_pinduoduo", "mall_id", "varchar(30)");
}
if (!session.ColumnExist("fl_order_pinduoduo", "db_status_time"))
{
session.AddColumn("fl_order_pinduoduo", "db_status_time", "varchar(25)");
}
if (!session.ColumnExist("fl_order_pinduoduo", "price_compare_status"))
{
session.AddColumn("fl_order_pinduoduo", "price_compare_status", "integer");
}
}
if (!session.TableExist<fl_order_jingdong>())
{
session.CreateTable<fl_order_jingdong>();
session.AddUnique<fl_order_jingdong>("orderId", "skuId");
//session.AddIndex<fl_order_jingdong>("orderId", "db_userid", "db_cpsnick", "orderTime");
//session.AddIndex<fl_order_jingdong>("db_cpsname", "positionId", "skuId", "skuName");
session.AddIndex<fl_order_jingdong>("db_userid", "db_status");
session.AddIndex<fl_order_jingdong>("orderTime", "db_status");
session.AddIndex<fl_order_jingdong>("orderTime", "db_userid");
session.AddIndex<fl_order_jingdong>("db_status", "finishTime");
session.AddIndex<fl_order_jingdong>("db_robotname", "db_robottype");
}
else
{
//if (!session.IndexExist<fl_order_jingdong>("db_status"))
//{
// session.AddIndex<fl_order_jingdong>("db_status", "db_userid");
//}
//if (!session.IndexExist<fl_order_jingdong>("db_userid"))
//{
// session.AddIndex<fl_order_jingdong>("db_userid", "db_cpsnick", "db_cpsname");
// session.AddIndex<fl_order_jingdong>("positionId", "skuId", "skuName", "orderTime");
//}
var flag1 = checkIndex(session, "fl_order_jingdong", "orderId", "db_userid", "db_cpsnick", "orderTime");
var flag2 = checkIndex(session, "fl_order_jingdong", "db_cpsname", "positionId", "skuId", "skuName");
var flag3 = checkIndex(session, "fl_order_jingdong", "db_status", "db_userid");
var flag4 = checkIndex(session, "fl_order_jingdong", "db_userid", "db_cpsnick", "db_cpsname");
var flag5 = checkIndex(session, "fl_order_jingdong", "positionId", "skuId", "skuName", "orderTime");
if (flag1 || flag2 || flag3 || flag4 || flag5)
{
session.AddIndex<fl_order_jingdong>("db_userid", "db_status");
session.AddIndex<fl_order_jingdong>("orderTime", "db_status");
session.AddIndex<fl_order_jingdong>("orderTime", "db_userid");
session.AddIndex<fl_order_jingdong>("db_status", "finishTime");
session.AddIndex<fl_order_jingdong>("db_robotname", "db_robottype");
}
#region plus
if (!session.ColumnExist("fl_order_jingdong", "plus"))
{
session.AddColumn("fl_order_jingdong", "plus", "integer default 0");
}
if (!session.ColumnExist("fl_order_jingdong", "db_status_time"))
{
session.AddColumn("fl_order_jingdong", "db_status_time", "varchar(25)");
}
#endregion
#region mysql中int类型,long的类型
//获取公共属性
//if (session.CurrentConnectionConfig.DbType == DbType.MySql)
//{
// PropertyInfo[] Propertys = typeof(fl_order_jingdong).GetProperties();
// foreach (var item in Propertys)
// {
// string _name = item.Name;
// string _type = string.Empty;
// bool _primary = false;
// var _attribute = item.GetCustomAttributes().FirstOrDefault(f => f.GetType() == typeof(SugarColumn)) as SugarColumn;
// if (_attribute != null)
// { }
// if (item.Name.ToLower() == "id" || _primary)
// { }
// else if (!string.IsNullOrEmpty(_type))
// { }
// else
// {
// if (item.PropertyType.FullName == typeof(Int64).ToString())
// {
// session.ExcuteSQL("ALTER TABLE fl_order_jingdong MODIFY COLUMN " + _name + " bigint(11) DEFAULT 0", new { });
// }
// }
// }
//}
#endregion
#region ,, 退
//session.ExcuteSQL("update fl_order_jingdong set db_status = 1002 where db_status = 998");
#endregion
if (!session.ColumnExist("fl_order_jingdong", "refundcreatetime"))
{
session.AddColumn("fl_order_jingdong", "refundcreatetime", "datetime");
}
}
//000000
if (!session.TableExist<fl_order_weipinhui>())
{
session.CreateTable<fl_order_weipinhui>();
session.AddUnique<fl_order_weipinhui>("orderSn", "goodsId", "sizeId");
//session.AddUnique<fl_order_weipinhui>("orderSn");
session.AddIndex<fl_order_weipinhui>("db_userid", "db_status");
session.AddIndex<fl_order_weipinhui>("orderTime", "db_status");
session.AddIndex<fl_order_weipinhui>("orderTime", "db_userid");
session.AddIndex<fl_order_weipinhui>("db_status", "db_endtime");
session.AddIndex<fl_order_weipinhui>("db_robotname", "db_robottype");
}
else
{
//if (session.CurrentConnectionConfig.DbType == DbType.Sqlite || (session.CurrentConnectionConfig.DbType == DbType.MySql && session.ExistUnique("fl_order_weipinhui", "orderSn")))
//{
// if (session.DeleteUnique("fl_order_weipinhui", "orderSn"))
// {
// try
// {
// session.AddUnique<fl_order_weipinhui>("orderSn", "goodsId");
// }
// catch (Exception ex)
// { }
// }
//}
if (session.CurrentConnectionConfig.DbType == DbType.Sqlite || (session.CurrentConnectionConfig.DbType == DbType.MySql && session.ExistUnique("fl_order_weipinhui", "orderSn", "goodsId")))
{
if (session.DeleteUnique("fl_order_weipinhui", "orderSn", "goodsId"))
{
try
{
session.AddUnique<fl_order_weipinhui>("orderSn", "goodsId", "sizeId");
}
catch (Exception ex)
{ }
}
}
}
//000000
if (!session.TableExist<fl_order_douyin>())
{
session.CreateTable<fl_order_douyin>();
session.AddUnique<fl_order_douyin>("order_id", "product_id");
session.AddIndex<fl_order_douyin>("db_userid", "db_status");
session.AddIndex<fl_order_douyin>("pay_time", "db_status");
session.AddIndex<fl_order_douyin>("pay_time", "db_userid");
session.AddIndex<fl_order_douyin>("db_status", "db_endtime");
session.AddIndex<fl_order_douyin>("db_robotname", "db_robottype");
}
if (!session.TableExist<fl_bind_cache>())
{
session.CreateTable<fl_bind_cache>();
session.AddIndex<fl_bind_cache>("orderid");
}
//try
//{
// if (session.TableExist("fl_alimama_activity_pid"))
// session.DropTable("fl_alimama_activity_pid");
// session.DropTable("fl_alimama_pid_activity");
//}
//catch (Exception)
//{ }
bool first = false;
if (!session.TableExist<fl_dictionary_item>())
{
session.CreateTable<fl_dictionary_item>();
session.AddUnique<fl_dictionary_item>("dickey");
first = true;
}
if (!session.TableExist<fl_exchange_info>())
{
session.CreateTable<fl_exchange_info>();
session.AddIndex<fl_exchange_info>("uid", "state");
if (session.TableExist("fl_plugin_pointmanage_exchange_list"))
{
var queryable = session.Queryable("fl_plugin_pointmanage_exchange_list", "pel").AddJoinInfo("fl_robot_info", "r", "r.name = pel.robot_name").Select<fl_exchange_info>("r.id as rid,pel.*").ToList();
session.Insertable(queryable).ExecuteCommand();
}
}
else
{
if (!session.IndexExist<fl_exchange_info>("uid", "state"))
{
session.AddIndex<fl_exchange_info>("uid", "state");
}
if (!session.ColumnExist("fl_exchange_info", "groupid"))
{
session.AddColumn("fl_exchange_info", "groupid", "varchar(255)");
}
if (!session.ColumnExist("fl_exchange_info", "check_time"))
{
session.AddColumn("fl_exchange_info", "check_time", "datetime default '2000-01-01 00:00:00'");
}
}
// session.Commit();
return first;
}
catch (Exception ex)
{
throw ex;
}
return false;
}
/// <summary>
/// 重置定时器
/// </summary>
public static void ResetTimer()
{
//关闭以前的线程
TimerTask.Close<ClearGarbageTimer>();
TimerTask.Close<DownPinduoduoTimer>();
TimerTask.Close<DownAlimamaTimer>();
TimerTask.Close<DownJingdongTimer>();
TimerTask.Close<DownWeipinhuiTimer>();
TimerTask.Close<DownDouyinTimer>();
TimerTask.Close<Update_NoticeQueue>();
TimerTask.Close<Update_CpsStatus>();
//启动新的线程
TimerTask.NewTimer<Update_NoticeQueue>(1);//处理队列消息
TimerTask.NewTimer<Update_CpsStatus>(360);//更新联盟状态
TimerTask.NewTimer<ClearGarbageTimer>(Setting.SystemConfig.timer_clear_memory); //注册清理垃圾线程
TimerTask.NewTimer<DownPinduoduoTimer>(Setting.SystemConfig.time_down_pinduoduo); //下载拼多多订单线程
TimerTask.NewTimer<DownAlimamaTimer>(Setting.SystemConfig.timer_down_alimama); //下载阿里妈妈订单线程
TimerTask.NewTimer<DownJingdongTimer>(Setting.SystemConfig.time_down_jingdong); //下载京东订单线程
TimerTask.NewTimer<DownWeipinhuiTimer>(Setting.SystemConfig.time_down_weipinhui); //下载唯品会订单线程
TimerTask.NewTimer<DownDouyinTimer>(Setting.SystemConfig.time_down_douyin); //下载抖音订单线程
}
/// <summary>
/// 缓存
/// </summary>
public static CacheTool Cache { get; private set; }
private static object getsession_lock = new object();
public static SqlSugarClient GetSession(Api.Framework.Tools.ConnectionConfig config = null, bool iscache = true)
{
if (config == null) config = Setting.DbConfig;
DbType type = DbType.MySql;
if (config.DatabaseType == DatabaseType.SQLITE) type = DbType.Sqlite;
else if (config.DatabaseType == DatabaseType.MYSQL) type = DbType.MySql;
else return null;
SqlSugarClient session = new SqlSugarClient(new SqlSugar.ConnectionConfig()
{
MoreSettings = new ConnMoreSettings() { IsAutoRemoveDataCache = true },
ConnectionString = config.ConnectionString, //必填
DbType = type, //必填
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
return session;
}
/// <summary>
/// 发送信息
/// </summary>
/// <param name="message">消息内容</param>
/// <param name="robot">通过哪个机器人发送</param>
public static void SendAdminMessage(string message, fl_robot_info robot, string title = "系统消息")
{
//邮件通知管理员
if (!string.IsNullOrEmpty(Setting.SystemConfig.account_admin_email))
{
//邮箱通知
var emails = Setting.SystemConfig.account_admin_email.Split(',');
foreach (var item in emails)
{
SendAdminEmail(item, title, title + "<br>" + message, true);
}
}
}
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="toemail">收件人</param>
/// <param name="title">标题</param>
/// <param name="content">内容</param>
/// <param name="tryException">捕获</param>
/// <param name="begin">异步</param>//ApiClient.SendAdminEmail(ApiClient.Setting.SystemConfig.account_admin_email, "机器人即将到期通知", msg, true);
public static void SendAdminEmail(string toemail, string title, string content, bool tryException = false, bool begin = true)
{
try
{
var config = Setting.SystemConfig;
Util.SendEmail(config.SMTP_Host, config.SMTP_Port, config.SMTP_User, config.SMTP_Pass, config.SMTP_SSL == SwitchType. ? true : false, toemail, title, content, begin);
}
catch (Exception ex)
{
if (tryException) return;
else EventClient.OnEvent(null, "发送邮件:" + ex.Message);
}
}
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="toemail">收件人</param>
/// <param name="title">标题</param>
/// <param name="content">内容</param>
/// <param name="file"></param>
/// <param name="tryException">捕获</param>
/// <param name="begin">异步</param>//ApiClient.SendAdminEmail(ApiClient.Setting.SystemConfig.account_admin_email, "机器人即将到期通知", msg, true);
public static void SendAdminEmail(string toemail, string title, string content, string file, bool tryException = false, bool begin = true)
{
try
{
var config = Setting.SystemConfig;
Util.SendEmail(config.SMTP_Host, config.SMTP_Port, config.SMTP_User, config.SMTP_Pass, config.SMTP_SSL == SwitchType., toemail, title, content, begin, file);
}
catch (Exception ex)
{
if (tryException) return;
else EventClient.OnEvent(null, "发送邮件:" + ex.Message);
}
}
/// <summary>
/// 商户支付
/// </summary>
/// <param name="remark"></param>
/// <param name="describe"></param>
/// <param name="money"></param>
/// <returns>返回 连接为点击领取
/// 返回 "已转账"为自动转账
/// 返回 空为异常</returns>
[Obsolete("改方法已过时")]
public static string SendWechatPay(object remark, string describe, double money)
{
try
{
var pay = new WechatPay();
var result = string.Empty;
if (!string.IsNullOrEmpty(Setting.SystemConfig.pay_wechat_hostSign))
{
result = pay.Create(Setting.SystemConfig.pay_wechat_hostSign, remark, describe, money);
Console.WriteLine(result);
}
else
{
result = pay.Create(Setting.SystemConfig.pay_wechat_gzh_appid, Setting.SystemConfig.pay_wechat_sh_appid, Setting.SystemConfig.pay_wechat_gzh_appsecret, Setting.SystemConfig.pay_wechat_sh_appsecret, money, HttpHelper.ObjectToJson(remark), describe);
}
//if (string.IsNullOrEmpty(Setting.SystemConfig.pay_wechat_host)) throw new Exception("您没有填写服务器信息!");
if (!string.IsNullOrEmpty(result))
{
if (result == "操作超时")
{
EventClient.OnEvent(null, $"【{money}积分】商户连接:{result}");
result = string.Empty;
}
else if (result == "已转账")
{
//返回为空,获取商户异常
return result;
}
}
return result;
}
catch (Exception ex)
{
EventClient.OnEvent(null, ex.Message);
}
return string.Empty;
}
public static string SendWechatPay(object remark, string describe, double money, out bool ispaid)
{
ispaid = false;
try
{
var pay = new WechatPay();
var result = string.Empty;
if (!string.IsNullOrEmpty(Setting.SystemConfig.pay_wechat_hostSign))
{
result = pay.Create(Setting.SystemConfig.pay_wechat_hostSign, remark, describe, money, out ispaid);
Console.WriteLine(result);
}
else
{
result = pay.Create(Setting.SystemConfig.pay_wechat_gzh_appid, Setting.SystemConfig.pay_wechat_sh_appid, Setting.SystemConfig.pay_wechat_gzh_appsecret, Setting.SystemConfig.pay_wechat_sh_appsecret, money, HttpHelper.ObjectToJson(remark), describe);
}
//if (string.IsNullOrEmpty(Setting.SystemConfig.pay_wechat_host)) throw new Exception("您没有填写服务器信息!");
if (!string.IsNullOrEmpty(result))
{
if (result == "操作超时")
{
EventClient.OnEvent(null, $"【{money}积分】商户连接:{result}");
ispaid = false;
return string.Empty;
}
//else if (result == "已转账")
//{
// //返回为空,获取商户异常
// return result;
//}
}
return result;
}
catch (Exception ex)
{
EventClient.OnEvent(null, ex.Message);
}
return string.Empty;
}
/// <summary>
/// 发送钉钉消息
/// </summary>
/// <param name="message">消息内容 </param>
/// <param name="api">默认选择系统自带接口、也可以自定义</param>
//public static void SendDingdingMessage(string _message, string api = "")
//{
// if (!string.IsNullOrEmpty(api) && ApiClient.Setting.SystemConfig.notice_robotname != "请选择(钉钉/微信群机器人API名称")
// {
// SendNoticeMessage(ApiClient.Setting.SystemConfig.notice_robotname, _message);
// return;
// }
// var _api = string.IsNullOrEmpty(api) ? ApiClient.Setting.SystemConfig.notice_dingding_robotapi : api;
// if (!string.IsNullOrEmpty(_api)) SendNoticeMessage(new fl_noticeapi_info() { name = "旧接口钉钉API地址", api_location = _api, notice_apitype = NoticeApiType.企业钉钉机器人API }, _message);
//}
public static void SendNewDingdingMessage(string _message, string api = "", string secret = "")
{
if (!string.IsNullOrEmpty(api) && ApiClient.Setting.SystemConfig.notice_robotname != "请选择(钉钉/微信群机器人API名称")
{
SendNoticeMessage(_message);
return;
}
var _api = string.IsNullOrEmpty(api) ? ApiClient.Setting.SystemConfig.notice_dingding_robotapi : api;
var _api_token = string.IsNullOrEmpty(api) ? ApiClient.Setting.SystemConfig.notice_dingding_robotSecret : secret;
if (!string.IsNullOrEmpty(_api)) SendNoticeMessage(new fl_noticeapi_info() { name = "旧接口钉钉API地址", token = _api_token, api_location = _api, notice_apitype = NoticeApiType.API }, _message);
}
/// <summary>
/// 发送通知【钉钉/微信群机器人】消息
/// </summary>
/// <param name="name">名称,为空为系统设置</param>
/// <param name="message">消息内容</param>
public static void SendNoticeMessage(string message, string name = "")
{
if (string.IsNullOrWhiteSpace(name) || name == "请选择(钉钉/微信群机器人API名称")
name = ApiClient.Setting.SystemConfig.notice_robotname;
var session = ApiClient.GetSession();
var api = session.FindNoticeapiRobots().FirstOrDefault(f => f.name == name);
if (api != null) SendNoticeMessage(api, message);
}
public static void SendNoticeMessage(fl_noticeapi_info api_entity, string message, bool is_begin = true)
{
if (api_entity == null || api_entity.name == "请选择(钉钉/微信群机器人API名称") return;
var _info = api_entity;
var _message = message.Replace("\r\n", "\n"); ;
Exception exception = null;
var action = new Action(delegate
{
for (int i = 0; i < 10; i++)
{
try
{
var http = new HttpHelper();
var item = http.GetItem(_info.api_location);
item.Method = "post";
item.ContentType = "application/json;";//返回类型 可选项有默认值
switch (_info.notice_apitype)
{
case NoticeApiType.API:
{
if (!string.IsNullOrEmpty(_info.token))
{
long dingTimestamp = (DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0, 0).Ticks) / 10000;
string canonicalString = $"{dingTimestamp}\n{_info.token}";
string signature = Convert.ToBase64String(Sign(Encoding.UTF8.GetBytes(canonicalString), Encoding.UTF8.GetBytes(_info.token)));
item.URL = item.URL + $"&timestamp={dingTimestamp}&sign={signature}";
}
item.PostDataType = CsharpHttpHelper.Enum.PostDataType.Byte;
item.PostdataByte = Encoding.UTF8.GetBytes(HttpHelper.ObjectToJson(new { msgtype = "text", text = new { content = _message } }));
}
break;
case NoticeApiType.API:
{
item.PostDataType = CsharpHttpHelper.Enum.PostDataType.Byte;
item.PostdataByte = Encoding.UTF8.GetBytes(HttpHelper.ObjectToJson(new { msgtype = "text", text = new { content = _message } }));
}
break;
case NoticeApiType.API:
{
item.PostDataType = CsharpHttpHelper.Enum.PostDataType.Byte;
if (_info.api_location.Contains("bot/v2/hook"))
item.PostdataByte = Encoding.UTF8.GetBytes(HttpHelper.ObjectToJson(new { msg_type = "text", content = new { text = _message } }));
else
item.PostdataByte = Encoding.UTF8.GetBytes(HttpHelper.ObjectToJson(new { title = "", text = _message }));
}
break;
default: throw new Exception("无法识别的API类型!" + _info.notice_apitype.ToString());
}
var html = http.GetHtml(item).Html;
Console.WriteLine(html);
if (html.Contains("ok") || html.Contains("success"))
return;
throw new Exception(html);
}
catch (Exception ex)
{
if (ex.Message.Contains("sign not match"))
{
Thread.Sleep(370);
continue;
}
exception = ex;
EventClient.OnEvent(null, $"{_info.name}提醒失败:" + ex.Message);
}
}
});
if (is_begin) action.BeginInvoke(null, null);
else
{
action.Invoke();
//抛出异常信息
if (exception != null) throw exception;
}
}
private static byte[] Sign(byte[] key, byte[] data)
{
HMACSHA256 sha256 = new HMACSHA256(data);
return sha256.ComputeHash(key);
}
static ConcurrentDictionary<string, ConcurrentQueue<temp_send_data>> MessageQueue = new ConcurrentDictionary<string, ConcurrentQueue<temp_send_data>>();
/// <summary>
/// 发送消息2
/// </summary>
/// <param name="robot">机器人</param>
/// <param name="tousername">发送给谁</param>
/// <param name="message">发送的消息SendNewDingdingMessage</param>
/// <param name="groupid">发送的群(空位私聊)</param>
/// <param name="TempMsgID">QQ的临时会话ID</param>
/// <param name="token">临时会话的token</param>
/// <returns></returns>
//public static Task SendWQMessage(fl_robot_info robot, string tousername, string message, string groupid = "", uint TempMsgID = 0, byte[] token = null)
//{
// return SendMessage(new temp_send_data() { Groupid = groupid, Message = message, TouserName = tousername, Robot = robot, TempMsgID = TempMsgID, token = token });
//}
/// <summary>
/// 发送消息1
/// </summary>
/// <param name="robot">机器人</param>
/// <param name="tousername">发送给谁</param>
/// <param name="message"></param>
/// <param name="groupid"></param>
public static Task SendMessage(fl_robot_info robot, string tousername, string message, string groupid = "")
{
return SendMessage(new temp_send_data() { Groupid = groupid, Message = message, TouserName = tousername, Robot = robot });
}
public static Task SendMessage(fl_robot_info robot, string tousername, string message, bool isTemp)
{
return SendMessage(new temp_send_data() { IsTemp = isTemp, Message = message, TouserName = tousername, Robot = robot });
}
public static Task SendMessage(params temp_send_data[] data)
{
var _data = data;
return Task.Run(() =>
{
try
{
for (int i = 0; i < _data.Length; i++)
{
var item = _data[i];
if (i > 0) Thread.Sleep(650);
try
{
#region
var session = ApiClient.GetSession();
var robots = session.FindRobots();
if (null != robots.FirstOrDefault(f => f.is_receives == Enums.SwitchType. && item.Robot.name == f.name))
continue;
#endregion
var groupid = item.Groupid;
var tousername = item.TouserName;
var robot = item.Robot;
var message = item.Message.Replace("[积分名称]", Setting.SystemConfig.PointName).Replace("[机器人账号]", robot.name).Replace("[机器人昵称]", robot.nick).Trim();
if (message.Contains("[编号]"))
{
string id = string.Empty;
var member = session.FindSingle<fl_member_info>("select * from fl_member_info where username = @username", new { username = item.TouserName });
if (member != null)
id = member.id.ToString();
message = message.Replace("[编号]", id);
}
switch (item.Robot.type)
{
case ChatType.QQ:
{
var qBase = ChatClient.QQClients.FirstOrDefault(f => f.Key.ToString() == robot.name).Value;
if (qBase is QQClientImpl_QQPlus)
{
var tmp = (qBase as QQClientImpl_QQPlus);
var qq = tmp.QQClient;
if (qq != null && qq.User != null && qq.User.LoginStatus == LoginStatus.Login)
{
if (!string.IsNullOrWhiteSpace(tousername))
{
var member = session.FindBlacklistMemberInfos().FirstOrDefault(f => f.username == tousername);
if (member != null) break;
if (message.Contains("[昵称]"))
{
member = session.FindSingle<fl_member_info>("select * from fl_member_info where robot_type = @robot_type and username = @username", new { username = tousername, robot_type = ChatType.QQ });
if (member != null)
message = message.Replace("[账号]", tousername).Replace("[昵称]", member.usernick);
else
message = message.Replace("[账号]", tousername).Replace("[昵称]", string.Empty);
}
}
message = new VariateReplace().ReplaceUserVariate(message).Replace("[时间]", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
uint target = 1;
var isGroup = false;
uint toUsernaem = 0;
if (string.IsNullOrEmpty(groupid))
uint.TryParse(tousername, out target);
else
{
uint.TryParse(groupid, out target);
isGroup = true;
}
tmp.SendMessage(target, message, isGroup, item.IsTemp);
}
}
}
break;
case ChatType.:
case ChatType.:
{
if (!string.IsNullOrWhiteSpace(tousername))
{
var member = session.FindBlacklistMemberInfos().FirstOrDefault(f => f.username == tousername);
if (member != null) break;
if (message.Contains("[昵称]"))
{
member = session.FindSingle<fl_member_info>("select * from fl_member_info where robot_type = @robot_type and username = @username", new { username = tousername, robot_type = item.Robot.type });
message = message.Replace("[昵称]", member == null ? string.Empty : member.usernick);
}
message = message.Replace("[账号]", tousername);
}
message = new VariateReplace().ReplaceUserVariate(message).Replace("[时间]", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
var wx = ChatClient.WXClient.FirstOrDefault(f => f.Key == robot.name).Value;
if (wx != null && wx.Status == Chat.Framework.WXSdk.WxStatus.线)
{
message.Replace("[机器人微信]", wx.User.Username);
wx.SendMessage(string.IsNullOrWhiteSpace(groupid) ? tousername : groupid, message);
//EventClient.OnEvent(item, $"协议:{wx.WeixinHao} 给 {tousername} 发送 -> {message}");
}
else
{
//EventClient.OnEvent(item, $"pc {robot.name} 发送:{message}");
var client = ChatClient.PCRobotPool.GetSession(robot.name);
if (client != null)
{
WechatMsgType messageType = WechatMsgType.;
PCRobotCMD robotCMD = PCRobotCMD.sendTxt;
message.Replace("[机器人微信]", robot.name);
#region
var match = Regex.Match(message, @"\[图片\=([^\]]+)\]", RegexOptions.IgnoreCase);
if (match.Success)
{
var image = match.Groups[1].Value;
//if (!image.StartsWith("http"))
//{
// if (File.Exists(image))
// {
// var bitmap = Util.PercentImage(Util.ReadImageFile(image), 280);
// var _image = image + Path.GetExtension(image);//压缩图片的地址
// if (Util.YaSuo(bitmap, _image, 70))
// {
// image = Util.FileToBase64(_image);
// }
// }
//}
message = image;
messageType = WechatMsgType.;
robotCMD = PCRobotCMD.sendImg;
}
#endregion
#region
match = Regex.Match(message, @"\[视频\=([^\]]+)\]", RegexOptions.IgnoreCase);
if (match.Success)
{
//var video = Util.StrToHex(match.Groups[1].Value);
//if (video != null)
//{
// var video_json = Encoding.UTF8.GetString(video);
// var video_data = CsharpHttpHelper.HttpExtend.JsonToDictionary(video_json);
// if (video_data != null)
// {
// //(username, video_data["cdnurl"].ToString(), video_data["aeskey"].ToString(), CDNType.发送视频);
// }
//}
message = match.Groups[1].Value;
messageType = WechatMsgType.;
robotCMD = PCRobotCMD.sendFile;
}
#endregion
#region
match = Regex.Match(message, @"\[语音\=([^\]]+)\]", RegexOptions.IgnoreCase);
if (match.Success)
{
throw new Exception("PC协议不支持语音发送");
}
#endregion
if (string.IsNullOrWhiteSpace(message)) return;
var msg = new ServerWechatMsg()
{
Cmd = robotCMD,
RobotType = item.Robot.type == ChatType. ? RobotType. : RobotType.,
RobotUsername = robot.name,
RobotUsernick = string.Empty,
ToMessage = message,
ToMessageType = messageType,
ToUsername = string.IsNullOrWhiteSpace(groupid) ? tousername : groupid,
Key = Setting.ServerConfig.SocketPassword
};
//Console.WriteLine(groupid);
var json = HttpHelper.ObjectToJson(msg);
var text = PackTool.CompressString(json);
//AESCryption aes = new AESCryption();
//json = aes.AesEncrypt(json,Setting.ServerConfig.SocketPassword.Substring(0,16));
//Console.WriteLine(json);
var need_send = $"{msg.Cmd} {text}\r\n";
//var need_send_data = Encoding.UTF8.GetBytes(need_send);
client.TrySend(need_send);
}
}
}
break;
case ChatType.:
break;
case ChatType.:
break;
default:
break;
}
}
catch (Exception ex)
{
EventClient.OnEvent(item, $"发送通知消息失败:{item.Robot.name}->{item.TouserName}->{item.Message},{ex.Message} - {ex.StackTrace}");
}
}
}
catch (Exception)
{ }
});
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="robot_name">机器人账号</param>
/// <param name="robot_type">机器人类型</param>
/// <param name="tousername">发送给谁</param>
/// <param name="message">发送消息内容</param>
/// <param name="groupid">发送的群号</param>
public static void SendMessage(string robot_name, ChatType robot_type, string tousername, string message, string groupid = "")
{
var session = GetSession();
var robot = session.FindRobots().FirstOrDefault(f => f.name == robot_name && f.type == robot_type);
if (robot != null) SendMessage(robot, tousername, message, groupid);
}
/// <summary>
/// 缩短网址 - 根据配置的短网址类型
/// </summary>
/// <param name="url">目标URL</param>
/// <returns></returns>
public static Task<string> ShortURL(string url)
{
return ShortURL(url, Setting.SystemConfig.dwz_type);
}
/// <summary>
/// 缩短网址 - 自定义短网址类型
/// </summary>
/// <param name="url">目标网址</param>
/// <param name="type">缩短类型</param>
/// <returns></returns>
public static Task<string> ShortURL(string url, DwzType type)
{
return Task.Factory.StartNew<string>(() =>
{
var http = new HttpHelper();
int num = 0;
var html = string.Empty;
Next:
try
{
num++;
if (EventClient.ReplaceURL != null)
{
var temp = EventClient.ReplaceURL(0, url);
if (!string.IsNullOrEmpty(temp)) return temp;
}
switch (type)
{
#region xxx
//case DwzType.新浪短网址:
//{
// #region 老的新浪 xx
// //html = http.GetHtml("http://api.t.sina.com.cn/short_url/shorten.json?source=3271760578&url_long=" + HttpHelper.URLEncode(url)).Html;
// //if (!string.IsNullOrWhiteSpace(html) && html.ToLower().Contains("url_short"))
// //{
// // var array = CsharpHttpHelper.HttpHelper.JsonToObject<ArrayList>(html) as ArrayList;
// // if (array != null && array.Count > 0)
// // {
// // var dic = array[0] as Dictionary<string, object>;
// // return dic["url_short"].ToString().Replace("http://", "https://");
// // }
// //}
// //break;
// #endregion
// #region 新浪
// var _url = $"https://service.weibo.com/share/share.php?url={HttpHelper.URLEncode(url)}&title=%e4%b8%ad%e9%97%b4%e9%a1%b5";
// html = http.GetHtml(_url).Html;
// if (!string.IsNullOrWhiteSpace(html))
// {
// var reg = Regex.Match(html, @"href=""(?<短连接>https?://t.cn/(?:[^""]+?))""");
// if (reg.Success)
// {
// var shorturl = reg.Groups["短连接"].Value;
// return shorturl.Replace("http://", "https://");
// }
// }
// break;
// #endregion
//}
//case DwzType.新新浪短网址:
//{
// var _url = $"https://service.weibo.com/share/share.php?url={HttpHelper.URLEncode(url)}&title=%e4%b8%ad%e9%97%b4%e9%a1%b5";
// html = http.GetHtml(_url).Html;
// if (!string.IsNullOrWhiteSpace(html))
// {
// var reg = Regex.Match(html, @"href=""(?<短连接>https?://t.cn/(?:[^""]+?))""");
// if (reg.Success)
// {
// var shorturl = reg.Groups["短连接"].Value;
// return shorturl.Replace("http://", "https://").Replace("t.cn/", "sinaurl.cn/");
// }
// }
// break;
//}
//case DwzType.腾讯短网址:
//{
// var data = CsharpHttpHelper.HttpHelper.URLEncode(url);
// html = http.GetHtml($"http://sa.sogou.com/gettiny?url={data}").Html;
// if (!string.IsNullOrWhiteSpace(html) && html.ToLower().Contains("url.cn"))
// return html;
// break;
//}
//case DwzType.百度短网址://收费
//{
//if (!string.IsNullOrWhiteSpace(Setting.SystemConfig.DwzToken))
//{
// try
// {
// var data = HttpHelper.ObjectToJson(new { Url = url, TermOfValidity = "1-year" });
// var item = new HttpItem()
// {
// URL = "https://dwz.cn/admin/v2/create",
// Method = "post",
// Encoding = Encoding.UTF8,
// UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0",//用户的浏览器类型,版本,操作系统 可选项有默认值
// ContentType = "application/json;",//返回类型 可选项有默认值
// PostDataType = CsharpHttpHelper.Enum.PostDataType.Byte,
// PostdataByte = Encoding.UTF8.GetBytes(data),//HttpUtility.UrlEncode(data),
// Timeout = 5000,
// ReadWriteTimeout = 5000
// };
// item.Header.Add("token", Setting.SystemConfig.DwzToken);
// html = http.GetHtml(item).Html;
// if (!string.IsNullOrWhiteSpace(html))
// {
// //{"Code":0,"ShortUrl":"https://dwz.cn/kiJerp0h","LongUrl":"https://www.hifige.com/collection-album/yuanzhua","ErrMsg":""}
// var json = HttpExtend.JsonToDictionary(html);
// if (json != null && json.ContainsKey("Code"))
// {
// var code = json["Code"].ToString();
// if (code == "0" && json.ContainsKey("ShortUrl"))
// {
// var shortUrl = json["ShortUrl"].ToString();
// return shortUrl;
// }
// EventClient.OnEvent(null, $"百度短连接获取失败:{html}");
// }
// }
// }
// catch (Exception ex)
// {
// EventClient.OnEvent(null, "百度短连接生成失败:" + ex.Message);
// }
//}
//else
//{
// EventClient.OnEvent(null, $"转链失败百度短网址Token值为空【系统设置 => 6.百度短网址设置 中设置】");
//}
//return url;
//break;
//}
//case DwzType.UC浏览器短网址:
//{
// // var url = "http://www.qq.com";
// byte[] sign_password = new byte[38];
// sign_password[0] = 48;
// sign_password[1] = 0;
// sign_password[2] = 57;
// sign_password[3] = 0;
// sign_password[4] = 58;
// sign_password[5] = 0;
// sign_password[6] = 49;
// sign_password[7] = 0;
// sign_password[8] = 53;
// sign_password[9] = 0;
// sign_password[10] = 89;
// sign_password[11] = 0;
// sign_password[12] = 103;
// sign_password[13] = 0;
// sign_password[14] = 125;
// sign_password[15] = 0;
// sign_password[16] = 78;
// sign_password[17] = 0;
// sign_password[18] = 74;
// sign_password[19] = 0;
// sign_password[20] = 112;
// sign_password[21] = 0;
// sign_password[22] = 125;
// sign_password[23] = 0;
// sign_password[24] = 85;
// sign_password[25] = 0;
// sign_password[26] = 67;
// sign_password[27] = 0;
// sign_password[28] = 83;
// sign_password[29] = 0;
// sign_password[30] = 104;
// sign_password[31] = 0;
// sign_password[32] = 97;
// sign_password[33] = 0;
// sign_password[34] = 114;
// sign_password[35] = 0;
// sign_password[36] = 101;
// sign_password[37] = 0;
// var sign = HttpHelper.ToMD5(System.Text.Encoding.Unicode.GetString(sign_password) + url).ToUpper();
// var item = http.GetItem("http://t.uc.cn/short_url/shorten", "", $"app_key=UCShare&url_long={HttpHelper.URLEncode(url)}&sign={sign}");
// html = http.GetHtml(item).Html;
// var success_reg = System.Text.RegularExpressions.Regex.Match(html, @"""url_short"":""http://fxt.ucdesk.cn/(.*?)""");
// if (success_reg.Success) return "http://t.uc.cn/" + success_reg.Groups[1].Value;
//}
//break;
#endregion
case DwzType.://收费
{
if (!string.IsNullOrWhiteSpace(Setting.SystemConfig.DwzToken))
{
try
{
var data = HttpHelper.ObjectToJson(new { Url = url, TermOfValidity = "1-year" });
var item = new HttpItem()
{
URL = "https://dwz.cn/admin/v2/create",
//URL = "https://dwz.cn/api/v3/short-urls",
Method = "post",
Encoding = Encoding.UTF8,
UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0",//用户的浏览器类型,版本,操作系统 可选项有默认值
ContentType = "application/json;",//返回类型 可选项有默认值
PostDataType = CsharpHttpHelper.Enum.PostDataType.Byte,
PostdataByte = Encoding.UTF8.GetBytes(data),//HttpUtility.UrlEncode(data),
Timeout = 5000,
ReadWriteTimeout = 5000
};
item.Header.Add("token", Setting.SystemConfig.DwzToken);
html = http.GetHtml(item).Html;
if (!string.IsNullOrWhiteSpace(html))
{
//{"Code":0,"ShortUrl":"https://dwz.cn/kiJerp0h","LongUrl":"https://www.hifige.com/collection-album/yuanzhua","ErrMsg":""}
var json = HttpExtend.JsonToDictionary(html);
if (json != null && json.ContainsKey("Code"))
{
var code = json["Code"].ToString();
if (code == "0" && json.ContainsKey("ShortUrl"))
{
var shortUrl = json["ShortUrl"].ToString();
return shortUrl;
}
EventClient.OnEvent(null, $"百度短连接获取失败:{html}");
}
}
}
catch (Exception ex)
{
EventClient.OnEvent(null, "百度短连接生成失败:" + ex.Message);
}
}
else
{
EventClient.OnEvent(null, $"转链失败百度短网址Token值为空【系统设置 => 6.百度短网址设置 中设置】");
}
return url;
break;
}
case DwzType.UC浏览器短网址:
case DwzType.:
case DwzType.:
case DwzType.:
//case DwzType.百度短网址:
case DwzType.:
{
//for (int i = 0; i < 3; i++)
//{
// var xx = HttpHelper.URLEncode(url);
// var sign = HttpHelper.ToMD5("23658" + url + "pMr7E2oPjvXI5ME1tZ0etTcenA7xgCzh");
// var _url = $"https://url.api.52cmg.cn/generate?url={xx}&sign={sign}&appid=23658";
// html = http.GetHtml(_url).Html;
// if (!string.IsNullOrWhiteSpace(html))
// {
// if (html.Contains("ok"))
// {
// JObject json = JObject.Parse(html);
// if (!(bool)json["ok"]) return url;
// return json["url"].ToString();
// }
// }
// Thread.Sleep(10);
// Console.WriteLine("html = " + html);
// Console.WriteLine("url = " + url);
//}
HttpHelper helper = new HttpHelper();
HttpItem item = new HttpItem();//https://url.api.52cmg.cn/generate?url=http://www.baidu.com&sign=E086A45084D1B490C411DEBD71E9DA4A&appid=23658
//var ccTLD = "https://url.api.52cmg.cn/generate";
//if (!string.IsNullOrWhiteSpace(ccTLD))
// ccTLD = ApiClient.Setting.SystemConfig.URLDwz;
item.URL = "https://url.api.52cmg.cn/generate?url=" + System.Web.HttpUtility.UrlEncode(url) + $"&sign={GetSign(url, "23658")}&appid=23658";
//item.URL = $"{ccTLD}?url={System.Web.HttpUtility.UrlEncode(url)}&sign={GetSign(url, "23658")}&appid=23658";
for (int z = 0; z < 5; z++)
{
html = helper.GetHtml(item).Html;
if (html.Contains("\"ok\":true"))
{
Newtonsoft.Json.Linq.JObject j = Newtonsoft.Json.Linq.JObject.Parse(html);
var result = j["url"].ToString();
if (!string.IsNullOrWhiteSpace(ApiClient.Setting.SystemConfig.URLDwz))
{
var reg = Regex.Match(result, "id=([a-zA-Z0-9]+)");
if (reg.Success)
{
if (ApiClient.Setting.SystemConfig.URLDwz.Contains("[序号]"))
{
result = ApiClient.Setting.SystemConfig.URLDwz.Replace("[序号]", reg.Groups[1].Value);
}
else if (ApiClient.Setting.SystemConfig.URLDwz.EndsWith("/"))
{
result = ApiClient.Setting.SystemConfig.URLDwz + "?id=" + reg.Groups[1].Value;
}
else
{
result = ApiClient.Setting.SystemConfig.URLDwz + "/?id=" + reg.Groups[1].Value;
}
if (!result.StartsWith("http")) result = "http://" + result;
}
}
return result;
}
Thread.Sleep(10);
Console.WriteLine("html = " + html);
Console.WriteLine("url = " + url);
Console.WriteLine("item.URL = " + item.URL);
}
return url;
}
break;
case DwzType.:
{
for (int i = 0; i < 3; i++)
{
var data = CsharpHttpHelper.HttpHelper.URLEncode(url);
var date = DateTime.Today.AddMonths(6).ToString("yyyy-MM-dd");
html = http.GetHtml($"http://suo.im/api.htm?url={data}&key=5dba8ad5b1a9c71e1cd3a570@731360bd06f09592d5843dd6bed51c2f&expireDate={date}").Html;
if (!string.IsNullOrWhiteSpace(html) && !html.Contains("未能解析此远程名称") && html.ToLower().Contains("suo.im"))
return html;
Thread.Sleep(100);
}
break;
}
case DwzType.:
{
return KuaiZhanShort.GetShort(url);
}
break;
case DwzType.:
return url;
}
}
catch (Exception ex)
{
EventClient.OnEvent(null, $"短连接异常html => {html} - { ex.Message} - {ex.Source}");
}
if (num <= 3)
{
if (type == DwzType.) type = DwzType.;
else if (type == DwzType.) type = DwzType.;
else if (type == DwzType.) type = DwzType.;
else type = DwzType.;
goto Next;
}
return url;
});
}
#region
public static string GetSign(string url, string appid)
{
var appSecret = "pMr7E2oPjvXI5ME1tZ0etTcenA7xgCzh";
if (!string.IsNullOrEmpty(appSecret))
{
string md5 = MD5Encrypt32(appid + url + appSecret);
return md5;
}
return "";
}
/// <summary>
/// 32位MD5加密
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
public static string MD5Encrypt32(string password)
{
string passwordFormat = FormsAuthPasswordFormat.MD5.ToString();
return FormsAuthentication.HashPasswordForStoringInConfigFile(password, passwordFormat);
}
#endregion
/// <summary>
/// 生成二维码图片
/// </summary>
/// <param name="text">二维码内容</param>
/// <returns></returns>
private static Bitmap Generate3(string text)
{
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix bm = writer.encode(text, BarcodeFormat.QR_CODE, 200, 200);
BarcodeWriter barcodeWriter = new BarcodeWriter();
Bitmap map = barcodeWriter.Write(bm);
int[] rectangle = bm.getEnclosingRectangle();
Bitmap bmpimg = new Bitmap(rectangle[2], rectangle[3], PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(bmpimg))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(map, 0 - rectangle[0], 0 - rectangle[1]);
}
return bmpimg;
}
public enum QrImageType
{
A = 0,
B = 1,
C = 2,
}
/// <summary>
/// 合成二维码
/// </summary>
/// <param name="title">标题</param>
/// <param name="price">价格</param>
/// <param name="cprice">券价格</param>
/// <param name="nprice">券后价格</param>
/// <param name="image">图片地址</param>
/// <param name="link">生成二维码的链接</param>
/// <param name="type">使用的模板</param>
/// <param name="cps">联盟类型,自动填写内容</param>
/// <param name="content">底栏内容</param>
/// <param name="basePath">保存路径</param>
/// <returns></returns>
public static string GetQRImage(string title, string price, string cprice, string nprice, string image, string link, QrImageType type = QrImageType.B, CpsType cps = CpsType., string content = "", string basePath = "")
{
if (string.IsNullOrWhiteSpace(content))
{
switch (cps)
{
case CpsType.:
{
if (type == QrImageType.A)
content = " 长按识别二维码 > 复制淘口令 > 打开手机淘宝 > 下单购买";
else if (type == QrImageType.B)
content = " 长按识别二维码 >> 复制淘口令 >> 打开手机淘宝 >> 下单购买";
else if (type == QrImageType.C)
content = "";
}
break;
case CpsType.:
{
if (type == QrImageType.A)
content = " 长按二维码 >> 识别图中二维码 >> 下单购买";
else if (type == QrImageType.B)
content = " 长按二维码 >> 识别图中二维码 >> 下单购买";
else if (type == QrImageType.C)
content = "";
}
break;
case CpsType.:
{
if (type == QrImageType.A)
content = " 长按二维码 >> 识别图中二维码 >> 下单购买";
else if (type == QrImageType.B)
content = " 长按二维码 >> 识别图中二维码 >> 下单购买";
else if (type == QrImageType.C)
content = "";
}
break;
case CpsType.:
{
if (type == QrImageType.A)
content = " 长按二维码 >> 识别图中二维码 >> 下单购买";
else if (type == QrImageType.B)
content = " 长按二维码 >> 识别图中二维码 >> 下单购买";
else if (type == QrImageType.C)
content = "";
}
break;
}
}
int number = 0;
Next:
Bitmap img = null;
Image mainpic = null;
try
{
string imagePath = string.Empty;
try
{
mainpic = null;
imagePath = Util.MapFile(DateTime.Now.Ticks.ToString() + ".jpg", "Cache\\image");
if (!image.StartsWith("http")) image = "http:" + image;
mainpic = FileTools.DownloadImage(image, imagePath);
}
catch (Exception ex)
{
throw new Exception($"读取图片异常:图片路径 = {imagePath} .{ex.Message} - {ex.StackTrace}");
}
if (mainpic == null) throw new Exception($"下载图片失败图片url = {image}");
switch (type)
{
case QrImageType.A:
{
double rate = mainpic.Width / 800.00;
double height = mainpic.Height / rate;
img = new Bitmap(800, int.Parse((height + 424).ToString("0")));
using (Graphics graphics = Graphics.FromImage(img))
{
graphics.Clear(Color.White);
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.High;
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.DrawImage(mainpic, 0, 0, 800, int.Parse((height).ToString("0")));
graphics.DrawImage(Properties.Resources.foot, 0, int.Parse((height).ToString("0")), 800, 424);
graphics.DrawImage(Generate3(link), 510, int.Parse((height + 50).ToString("0")), 225, 220);
var font = new Font("微软雅黑", 20, System.Drawing.FontStyle.Regular);
RectangleF rec = new RectangleF(20, int.Parse((height + 50).ToString("0")), 450, 150);
Brush brush = new SolidBrush(Color.FromArgb(53, 53, 53));
graphics.DrawString(" " + title, font, brush, rec);
graphics.DrawString("¥", new Font("微软雅黑", 20, System.Drawing.FontStyle.Regular), new SolidBrush(Color.FromArgb(148, 148, 148)), 90, int.Parse((height + 204).ToString("0")));
graphics.DrawString(price, new Font("微软雅黑", 20, System.Drawing.FontStyle.Strikeout), new SolidBrush(Color.FromArgb(148, 148, 148)), 115, int.Parse((height + 204).ToString("0")));
graphics.DrawString(nprice, new Font("微软雅黑", 28, System.Drawing.FontStyle.Regular), new SolidBrush(Color.FromArgb(243, 119, 7)), 265, int.Parse((height + 247).ToString("0")));
graphics.DrawString(cprice.Split('.')[0] + "元", new Font("微软雅黑", 20, System.Drawing.FontStyle.Regular), new SolidBrush(Color.FromArgb(243, 119, 7)), 65, int.Parse((height + 255).ToString("0")));
RectangleF rec2 = new RectangleF(10, int.Parse((height + 337).ToString("0")), 780, 70);
Brush brush2 = new SolidBrush(Color.FromArgb(243, 119, 7));
graphics.DrawString(content, font, brush2, rec2);
}
}
break;
case QrImageType.B:
{
var foot = Properties.Resources.B;
var width = (int)foot.Width;
var height = (int)foot.Height;
img = new Bitmap(width, height);
using (Graphics graphics = Graphics.FromImage(img))
{
graphics.Clear(Color.White);
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.High;
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.DrawImage(foot, 0, 0, width, height);
graphics.DrawImage(mainpic, 0, 0, width, (int)(height * 0.56));
graphics.DrawImage(Generate3(link), 296, 1050, 165, 165);
RectangleF rec = new RectangleF(20, 760, 700, 150);
Brush brush = new SolidBrush(Color.FromArgb(53, 53, 53));
graphics.DrawString(" " + title, new Font("微软雅黑", 20, System.Drawing.FontStyle.Regular), brush, rec);
graphics.DrawString(nprice, new Font("微软雅黑", 25, System.Drawing.FontStyle.Regular), new SolidBrush(Color.FromArgb(178, 34, 34)), 45, 895);
graphics.DrawString(price, new Font("微软雅黑", 25, System.Drawing.FontStyle.Strikeout), new SolidBrush(Color.FromArgb(148, 148, 148)), 335, 895);
graphics.DrawString(cprice, new Font("微软雅黑", 28, System.Drawing.FontStyle.Regular), new SolidBrush(Color.FromArgb(70, 130, 180)), 595, 892);
RectangleF rec2 = new RectangleF(10, 1298, width - 40, 42);
Brush brush2 = new SolidBrush(Color.FromArgb(250, 250, 210));
graphics.DrawString(content, new Font("微软雅黑", 16, System.Drawing.FontStyle.Bold), brush2, rec2);
}
}
break;
case QrImageType.C:
{
var foot = Properties.Resources.C;
var width = foot.Width;
var height = foot.Height;
img = new Bitmap(width, height);
using (Graphics graphics = Graphics.FromImage(img))
{
graphics.Clear(Color.White);
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.High;
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.DrawImage(foot, 0, 0, width, height);//填充背景图片
//添加标题
RectangleF rec = new RectangleF(40, 17, 728, 110);
Brush brush = new SolidBrush(Color.FromArgb(53, 53, 53));
graphics.DrawString(title, new Font("微软雅黑", 30, System.Drawing.FontStyle.Regular), brush, rec);
graphics.DrawImage(mainpic, 45, 131, 413, 388);//填充商品图片
graphics.DrawImage(Generate3(link), 557, 277, 152, 152);
//graphics.DrawImage(Image.FromFile(@"D:\A.png"), 557, 277, 152, 152);
graphics.DrawString($"券后【{nprice}元】包邮秒杀", new Font("微软雅黑", 40, System.Drawing.FontStyle.Regular), new SolidBrush(Color.FromArgb(178, 34, 34)), 44, 565);
//graphics.DrawString(price, new Font("微软雅黑", 25, FontStyle.Strikeout), new SolidBrush(Color.FromArgb(148, 148, 148)), 335, 895);
graphics.DrawString($"减{cprice}元", new Font("微软雅黑", 28, System.Drawing.FontStyle.Regular), new SolidBrush(Color.FromArgb(70, 130, 180)), 600, 182);
RectangleF rec2 = new RectangleF(40, 667, 745, 122);
graphics.DrawString(content, new Font("微软雅黑", 18, System.Drawing.FontStyle.Bold), brush, rec2);
}
}
break;
}
string path = string.Empty;
if (img != null)
{
if (!string.IsNullOrEmpty(basePath))
path = Util.MapFile(DateTime.Now.Ticks.ToString() + ".jpg", basePath);
else path = Util.MapFile(DateTime.Now.Ticks.ToString() + ".jpg", "Cache\\image");
img.Save(path, ImageFormat.Jpeg);
}
return path;
}
catch (Exception ex)
{
number++;
if (number <= 3)
{
Thread.Sleep(300);
goto Next;
}
EventClient.OnEvent(null, $"合成二维码图片:{ex.Message} - {ex.StackTrace}");
return string.Empty;
}
finally
{
if (img != null) img.Dispose();
if (mainpic != null) mainpic.Dispose();
}
}
/// <summary>
/// 将方形图片变成雏形
/// </summary>
/// <param name="img">要转变的图片</param>
/// <param name="rec">大小和位置</param>
/// <param name="size"></param>
/// <returns></returns>
private static Image CutEllipse(Image img, Rectangle rec, Size size)
{
Bitmap bitmap = new Bitmap(size.Width, size.Height);
using (Graphics g = Graphics.FromImage(bitmap))
{
using (TextureBrush br = new TextureBrush(img, System.Drawing.Drawing2D.WrapMode.Clamp, rec))
{
br.ScaleTransform(bitmap.Width / (float)rec.Width, bitmap.Height / (float)rec.Height);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.FillEllipse(br, new Rectangle(Point.Empty, size));
}
}
return bitmap;
}
/// <summary>
/// 合成优惠券图(新版)
/// </summary>
/// <param name="image">优惠券底图</param>
/// <param name="shopname">店铺名称</param>
/// <param name="shopimage">店铺头像</param>
/// <param name="title">宝贝标题</param>
/// <param name="price">宝贝原价</param>
/// <param name="couponprice">优惠券金额</param>
/// <param name="itemimage">宝贝图片</param>
/// <param name="indate">优惠券有效期区间(2018.02.12 - 2018.03.12)</param>
/// <param name="sellcount">月销量</param>
/// <param name="basePath">图片保存路径</param>
/// <returns></returns>
public static string GetCouponImage2(string image, string shopname, Image shopimage, string title, string price, string couponprice, Image itemimage, string indate, string sellcount, string basePath = "")
{
int number = 0;
Image mainpic = null;
Image shoppic = null;
Next:
try
{
HttpHelper http = new HttpHelper();
if (image.StartsWith("http"))
mainpic = http.GetImage(http.GetItem(image));
else
mainpic = ReadImageFile(image);
//店铺头像
shoppic = CutEllipse(shopimage, new Rectangle(0, 0, 150, 150), new Size(150, 150));
var width = (int)mainpic.Width;
var height = (int)mainpic.Height;
string path = string.Empty;
using (Bitmap img = new Bitmap(width, height))
{
using (Graphics graphics = Graphics.FromImage(img))
{
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.DrawImage(mainpic, 0, 0, width, height);//将优惠券底图放置画板中
graphics.DrawImage(shoppic, (width - 135) / 2, 154, 135, 135);//画板中绘画店铺头像
#region
var couponTitleFont = new Font("微软雅黑", 26, System.Drawing.FontStyle.Regular);
var wid = graphics.MeasureString(shopname, couponTitleFont);
RectangleF rec = new RectangleF((width - wid.Width) / 2, 294, wid.Width, wid.Height);//优惠券标题
graphics.DrawString(shopname, couponTitleFont, new SolidBrush(Color.White), rec);
#endregion
#region
var couponFont = new Font("微软雅黑", 70, System.Drawing.FontStyle.Regular);//优惠券金额字体
var couponpriceWid = graphics.MeasureString(couponprice, couponFont);//优惠券金额字体大小
graphics.DrawString(couponprice, couponFont, new SolidBrush(Color.FromArgb(0xCD, 0x00, 0x00)), 210, 346);//画板中绘画优惠券金额
#endregion
#region
var couponIndateFont = new Font("微软雅黑", 19, System.Drawing.FontStyle.Regular);//优惠券有效期字体
graphics.DrawString(indate, couponIndateFont, new SolidBrush(Color.FromArgb(0xc0, 0xc0, 0xc0)), 108, 511);//画板中绘画优惠券有效期
#endregion
#region
//店铺头像
graphics.DrawImage(itemimage, 23, 607, 250, 268);//画板中绘画店铺头像
#endregion
#region
var priceFont = new Font("微软雅黑", 27, System.Drawing.FontStyle.Strikeout);
graphics.DrawString(price, priceFont, new SolidBrush(Color.Black), 385, 740);
#endregion
#region
var finalPriceFont = new Font("微软雅黑", 45, System.Drawing.FontStyle.Regular);
wid = graphics.MeasureString(price, finalPriceFont);
graphics.DrawString((decimal.Parse(price) - decimal.Parse(couponprice)).ToString(), finalPriceFont, new SolidBrush(Color.Red), 438, 774);
#endregion
#region
var titleFont = new Font("微软雅黑", 18, System.Drawing.FontStyle.Regular);
int num = 18;
int rows = (int)Math.Floor(((decimal)title.Length / (decimal)num));
for (int i = 1; i <= rows; i++)
{
var index = (num * i) + ((i - 1) * 2);
title = title.Insert(index, @"
");
}
graphics.DrawString(title, titleFont, new SolidBrush(Color.Black), 298, 595);
#endregion
#region
var sellcountFont = new Font("微软雅黑", 22, System.Drawing.FontStyle.Regular);//优惠券有效期字体
graphics.DrawString(sellcount + "笔成交", sellcountFont, new SolidBrush(Color.FromArgb(0xc0, 0xc0, 0xc0)), 563, 692);//画板中绘画优惠券有效期
#endregion
}
path = !string.IsNullOrEmpty(basePath) ? Util.MapFile(DateTime.Now.Ticks.ToString() + ".jpg", basePath) : Util.MapFile(DateTime.Now.Ticks.ToString() + ".jpg", "Cache\\image");
img.Save(path, ImageFormat.Jpeg);
}
return path;
}
catch (Exception ex)
{
number++;
if (number <= 3) goto Next;
throw ex;
}
}
/// <summary>
/// 合成优惠券图
/// </summary>
/// <param name="image">优惠券底图</param>
/// <param name="shopname">店铺名称</param>
/// <param name="shoppic">店铺头像</param>
/// <param name="couponprice">优惠券金额</param>
/// <param name="indate">优惠券有效期区间(2018.02.12 - 2018.03.12)</param>
/// <param name="basePath">图片保存路径</param>
/// <returns></returns>
public static string GetCouponImage(string image, string shopname, string shopimage, string couponprice, string indate, string basePath = "")
{
int number = 0;
Image mainpic = null;
Image shoppic = null;
Next:
try
{
HttpHelper http = new HttpHelper();
if (image.StartsWith("http"))
mainpic = http.GetImage(http.GetItem(image));
else
mainpic = ReadImageFile(image);
shoppic = http.GetImage(http.GetItem(shopimage));
var width = (int)mainpic.Width;
var height = (int)mainpic.Height;
string path = string.Empty;
using (Bitmap img = new Bitmap(width, height))
{
using (Graphics graphics = Graphics.FromImage(img))
{
graphics.Clear(Color.White);
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.High;
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.DrawImage(mainpic, 0, 0, width, height);//将优惠券底图放置画板中
//graphics.DrawImage(Properties.Resources.foot, 0, int.Parse((height).ToString("0")), 800, 424);
//graphics.DrawImage(Generate3(link), 510, int.Parse((height + 50).ToString("0")), 225, 220);
graphics.DrawImage(shoppic, 38, 417, 60, 60);//画板中绘画店铺头像
#region
var _shopname = shopname + "优惠券";
var couponTitleFont = new Font("微软雅黑", 20, System.Drawing.FontStyle.Regular);
var wid = graphics.MeasureString(_shopname, couponTitleFont);
RectangleF rec = new RectangleF((width - wid.Width) / 2, (91 - wid.Height) / 2, wid.Width, wid.Height);//优惠券标题
Brush brush = new SolidBrush(Color.FromArgb(53, 53, 53));
graphics.DrawString(_shopname, couponTitleFont, brush, rec);
#endregion
#region
var couponFont = new Font("微软雅黑", 28, System.Drawing.FontStyle.Bold);//优惠券金额字体
var couponpriceWid = graphics.MeasureString(couponprice, couponFont);//优惠券金额字体大小
graphics.DrawString(couponprice, couponFont, new SolidBrush(Color.FromArgb(255, 99, 71)), (width - couponpriceWid.Width) / 2, 197);//画板中绘画优惠券金额
#endregion
#region
indate = "使用期限 " + indate;
var couponIndateFont = new Font("微软雅黑", 15, System.Drawing.FontStyle.Regular);//优惠券有效期字体
var couponindateWid = graphics.MeasureString(indate, couponIndateFont);//优惠券有效期字体大小
graphics.DrawString(indate, couponIndateFont, new SolidBrush(Color.FromArgb(169, 169, 169)), (width - couponindateWid.Width) / 2, 115);//画板中绘画优惠券有效期
#endregion
#region
var shopNameFont = new Font("微软雅黑", 20, System.Drawing.FontStyle.Regular);
wid = graphics.MeasureString(shopname, shopNameFont);
//RectangleF rec = new RectangleF((width - wid.Width) / 2, 50, 50, wid.Height);//优惠券标题
graphics.DrawString(shopname, shopNameFont, new SolidBrush(Color.Black), 103, 402 + (90 - wid.Height) / 2);
#endregion
}
if (!string.IsNullOrEmpty(basePath))
path = Util.MapFile(DateTime.Now.Ticks.ToString() + ".jpg", basePath);
else path = Util.MapFile(DateTime.Now.Ticks.ToString() + ".jpg", "Cache\\image");
img.Save(path, ImageFormat.Jpeg);
}
return path;
}
catch (Exception ex)
{
number++;
if (number <= 3) goto Next;
throw ex;
}
}
/// <summary>
/// 通过FileStream 来打开文件这样就可以实现不锁定Image文件到时可以让多用户同时访问Image文件
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private static Bitmap ReadImageFile(string path)
{
FileStream fs = File.OpenRead(path); //OpenRead
int filelength = 0;
filelength = (int)fs.Length; //获得文件长度
Byte[] image = new Byte[filelength]; //建立一个字节数组
fs.Read(image, 0, filelength); //按字节流读取
Image result = Image.FromStream(fs);
fs.Close();
Bitmap bit = new Bitmap(result);
return bit;
}
}
}