Commit 435892ff authored by hirono's avatar hirono Committed by Commit bot

Drive: Add multipart related utility methods.

The CL extracts existing code as utility methods so that they can be used by
newly added BatchRequest class.

BUG=451917
TEST=None

Review URL: https://codereview.chromium.org/1053623004

Cr-Commit-Position: refs/heads/master@{#323892}
parent fe2e7c82
...@@ -55,17 +55,27 @@ const char kUploadResponseLocation[] = "location"; ...@@ -55,17 +55,27 @@ const char kUploadResponseLocation[] = "location";
const char kUploadContentRange[] = "Content-Range: bytes "; const char kUploadContentRange[] = "Content-Range: bytes ";
const char kUploadResponseRange[] = "range"; const char kUploadResponseRange[] = "range";
// The prefix of multipart/related mime type. // Mime type of JSON.
const char kMultipartMimeTypePrefix[] = "multipart/related; boundary="; const char kJsonMimeType[] = "application/json";
// Template for multipart request body. // Mime type of multipart related.
const char kMessageFormatBeforeFile[] = const char kMultipartRelatedMimeTypePrefix[] =
"--%s\nContent-Type: %s\n\n%s\n--%s\nContent-Type: %s\n\n"; "multipart/related; boundary=";
const char kMessageFormatAfterFile[] = "\n--%s--";
// Mime type of multipart mixed.
const char kMultipartMixedMimeTypePrefix[] =
"multipart/mixed; boundary=";
// Header for each item in a multipart message.
const char kMultipartItemHeaderFormat[] = "--%s\nContent-Type: %s\n\n";
// Footer for whole multipart message.
const char kMultipartFooterFormat[] = "--%s--";
// Characters to be used for multipart/related boundary. // Characters to be used for multipart/related boundary.
const char kBoundaryCharacters[] = const char kBoundaryCharacters[] =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Size of multipart/related's boundary. // Size of multipart/related's boundary.
const char kBoundarySize = 70; const char kBoundarySize = 70;
...@@ -102,10 +112,6 @@ std::string GetResponseHeadersAsString(const URLFetcher* url_fetcher) { ...@@ -102,10 +112,6 @@ std::string GetResponseHeadersAsString(const URLFetcher* url_fetcher) {
return headers; return headers;
} }
bool IsSuccessfulResponseCode(int response_code) {
return 200 <= response_code && response_code <= 299;
}
// Obtains the multipart body for the metadata string and file contents. If // Obtains the multipart body for the metadata string and file contents. If
// predetermined_boundary is empty, the function generates the boundary string. // predetermined_boundary is empty, the function generates the boundary string.
bool GetMultipartContent(const std::string& predetermined_boundary, bool GetMultipartContent(const std::string& predetermined_boundary,
...@@ -114,36 +120,18 @@ bool GetMultipartContent(const std::string& predetermined_boundary, ...@@ -114,36 +120,18 @@ bool GetMultipartContent(const std::string& predetermined_boundary,
const base::FilePath& path, const base::FilePath& path,
std::string* upload_content_type, std::string* upload_content_type,
std::string* upload_content_data) { std::string* upload_content_data) {
std::string file_content; std::vector<google_apis::ContentTypeAndData> parts(2);
if (!ReadFileToString(path, &file_content)) parts[0].type = kJsonMimeType;
parts[0].data = metadata_json;
parts[1].type = content_type;
if (!ReadFileToString(path, &parts[1].data))
return false; return false;
std::string boundary; google_apis::ContentTypeAndData output;
if (predetermined_boundary.empty()) { GenerateMultipartBody(
while (true) { google_apis::MULTIPART_RELATED, predetermined_boundary, parts, &output);
boundary.resize(kBoundarySize); upload_content_type->swap(output.type);
for (int i = 0; i < kBoundarySize; ++i) { upload_content_data->swap(output.data);
// Subtract 2 from the array size to exclude '\0', and to turn the size
// into the last index.
const int last_char_index = arraysize(kBoundaryCharacters) - 2;
boundary[i] = kBoundaryCharacters[base::RandInt(0, last_char_index)];
}
if (metadata_json.find(boundary, 0) == std::string::npos &&
file_content.find(boundary, 0) == std::string::npos) {
break;
}
}
} else {
boundary = predetermined_boundary;
}
const std::string body_before_file = base::StringPrintf(
kMessageFormatBeforeFile, boundary.c_str(), "application/json",
metadata_json.c_str(), boundary.c_str(), content_type.c_str());
const std::string body_after_file =
base::StringPrintf(kMessageFormatAfterFile, boundary.c_str());
*upload_content_type = kMultipartMimeTypePrefix + boundary;
*upload_content_data = body_before_file + file_content + body_after_file;
return true; return true;
} }
...@@ -175,6 +163,55 @@ scoped_ptr<base::Value> ParseJson(const std::string& json) { ...@@ -175,6 +163,55 @@ scoped_ptr<base::Value> ParseJson(const std::string& json) {
return value.Pass(); return value.Pass();
} }
void GenerateMultipartBody(MultipartType multipart_type,
const std::string& predetermined_boundary,
const std::vector<ContentTypeAndData>& parts,
ContentTypeAndData* output) {
std::string boundary;
// Generate random boundary.
if (predetermined_boundary.empty()) {
while (true) {
boundary.resize(kBoundarySize);
for (int i = 0; i < kBoundarySize; ++i) {
// Subtract 2 from the array size to exclude '\0', and to turn the size
// into the last index.
const int last_char_index = arraysize(kBoundaryCharacters) - 2;
boundary[i] = kBoundaryCharacters[base::RandInt(0, last_char_index)];
}
bool conflict_with_content = false;
for (auto& part : parts) {
if (part.data.find(boundary, 0) != std::string::npos) {
conflict_with_content = true;
break;
}
}
if (!conflict_with_content)
break;
}
} else {
boundary = predetermined_boundary;
}
switch (multipart_type) {
case MULTIPART_RELATED:
output->type = kMultipartRelatedMimeTypePrefix + boundary;
break;
case MULTIPART_MIXED:
output->type = kMultipartMixedMimeTypePrefix + boundary;
break;
}
output->data.clear();
for (auto& part : parts) {
output->data.append(base::StringPrintf(
kMultipartItemHeaderFormat, boundary.c_str(), part.type.c_str()));
output->data.append(part.data);
output->data.append("\n");
}
output->data.append(
base::StringPrintf(kMultipartFooterFormat, boundary.c_str()));
}
//=========================== ResponseWriter ================================== //=========================== ResponseWriter ==================================
ResponseWriter::ResponseWriter(base::SequencedTaskRunner* file_task_runner, ResponseWriter::ResponseWriter(base::SequencedTaskRunner* file_task_runner,
const base::FilePath& file_path, const base::FilePath& file_path,
...@@ -294,7 +331,7 @@ void UrlFetchRequestBase::StartAfterPrepare( ...@@ -294,7 +331,7 @@ void UrlFetchRequestBase::StartAfterPrepare(
const GURL url = GetURL(); const GURL url = GetURL();
DriveApiErrorCode error_code; DriveApiErrorCode error_code;
if (code != HTTP_SUCCESS && code != HTTP_CREATED && code != HTTP_NO_CONTENT) if (IsSuccessfulDriveApiErrorCode(code))
error_code = code; error_code = code;
else if (url.is_empty()) else if (url.is_empty())
error_code = DRIVE_OTHER_ERROR; error_code = DRIVE_OTHER_ERROR;
...@@ -449,7 +486,7 @@ void UrlFetchRequestBase::OnURLFetchComplete(const URLFetcher* source) { ...@@ -449,7 +486,7 @@ void UrlFetchRequestBase::OnURLFetchComplete(const URLFetcher* source) {
// The server may return detailed error status in JSON. // The server may return detailed error status in JSON.
// See https://developers.google.com/drive/handle-errors // See https://developers.google.com/drive/handle-errors
if (!IsSuccessfulResponseCode(error_code_)) { if (!IsSuccessfulDriveApiErrorCode(error_code_)) {
DVLOG(1) << response_writer_->data(); DVLOG(1) << response_writer_->data();
const char kErrorKey[] = "error"; const char kErrorKey[] = "error";
......
...@@ -30,6 +30,18 @@ namespace google_apis { ...@@ -30,6 +30,18 @@ namespace google_apis {
class FileResource; class FileResource;
class RequestSender; class RequestSender;
// Content type for multipart body.
enum MultipartType {
MULTIPART_RELATED,
MULTIPART_MIXED
};
// Pair of content type and data.
struct ContentTypeAndData {
std::string type;
std::string data;
};
typedef base::Callback<void(DriveApiErrorCode)> PrepareCallback; typedef base::Callback<void(DriveApiErrorCode)> PrepareCallback;
// Callback used for requests that the server returns FileResource data // Callback used for requests that the server returns FileResource data
...@@ -49,6 +61,14 @@ typedef base::Callback<void( ...@@ -49,6 +61,14 @@ typedef base::Callback<void(
// Parses JSON passed in |json|. Returns NULL on failure. // Parses JSON passed in |json|. Returns NULL on failure.
scoped_ptr<base::Value> ParseJson(const std::string& json); scoped_ptr<base::Value> ParseJson(const std::string& json);
// Generate multipart body. If |predetermined_boundary| is not empty, it uses
// the string as boundary. Otherwise it generates random boundary that does not
// conflict with |parts|.
void GenerateMultipartBody(MultipartType multipart_type,
const std::string& predetermined_boundary,
const std::vector<ContentTypeAndData>& parts,
ContentTypeAndData* output);
//======================= AuthenticatedRequestInterface ====================== //======================= AuthenticatedRequestInterface ======================
// An interface class for implementing a request which requires OAuth2 // An interface class for implementing a request which requires OAuth2
......
...@@ -90,4 +90,8 @@ std::string DriveApiErrorCodeToString(DriveApiErrorCode error) { ...@@ -90,4 +90,8 @@ std::string DriveApiErrorCodeToString(DriveApiErrorCode error) {
return "UNKNOWN_ERROR_" + base::IntToString(error); return "UNKNOWN_ERROR_" + base::IntToString(error);
} }
bool IsSuccessfulDriveApiErrorCode(DriveApiErrorCode error) {
return 200 <= error && error <= 299;
}
} // namespace google_apis } // namespace google_apis
...@@ -41,6 +41,9 @@ enum DriveApiErrorCode { ...@@ -41,6 +41,9 @@ enum DriveApiErrorCode {
// Returns a string representation of DriveApiErrorCode. // Returns a string representation of DriveApiErrorCode.
std::string DriveApiErrorCodeToString(DriveApiErrorCode error); std::string DriveApiErrorCodeToString(DriveApiErrorCode error);
// Checks if the error code represents success.
bool IsSuccessfulDriveApiErrorCode(DriveApiErrorCode error);
} // namespace google_apis } // namespace google_apis
#endif // GOOGLE_APIS_DRIVE_DRIVE_API_ERROR_CODES_H_ #endif // GOOGLE_APIS_DRIVE_DRIVE_API_ERROR_CODES_H_
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment