-
Notifications
You must be signed in to change notification settings - Fork 756
/
Copy pathFileProvider.cs
345 lines (302 loc) · 12.5 KB
/
FileProvider.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Services.OutputCache.Providers
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using DotNetNuke.Collections.Internal;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Services.Log.EventLog;
/// <summary>
/// FileProvider implements the OutputCachingProvider for file storage.
/// </summary>
public class FileProvider : OutputCachingProvider
{
public const string DataFileExtension = ".data.resources";
public const string AttribFileExtension = ".attrib.resources";
public const string TempFileExtension = ".temp.resources";
private static readonly SharedDictionary<int, string> CacheFolderPath = new SharedDictionary<int, string>(LockingStrategy.ReaderWriter);
/// <inheritdoc/>
public override int GetItemCount(int tabId)
{
return GetCachedItemCount(tabId);
}
/// <inheritdoc/>
public override byte[] GetOutput(int tabId, string cacheKey)
{
string cachedOutput = GetCachedOutputFileName(tabId, cacheKey);
if (!File.Exists(cachedOutput))
{
return null;
}
var fInfo = new FileInfo(cachedOutput);
long numBytes = fInfo.Length;
using (var fStream = new FileStream(cachedOutput, FileMode.Open, FileAccess.Read))
using (var br = new BinaryReader(fStream))
{
return br.ReadBytes(Convert.ToInt32(numBytes));
}
}
/// <inheritdoc/>
public override OutputCacheResponseFilter GetResponseFilter(int tabId, int maxVaryByCount, Stream responseFilter, string cacheKey, TimeSpan cacheDuration)
{
return new FileResponseFilter(tabId, maxVaryByCount, responseFilter, cacheKey, cacheDuration);
}
/// <inheritdoc/>
public override void PurgeCache(int portalId)
{
string cacheFolder = GetCacheFolder(portalId);
if (!string.IsNullOrEmpty(cacheFolder))
{
this.PurgeCache(cacheFolder);
}
}
/// <inheritdoc/>
public override void PurgeExpiredItems(int portalId)
{
var filesNotDeleted = new StringBuilder();
int i = 0;
string cacheFolder = GetCacheFolder(portalId);
if (!string.IsNullOrEmpty(cacheFolder))
{
foreach (string file in Directory.GetFiles(cacheFolder, "*" + AttribFileExtension))
{
if (this.IsFileExpired(file))
{
string fileToDelete = file.Replace(AttribFileExtension, DataFileExtension);
if (!FileSystemUtils.DeleteFileWithWait(fileToDelete, 100, 200))
{
filesNotDeleted.Append(fileToDelete + ";");
}
else
{
i += 1;
}
}
}
if (filesNotDeleted.Length > 0)
{
throw new IOException("Deleted " + i + " files, however, some files are locked. Could not delete the following files: " + filesNotDeleted);
}
}
}
/// <inheritdoc/>
public override void Remove(int tabId)
{
try
{
Dictionary<int, int> portals = PortalController.GetPortalDictionary();
if (portals.ContainsKey(tabId) && portals[tabId] > Null.NullInteger)
{
var filesNotDeleted = new StringBuilder();
int i = 0;
string cacheFolder = GetCacheFolder(portals[tabId]);
if (!string.IsNullOrEmpty(cacheFolder))
{
foreach (string file in Directory.GetFiles(cacheFolder, string.Concat(tabId, "_*.*")))
{
if (!FileSystemUtils.DeleteFileWithWait(file, 100, 200))
{
filesNotDeleted.Append(string.Concat(file, ";"));
}
else
{
i += 1;
}
}
if (filesNotDeleted.Length > 0)
{
var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() };
var logDetail = new LogDetailInfo
{
PropertyName = "FileOutputCacheProvider",
PropertyValue =
string.Format(
"Deleted {0} files, however, some files are locked. Could not delete the following files: {1}",
i, filesNotDeleted),
};
var properties = new LogProperties { logDetail };
log.LogProperties = properties;
LogController.Instance.AddLog(log);
}
}
}
}
catch (Exception ex)
{
Exceptions.Exceptions.LogException(ex);
}
}
/// <inheritdoc/>
public override void SetOutput(int tabId, string cacheKey, TimeSpan duration, byte[] output)
{
string attribFile = GetAttribFileName(tabId, cacheKey);
string cachedOutputFile = GetCachedOutputFileName(tabId, cacheKey);
try
{
if (File.Exists(cachedOutputFile))
{
FileSystemUtils.DeleteFileWithWait(cachedOutputFile, 100, 200);
}
using (var captureStream = new FileStream(cachedOutputFile, FileMode.CreateNew, FileAccess.Write))
{
captureStream.Write(output, 0, output.Length);
captureStream.Close();
}
using (var oWrite = File.CreateText(attribFile))
{
var currentCulture = CultureInfo.CurrentCulture.DateTimeFormat;
var currentCultureX = CultureInfo.DefaultThreadCurrentCulture.DateTimeFormat;
var datetimeUtc = DateTime.UtcNow.Add(duration).ToString(CultureInfo.InvariantCulture);
var datetime1 = DateTime.UtcNow.Add(duration).ToString();
var datetime2 = DateTime.UtcNow.Add(duration).ToString();
oWrite.WriteLine(DateTime.UtcNow.Add(duration).ToString(CultureInfo.InvariantCulture));
oWrite.Close();
}
}
catch (Exception ex)
{
// TODO: Need to implement multi-threading.
// The current code is not thread safe and threw error if two threads tried creating cache file
// A thread could create a file between the time another thread deleted it and tried to create new cache file.
// This would result in a system.IO.IOException. Also, there was no error handling in place so the
// Error would bubble up to the user and provide details on the file structure of the site.
Exceptions.Exceptions.LogException(ex);
}
}
/// <inheritdoc/>
public override bool StreamOutput(int tabId, string cacheKey, HttpContext context)
{
bool foundFile = false;
try
{
string attribFile = GetAttribFileName(tabId, cacheKey);
if (!File.Exists(attribFile))
{
return false;
}
string captureFile = GetCachedOutputFileName(tabId, cacheKey);
StreamReader oRead = File.OpenText(attribFile);
DateTime expires = Convert.ToDateTime(oRead.ReadLine());
oRead.Close();
if (expires < DateTime.UtcNow)
{
FileSystemUtils.DeleteFileWithWait(attribFile, 100, 200);
FileSystemUtils.DeleteFileWithWait(captureFile, 100, 200);
return false;
}
context.Response.WriteFile(captureFile);
foundFile = true;
}
catch (Exception ex)
{
Exceptions.Exceptions.LogException(ex);
}
return foundFile;
}
internal static string GetAttribFileName(int tabId, string cacheKey)
{
return string.Concat(GetCacheFolder(), cacheKey, AttribFileExtension);
}
internal static int GetCachedItemCount(int tabId)
{
return Directory.GetFiles(GetCacheFolder(), $"{tabId}_*{DataFileExtension}").Length;
}
internal static string GetCachedOutputFileName(int tabId, string cacheKey)
{
return string.Concat(GetCacheFolder(), cacheKey, DataFileExtension);
}
internal static string GetTempFileName(int tabId, string cacheKey)
{
return string.Concat(GetCacheFolder(), cacheKey, TempFileExtension);
}
private static string GetCacheFolder()
{
int portalId = PortalController.Instance.GetCurrentPortalSettings().PortalId;
return GetCacheFolder(portalId);
}
private static string GetCacheFolder(int portalId)
{
string cacheFolder;
using (var readerLock = CacheFolderPath.GetReadLock())
{
if (CacheFolderPath.TryGetValue(portalId, out cacheFolder))
{
return cacheFolder;
}
}
var portalInfo = PortalController.Instance.GetPortal(portalId);
string homeDirectoryMapPath = portalInfo.HomeSystemDirectoryMapPath;
if (!string.IsNullOrEmpty(homeDirectoryMapPath))
{
cacheFolder = string.Concat(homeDirectoryMapPath, "Cache\\Pages\\");
if (!Directory.Exists(cacheFolder))
{
Directory.CreateDirectory(cacheFolder);
}
}
using (var writerLock = CacheFolderPath.GetWriteLock())
{
CacheFolderPath.Add(portalId, cacheFolder);
}
return cacheFolder;
}
private bool IsFileExpired(string file)
{
StreamReader oRead = null;
try
{
oRead = File.OpenText(file);
DateTime expires = Convert.ToDateTime(oRead.ReadLine());
if (expires < DateTime.UtcNow)
{
return true;
}
else
{
return false;
}
}
finally
{
if (oRead != null)
{
oRead.Close();
}
}
}
private void PurgeCache(string folder)
{
try
{
var filesNotDeleted = new StringBuilder();
int i = 0;
foreach (string file in Directory.GetFiles(folder, "*.resources"))
{
if (!FileSystemUtils.DeleteFileWithWait(file, 100, 200))
{
filesNotDeleted.Append(file + ";");
}
else
{
i += 1;
}
}
if (filesNotDeleted.Length > 0)
{
throw new IOException("Deleted " + i + " files, however, some files are locked. Could not delete the following files: " + filesNotDeleted);
}
}
catch (Exception ex)
{
Exceptions.Exceptions.LogException(ex);
}
}
}
}