This repository has been archived by the owner on Aug 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombine.cs
200 lines (173 loc) · 6.7 KB
/
Combine.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
namespace HikDownloader
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Combinar.
/// </summary>
public static class Combine
{
/// <summary>
/// Combina todas las grabaciones de cada día en un único archivo.
/// </summary>
public static void Execute()
{
Console.WriteLine("Combinando...");
Console.WriteLine(" > Configuración:");
Console.WriteLine($" Ruta de guardado: {Program.Config.FFmpeg.Dir}");
Console.WriteLine($" Ruta de FFmpeg: {Program.Config.FFmpeg.Bin}");
Console.WriteLine($" Tareas simultáneas: {Program.Config.FFmpeg.SimultaneousTasks}\n");
Console.WriteLine(" > Progreso:");
var files = GenerateFileLists();
var error = false;
if (files.Count > 0)
{
Parallel.ForEach(
files,
new ParallelOptions
{
MaxDegreeOfParallelism = Program.Config.FFmpeg.SimultaneousTasks
},
file =>
{
if (!CombineRecordings(file))
{
error = true;
}
}
);
Cleanup();
if (!error)
{
Console.WriteLine($"\r Se han combinado los archivos. \n");
}
else
{
Console.WriteLine($"\r Se han combinado los archivos (con errores). \n");
}
}
else
{
Console.WriteLine($"\n No se han encontrado archivos.\n");
}
}
/// <summary>
/// Genera listas agrupadas por canal y fecha de las grabaciones.
/// </summary>
/// <returns>Una lista de archivos que contiene las grabaciones agrupadas por canal y fecha.</returns>
private static List<string> GenerateFileLists()
{
var groups = Directory.EnumerateFiles(Program.Config.HikDownloader.Downloads.Dir, "*.avi", SearchOption.AllDirectories)
.Select(x => $"file '{x}'")
.GroupBy(i =>
{
var parts = i.Split('\\');
var channel = parts[parts.Length - 2];
var date = parts[parts.Length - 1].Split('_')[0];
return $"{channel}_{date}";
});
var results = new List<string>();
var path = Util.GetPath("temp");
foreach (var group in groups)
{
var fileName = group.Key + ".txt";
File.WriteAllLines(path + "\\" + fileName, group);
results.Add(path + "\\" + fileName);
}
return results.OrderBy(q => q).ToList();
}
/// <summary>
/// Combina grabaciones.
/// </summary>
/// <param name="file">Ruta al archivo que contiene la lista de grabaciones.</param>
private static bool CombineRecordings(string file)
{
var ok = true;
var fileName = Path.GetFileNameWithoutExtension(file);
var parts = fileName.Split('_');
var path = Program.Config.FFmpeg.Dir;
var outFile = string.Format("{0}\\{1}\\{2}\\{3}.avi", path, parts[1].Substring(0, parts[1].Length - 3), parts[0], parts[1]);
var workingDirectory = Path.GetDirectoryName(outFile);
if (!Directory.Exists(workingDirectory))
{
Directory.CreateDirectory(workingDirectory);
}
var log = new StringBuilder();
using (var ffmpeg = new Process())
{
ffmpeg.StartInfo.FileName = Program.Config.FFmpeg.Bin;
ffmpeg.StartInfo.Arguments = string.Format("-y -loglevel error -f concat -safe 0 -i \"{0}\" -c copy \"{1}\"", file, outFile);
ffmpeg.StartInfo.UseShellExecute = false;
ffmpeg.StartInfo.RedirectStandardOutput = true;
ffmpeg.StartInfo.RedirectStandardError = true;
ffmpeg.StartInfo.CreateNoWindow = true;
ffmpeg.StartInfo.WorkingDirectory = workingDirectory;
ffmpeg.EnableRaisingEvents = true;
ffmpeg.OutputDataReceived += (s, e) => log.AppendLine(e.Data);
ffmpeg.ErrorDataReceived += (s, e) => log.AppendLine(e.Data);
ffmpeg.Start();
ffmpeg.BeginOutputReadLine();
ffmpeg.BeginErrorReadLine();
ffmpeg.WaitForExit();
}
var results = log.ToString().Trim();
if (results.Length == 0)
{
File.ReadAllLines(file)
.Select(i => i.Replace("file '", string.Empty).TrimEnd('\''))
.ToList()
.ForEach(delegate (string f)
{
File.Delete(f);
});
File.Delete(file);
Console.Write($"\r {fileName}");
}
else
{
ok = false;
var logPath = Util.GetPath("logs");
var logFile = $"ffmpeg-{fileName}.log";
File.WriteAllText(logPath + "\\" + logFile, results);
}
return ok;
}
/// <summary>
/// Limpieza.
/// </summary>
private static void Cleanup()
{
DeleteEmptyDirs(Program.Config.HikDownloader.Downloads.Dir);
if (!Directory.Exists(Program.Config.HikDownloader.Downloads.Dir))
{
Directory.CreateDirectory(Program.Config.HikDownloader.Downloads.Dir);
}
}
/// <summary>
/// Elimina directorios vacíos de forma recursiva.
/// </summary>
/// <param name="path"></param>
private static void DeleteEmptyDirs(string path)
{
foreach (var dir in Directory.EnumerateDirectories(path))
{
DeleteEmptyDirs(dir);
}
var entries = Directory.EnumerateFileSystemEntries(path);
if (!entries.Any())
{
try
{
Directory.Delete(path);
}
catch (UnauthorizedAccessException) { }
catch (DirectoryNotFoundException) { }
}
}
}
}