86 lines
3.5 KiB
C#
86 lines
3.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text.RegularExpressions;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using DBObj;
|
|
|
|
namespace DataCheck
|
|
{
|
|
public class PublicSongChecker
|
|
{
|
|
|
|
private List<SongData> publicSongList = new();
|
|
public PublicSongChecker()
|
|
{
|
|
string serverPath = Utils.Env.GetPath("video", "");
|
|
string localPath = @"D:\video";
|
|
// 加入你要同步的資料夾
|
|
SyncFolder(serverPath, localPath, "video", new[] { ".mpg" });
|
|
}
|
|
public List<SongData> GetSongs()
|
|
{
|
|
return publicSongList;
|
|
}
|
|
|
|
private void SyncFolder(string serverPath, string localPath, string label, string[] extensions)
|
|
{
|
|
|
|
if (!Directory.Exists(localPath)) Directory.CreateDirectory(localPath);
|
|
if (!Directory.Exists(serverPath)) {
|
|
Console.WriteLine($"找不到伺服器資料夾:{serverPath}");
|
|
return;
|
|
}
|
|
|
|
var serverFiles = Directory.GetFiles(serverPath)
|
|
.Where(f => extensions.Contains(Path.GetExtension(f), StringComparer.OrdinalIgnoreCase))
|
|
.Select(f => new FileInfo(f))
|
|
.ToDictionary(f => f.Name, f => f);
|
|
|
|
var localFiles = Directory.GetFiles(localPath)
|
|
.Where(f => extensions.Contains(Path.GetExtension(f), StringComparer.OrdinalIgnoreCase))
|
|
.Select(f => new FileInfo(f))
|
|
.ToDictionary(f => f.Name, f => f);
|
|
|
|
// 1. 複製或更新檔案
|
|
foreach (var serverFile in serverFiles) {
|
|
string dest = Path.Combine(localPath, serverFile.Key);
|
|
bool needsCopy = !localFiles.ContainsKey(serverFile.Key) ||
|
|
serverFile.Value.LastWriteTime > localFiles[serverFile.Key].LastWriteTime;
|
|
if (needsCopy) {
|
|
try {
|
|
File.Copy(serverFile.Value.FullName, dest, true);
|
|
Console.WriteLine($"✅ 更新 {label}: {serverFile.Key}");
|
|
} catch (Exception ex) {
|
|
Console.WriteLine($"❌ 複製 {label} 失敗 {serverFile.Key}: {ex.Message}");
|
|
continue; // 如果複製失敗就不加入 SongData
|
|
}
|
|
}
|
|
string fileName = Path.GetFileNameWithoutExtension(serverFile.Key);
|
|
Match match = Regex.Match(fileName, @"^(?<songNumber>\d+)-.*?-(?<songName>[^-]+)-");
|
|
if (match.Success) {
|
|
publicSongList.Add(new SongData(
|
|
match.Groups["songNumber"].Value, // songNumber
|
|
match.Groups["songName"].Value, // song
|
|
Path.Combine(localPath, serverFile.Key), // songFilePathHost1
|
|
1, // priority
|
|
true
|
|
));
|
|
}
|
|
}
|
|
|
|
// 2. 刪除多餘的本地檔案
|
|
foreach (var localFile in localFiles) {
|
|
if (!serverFiles.ContainsKey(localFile.Key)) {
|
|
try {
|
|
File.Delete(localFile.Value.FullName);
|
|
Console.WriteLine($"刪除多餘{label}: {localFile.Key}");
|
|
} catch (Exception ex) {
|
|
Console.WriteLine($"刪除{label}失敗 {localFile.Key}: {ex.Message}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|