-
Notifications
You must be signed in to change notification settings - Fork 9
/
GetCheckinLabel.ashx.cs
336 lines (302 loc) · 14.5 KB
/
GetCheckinLabel.ashx.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
// <copyright>
// Copyright by the Spark Development Network
//
// Licensed under the Rock Community License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.rockrms.com/license
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using Rock;
using Rock.Data;
using Rock.Model;
using Rock.Security;
namespace RockWeb
{
/// <summary>
/// Handles retrieving file data from storage
/// </summary>
public class GetCheckinLabel : IHttpAsyncHandler
{
/// <summary>
/// Called to initialize an asynchronous call to the HTTP handler.
/// </summary>
/// <param name="context">An HttpContext that provides references to intrinsic server objects used to service HTTP requests.</param>
/// <param name="cb">The AsyncCallback to call when the asynchronous method call is complete.</param>
/// <param name="extraData">Any state data needed to process the request.</param>
/// <returns>An IAsyncResult that contains information about the status of the process.</returns>
public IAsyncResult BeginProcessRequest( HttpContext context, AsyncCallback cb, object extraData )
{
try
{
// Check to see if this is a BinaryFileType/BinaryFile or just a plain content file (if isBinaryFile not specified, assume it is a BinaryFile)
bool isBinaryFile = ( context.Request.QueryString["isBinaryFile"] ?? "T" ).AsBoolean();
context.Items.Add( "isBinaryFile", isBinaryFile );
if ( isBinaryFile )
{
return BeginProcessBinaryFileRequest( context, cb );
}
else
{
return BeginProcessContentFileRequest( context );
}
}
catch ( Exception ex )
{
ExceptionLogService.LogException( ex, context );
context.Response.StatusCode = 500;
context.Response.StatusDescription = ex.Message;
context.ApplicationInstance.CompleteRequest();
return null;
}
}
/// <summary>
/// Begins the process content file request.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
/// <exception cref="System.Exception">fileName must be specified</exception>
private static IAsyncResult BeginProcessContentFileRequest( HttpContext context )
{
string relativeFilePath = context.Request.QueryString["fileName"];
if ( string.IsNullOrWhiteSpace( relativeFilePath ) )
{
throw new Exception( "fileName must be specified" );
}
return Task.Run( () =>
{
const string RootContentFolder = "~/Content";
string physicalRootFolder = context.Request.MapPath( RootContentFolder );
string physicalContentFileName = Path.Combine( physicalRootFolder, relativeFilePath.TrimStart( new char[] { '/', '\\' } ) );
var sourceStream = File.OpenRead( physicalContentFileName );
context.Items.Add( "fileContents", sourceStream );
context.Items.Add( "physicalContentFileName", physicalContentFileName );
} );
}
/// <summary>
/// Begins the process binary file request.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="cb">The cb.</param>
/// <returns></returns>
/// <exception cref="System.Exception">file id key must be a guid or an int</exception>
private static IAsyncResult BeginProcessBinaryFileRequest( HttpContext context, AsyncCallback cb )
{
int fileId = context.Request.QueryString["id"].AsInteger();
Guid fileGuid = context.Request.QueryString["guid"].AsGuid();
if ( fileId == 0 && fileGuid.Equals( Guid.Empty ) )
{
throw new Exception( "file id key must be a guid or an int" );
}
BinaryFileService binaryFileService = new BinaryFileService( new RockContext() );
if ( fileGuid != Guid.Empty )
{
return binaryFileService.BeginGet( cb, context, fileGuid );
}
else
{
return binaryFileService.BeginGet( cb, context, fileId );
}
}
/// <summary>
/// Provides an end method for an asynchronous process.
/// </summary>
/// <param name="result">An IAsyncResult that contains information about the status of the process.</param>
public void EndProcessRequest( IAsyncResult result )
{
// restore the context from the asyncResult.AsyncState
HttpContext context = (HttpContext)result.AsyncState;
try
{
context.Response.Clear();
bool isBinaryFile = (bool)context.Items["isBinaryFile"];
if ( isBinaryFile )
{
var rockContext = new RockContext();
bool requiresViewSecurity = false;
BinaryFile binaryFile = new BinaryFileService( rockContext ).EndGet( result, context, out requiresViewSecurity );
if ( binaryFile != null )
{
//// if the binaryFile's BinaryFileType requires security, check security
//// note: we put a RequiresViewSecurity flag on BinaryFileType because checking security for every file would be slow (~40ms+ per request)
if ( requiresViewSecurity )
{
var currentUser = new UserLoginService( rockContext ).GetByUserName( UserLogin.GetCurrentUserName() );
Person currentPerson = currentUser != null ? currentUser.Person : null;
binaryFile.BinaryFileType = binaryFile.BinaryFileType ?? new BinaryFileTypeService( rockContext ).Get( binaryFile.BinaryFileTypeId.Value );
if ( !binaryFile.IsAuthorized( Authorization.VIEW, currentPerson ) )
{
SendNotAuthorized( context );
return;
}
}
SendFile( context, binaryFile.ContentStream, binaryFile.MimeType, binaryFile.FileName, binaryFile.Guid.ToString("N") );
return;
}
}
else
{
Stream fileContents = (Stream)context.Items["fileContents"];
string physicalContentFileName = context.Items["physicalContentFileName"] as string;
if ( fileContents != null )
{
string mimeType = System.Web.MimeMapping.GetMimeMapping( physicalContentFileName );
string fileName = Path.GetFileName( physicalContentFileName );
SendFile( context, fileContents, mimeType, fileName, "" );
return;
}
}
context.Response.StatusCode = 404;
context.Response.StatusDescription = "Unable to find the requested file.";
}
catch ( Exception ex )
{
ExceptionLogService.LogException( ex, context );
try
{
context.Response.StatusCode = 500;
context.Response.StatusDescription = ex.Message;
context.Response.Flush();
context.ApplicationInstance.CompleteRequest();
}
catch ( Exception ex2 )
{
ExceptionLogService.LogException( ex2, context );
}
}
}
/// <summary>
/// Sends the file.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="fileContents">The file contents.</param>
/// <param name="mimeType">Type of the MIME.</param>
/// <param name="fileName">Name of the file.</param>
/// <param name="eTag">The e tag.</param>
private void SendFile( HttpContext context, Stream fileContents, string mimeType, string fileName, string eTag )
{
int startIndex = 0;
int fileLength = (int)fileContents.Length;
int responseLength = fileLength;
if (responseLength > 1000000)
{
SendNotAuthorized(context);
return;
}
// resumable logic from http://stackoverflow.com/a/6475414/1755417
if ( context.Request.Headers["Range"] != null && ( context.Request.Headers["If-Range"] == null ) )
{
var match = Regex.Match( context.Request.Headers["Range"], @"bytes=(\d*)-(\d*)" );
startIndex = match.Groups[1].Value.AsInteger();
responseLength = (match.Groups[2].Value.AsIntegerOrNull() + 1 ?? fileLength ) - startIndex;
context.Response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent;
}
context.Response.Clear();
context.Response.Buffer = false;
context.Response.Headers["Accept-Ranges"] = "bytes";
bool sendAsAttachment = context.Request.QueryString["attachment"].AsBooleanOrNull() ?? false;
context.Response.AddHeader( "content-disposition", string.Format( "{1};filename={0}", fileName.MakeValidFileName(), sendAsAttachment ? "attachment" : "inline" ) );
context.Response.Cache.SetCacheability( HttpCacheability.Public ); // required for etag output
context.Response.Cache.SetETag( eTag ); // required for IE9 resumable downloads
context.Response.ContentType = mimeType;
byte[] buffer = new byte[4096];
String labelData = "";
if ( context.Response.IsClientConnected )
{
using ( var fileStream = fileContents )
{
if ( fileStream.CanSeek )
{
fileStream.Seek( startIndex, SeekOrigin.Begin );
}
while ( true )
{
var bytesRead = fileStream.Read( buffer, 0, buffer.Length );
if ( bytesRead == 0 )
{
break;
}
if ( !context.Response.IsClientConnected )
{
// quit sending if the client isn't connected
break;
}
try
{
labelData += System.Text.Encoding.UTF8.GetString( buffer, 0, bytesRead );
}
catch ( HttpException ex )
{
if ( !context.Response.IsClientConnected )
{
// if client disconnected during the .write, ignore
}
else
{
throw ex;
}
}
}
}
if ( context.Response.IsClientConnected )
{
if ( (context.Request.QueryString["delaycut"] ?? "F").AsBoolean() )
{
labelData = labelData.Replace( "^PQ1,1,1,Y", "" );
labelData = labelData.Replace( "^XZ", "^XB^XZ" );
}
byte[] bytes = System.Text.Encoding.UTF8.GetBytes( labelData );
context.Response.AddHeader( "content-length", bytes.Length.ToString() );
if ( context.Request.Headers["Range"] != null && (context.Request.Headers["If-Range"] == null) )
{
context.Response.Headers["Content-Range"] = "bytes " + startIndex + "-" + (startIndex + bytes.Length - 1) + "/" + bytes.Length;
}
context.Response.OutputStream.Write( bytes, 0, bytes.Length );
}
}
context.ApplicationInstance.CompleteRequest();
}
/// <summary>
/// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface.
/// </summary>
/// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
/// <exception cref="System.NotImplementedException"></exception>
public void ProcessRequest( HttpContext context )
{
throw new NotImplementedException( "The method or operation is not implemented. This is an asynchronous file handler." );
}
/// <summary>
/// Sends a 403 (forbidden)
/// </summary>
/// <param name="context">The context.</param>
private void SendNotAuthorized( HttpContext context )
{
context.Response.StatusCode = System.Net.HttpStatusCode.Forbidden.ConvertToInt();
context.Response.StatusDescription = "Not authorized to view file";
context.ApplicationInstance.CompleteRequest();
}
/// <summary>
/// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler" /> instance.
/// </summary>
/// <returns>true if the <see cref="T:System.Web.IHttpHandler" /> instance is reusable; otherwise, false.</returns>
public bool IsReusable
{
get
{
return false;
}
}
}
}