This repository has been archived by the owner on Aug 22, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
PublicHelper.cs
268 lines (249 loc) · 8.95 KB
/
PublicHelper.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web;
using System.Xml.Linq;
using Microsoft.Win32;
using Mygod.Net;
using Mygod.Xml.Linq;
namespace Mygod.Skylark
{
public static partial class Helper
{
public const string Unknown = "未知";
static Helper()
{
var mimeMappingType = Assembly.GetAssembly(typeof(HttpRuntime)).GetType("System.Web.MimeMapping");
if (mimeMappingType == null) throw new SystemException("Couldn't find MimeMapping type");
GetMimeMappingMethodInfo = mimeMappingType.GetMethod("GetMimeMapping",
BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
if (GetMimeMappingMethodInfo == null) throw new SystemException("Couldn't find GetMimeMapping method");
if (GetMimeMappingMethodInfo.ReturnType != typeof(string))
throw new SystemException("GetMimeMapping method has invalid return type");
if (GetMimeMappingMethodInfo.GetParameters().Length != 1
&& GetMimeMappingMethodInfo.GetParameters()[0].ParameterType != typeof(string))
throw new SystemException("GetMimeMapping method has invalid parameters");
}
private static readonly object Locker = new object();
private static readonly MethodInfo GetMimeMappingMethodInfo;
public static string GetMimeType(string fileName)
{
lock (Locker) return (string)GetMimeMappingMethodInfo.Invoke(null, new object[] { fileName });
}
public static string GetDefaultExtension(string mimeType)
{
try
{
var key = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type\" + mimeType, false);
var value = key != null ? key.GetValue("Extension", null) : null;
return value != null ? value.ToString() : null;
}
catch
{
return null;
}
}
public static string GetMime(string contentType)
{
try
{
return contentType.Split(';')[0]; // kill that "; charset=utf-8" stupid stuff
}
catch
{
return contentType;
}
}
public static string Shorten(this DateTime value)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(value.Ticks.ToString(CultureInfo.InvariantCulture)));
}
public static DateTime Deshorten(string value)
{
return new DateTime(long.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(value))),
DateTimeKind.Utc);
}
}
public static partial class FileHelper
{
public static string Combine(params string[] paths)
{
var result = string.Empty;
foreach (var path in paths.Select(path => path.Trim('/')))
{
if (!string.IsNullOrEmpty(result)) result += '/';
result += path;
}
return result;
}
public static void WriteAllText(string path, string contents)
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
File.WriteAllText(path, contents);
}
public static XElement GetElement(string path)
{
try
{
return XHelper.Load(path).Root;
}
catch
{
return null;
}
}
public static string GetFileValue(string path, string attribute)
{
try
{
return GetElement(path).GetAttributeValue(attribute);
}
catch
{
return null;
}
}
public static void SetFileValue(string path, string attribute, string value)
{
XDocument doc;
try
{
doc = XHelper.Load(path);
}
catch
{
doc = new XDocument(new XElement("file"));
}
var root = doc.Element("file");
root.SetAttributeValue(attribute, value);
doc.Save(path);
}
public static string GetState(string dataPath)
{
return GetFileValue(dataPath, "state");
}
public static bool IsReady(string dataPath)
{
return GetState(dataPath) == TaskType.NoTask;
}
public static void WaitForReady(string dataPath, int timeoutSeconds = -1)
{
while (!IsReady(dataPath))
{
if (timeoutSeconds-- == 0) throw new TimeoutException();
Thread.Sleep(1000);
}
}
public static bool? IsFileExtended(string path)
{
if (File.Exists(path)) return true;
if (Directory.Exists(path)) return false;
return null;
}
public static bool IsFile(string path)
{
var result = IsFileExtended(path);
if (result.HasValue) return result.Value;
throw new FileNotFoundException();
}
public static void DeleteWithRetries(string path)
{
retry:
try
{
if (File.Exists(path)) File.Delete(path);
else if (Directory.Exists(path)) Directory.Delete(path, true);
}
catch
{
Thread.Sleep(100);
goto retry;
}
}
public static void DeleteWithRetries(IEnumerable<string> paths)
{
foreach (var path in paths) DeleteWithRetries(path);
}
public static void CancelControl(string dataPath)
{
if (Directory.Exists(dataPath))
{
foreach (var stuff in Directory.EnumerateFileSystemEntries(dataPath)) CancelControl(stuff);
return;
}
if (!File.Exists(dataPath) || !dataPath.EndsWith(".data", true, CultureInfo.InvariantCulture))
return; // ignore non-data files
var element = GetElement(dataPath);
if (element.GetAttributeValue("state") == TaskType.NoTask) return;
CloudTask.KillProcessTree(element.GetAttributeValueWithDefault<int>("pid"));
}
public static void Delete(string path)
{
var filePath = GetFilePath(path);
var isFile = IsFileExtended(filePath);
if (!isFile.HasValue) return;
var dataPath = isFile.Value ? GetDataFilePath(path) : GetDataPath(path);
CancelControl(dataPath);
DeleteWithRetries(GetFilePath(path));
DeleteWithRetries(dataPath);
if (!isFile.Value) return;
string dirPath = GetDataPath(Path.GetDirectoryName(path)), fileName = Path.GetFileName(path);
DeleteWithRetries(Directory.EnumerateFiles(dirPath, fileName + ".incomplete.part*")
.Concat(Directory.EnumerateFiles(dirPath, fileName + ".complete.part*")));
}
public static void SetDefaultMime(string path, string value)
{
SetFileValue(path, "mime", value);
}
}
public static partial class FFmpeg
{
private static readonly string Root, Ffprobe;
private static Process CreateProcess(string path, string arguments)
{
var result = new Process
{
StartInfo = new ProcessStartInfo(path, arguments) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = Root }
};
result.Start();
return result;
}
public static string Analyze(string path)
{
try
{
var process = CreateProcess(Ffprobe, '"' + path + '"');
while (!process.StandardError.ReadLine().StartsWith("Input", StringComparison.Ordinal))
{
}
return process.StandardError.ReadToEnd();
}
catch
{
return "分析失败。";
}
}
public static TimeSpan Parse(string value, TimeSpan defaultValue = default(TimeSpan))
{
if (string.IsNullOrWhiteSpace(value)) return defaultValue;
return value.Contains(":") ? TimeSpan.Parse(value) : TimeSpan.FromSeconds(double.Parse(value));
}
}
public static class Rbase64
{
public static string Encode(string value)
{
return LinkConverter.Base64Encode(LinkConverter.Reverse(value), Encoding.UTF8);
}
public static string Decode(string value)
{
return LinkConverter.Reverse(LinkConverter.Base64Decode(value, Encoding.UTF8));
}
}
}