2016-03-04 04:30:13 +00:00
|
|
|
/// A library for parsing HTTP request bodies and queries.
|
2016-03-04 03:47:20 +00:00
|
|
|
library body_parser;
|
|
|
|
|
|
|
|
import 'dart:async';
|
|
|
|
import 'dart:convert';
|
|
|
|
import 'dart:io';
|
|
|
|
|
2016-04-17 19:51:40 +00:00
|
|
|
part 'file_upload_info.dart';
|
|
|
|
|
2016-03-04 03:47:20 +00:00
|
|
|
/// A representation of data from an incoming request.
|
|
|
|
class BodyParseResult {
|
|
|
|
/// The parsed body.
|
|
|
|
Map body = {};
|
|
|
|
|
|
|
|
/// The parsed query string.
|
|
|
|
Map query = {};
|
2016-04-17 03:51:55 +00:00
|
|
|
|
|
|
|
/// All files uploaded within this request.
|
2016-04-17 19:51:40 +00:00
|
|
|
List<FileUploadInfo> files = [];
|
2016-03-04 03:47:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Grabs data from an incoming request.
|
|
|
|
///
|
2016-04-17 19:51:40 +00:00
|
|
|
/// Supports urlencoded and JSON, as well as multipart/form-data uploads.
|
|
|
|
/// On a file upload request, only fields with the name **'file'** are processed
|
|
|
|
/// as files. Anything else is put in the body. You can change the upload file name
|
|
|
|
/// via the *fileUploadName* parameter. :)
|
|
|
|
Future<BodyParseResult> parseBody(HttpRequest request,
|
|
|
|
{String fileUploadName: 'file'}) async {
|
2016-03-04 03:47:20 +00:00
|
|
|
BodyParseResult result = new BodyParseResult();
|
|
|
|
ContentType contentType = request.headers.contentType;
|
|
|
|
|
|
|
|
// Parse body
|
|
|
|
if (contentType != null) {
|
|
|
|
if (contentType.mimeType == 'application/json')
|
|
|
|
result.body = JSON.decode(await request.transform(UTF8.decoder).join());
|
|
|
|
else if (contentType.mimeType == 'application/x-www-form-urlencoded') {
|
|
|
|
String body = await request.transform(UTF8.decoder).join();
|
|
|
|
buildMapFromUri(result.body, body);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Parse query
|
|
|
|
RegExp queryRgx = new RegExp(r'\?(.+)$');
|
|
|
|
String uriString = request.requestedUri.toString();
|
|
|
|
if (queryRgx.hasMatch(uriString)) {
|
|
|
|
Match queryMatch = queryRgx.firstMatch(uriString);
|
|
|
|
buildMapFromUri(result.query, queryMatch.group(1));
|
|
|
|
}
|
|
|
|
|
2016-04-17 03:51:55 +00:00
|
|
|
// Accept file
|
|
|
|
if (contentType != null && request.method == 'POST') {
|
|
|
|
RegExp parseBoundaryRgx = new RegExp(
|
2016-04-17 19:51:40 +00:00
|
|
|
r'multipart\/form-data;\s*boundary=([^\s;]+)');
|
2016-04-17 03:51:55 +00:00
|
|
|
if (parseBoundaryRgx.hasMatch(contentType.toString())) {
|
|
|
|
Match boundaryMatch = parseBoundaryRgx.firstMatch(contentType.toString());
|
2016-04-17 19:51:40 +00:00
|
|
|
String boundary = boundaryMatch.group(1);
|
2016-04-17 03:51:55 +00:00
|
|
|
String body = await request.transform(UTF8.decoder).join();
|
2016-04-17 19:51:40 +00:00
|
|
|
for (String chunk in body.split(boundary)) {
|
|
|
|
var fileData = getFileDataFromChunk(
|
|
|
|
chunk, boundary, fileUploadName, result.body);
|
2016-04-17 03:51:55 +00:00
|
|
|
if (fileData != null)
|
2016-04-17 19:51:40 +00:00
|
|
|
fileData.forEach((x) => result.files.add(x));
|
2016-04-17 03:51:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-03-04 03:47:20 +00:00
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2016-04-17 03:51:55 +00:00
|
|
|
/// Parses file data from a multipart/form-data chunk.
|
2016-04-17 19:51:40 +00:00
|
|
|
List<FileUploadInfo> getFileDataFromChunk(String chunk, String boundary, String fileUploadName,
|
|
|
|
Map body) {
|
|
|
|
FileUploadInfo result = new FileUploadInfo();
|
2016-04-17 03:51:55 +00:00
|
|
|
RegExp isFormDataRgx = new RegExp(
|
2016-04-17 19:51:40 +00:00
|
|
|
r'Content-Disposition:\s*([^;]+);\s*name="([^"]+)"');
|
2016-04-17 03:51:55 +00:00
|
|
|
|
|
|
|
if (isFormDataRgx.hasMatch(chunk)) {
|
2016-04-17 19:51:40 +00:00
|
|
|
Match formDataMatch = isFormDataRgx.firstMatch(chunk);
|
|
|
|
String disposition = formDataMatch.group(1);
|
|
|
|
String name = formDataMatch.group(2);
|
|
|
|
String restOfChunk = chunk.substring(formDataMatch.end);
|
|
|
|
|
|
|
|
RegExp parseFilenameRgx = new RegExp(r'filename="([^"]+)"');
|
|
|
|
if (parseFilenameRgx.hasMatch(chunk)) {
|
|
|
|
result.filename = parseFilenameRgx.firstMatch(chunk).group(1);
|
|
|
|
}
|
2016-04-17 03:51:55 +00:00
|
|
|
|
2016-04-17 19:51:40 +00:00
|
|
|
RegExp contentTypeRgx = new RegExp(r'Content-Type:\s*([^\r\n]+)\r\n');
|
|
|
|
if (contentTypeRgx.hasMatch(restOfChunk)) {
|
|
|
|
Match contentTypeMatch = contentTypeRgx.firstMatch(restOfChunk);
|
|
|
|
restOfChunk = restOfChunk.substring(contentTypeMatch.end);
|
|
|
|
result.mimeType = contentTypeMatch.group(1);
|
|
|
|
} else restOfChunk = restOfChunk.replaceAll(new RegExp(r'^(\r\n)+'), "");
|
|
|
|
|
|
|
|
restOfChunk = restOfChunk
|
|
|
|
.replaceAll(boundary, "")
|
|
|
|
.replaceFirst(new RegExp(r'\r\n$'), "");
|
|
|
|
|
|
|
|
if (disposition == 'file' && name == fileUploadName) {
|
|
|
|
result.name = name;
|
|
|
|
result.data = UTF8.encode(restOfChunk);
|
|
|
|
return [result];
|
|
|
|
} else {
|
|
|
|
buildMapFromUri(body, "$name=$restOfChunk");
|
|
|
|
return null;
|
2016-04-17 03:51:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2016-03-04 03:47:20 +00:00
|
|
|
/// Parses a URI-encoded string into real data! **Wow!**
|
2016-03-04 04:35:59 +00:00
|
|
|
///
|
|
|
|
/// Whichever map you provide will be automatically populated from the urlencoded body string you provide.
|
2016-03-04 03:47:20 +00:00
|
|
|
buildMapFromUri(Map map, String body) {
|
2016-04-17 03:51:55 +00:00
|
|
|
RegExp parseArrayRgx = new RegExp(r'^(.+)\[\]$');
|
2016-04-17 03:07:59 +00:00
|
|
|
|
2016-03-04 03:47:20 +00:00
|
|
|
for (String keyValuePair in body.split('&')) {
|
|
|
|
if (keyValuePair.contains('=')) {
|
|
|
|
List<String> split = keyValuePair.split('=');
|
|
|
|
String key = Uri.decodeQueryComponent(split[0]);
|
|
|
|
String value = Uri.decodeQueryComponent(split[1]);
|
2016-04-17 03:07:59 +00:00
|
|
|
|
2016-04-17 03:51:55 +00:00
|
|
|
if (parseArrayRgx.hasMatch(key)) {
|
|
|
|
Match queryMatch = parseArrayRgx.firstMatch(key);
|
2016-04-17 03:07:59 +00:00
|
|
|
key = queryMatch.group(1);
|
|
|
|
if (!(map[key] is List)) {
|
|
|
|
map[key] = [];
|
|
|
|
}
|
|
|
|
|
|
|
|
map[key].add(getValue(value));
|
2016-04-17 03:51:55 +00:00
|
|
|
} else if (key.contains('.')) {
|
2016-04-17 03:07:59 +00:00
|
|
|
// i.e. map.foo.bar => [map, foo, bar]
|
|
|
|
List<String> keys = key.split('.');
|
|
|
|
|
|
|
|
Map targetMap = map[keys[0]] ?? {};
|
|
|
|
map[keys[0]] = targetMap;
|
|
|
|
for (int i = 1; i < keys.length; i++) {
|
|
|
|
if (i < keys.length - 1) {
|
|
|
|
targetMap[keys[i]] = targetMap[keys[i]] ?? {};
|
|
|
|
targetMap = targetMap[keys[i]];
|
|
|
|
} else {
|
|
|
|
targetMap[keys[i]] = getValue(value);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else map[key] = getValue(value);
|
2016-03-04 03:47:20 +00:00
|
|
|
} else map[Uri.decodeQueryComponent(keyValuePair)] = true;
|
|
|
|
}
|
2016-04-17 03:07:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
getValue(String value) {
|
|
|
|
num numValue = num.parse(value, (_) => double.NAN);
|
|
|
|
if (!numValue.isNaN)
|
|
|
|
return numValue;
|
|
|
|
else if (value.startsWith('[') && value.endsWith(']'))
|
|
|
|
return JSON.decode(value);
|
|
|
|
else if (value.startsWith('{') && value.endsWith('}'))
|
|
|
|
return JSON.decode(value);
|
|
|
|
else if (value.trim().toLowerCase() == 'null')
|
|
|
|
return null;
|
|
|
|
else return value;
|
2016-03-04 03:47:20 +00:00
|
|
|
}
|