using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text.RegularExpressions;
using Library;
using System.IO;
using System.Web;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using MySystem.Service.Main;
namespace MySystem
{
public class PublicFunction
{
#region 中译英
public string TranslateZHToEn(string Source)
{
string result = function.GetWebRequest("http://fanyi.youdao.com/translate?&doctype=json&type=ZH_CN2EN&i=" + Source);
//{"type":"ZH_CN2EN","errorCode":0,"elapsedTime":2,"translateResult":[[{"src":"大事件","tgt":"The big event"}]]}
Match match = Regex.Match(result, "\"tgt\":\".*?\"");
if (match.Success)
{
return match.Value.Replace("\"tgt\":", "").Trim('"');
}
return "";
}
#endregion
#region 解析编辑器里的视频代码
public string CheckMediaFromHtml(string content)
{
if (string.IsNullOrEmpty(content))
{
return "";
}
string result = content;
MatchCollection mc = Regex.Matches(content, "");
foreach (Match submc in mc)
{
string info = submc.Value;
Match match = Regex.Match(info, "src=\".*?\"");
if (match.Success)
{
string path = match.Value;
path = path.Replace("src=\"", "");
path = path.TrimEnd(new char[] { '"' });
string html = "";
string width = "600";
string height = "300";
Match width_match = Regex.Match(info, "width=\".*?\"");
if (width_match.Success)
{
width = width_match.Value.Replace("width=", "").Trim('"');
}
Match height_match = Regex.Match(info, "height=\".*?\"");
if (height_match.Success)
{
height = height_match.Value.Replace("height=", "").Trim('"');
}
if (path.EndsWith(".mp4"))
{
if (string.IsNullOrEmpty(html))
{
html = "";
}
}
else if (path.EndsWith(".mp3"))
{
html = "";
}
result = result.Replace(info, html);
}
}
return result;
}
#endregion
#region 对象转Json字符串
public static string ObjectToJsonString(object obj)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
}
#endregion
#region Json字符串转对象
public static T DeserializeJSON(string json)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject(json);
}
#endregion
#region 删除文件
public static bool DeleteFile(string VirtualPath)
{
string FilePath = function.getPath(VirtualPath);
if (System.IO.File.Exists(FilePath))
{
System.IO.File.Delete(FilePath);
return true;
}
return false;
}
#endregion
#region 两点距离
public static double GetDistanceNumber(string start, string end)
{
if (!string.IsNullOrEmpty(start) && !string.IsNullOrEmpty(end))
{
string[] startpos = start.Split(',');
string[] endpos = end.Split(',');
double lng1 = double.Parse(startpos[0]);
double lat1 = double.Parse(startpos[1]);
double lng2 = double.Parse(endpos[0]);
double lat2 = double.Parse(endpos[1]);
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double a = radLat1 - radLat2;
double b = rad(lng1) - rad(lng2);
double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
s = s * EARTH_RADIUS;
s = Math.Round(s * 10000) / 10000;
return s;
}
return 10000000;
}
private static double rad(double d)
{
return d * Math.PI / 180.0;
}
private static double EARTH_RADIUS = 6378.137;
#endregion
#region 获取OSS开关
public string GetOssStatus()
{
return "-oss";
}
#endregion
#region 通过表名、文本、值获得字典数据
public Dictionary GetDictionaryByTableName(string tableEnName, string Text, string Value)
{
Text = Text.Split('_')[0];
Value = Value.Split('_')[0];
Dictionary dic = new Dictionary();
DataTable dt = dbconn.dtable("select " + Text + "," + Value + " from " + tableEnName + " order by Sort desc,Id asc");
foreach (DataRow dr in dt.Rows)
{
dic.Add(dr[1].ToString(), dr[0].ToString());
}
return dic;
}
#endregion
#region 接口通用DES解密
public static string DesDecrypt(string content)
{
content = HttpUtility.UrlDecode(content);
return dbconn.DesDecrypt(content, "*ga34|^7");
}
#endregion
#region 获取jwt的token
public static string AppToken(string username)
{
string test = function.get_Random(10);
var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtConfig.JwtSecret)), SecurityAlgorithms.HmacSha256);
var claims = new Claim[] {
new Claim(JwtRegisteredClaimNames.Iss, JwtConfig.JwtIss),
new Claim(JwtRegisteredClaimNames.Aud, test),
new Claim("Guid", Guid.NewGuid().ToString("D")),
new Claim(ClaimTypes.Role, "system"),
new Claim(ClaimTypes.Role, "admin"),
};
SecurityToken securityToken = new JwtSecurityToken(
signingCredentials: securityKey,
expires: DateTime.Now.AddDays(10),//过期时间
claims: claims,
audience: test,
issuer: username
);
RedisDbconn.Instance.Set("utoken:" + username, test);
RedisDbconn.Instance.SetExpire("utoken:" + username, 3600 * 24 * 10);
//生成jwt令牌
return new JwtSecurityTokenHandler().WriteToken(securityToken);
}
#endregion
#region 统计机具绑定数据
///
/// 统计机具绑定数据
///
/// 创客Id
/// 品牌Id
/// 数量
public static void StatUserMachineData(int UserId, int BrandId, int Count)
{
string IdBrand = UserId + "_" + BrandId;
var MachineData = UserMachineDataService.Query(IdBrand);
if (MachineData == null)
{
Dictionary machineData = new Dictionary();
machineData.Add("IdBrand", IdBrand);
UserMachineDataService.Add(machineData);
}
if (Count < 0)
{
Dictionary machineData = new Dictionary();
MachineData.TotalMachineCount -= Math.Abs(Count);
MachineData.UnBindCount -= Math.Abs(Count);
machineData.Add("TotalMachineCount", MachineData.TotalMachineCount);
machineData.Add("UnBindCount", MachineData.UnBindCount);
UserMachineDataService.Edit(machineData, "and IdBrand='" + IdBrand + "'");
}
else
{
Dictionary machineData = new Dictionary();
MachineData.TotalMachineCount += Count;
MachineData.UnBindCount += Count;
machineData.Add("TotalMachineCount", MachineData.TotalMachineCount);
machineData.Add("UnBindCount", MachineData.UnBindCount);
UserMachineDataService.Edit(machineData, "and IdBrand='" + IdBrand + "'");
}
}
#endregion
}
}