代码上传
This commit is contained in:
1 parent
4150cd1c02
commit
c324c71fe9
42 files changed
+3534
No files matched your search
@@ -0,0 +1,218 @@
|
||||
using FileProcessClient.domain;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace edu.huvtc.utils
|
||||
{
|
||||
internal class CommonUtils
|
||||
{
|
||||
[DllImport("kernel32")]
|
||||
private static extern long WritePrivateProfileString(string name, string key, string val,
|
||||
string filePath);
|
||||
[DllImport("kernel32")]
|
||||
private static extern int GetPrivateProfileString(string section, string key, string def,
|
||||
StringBuilder retVal, int size,
|
||||
string filePath);
|
||||
|
||||
private const int AesBlockByteSize = 128 / 8;
|
||||
|
||||
private const int PasswordSaltByteSize = 128 / 8;
|
||||
|
||||
private const int PasswordByteSize = 256 / 8;
|
||||
|
||||
private const int PasswordIterationCount = 100_000;
|
||||
|
||||
private static readonly Encoding StringEncoding = Encoding.UTF8;
|
||||
|
||||
private static readonly RandomNumberGenerator Random = RandomNumberGenerator.Create();
|
||||
|
||||
private static String password = "from huvtc passwords 123412;,[p;[; 172634812";
|
||||
|
||||
private static string INIPath = Convert.ToString(System.AppDomain.CurrentDomain.BaseDirectory) + "Config.ini";
|
||||
|
||||
private static string Token = "";
|
||||
|
||||
private static string serverUrl = "";
|
||||
|
||||
private static User user;
|
||||
|
||||
public static User getUser()
|
||||
{
|
||||
return user;
|
||||
}
|
||||
|
||||
public static void setUser(User data)
|
||||
{
|
||||
user = data;
|
||||
}
|
||||
|
||||
|
||||
public static void setToken(string token)
|
||||
{
|
||||
writeToIni("security", "token", token);
|
||||
Token = token;
|
||||
}
|
||||
|
||||
public static string getToken()
|
||||
{
|
||||
if (Token == null || Token == "")
|
||||
{
|
||||
Token = readFromFile("security", "token");
|
||||
}
|
||||
return Token;
|
||||
}
|
||||
|
||||
public static void writeToIni(string name, string key, string value)
|
||||
{
|
||||
WritePrivateProfileString(name, key, value, INIPath);
|
||||
}
|
||||
|
||||
public static string readFromFile(string name, string key)
|
||||
{
|
||||
StringBuilder builder = new StringBuilder(255);
|
||||
int ini = GetPrivateProfileString(name, key, "", builder, 255, INIPath);
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
|
||||
public static byte[] EncryptString(string toEncrypt)
|
||||
{
|
||||
using (var aes = Aes.Create())
|
||||
{
|
||||
var keySalt = GenerateRandomBytes(PasswordSaltByteSize);
|
||||
var key = GetKey(keySalt);
|
||||
var iv = GenerateRandomBytes(AesBlockByteSize);
|
||||
|
||||
using (var encryptor = aes.CreateEncryptor(key, iv))
|
||||
{
|
||||
var plainText = StringEncoding.GetBytes(toEncrypt);
|
||||
var cipherText = encryptor
|
||||
.TransformFinalBlock(plainText, 0, plainText.Length);
|
||||
|
||||
var result = MergeArrays(keySalt, iv, cipherText);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static string DecryptToString(byte[] encryptedData)
|
||||
{
|
||||
using (var aes = Aes.Create())
|
||||
{
|
||||
var keySalt = encryptedData.Take(PasswordSaltByteSize).ToArray();
|
||||
var key = GetKey(keySalt);
|
||||
var iv = encryptedData
|
||||
.Skip(PasswordSaltByteSize).Take(AesBlockByteSize).ToArray();
|
||||
var cipherText = encryptedData
|
||||
.Skip(PasswordSaltByteSize + AesBlockByteSize).ToArray();
|
||||
|
||||
using (var encryptor = aes.CreateDecryptor(key, iv))
|
||||
{
|
||||
var decryptedBytes = encryptor
|
||||
.TransformFinalBlock(cipherText, 0, cipherText.Length);
|
||||
return StringEncoding.GetString(decryptedBytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] GetKey(byte[] passwordSalt)
|
||||
{
|
||||
var keyBytes = StringEncoding.GetBytes(password);
|
||||
|
||||
using (var derivator = new Rfc2898DeriveBytes(
|
||||
keyBytes, passwordSalt,
|
||||
PasswordIterationCount, HashAlgorithmName.SHA256))
|
||||
{
|
||||
return derivator.GetBytes(PasswordByteSize);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] GenerateRandomBytes(int numberOfBytes)
|
||||
{
|
||||
var randomBytes = new byte[numberOfBytes];
|
||||
Random.GetBytes(randomBytes);
|
||||
return randomBytes;
|
||||
}
|
||||
|
||||
private static byte[] MergeArrays(params byte[][] arrays)
|
||||
{
|
||||
var merged = new byte[arrays.Sum(a => a.Length)];
|
||||
var mergeIndex = 0;
|
||||
for (int i = 0; i < arrays.GetLength(0); i++)
|
||||
{
|
||||
arrays[i].CopyTo(merged, mergeIndex);
|
||||
mergeIndex += arrays[i].Length;
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
public static string getServerUrl()
|
||||
{
|
||||
if (serverUrl == null || serverUrl.Length == 0)
|
||||
{
|
||||
serverUrl = readFromFile("common", "server_url");
|
||||
}
|
||||
return serverUrl;
|
||||
}
|
||||
|
||||
public static string getTokenFormIni()
|
||||
{
|
||||
return readFromFile("security", "token");
|
||||
}
|
||||
|
||||
public static void savePassword(string username, string password)
|
||||
{
|
||||
username = Convert.ToBase64String(CommonUtils.EncryptString(username));
|
||||
|
||||
password = Convert.ToBase64String(CommonUtils.EncryptString(password));
|
||||
|
||||
writeToIni("userData", "userName", username);
|
||||
|
||||
writeToIni("userData", "password", password);
|
||||
}
|
||||
|
||||
public static string getApiUrl(string name)
|
||||
{
|
||||
return readFromFile("ApiUrls", name);
|
||||
|
||||
}
|
||||
|
||||
public static string getFtpServer()
|
||||
{
|
||||
return readFromFile("ftp_server", "server_ip");
|
||||
}
|
||||
|
||||
public static string getFtpUsr()
|
||||
{
|
||||
return getDecryptValue("ftp_server", "ftp_user");
|
||||
}
|
||||
|
||||
public static string getFtpPassword()
|
||||
{
|
||||
return getDecryptValue("ftp_server", "ftp_password");
|
||||
|
||||
}
|
||||
|
||||
private static string getDecryptValue(string name, string item)
|
||||
{
|
||||
string str = readFromFile(name, item);
|
||||
if (str == null)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
else
|
||||
{
|
||||
return DecryptToString(Convert.FromBase64String(str));
|
||||
}
|
||||
}
|
||||
|
||||
public static int getFtpServerPort()
|
||||
{
|
||||
return int.Parse(readFromFile("ftp_server", "server_port"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
using edu.huvtc.utils;
|
||||
using FileProcessClient.domain;
|
||||
using FluentFTP;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace FileProcessClient.utils
|
||||
{
|
||||
internal class FileUploadUtils
|
||||
{
|
||||
public static async Task UploadFileAsync(string localPath, string remoteFilePath, Action<int> callback)
|
||||
{
|
||||
var token = new CancellationToken();
|
||||
using (var conn = new AsyncFtpClient(CommonUtils.getFtpServer(), CommonUtils.getFtpUsr(), CommonUtils.getFtpPassword(), CommonUtils.getFtpServerPort(), config: new FtpConfig
|
||||
{
|
||||
DataConnectionType = FtpDataConnectionType.PORT
|
||||
}))
|
||||
{
|
||||
try
|
||||
{
|
||||
await conn.Connect(token);
|
||||
Progress<FtpProgress> progress = new Progress<FtpProgress>(p =>
|
||||
{
|
||||
callback((int)(p.Progress));
|
||||
//Trace.WriteLine(p.Progress);
|
||||
});
|
||||
await conn.UploadFile(localPath, remoteFilePath, FtpRemoteExists.Overwrite, false, FtpVerify.None, progress, token);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
callback(-1);
|
||||
//Trace.WriteLine(ex.ToString());
|
||||
}
|
||||
finally
|
||||
{
|
||||
await conn.Disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static async Task<bool> UploadFilesAsync(List<MediaFileItem> list, string remoteRootPath, Action<int, int> callback)
|
||||
{
|
||||
var token = new CancellationToken();
|
||||
using (var conn = new AsyncFtpClient(CommonUtils.getFtpServer(), CommonUtils.getFtpUsr(), CommonUtils.getFtpPassword(), CommonUtils.getFtpServerPort(), config: new FtpConfig
|
||||
{
|
||||
DataConnectionType = FtpDataConnectionType.PASV,
|
||||
ConnectTimeout = 60000,
|
||||
ReadTimeout = 60000
|
||||
}))
|
||||
{
|
||||
int index = 0;
|
||||
try
|
||||
{
|
||||
await conn.Connect(token);
|
||||
|
||||
//conn.AutoDetect(FtpDataConnectionType.PORT);
|
||||
Progress<FtpProgress> progress = new Progress<FtpProgress>(p =>
|
||||
{
|
||||
//Trace.WriteLine(p.Progress);
|
||||
callback(index, (int)(p.Progress));
|
||||
|
||||
});
|
||||
|
||||
bool pathExits = await conn.DirectoryExists(remoteRootPath + "/json", token);
|
||||
if (!pathExits)
|
||||
{
|
||||
await conn.CreateDirectory(remoteRootPath + "/json", true, token);
|
||||
}
|
||||
|
||||
pathExits = await conn.DirectoryExists(remoteRootPath + "/media", token);
|
||||
if (!pathExits)
|
||||
{
|
||||
await conn.CreateDirectory(remoteRootPath + "/media", true, token);
|
||||
}
|
||||
|
||||
foreach (MediaFileItem file in list)
|
||||
{
|
||||
//Trace.WriteLine(file.fileName);
|
||||
//Trace.WriteLine(file.urlPath);
|
||||
await conn.UploadFile(file.fileName, file.urlPath, FtpRemoteExists.Overwrite, false, FtpVerify.None, progress, token);
|
||||
index++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
callback(index, -1);
|
||||
Trace.WriteLine(ex.ToString());
|
||||
//return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
await conn.Disconnect();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<bool> UploadFilesAsync(List<string> localFiles, string remoteRootPath, Action<int, int> callback)
|
||||
{
|
||||
var token = new CancellationToken();
|
||||
using (var conn = new AsyncFtpClient(CommonUtils.getFtpServer(), CommonUtils.getFtpUsr(), CommonUtils.getFtpPassword(), CommonUtils.getFtpServerPort(), config: new FtpConfig
|
||||
{
|
||||
DataConnectionType = FtpDataConnectionType.PORT
|
||||
}))
|
||||
{
|
||||
int index = 0;
|
||||
try
|
||||
{
|
||||
await conn.Connect(token);
|
||||
Progress<FtpProgress> progress = new Progress<FtpProgress>(p =>
|
||||
{
|
||||
callback(index, (int)(p.Progress));
|
||||
|
||||
});
|
||||
bool pathExits = await conn.DirectoryExists(remoteRootPath, token);
|
||||
if (!pathExits)
|
||||
{
|
||||
await conn.CreateDirectory(remoteRootPath, true, token);
|
||||
}
|
||||
foreach (var file in localFiles)
|
||||
{
|
||||
//Trace.WriteLine(file);
|
||||
//Trace.WriteLine(remoteRootPath + "/" + getFileName(file));
|
||||
await conn.UploadFile(file, remoteRootPath + "/" + getFileName(file), FtpRemoteExists.Overwrite, false, FtpVerify.None, progress, token);
|
||||
index++;
|
||||
}
|
||||
return true;
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
callback(index, -1);
|
||||
return false;
|
||||
//Trace.WriteLine(ex.ToString());
|
||||
}
|
||||
finally
|
||||
{
|
||||
await conn.Disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static string getFileName(string fullPath)
|
||||
{
|
||||
string[] arr = fullPath.Split(Path.DirectorySeparatorChar);
|
||||
return arr[arr.Length - 1];
|
||||
}
|
||||
|
||||
public static string getFileExt(string fullPath)
|
||||
{
|
||||
string[] arr = fullPath.Split("\\.");
|
||||
return arr[arr.Length - 1];
|
||||
}
|
||||
|
||||
|
||||
public static string getFileCreateDataTime(string filePath)
|
||||
{
|
||||
FileInfo fileInfo = new FileInfo(filePath);
|
||||
return fileInfo.CreationTime.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
using FileProcessClient.domain;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace edu.huvtc.utils
|
||||
{
|
||||
internal class HttpUtils
|
||||
{
|
||||
|
||||
public static async Task<string> HttpClientPost(string url, string data)
|
||||
{
|
||||
string token = CommonUtils.getToken();
|
||||
|
||||
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.None };
|
||||
|
||||
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true;
|
||||
|
||||
string serverUrl = CommonUtils.getServerUrl();
|
||||
|
||||
using (var httpclient = new HttpClient(handler))
|
||||
{
|
||||
try
|
||||
{
|
||||
httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
|
||||
httpclient.BaseAddress = new Uri(serverUrl + url);
|
||||
|
||||
HttpContent content = new StringContent(data, System.Text.Encoding.UTF8, "application/json");
|
||||
|
||||
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
|
||||
|
||||
var response = await httpclient.PostAsync(url, content);
|
||||
|
||||
string responseString = await response.Content.ReadAsStringAsync();
|
||||
|
||||
//Trace.WriteLine(responseString);
|
||||
|
||||
return responseString;
|
||||
}
|
||||
catch (HttpRequestException e)
|
||||
{
|
||||
// 捕获 HttpRequestException 异常以处理网络错误
|
||||
//Console.WriteLine($"请求异常: {e.Message}");
|
||||
MessageBox.Show("网络异常,请确认是否联网!");
|
||||
return "";
|
||||
}
|
||||
catch (TaskCanceledException e)
|
||||
{
|
||||
MessageBox.Show("请求超时!");
|
||||
return "";
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// 捕获其他异常
|
||||
//Console.WriteLine($"其他异常: {e.Message}");
|
||||
MessageBox.Show("发生未知错误");
|
||||
return "503";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static async Task<string> HttpClientGet(string url, string query)
|
||||
{
|
||||
string token = CommonUtils.getToken();
|
||||
|
||||
url = CommonUtils.getServerUrl() + url;
|
||||
|
||||
Trace.WriteLine(url);
|
||||
|
||||
using (HttpClient client = new HttpClient())
|
||||
{
|
||||
try
|
||||
{
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
|
||||
var builder = new UriBuilder(url);
|
||||
|
||||
//var query = System.Web.HttpUtility.ParseQueryString(builder.Query);
|
||||
//query["param1"] = "value1";
|
||||
//query["param2"] = "value2";
|
||||
|
||||
builder.Query = query;
|
||||
|
||||
string str_url = builder.ToString();
|
||||
|
||||
HttpResponseMessage response = await client.GetAsync(str_url);
|
||||
|
||||
|
||||
return await response.Content.ReadAsStringAsync();
|
||||
}
|
||||
catch (HttpRequestException e)
|
||||
{
|
||||
// 捕获 HttpRequestException 异常以处理网络错误
|
||||
//Console.WriteLine($"请求异常: {e.Message}");
|
||||
MessageBox.Show("网络或服务器异常!");
|
||||
return "";
|
||||
}
|
||||
catch (TaskCanceledException e)
|
||||
{
|
||||
MessageBox.Show("请求超时!");
|
||||
return "";
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// 捕获其他异常
|
||||
//Console.WriteLine($"其他异常: {e.Message}");
|
||||
MessageBox.Show("发生未知错误");
|
||||
return "";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static async Task<bool> getUserInfo()
|
||||
{
|
||||
string token = CommonUtils.getToken();
|
||||
//Trace.WriteLine(token);
|
||||
if (token != null && token != "")
|
||||
{
|
||||
string url = CommonUtils.getApiUrl("user_info_url");
|
||||
string result = await HttpUtils.HttpClientGet(url, "");
|
||||
|
||||
//Trace.WriteLine(result);
|
||||
if (result == "")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
JObject jsonObject = JObject.Parse(result);
|
||||
int code = (int)jsonObject["code"]!;
|
||||
if (code != 200)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
string strUser = jsonObject["user"]!.ToString();
|
||||
|
||||
//Trace.WriteLine(strUser);
|
||||
|
||||
JObject obj = JObject.Parse(strUser);
|
||||
int id = (int)obj["userId"]!;
|
||||
string loginId = (string)obj["userName"]!;
|
||||
string phone = (string)obj["phonenumber"]!;
|
||||
string name = (string)obj["nickName"]!;
|
||||
int deptId = (int)obj["deptId"]!;
|
||||
User user = new User(id, name, loginId, phone, deptId);
|
||||
CommonUtils.setUser(user);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<bool> saveMediaFileInfo(MediaFileInfo mediaFileInfo)
|
||||
{
|
||||
var jsonString = JsonConvert.SerializeObject(mediaFileInfo);
|
||||
//Trace.WriteLine(jsonString);
|
||||
string url = CommonUtils.getApiUrl("save_media_file_url");
|
||||
string res = await HttpClientPost(url, jsonString);
|
||||
if (res == "")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static async Task<List<ComboboxItem>> getVersionList()
|
||||
{
|
||||
string url = CommonUtils.getApiUrl("file_version_list_url");
|
||||
|
||||
string res = await HttpUtils.HttpClientGet(url, "");
|
||||
//Trace.WriteLine(res);
|
||||
if (res == null)
|
||||
{
|
||||
return new List<ComboboxItem>();
|
||||
}
|
||||
|
||||
List<ComboboxItem> list = new List<ComboboxItem>();
|
||||
JArray array = JArray.Parse(res);
|
||||
|
||||
foreach (var item in array)
|
||||
{
|
||||
list.Add(new ComboboxItem(item["dictLabel"]!.ToString(), item["dictCode"]!.ToString()));
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public static async Task<List<ComboboxItem>> getCameraList()
|
||||
{
|
||||
string url = CommonUtils.getApiUrl("camera_list_url");
|
||||
|
||||
string res = await HttpUtils.HttpClientGet(url, "");
|
||||
if (res == null)
|
||||
{
|
||||
return new List<ComboboxItem>();
|
||||
}
|
||||
|
||||
List<ComboboxItem> list = new List<ComboboxItem>();
|
||||
|
||||
JArray array = JArray.Parse(res);
|
||||
|
||||
foreach (var item in array)
|
||||
{
|
||||
list.Add(new ComboboxItem(item["duid"]!.ToString(), item["id"]!.ToString()));
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public static async Task<bool> validateLogin(string username, string password)
|
||||
{
|
||||
JsonObject obj = new JsonObject();
|
||||
obj.Add("username", username);
|
||||
obj.Add("password", password);
|
||||
obj.Add("loginType", 1);
|
||||
string result = await HttpUtils.HttpClientPost("/login", obj.ToString());
|
||||
Trace.WriteLine("==================="+result);
|
||||
if (result == "")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
JObject jsonObject = JObject.Parse(result);
|
||||
|
||||
int code = (int)jsonObject["code"]!;
|
||||
if (code == 200)
|
||||
{
|
||||
string token = (string)jsonObject["token"]!;
|
||||
CommonUtils.setToken(token);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user