Work around unreliable metadata for HLS in WebMediaPlayerAndroid
[chromium-blink-merge.git] / components / safe_json / json_sanitizer.cc
blobe00043e779804b4afc2c9fd554114424c5f8af29
1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/safe_json/json_sanitizer.h"
7 #if defined(OS_ANDROID)
8 #error Build json_sanitizer_android.cc instead of this file on Android.
9 #endif
11 #include "base/bind.h"
12 #include "base/callback.h"
13 #include "base/json/json_writer.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/strings/string_util.h"
16 #include "base/values.h"
17 #include "components/safe_json/safe_json_parser.h"
19 namespace safe_json {
21 namespace {
23 class OopJsonSanitizer : public JsonSanitizer {
24 public:
25 OopJsonSanitizer(const std::string& unsafe_json,
26 const StringCallback& success_callback,
27 const StringCallback& error_callback);
29 private:
30 friend struct base::DefaultDeleter<OopJsonSanitizer>;
31 ~OopJsonSanitizer() {}
33 void OnParseSuccess(scoped_ptr<base::Value> value);
34 void OnParseError(const std::string& error);
36 StringCallback success_callback_;
37 StringCallback error_callback_;
39 DISALLOW_COPY_AND_ASSIGN(OopJsonSanitizer);
42 OopJsonSanitizer::OopJsonSanitizer(const std::string& unsafe_json,
43 const StringCallback& success_callback,
44 const StringCallback& error_callback)
45 : success_callback_(success_callback), error_callback_(error_callback) {
46 SafeJsonParser::Parse(unsafe_json,
47 base::Bind(&OopJsonSanitizer::OnParseSuccess,
48 base::Unretained(this)),
49 base::Bind(&OopJsonSanitizer::OnParseError,
50 base::Unretained(this)));
53 void OopJsonSanitizer::OnParseSuccess(scoped_ptr<base::Value> value) {
54 // Self-destruct at the end of this method.
55 scoped_ptr<OopJsonSanitizer> deleter(this);
57 // A valid JSON document may only have a dictionary or list as its top-level
58 // type, but the JSON parser also accepts other types, so we filter them out.
59 base::Value::Type type = value->GetType();
60 if (type != base::Value::TYPE_DICTIONARY && type != base::Value::TYPE_LIST) {
61 error_callback_.Run("Invalid top-level type");
62 return;
65 std::string json;
66 if (!base::JSONWriter::Write(*value, &json)) {
67 error_callback_.Run("Encoding error");
68 return;
71 success_callback_.Run(json);
74 void OopJsonSanitizer::OnParseError(const std::string& error) {
75 error_callback_.Run("Parse error: " + error);
76 delete this;
79 } // namespace
81 // static
82 void JsonSanitizer::Sanitize(const std::string& unsafe_json,
83 const StringCallback& success_callback,
84 const StringCallback& error_callback) {
85 // OopJsonSanitizer destroys itself when it is finished.
86 new OopJsonSanitizer(unsafe_json, success_callback, error_callback);
89 } // namespace safe_json