This repository was archived by the owner on Feb 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathFileStreamCaptureHandler.cs
More file actions
222 lines (180 loc) · 7.9 KB
/
Copy pathFileStreamCaptureHandler.cs
File metadata and controls
222 lines (180 loc) · 7.9 KB
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// <copyright file="FileStreamCaptureHandler.cs" company="Techyian">
// Copyright (c) Ian Auty and contributors. All rights reserved.
// Licensed under the MIT License. Please see LICENSE.txt for License info.
// </copyright>
using Microsoft.Extensions.Logging;
using MMALSharp.Common;
using MMALSharp.Common.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MMALSharp.Handlers
{
/// <summary>
/// Processes image data to a <see cref="FileStream"/>.
/// </summary>
public class FileStreamCaptureHandler : StreamCaptureHandler<FileStream>, IFileStreamCaptureHandler
{
private readonly bool _customFilename;
private int _increment;
/// <summary>
/// A list of files that have been processed by this capture handler.
/// </summary>
public List<ProcessedFileResult> ProcessedFiles { get; set; } = new List<ProcessedFileResult>();
/// <summary>
/// The directory to save to (if applicable).
/// </summary>
public string Directory { get; set; }
/// <summary>
/// The extension of the file (if applicable).
/// </summary>
public string Extension { get; set; }
/// <summary>
/// The name of the file associated with the FileStream (without a path or extension).
/// </summary>
public string CurrentFilename { get; set; }
/// <summary>
/// When true, the Dispose method will delete the zero-length file identified by CurrentStream.Name.
/// Inheriting classes should set this to false any time they write to the file stream.
/// </summary>
protected bool FileIsEmpty { get; set; }
/// <summary>
/// Creates a new instance of the <see cref="FileStreamCaptureHandler"/> class without provisions for writing to a file. Supports
/// subclasses in which file output is optional.
/// </summary>
public FileStreamCaptureHandler()
{
MMALLog.Logger.LogDebug($"{nameof(FileStreamCaptureHandler)} empty ctor invoked, no file will be written");
// Prevent Dispose from attempting to delete a non-existent file.
this.FileIsEmpty = false;
}
/// <summary>
/// Creates a new instance of the <see cref="FileStreamCaptureHandler"/> class with the specified directory and filename extension. Filenames will be in the
/// format "dd-MMM-yy HH-mm-ss" taken from this moment in time.
/// </summary>
/// <param name="directory">The directory to save captured data.</param>
/// <param name="extension">The filename extension for saving files.</param>
public FileStreamCaptureHandler(string directory, string extension)
{
this.Directory = directory.TrimEnd('/');
this.Extension = extension.TrimStart('.');
MMALLog.Logger.LogDebug($"{nameof(FileStreamCaptureHandler)} created for directory {this.Directory} and extension {this.Extension}");
System.IO.Directory.CreateDirectory(this.Directory);
var now = DateTime.Now.ToString("dd-MMM-yy HH-mm-ss");
int i = 1;
var fileName = $"{this.Directory}/{now}.{this.Extension}";
while (File.Exists(fileName))
{
fileName = $"{this.Directory}/{now} {i}.{this.Extension}";
i++;
}
var fileInfo = new FileInfo(fileName);
this.CurrentFilename = Path.GetFileNameWithoutExtension(fileInfo.Name);
this.CurrentStream = File.Create(fileName);
this.FileIsEmpty = true;
}
/// <summary>
/// Creates a new instance of the <see cref="FileStreamCaptureHandler"/> class with the specified file path.
/// </summary>
/// <param name="fullPath">The absolute full path to save captured data to.</param>
public FileStreamCaptureHandler(string fullPath)
{
var fileInfo = new FileInfo(fullPath);
this.Directory = fileInfo.DirectoryName;
this.CurrentFilename = Path.GetFileNameWithoutExtension(fileInfo.Name);
var ext = fullPath.Split('.').LastOrDefault();
if (string.IsNullOrEmpty(ext))
{
throw new ArgumentNullException(nameof(ext), "Could not get file extension from path string.");
}
this.Extension = ext;
MMALLog.Logger.LogDebug($"{nameof(FileStreamCaptureHandler)} created for directory {this.Directory} and extension {this.Extension}");
_customFilename = true;
System.IO.Directory.CreateDirectory(this.Directory);
this.CurrentStream = File.Create(fullPath);
this.FileIsEmpty = true;
}
/// <inheritdoc />
public override void Process(ImageContext context)
{
base.Process(context);
this.FileIsEmpty = false;
}
/// <summary>
/// Gets the filename that a FileStream points to without a path or extension.
/// </summary>
/// <returns>The filename.</returns>
public string GetFilename() =>
(this.CurrentStream != null) ? Path.GetFileNameWithoutExtension(this.CurrentStream.Name) : string.Empty;
/// <summary>
/// Gets the full file pathname that a FileStream points to.
/// </summary>
/// <returns>The filepath.</returns>
public string GetFilepath() =>
this.CurrentStream?.Name ?? string.Empty;
/// <summary>
/// Creates a new File (FileStream), assigns it to the Stream instance of this class and disposes of any existing stream.
/// </summary>
public virtual void NewFile()
{
if (this.CurrentStream == null)
{
return;
}
this.CurrentStream?.Dispose();
string newFilename = string.Empty;
if (_customFilename)
{
// If we're taking photos from video port, we don't want to be hammering File.Exists as this is added I/O overhead. Camera can take multiple photos per second
// so we can't do this when filename uses the current DateTime.
_increment++;
newFilename = $"{this.Directory}/{this.CurrentFilename} {_increment}.{this.Extension}";
}
else
{
string tempFilename = DateTime.Now.ToString("dd-MMM-yy HH-mm-ss");
int i = 1;
newFilename = $"{this.Directory}/{tempFilename}.{this.Extension}";
while (File.Exists(newFilename))
{
newFilename = $"{this.Directory}/{tempFilename} {i}.{this.Extension}";
i++;
}
}
this.CurrentStream = File.Create(newFilename);
this.FileIsEmpty = true;
}
/// <inheritdoc />
public override void PostProcess()
{
if (this.CurrentStream == null)
{
return;
}
this.ProcessedFiles.Add(new ProcessedFileResult(this.Directory, this.GetFilename(), this.Extension));
base.PostProcess();
}
/// <inheritdoc />
public override string TotalProcessed()
{
return $"{this.Processed}";
}
/// <inheritdoc />
public override void Dispose()
{
base.Dispose();
// Disposing the stream can leave a zero-length file on disk if nothing
// was recorded into it -- but after recording has taken place, only
// calling NewFile (or Split for videos) will create a new empty file.
if (this.FileIsEmpty)
{
try
{
File.Delete(this.CurrentStream.Name);
}
catch { }
}
}
}
}