blob: 0c80a21861f3199e86ca187760aa2bc494d68814 [file] [log] [blame]
Alex Vakulenkoc70c04e2015-09-25 11:23:00 -07001// Copyright 2015 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include <libwebserv/request_utils.h>
16
17#include <base/bind.h>
18#include <chromeos/streams/memory_stream.h>
19#include <chromeos/streams/stream_utils.h>
20#include <libwebserv/request.h>
21#include <libwebserv/response.h>
22
23namespace libwebserv {
24
25namespace {
26
27struct RequestDataContainer {
28 std::unique_ptr<Request> request;
29 std::unique_ptr<Response> response;
30 GetRequestDataSuccessCallback success_callback;
31 GetRequestDataErrorCallback error_callback;
32 std::vector<uint8_t> data;
33};
34
35void OnCopySuccess(std::shared_ptr<RequestDataContainer> container,
36 chromeos::StreamPtr in_stream, chromeos::StreamPtr out_stream,
37 uint64_t size_copied) {
38 // Close/release the memory stream so we can work with underlying data buffer.
39 out_stream->CloseBlocking(nullptr);
40 out_stream.reset();
41 container->success_callback.Run(std::move(container->request),
42 std::move(container->response),
43 std::move(container->data));
44}
45
46void OnCopyError(std::shared_ptr<RequestDataContainer> container,
47 chromeos::StreamPtr in_stream, chromeos::StreamPtr out_stream,
48 const chromeos::Error* error) {
49 container->error_callback.Run(std::move(container->request),
50 std::move(container->response), error);
51}
52
53} // anonymous namespace
54
55void GetRequestData(std::unique_ptr<Request> request,
56 std::unique_ptr<Response> response,
57 const GetRequestDataSuccessCallback& success_callback,
58 const GetRequestDataErrorCallback& error_callback) {
59 auto container = std::make_shared<RequestDataContainer>();
60 auto in_stream = request->GetDataStream();
61 auto out_stream =
62 chromeos::MemoryStream::CreateRef(&container->data, nullptr);
63 container->request = std::move(request);
64 container->response = std::move(response);
65 container->success_callback = success_callback;
66 container->error_callback = error_callback;
67 chromeos::stream_utils::CopyData(std::move(in_stream), std::move(out_stream),
68 base::Bind(&OnCopySuccess, container),
69 base::Bind(&OnCopyError, container));
70}
71
72} // namespace libwebserv