1、初始化仓库

This commit is contained in:
2025-05-19 14:06:21 +08:00
commit 8a1d028f3e
28 changed files with 3832 additions and 0 deletions

View File

@ -0,0 +1,27 @@
Imports System.Net.Http
Public Class CopyService
'本地缓存'
Public LocalKeyWords As KeywordItem() = {}
Public client As HttpClient = New HttpClient
''' <summary>
''' 缓存关键词数据
''' </summary>
''' <returns></returns>
Public Async Function InitLocal(baseUrl As String) As Task
Try
Dim url As String = $"{baseUrl}/mm-machine/keywords"
Dim response As HttpResponseMessage = Await client.GetAsync(url)
If response.IsSuccessStatusCode Then
Dim responseText As String = Await response.Content.ReadAsStringAsync()
If responseText = "成功更新数据" Then
End If
End If
Catch ex As Exception
End Try
End Function
End Class

View File

@ -0,0 +1,3 @@
Public Class FileService
End Class

143
Yjpp36/service/Logger.vb Normal file
View File

@ -0,0 +1,143 @@
Imports System.IO
Imports System.Text
Imports System.Collections.Concurrent
Public Module Logger
Private ReadOnly logDirectory As String = "c:\\logs"
Private ReadOnly maxLogSizeBytes As Long = 10 * 1024 * 1024 ' 每个文件最大10MB
Private ReadOnly logRetentionDays As Integer = 1
Private ReadOnly logLock As New Object()
Private ReadOnly logQueue As New ConcurrentQueue(Of String)()
Private ReadOnly logWritingTask As Task
Public Enum LogLevel
Info
Warn
[Error]
Debug
End Enum
''' <summary>
''' 初始化日志写入任务
''' </summary>
Sub New()
logWritingTask = Task.Run(AddressOf ProcessLogQueue)
End Sub
''' <summary>
''' 异步写入带等级的日志
''' </summary>
Public Sub WriteLog(level As LogLevel, message As String)
Dim logEntry As String = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} [{level.ToString().ToUpper()}] {message}"
logQueue.Enqueue(logEntry)
End Sub
''' <summary>
''' 定期从队列中取出日志并写入文件
''' </summary>
Private Async Sub ProcessLogQueue()
While True
' 确保日志写入任务不会频繁创建线程
If logQueue.IsEmpty Then
Await Task.Delay(500) ' 等待一段时间再检查队列
End If
' 使用 TryDequeue 从队列中获取 logEntry
Dim logEntry As String = Nothing
If logQueue.TryDequeue(logEntry) Then
WriteLogToFile(logEntry)
End If
End While
End Sub
''' <summary>
''' 写入日志到文件
''' </summary>
Private Sub WriteLogToFile(logEntry As String)
Try
SyncLock logLock
If Not Directory.Exists(logDirectory) Then
Directory.CreateDirectory(logDirectory)
End If
CleanupOldLogs()
Dim todayFile As String = Path.Combine(logDirectory, $"{Date.Today:yyyy-MM-dd}.log")
If File.Exists(todayFile) Then
Dim fileInfo As New FileInfo(todayFile)
If fileInfo.Length > maxLogSizeBytes Then
BackupAndClear(todayFile)
End If
End If
Using sw As New StreamWriter(todayFile, append:=True, encoding:=Encoding.UTF8)
sw.WriteLine(logEntry)
End Using
End SyncLock
Catch
' 忽略日志写入错误
End Try
End Sub
''' <summary>
''' 清理过期的日志文件
''' </summary>
Private Sub CleanupOldLogs()
Try
Dim files = Directory.GetFiles(logDirectory)
For Each file In files
Dim fileName = Path.GetFileNameWithoutExtension(file)
Dim dateStr = fileName.Split("_"c).FirstOrDefault()
If Date.TryParse(dateStr, Nothing) Then
Dim fileDate = Date.Parse(dateStr)
If (Date.Today - fileDate).Days >= logRetentionDays Then
file.Remove(file)
End If
End If
Next
Catch
' 忽略清理错误
End Try
End Sub
''' <summary>
''' 备份并清空日志文件
''' </summary>
Private Sub BackupAndClear(filePath As String)
Try
Dim bakFile As String = filePath.Replace(".log", $"_{DateTime.Now:HHmmss}.bak")
File.Copy(filePath, bakFile, overwrite:=True)
File.WriteAllText(filePath, "") ' 清空日志内容
Catch
' 忽略备份错误
End Try
End Sub
''' <summary>
''' 快捷方法:写 Info 日志
''' </summary>
Public Sub Info(message As String)
'WriteLog(LogLevel.Info, message)
End Sub
''' <summary>
''' 快捷方法:写 Warning 日志
''' </summary>
Public Sub Warn(message As String)
'WriteLog(LogLevel.Warn, message)
End Sub
''' <summary>
''' 快捷方法:写 Error 日志
''' </summary>
Public Sub [Error](message As String)
'WriteLog(LogLevel.Error, message)
End Sub
''' <summary>
''' 快捷方法:写 Debug 日志
''' </summary>
Public Sub Debug(message As String)
'WriteLog(LogLevel.Debug, message)
End Sub
End Module

View File

@ -0,0 +1,157 @@
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text
Public Class StringEncryption
Public Shared KeyBase64 As String = "JVr/l75Wv29+d643g7+h89Q2Z4m/a1bY09iKz8Wn6as="
Public Shared IVBase64 As String = "n869V+6/7Q11p049/wE99g=="
''' <summary>
''' 使用 AES 加密字符串。
''' </summary>
''' <param name="plainText">要加密的明文字符串。</param>
''' <param name="key">用于加密的密钥(必须是 AES 密钥大小,例如 128, 192 或 256 位)。</param>
''' <param name="iv">初始化向量IV用于增加加密的随机性必须是 AES 块大小,即 16 字节)。</param>
''' <returns>Base64 编码的密文字符串。</returns>
Public Shared Function EncryptStringAES(plainText As String, KeyBase64 As String, IVBase64 As String) As String
Dim Key As Byte()
Dim iv As Byte()
Try
Key = System.Convert.FromBase64String(KeyBase64)
iv = System.Convert.FromBase64String(IVBase64)
Catch ex As Exception
Console.WriteLine("密钥和向量失败 err:", ex.Message)
End Try
' 检查输入是否有效
If plainText Is Nothing OrElse plainText.Length <= 0 Then
Throw New ArgumentNullException("plainText")
End If
If Key Is Nothing OrElse Key.Length <= 0 Then
Throw New ArgumentNullException("key")
End If
If iv Is Nothing OrElse iv.Length <= 0 Then
Throw New ArgumentNullException("iv")
End If
If Key.Length <> 16 AndAlso Key.Length <> 24 AndAlso Key.Length <> 32 Then
Throw New ArgumentException("密钥长度必须为 128, 192 或 256 位 (16, 24 或 32 字节)。")
End If
If iv.Length <> 16 Then
Throw New ArgumentException("IV 长度必须为 128 位 (16 字节)。")
End If
Dim encrypted As Byte()
' 使用 AES 加密
Using aesAlg As Aes = Aes.Create()
aesAlg.Key = Key
aesAlg.IV = iv
' 创建加密器
Dim encryptor As ICryptoTransform = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)
' 使用内存流进行加密
Using msEncrypt As New MemoryStream()
Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
Using swEncrypt As New StreamWriter(csEncrypt)
' 将所有数据写入流。
swEncrypt.Write(plainText)
End Using
encrypted = msEncrypt.ToArray()
End Using
End Using
End Using
' 返回 Base64 编码的加密字节
Return Convert.ToBase64String(encrypted)
End Function
''' <summary>
''' 使用 AES 解密字符串。
''' </summary>
''' <param name="cipherText">要解密的 Base64 编码的密文字符串。</param>
''' <param name="key">用于解密的密钥(必须与加密时使用的密钥相同)。</param>
''' <param name="iv">用于解密的初始化向量(必须与加密时使用的 IV 相同)。</param>
''' <returns>解密后的明文字符串。</returns>
Public Shared Function DecryptStringAES(cipherText As String, keyBase As String, ivBase As String) As String
Dim key As Byte()
Dim iv As Byte()
Try
key = Convert.FromBase64String(KeyBase64)
iv = Convert.FromBase64String(IVBase64)
Catch ex As Exception
Console.WriteLine("密钥和向量失败 err:", ex.Message)
End Try
' 检查输入是否有效
If cipherText Is Nothing OrElse cipherText.Length <= 0 Then
Throw New ArgumentNullException("cipherText")
End If
If key Is Nothing OrElse key.Length <= 0 Then
Throw New ArgumentNullException("key")
End If
If iv Is Nothing OrElse iv.Length <= 0 Then
Throw New ArgumentNullException("iv")
End If
If key.Length <> 16 AndAlso key.Length <> 24 AndAlso key.Length <> 32 Then
Throw New ArgumentException("密钥长度必须为 128, 192 或 256 位 (16, 24 或 32 字节)。")
End If
If iv.Length <> 16 Then
Throw New ArgumentException("IV 长度必须为 128 位 (16 字节)。")
End If
' 将 Base64 编码的密文转换为字节数组
Dim encryptedBytes As Byte() = Convert.FromBase64String(cipherText)
' 用于存储解密后的明文
Dim plaintext As String = String.Empty
' 使用 AES 解密
Using aesAlg As Aes = Aes.Create()
aesAlg.Key = key
aesAlg.IV = iv
' 创建解密器
Dim decryptor As ICryptoTransform = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV)
' 使用内存流进行解密
Using msDecrypt As New MemoryStream(encryptedBytes)
Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
Using srDecrypt As New StreamReader(csDecrypt)
' 从解密流中读取所有字节并将其解码为字符串。
plaintext = srDecrypt.ReadToEnd()
End Using
End Using
End Using
End Using
Return plaintext
End Function
''' <summary>
''' 生成一个随机的 AES 密钥。
''' </summary>
''' <param name="keySize">所需的密钥大小(以位为单位,例如 128, 192 或 256。</param>
''' <returns>随机生成的密钥字节数组。</returns>
Public Shared Function GenerateRandomKey(keySize As Integer) As Byte()
Using aesAlg As Aes = Aes.Create()
aesAlg.KeySize = keySize
aesAlg.GenerateKey()
Return aesAlg.Key
End Using
End Function
''' <summary>
''' 生成一个随机的 AES 初始化向量 (IV)。
''' </summary>
''' <returns>随机生成的 IV 字节数组。</returns>
Public Shared Function GenerateRandomIV() As Byte()
Using aesAlg As Aes = Aes.Create()
aesAlg.GenerateIV()
Return aesAlg.IV
End Using
End Function
End Class

72
Yjpp36/service/Updater.vb Normal file
View File

@ -0,0 +1,72 @@
Imports System.IO
Imports System.Net
Imports System.Web
Public Class Updater
'Private Shared ReadOnly localPath As String = Application.ExecutablePath
Private Shared ReadOnly tempPath As String = Path.Combine(Path.GetTempPath(), "update_temp.exe")
Private Shared ReadOnly vbsPath As String = Path.Combine(Path.GetTempPath(), "update_script.vbs")
''' <summary>
''' 开始更新任务
''' </summary>
''' <param name="localPath">目标地址</param>
''' <param name="updateUrl">更新文件地址</param>
''' <returns></returns>
Public Shared Async Function StartUpdateAsync(localPath As String, updateUrl As String) As Task
Try
' 下载更新文件
Using client As New WebClient()
Await client.DownloadFileTaskAsync(updateUrl, tempPath)
Logger.Info(updateUrl & "文件下载完毕")
End Using
' 创建 VBS 脚本 (修正了 VBScript 语法错误)
Dim vbsContent As String = $"
Set WshShell = CreateObject(""WScript.Shell"")
WScript.Sleep 4000
' 解除保护并替换 EXE
On Error Resume Next
Set fso = CreateObject(""Scripting.FileSystemObject"")
If fso.FileExists(""{Replace(localPath, "\", "\\")}"") Then
Set f = fso.GetFile(""{Replace(localPath, "\", "\\")}"")
f.Attributes = 0
End If
If fso.FileExists(""{Replace(tempPath, "\", "\\")}"") Then
fso.CopyFile ""{Replace(tempPath, "\", "\\")}"", ""{Replace(localPath, "\", "\\")}"", True
fso.DeleteFile ""{Replace(tempPath, "\", "\\")}"", True
End If
' 设置属性
If fso.FileExists(""{Replace(localPath, "\", "\\")}"") Then
Set f = fso.GetFile(""{Replace(localPath, "\", "\\")}"")
f.Attributes = 4 + 2 + 1 ' System + Hidden + ReadOnly
End If
' 启动新程序
WshShell.Run ""{Replace(localPath, "\", "\\")}"", 0, False
' 删除自己
fso.DeleteFile WScript.ScriptFullName, True
"
File.WriteAllText(vbsPath, vbsContent)
Logger.Info("启动脚本:" & vbsContent)
' 启动 VBS 脚本
Dim p As New Process()
p.StartInfo.FileName = "wscript"
p.StartInfo.Arguments = """" & vbsPath & """" ' 使用引号包裹路径
p.Start()
Logger.Info("退出程序")
' 退出当前程序
Environment.Exit(0)
Catch ex As Exception
Logger.Error("更新失败:" & ex.Message)
Throw ' 重要的:重新抛出异常,让调用者知道更新失败
End Try
End Function
End Class