diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index c190ea5c9ec..b7a5cf0ae0d 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -3,7 +3,6 @@ patches/ @brave/patch-reviewers chromium_src/ @brave/chromium-src-reviewers script/build-bisect.py @bsclifton script/uplift.py @bsclifton -vendor/brave-ios/ @kylehickinson /README.md @bsclifton Jenkinsfile @mihaiplesa DEPS @brave/deps-reviewers @@ -106,3 +105,8 @@ third_party/bitcoin-core/BUILD.gn @orspetol # Network auditor build/commands/lib/whitelistedUrlPatterns.js @brave/sec-team build/commands/lib/whitelistedUrlPrefixes.js @brave/sec-team + +# iOS +ios/ @brave/ios +build/ios/ @brave/ios + diff --git a/.gitignore b/.gitignore index a2107e00f17..c93c9bc16c3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,6 @@ /vendor/* !/vendor/bat-native-ledger !/vendor/bat-native-ads -!/vendor/brave-ios -!/vendor/CPPLINT.cfg .DS_Store .tags* /.idea/ diff --git a/build/commands/lib/config.js b/build/commands/lib/config.js index 0e0eace9c0f..f291a000018 100755 --- a/build/commands/lib/config.js +++ b/build/commands/lib/config.js @@ -720,7 +720,7 @@ Config.prototype.update = function (options) { if (options.xcode_gen) { assert(process.platform === 'darwin' || options.target_os === 'ios') if (options.xcode_gen === 'ios') { - this.xcode_gen_target = '//brave/vendor/brave-ios:*' + this.xcode_gen_target = '//brave/ios:*' } else { this.xcode_gen_target = options.xcode_gen } diff --git a/build/ios/BUILD.gn b/build/ios/BUILD.gn index 0ac64e334db..1d41d4afe28 100644 --- a/build/ios/BUILD.gn +++ b/build/ios/BUILD.gn @@ -1,5 +1,5 @@ import("//brave/build/config.gni") group("brave") { - deps = [ "//brave/vendor/brave-ios" ] + deps = [ "//brave/ios:brave_ios" ] } diff --git a/build/ios/coredata_model.gni b/build/ios/coredata_model.gni new file mode 100644 index 00000000000..4e32635f70e --- /dev/null +++ b/build/ios/coredata_model.gni @@ -0,0 +1,41 @@ +# Copyright (c) 2021 The Brave Authors. All rights reserved. +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this file, +# You can obtain one at http://mozilla.org/MPL/2.0/. + +import("//build/config/ios/ios_sdk.gni") + +# Template to compile an .xcdatamodeld file +# +# Arguments +# +# model_file +# path to .xcdatamodeld file that must be compiled +# +template("coredata_model") { + assert(defined(invoker.model_file) && invoker.model_file != "", + "model_file must be defined for $target_name") + + _compile_model_target = "${target_name}_compile_model" + _compile_model_output = + "$target_gen_dir/" + get_path_info(invoker.model_file, "name") + ".momd" + + action(_compile_model_target) { + script = "//build/apple/xcrun.py" + inputs = [ invoker.model_file ] + outputs = [ _compile_model_output ] + args = [ + "momc", + "--action", + "compile", + rebase_path(invoker.model_file, root_build_dir), + rebase_path(target_gen_dir, root_build_dir), + ] + } + + bundle_data(target_name) { + sources = [ _compile_model_output ] + outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ] + public_deps = [ ":$_compile_model_target" ] + } +} diff --git a/build/ios/mojom/CPPLINT.cfg b/build/ios/mojom/CPPLINT.cfg new file mode 100644 index 00000000000..eda4e1fc9a8 --- /dev/null +++ b/build/ios/mojom/CPPLINT.cfg @@ -0,0 +1,2 @@ +# cpp_transformations.h Use int16/int64/etc, rather than the C type long +filter=-runtime/int diff --git a/build/ios/mojom/cpp_transformations.h b/build/ios/mojom/cpp_transformations.h new file mode 100644 index 00000000000..a638a714aa8 --- /dev/null +++ b/build/ios/mojom/cpp_transformations.h @@ -0,0 +1,321 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_BUILD_IOS_MOJOM_CPP_TRANSFORMATIONS_H_ +#define BRAVE_BUILD_IOS_MOJOM_CPP_TRANSFORMATIONS_H_ + +#import +#import +#include +#include +#include +#include +#include "base/containers/flat_map.h" + +static std::map numberInitMap = { + {@encode(bool), @selector(numberWithBool:)}, + {@encode(char), @selector(numberWithChar:)}, + {@encode(double), @selector(numberWithDouble:)}, + {@encode(float), @selector(numberWithFloat:)}, + {@encode(int), @selector(numberWithInt:)}, + {@encode(NSInteger), @selector(numberWithInteger:)}, + {@encode(long), @selector(numberWithLong:)}, + {@encode(long long), @selector(numberWithLongLong:)}, + {@encode(short), @selector(numberWithShort:)}, + {@encode(unsigned char), @selector(numberWithUnsignedChar:)}, + {@encode(unsigned int), @selector(numberWithUnsignedInt:)}, + {@encode(NSUInteger), @selector(numberWithUnsignedInteger:)}, + {@encode(unsigned long), @selector(numberWithUnsignedLong:)}, + {@encode(unsigned long long), @selector(numberWithUnsignedLongLong:)}, + {@encode(unsigned short), @selector(numberWithUnsignedShort:)}, +}; + +static std::map numberGetterMap = { + {@encode(bool), @selector(boolValue)}, + {@encode(char), @selector(charValue)}, + {@encode(double), @selector(doubleValue)}, + {@encode(float), @selector(floatValue)}, + {@encode(int), @selector(intValue)}, + {@encode(NSInteger), @selector(integerValue)}, + {@encode(long), @selector(longValue)}, + {@encode(long long), @selector(longLongValue)}, + {@encode(short), @selector(shortValue)}, + {@encode(unsigned char), @selector(unsignedCharValue)}, + {@encode(unsigned int), @selector(unsignedIntValue)}, + {@encode(NSUInteger), @selector(unsignedIntegerValue)}, + {@encode(unsigned long), @selector(unsignedLongValue)}, + {@encode(unsigned long long), @selector(unsignedLongLongValue)}, + {@encode(unsigned short), @selector(unsignedShortValue)}, +}; + +#pragma mark - Vectors + +/// Convert a vector storing primatives to an array of NSNumber's +template +NS_INLINE NSArray* NSArrayFromVector(std::vector v) { + const auto a = [NSMutableArray new]; + if (v.empty()) { + return @[]; + } + // Since vector's are uniformly typed, we can just use v[0] + const auto encode = @encode(__typeof__(v[0])); + const auto selector = numberInitMap[encode]; + if (selector == nullptr) { + return @[]; + } + const auto method = class_getClassMethod(NSNumber.class, selector); + typedef NSNumber* (*NSNumberCall)(id, SEL, T); + NSNumberCall call = (NSNumberCall)method_getImplementation(method); + + for (auto t : v) { + NSNumber* number = + reinterpret_cast(call(NSNumber.class, selector, t)); + [a addObject:number]; + } + return a; +} + +/// Convert an NSArray storing NSNumber's to a std::vector storing primatives +template +NS_INLINE std::vector VectorFromNSArray(NSArray* a) { + std::vector v; + if (a.count == 0) { + return v; + } + const auto encode = @encode(__typeof__(T)); + const auto selector = numberGetterMap[encode]; + if (selector == nullptr) { + return v; + } + const auto method = class_getInstanceMethod(NSNumber.class, selector); + typedef T (*NSNumberCall)(id, SEL); + NSNumberCall call = (NSNumberCall)method_getImplementation(method); + + for (NSNumber* number in a) { + v.push_back(call(number, selector)); + } + return v; +} + +/// Convert a vector storing strings to an array of NSString's +NS_INLINE NSArray* NSArrayFromVector(std::vector v) { + const auto a = [NSMutableArray new]; + for (auto s : v) { + [a addObject:[NSString stringWithCString:s.c_str() + encoding:NSUTF8StringEncoding]]; + } + return a; +} + +/// Convert an NSArray storing strings to an vector of std::string's +NS_INLINE std::vector VectorFromNSArray(NSArray* a) { + std::vector v; + for (NSString* str in a) { + v.push_back(std::string(str.UTF8String)); + } + return v; +} + +/// Convert a vector storing objects to an array of transformed objects's +template +NS_INLINE NSArray* NSArrayFromVector(std::vector v, + T (^transformValue)(const U&)) { + const auto a = [NSMutableArray new]; + for (const auto& o : v) { + [a addObject:transformValue(o)]; + } + return a; +} + +/// Convert a vector storing objects to an array of transformed objects's +template +NS_INLINE NSArray* NSArrayFromVector(const std::vector* v, + T (^transformValue)(const U&)) { + const auto a = [NSMutableArray new]; + if (v == nullptr) { + return a; + } + for (const auto& o : *v) { + [a addObject:transformValue(o)]; + } + return a; +} + +/// Convert a NSArray storing objects to an std::vector of transformed objects's +template +NS_INLINE std::vector VectorFromNSArray(NSArray* a, + U (^transformValue)(T)) { + std::vector v; + for (id t in a) { + v.push_back(transformValue(t)); + } + return v; +} + +#pragma mark - Maps + +/// Get an NSNumber object from a primitive type (int, bool, etc.) +template +NS_INLINE NSNumber* NumberFromPrimitive(T t) { + const auto encode = @encode(__typeof__(t)); + const auto selector = numberInitMap[encode]; + if (selector == nullptr) { + return nil; + } + const auto method = class_getClassMethod(NSNumber.class, selector); + typedef NSNumber* (*NSNumberCall)(id, SEL, T); + NSNumberCall call = + reinterpret_cast(method_getImplementation(method)); + return call(NSNumber.class, selector, t); +} + +/// Convert a String's to primitives mapping to an NSDictionary +template +NS_INLINE NSDictionary* NSDictionaryFromMap( + std::map m) { + const auto d = [NSMutableDictionary new]; + if (m.empty()) { + return @{}; + } + for (auto item : m) { + d[[NSString stringWithCString:item.first.c_str() + encoding:NSUTF8StringEncoding]] = + NumberFromPrimitive(item.second); + } + return d; +} + +/// Convert a String's to primitives mapping to an NSDictionary +template +NS_INLINE NSDictionary* NSDictionaryFromMap( + base::flat_map m) { + const auto d = [NSMutableDictionary new]; + if (m.empty()) { + return @{}; + } + for (auto item : m) { + d[[NSString stringWithCString:item.first.c_str() + encoding:NSUTF8StringEncoding]] = + NumberFromPrimitive(item.second); + } + return d; +} + +/// Convert a String to String mapping to an NSDictionary +NS_INLINE NSDictionary* NSDictionaryFromMap( + std::map m) { + const auto d = [NSMutableDictionary new]; + if (m.empty()) { + return @{}; + } + for (auto item : m) { + d[[NSString stringWithCString:item.first.c_str() + encoding:NSUTF8StringEncoding]] = + [NSString stringWithCString:item.second.c_str() + encoding:NSUTF8StringEncoding]; + } + return d; +} + +/// Convert a String to String mapping to an NSDictionary +NS_INLINE NSDictionary* NSDictionaryFromMap( + base::flat_map m) { + const auto d = [NSMutableDictionary new]; + if (m.empty()) { + return @{}; + } + for (auto item : m) { + d[[NSString stringWithCString:item.first.c_str() + encoding:NSUTF8StringEncoding]] = + [NSString stringWithCString:item.second.c_str() + encoding:NSUTF8StringEncoding]; + } + return d; +} + +/// Convert a String to C++ object mapping to an NSDictionary of String to Obj-C +/// objects +template +NS_INLINE NSDictionary* NSDictionaryFromMap( + std::map m, + ObjCObj (^transformValue)(V)) { + const auto d = [NSMutableDictionary new]; + if (m.empty()) { + return @{}; + } + for (auto item : m) { + d[[NSString stringWithCString:item.first.c_str() + encoding:NSUTF8StringEncoding]] = + transformValue(item.second); + } + return d; +} + +/// Convert a String to C++ object mapping to an NSDictionary of String to Obj-C +/// objects +template +NS_INLINE NSDictionary* NSDictionaryFromMap( + base::flat_map m, + ObjCObj (^transformValue)(V)) { + const auto d = [NSMutableDictionary new]; + if (m.empty()) { + return @{}; + } + for (auto item : m) { + d[[NSString stringWithCString:item.first.c_str() + encoding:NSUTF8StringEncoding]] = + transformValue(item.second); + } + return d; +} + +/// Convert any mapping to an NSDictionary of Obj-C objects by transforming both +/// the key and the value types to Obj-C types +template +NS_INLINE NSDictionary* NSDictionaryFromMap( + std::map m, + KObjC (^transformKey)(K), + VObjC (^transformValue)(V)) { + const auto d = [NSMutableDictionary new]; + if (m.empty()) { + return @{}; + } + for (auto item : m) { + d[transformKey(item.first)] = transformValue(item.second); + } + return d; +} + +/// Convert any mapping to an NSDictionary of Obj-C objects by transforming both +/// the key and the value types to Obj-C types +template +NS_INLINE NSDictionary* NSDictionaryFromMap( + base::flat_map m, + KObjC (^transformKey)(K), + VObjC (^transformValue)(V)) { + const auto d = [NSMutableDictionary new]; + if (m.empty()) { + return @{}; + } + for (auto item : m) { + d[transformKey(item.first)] = transformValue(item.second); + } + return d; +} + +/// Converts an NSDictionary that has NSString keys & values to a base::flat_map +/// with std::string keys & values +NS_INLINE base::flat_map MapFromNSDictionary( + NSDictionary* d) { + base::flat_map map; + for (NSString* key in d) { + map.insert(std::make_pair(key.UTF8String, d[key].UTF8String)); + } + return map; +} + +#endif // BRAVE_BUILD_IOS_MOJOM_CPP_TRANSFORMATIONS_H_ diff --git a/vendor/brave-ios/scripts/mojo/gen_model_wrappers.py b/build/ios/mojom/gen_model_wrappers.py similarity index 86% rename from vendor/brave-ios/scripts/mojo/gen_model_wrappers.py rename to build/ios/mojom/gen_model_wrappers.py index 846dbea016d..5adb07c55ba 100644 --- a/vendor/brave-ios/scripts/mojo/gen_model_wrappers.py +++ b/build/ios/mojom/gen_model_wrappers.py @@ -7,7 +7,7 @@ import os import sys _current_dir = os.path.dirname(os.path.realpath(__file__)) -sys.path.insert(1, os.path.join(_current_dir, *([os.pardir] * 5 + ['mojo/public/tools/mojom']))) +sys.path.insert(1, os.path.join(_current_dir, *([os.pardir] * 4 + ['mojo/public/tools/mojom']))) import mojom.fileutil as fileutil from mojom.generate import template_expander @@ -17,8 +17,8 @@ def parse_args(): parser = argparse.ArgumentParser(description='Generate Obj-C files from mojo definitions') parser.add_argument('--mojom-module', nargs=1) parser.add_argument('--module-include-path', nargs=1) - parser.add_argument('--mojom-file', nargs=1) parser.add_argument('--output-dir', nargs=1) + parser.add_argument('--class-prefix', nargs='?', default="") return parser.parse_args() def main(): @@ -28,6 +28,7 @@ def main(): mojom_module = args.mojom_module[0] module_include_path = args.module_include_path[0] output_dir = args.output_dir[0] + class_prefix = args.class_prefix ast_root_dir = os.path.dirname(mojom_module) @@ -37,6 +38,8 @@ def main(): template_expander.PrecompileTemplates({"objc": generator_module}, bytecode_path) generator = generator_module.Generator(None) + if len(class_prefix) > 0: + generator.class_prefix = class_prefix generator.bytecode_path = bytecode_path generator.module_include_path = module_include_path with open(mojom_module, 'rb') as f: diff --git a/vendor/brave-ios/scripts/mojo/mojom_objc_generator.py b/build/ios/mojom/mojom_objc_generator.py similarity index 99% rename from vendor/brave-ios/scripts/mojo/mojom_objc_generator.py rename to build/ios/mojom/mojom_objc_generator.py index bacc359b012..efc7a352ecd 100644 --- a/vendor/brave-ios/scripts/mojo/mojom_objc_generator.py +++ b/build/ios/mojom/mojom_objc_generator.py @@ -35,7 +35,7 @@ _kind_to_nsnumber_getter = { class Generator(generator.Generator): def __init__(self, *args, **kwargs): super(Generator, self).__init__(*args, **kwargs) - self.class_prefix = "BAT" + self.class_prefix = "" @staticmethod def GetTemplatePrefix(): diff --git a/build/ios/mojom/mojom_wrappers.gni b/build/ios/mojom/mojom_wrappers.gni new file mode 100644 index 00000000000..a207b054a9a --- /dev/null +++ b/build/ios/mojom/mojom_wrappers.gni @@ -0,0 +1,93 @@ +# Copyright (c) 2021 The Brave Authors. All rights reserved. +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this file, +# You can obtain one at http://mozilla.org/MPL/2.0/. + +import("//build/config/ios/ios_sdk.gni") + +# Template to generate Obj-C wrappers for generated C++ mojo files +# +# Arguments +# +# mojom_target +# the target which generates C++ mojom files +# mojom_file +# path to the .mojom file +# class_prefix +# an optional string to prefix all generated wrapper classes. +# +template("mojom_wrappers") { + assert(defined(invoker.mojom_target) && invoker.mojom_target != "", + "mojom_target must be defined for $target_name") + assert(defined(invoker.mojom_file) && invoker.mojom_file != "", + "mojom_file must be defined for $target_name") + + _mojom_target_parser = + get_path_info("${invoker.mojom_target}:interfaces__parser", "abspath") + _mojom_target_parser_gen_dir = + get_label_info(_mojom_target_parser, "target_gen_dir") + _mojom_include_dir = string_replace( + get_path_info(get_label_info(invoker.mojom_target, "dir"), "abspath"), + "//", + "", + 1) + _mojom_output_dir = rebase_path(target_gen_dir) + _mojom_file = invoker.mojom_file + _mojom_filename = get_path_info(_mojom_file, "file") + _mojom_module = + rebase_path("$_mojom_target_parser_gen_dir/$_mojom_filename-module") + + _generate_wrappers_target = "${target_name}_generate_wrappers" + _generate_wrappers_output = [ + "$target_gen_dir/$_mojom_filename.objc.h", + "$target_gen_dir/$_mojom_filename.objc+private.h", + "$target_gen_dir/$_mojom_filename.objc.mm", + ] + + action(_generate_wrappers_target) { + script = "//brave/build/ios/mojom/gen_model_wrappers.py" + inputs = [ + _mojom_module, + "//brave/build/ios/mojom/cpp_transformations.h", + "//brave/build/ios/mojom/objc_templates/enum.tmpl", + "//brave/build/ios/mojom/objc_templates/module.h.tmpl", + "//brave/build/ios/mojom/objc_templates/module+private.h.tmpl", + "//brave/build/ios/mojom/objc_templates/module.mm.tmpl", + "//brave/build/ios/mojom/objc_templates/interface_declaration.tmpl", + "//brave/build/ios/mojom/objc_templates/private_interface_declaration.tmpl", + "//brave/build/ios/mojom/objc_templates/private_interface_implementation.tmpl", + ] + outputs = _generate_wrappers_output + args = [ + "--mojom-module=$_mojom_module", + "--module-include-path=$_mojom_include_dir", + "--output-dir=$_mojom_output_dir", + ] + if (defined(invoker.class_prefix)) { + args += [ "--class-prefix=${invoker.class_prefix}" ] + } + deps = [ + "//mojo/public/cpp/bindings", + _mojom_target_parser, + ] + } + + source_set(target_name) { + forward_variables_from(invoker, + "*", + [ + "mojom_file", + "mojom_target", + "sources", + ]) + if (!defined(public_deps)) { + public_deps = [] + } + sources = _generate_wrappers_output + configs += [ "//build/config/compiler:enable_arc" ] + public_deps += [ + ":$_generate_wrappers_target", + "//base", + ] + } +} diff --git a/vendor/brave-ios/scripts/mojo/objc_templates/enum.tmpl b/build/ios/mojom/objc_templates/enum.tmpl similarity index 100% rename from vendor/brave-ios/scripts/mojo/objc_templates/enum.tmpl rename to build/ios/mojom/objc_templates/enum.tmpl diff --git a/vendor/brave-ios/scripts/mojo/objc_templates/interface_declaration.tmpl b/build/ios/mojom/objc_templates/interface_declaration.tmpl similarity index 100% rename from vendor/brave-ios/scripts/mojo/objc_templates/interface_declaration.tmpl rename to build/ios/mojom/objc_templates/interface_declaration.tmpl diff --git a/vendor/brave-ios/scripts/mojo/objc_templates/module+private.h.tmpl b/build/ios/mojom/objc_templates/module+private.h.tmpl similarity index 100% rename from vendor/brave-ios/scripts/mojo/objc_templates/module+private.h.tmpl rename to build/ios/mojom/objc_templates/module+private.h.tmpl diff --git a/vendor/brave-ios/scripts/mojo/objc_templates/module.h.tmpl b/build/ios/mojom/objc_templates/module.h.tmpl similarity index 100% rename from vendor/brave-ios/scripts/mojo/objc_templates/module.h.tmpl rename to build/ios/mojom/objc_templates/module.h.tmpl diff --git a/vendor/brave-ios/scripts/mojo/objc_templates/module.mm.tmpl b/build/ios/mojom/objc_templates/module.mm.tmpl similarity index 91% rename from vendor/brave-ios/scripts/mojo/objc_templates/module.mm.tmpl rename to build/ios/mojom/objc_templates/module.mm.tmpl index 92e4582b7a9..7658a9ecb64 100644 --- a/vendor/brave-ios/scripts/mojo/objc_templates/module.mm.tmpl +++ b/build/ios/mojom/objc_templates/module.mm.tmpl @@ -5,7 +5,7 @@ #import #import "{{module_name}}.objc+private.h" -#import "CppTransformations.h" +#import "brave/build/ios/mojom/cpp_transformations.h" #import "base/containers/flat_map.h" #if !defined(__has_feature) || !__has_feature(objc_arc) diff --git a/vendor/brave-ios/scripts/mojo/objc_templates/private_interface_declaration.tmpl b/build/ios/mojom/objc_templates/private_interface_declaration.tmpl similarity index 100% rename from vendor/brave-ios/scripts/mojo/objc_templates/private_interface_declaration.tmpl rename to build/ios/mojom/objc_templates/private_interface_declaration.tmpl diff --git a/vendor/brave-ios/scripts/mojo/objc_templates/private_interface_implementation.tmpl b/build/ios/mojom/objc_templates/private_interface_implementation.tmpl similarity index 100% rename from vendor/brave-ios/scripts/mojo/objc_templates/private_interface_implementation.tmpl rename to build/ios/mojom/objc_templates/private_interface_implementation.tmpl diff --git a/common/BUILD.gn b/common/BUILD.gn index c854e8b6fc7..548b0bf0b1e 100644 --- a/common/BUILD.gn +++ b/common/BUILD.gn @@ -148,8 +148,6 @@ source_set("common") { ":switches", "//base", "//brave/chromium_src:common", - "//brave/components/resources", - "//components/resources", "//extensions/buildflags", "//services/service_manager", "//ui/base", diff --git a/ios/BUILD.gn b/ios/BUILD.gn new file mode 100644 index 00000000000..1c2afad69a8 --- /dev/null +++ b/ios/BUILD.gn @@ -0,0 +1,80 @@ +# Copyright (c) 2019 The Brave Authors. All rights reserved. +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +import("//build/config/ios/rules.gni") + +config("internal_config") { + visibility = [ ":*" ] + ldflags = [ "-Wl,-no_compact_unwind,-rpath,/usr/lib/swift,-rpath,@executable_path/../Frameworks" ] +} + +group("brave_ios") { + public_deps = [ ":brave_core_ios_framework" ] +} + +group("brave_ios_tests") { + testonly = true + public_deps = [ "testing:brave_core_ios_tests" ] +} + +brave_core_public_headers = [ + "//brave/ios/app/brave_core_main.h", + "//brave/ios/browser/api/bookmarks/brave_bookmarks_api.h", + "//brave/ios/browser/api/bookmarks/brave_bookmarks_observer.h", + "//brave/ios/browser/api/bookmarks/importer/brave_bookmarks_importer.h", + "//brave/ios/browser/api/bookmarks/exporter/brave_bookmarks_exporter.h", + "//brave/ios/browser/api/history/brave_history_api.h", + "//brave/ios/browser/api/history/brave_history_observer.h", + "//brave/ios/browser/api/sync/brave_sync_api.h", + "//brave/ios/browser/api/sync/driver/brave_sync_profile_service.h", + "//brave/ios/browser/api/wallet/brave_wallet_api.h", + "//brave/ios/browser/api/wallet/hd_keyring_ios.h", + "//brave/ios/browser/api/wallet/keyring_controller_ios.h", + "//brave/ios/browser/api/ads/brave_ads.h", + "//brave/ios/browser/api/ads/ad_notification_ios.h", + "//brave/ios/browser/api/ads/inline_content_ad_ios.h", + "$root_gen_dir/brave/ios/browser/api/ads/ads.mojom.objc.h", + "//brave/ios/browser/api/ledger/brave_ledger.h", + "//brave/ios/browser/api/ledger/brave_ledger_observer.h", + "//brave/ios/browser/api/ledger/rewards_notification.h", + "//brave/ios/browser/api/ledger/promotion_solution.h", + "$root_gen_dir/brave/ios/browser/api/ledger/ledger.mojom.objc.h", +] + +action("brave_core_umbrella_header") { + script = "//build/config/ios/generate_umbrella_header.py" + + full_header_path = target_gen_dir + "/BraveCore.h" + outputs = [ full_header_path ] + + args = [ + "--output-path", + rebase_path(full_header_path, root_build_dir), + ] + + args += rebase_path(brave_core_public_headers, root_build_dir) +} + +ios_framework_bundle("brave_core_ios_framework") { + output_name = "BraveCore" + output_dir = root_out_dir + + info_plist = "Info.plist" + + configs += [ ":internal_config" ] + configs += [ "//build/config/compiler:enable_arc" ] + + deps = [ + ":brave_core_umbrella_header", + "//brave/ios/app", + "//brave/ios/browser/api/ads:ads_mojom_wrappers", + "//brave/ios/browser/api/ledger:ledger_mojom_wrappers", + ] + + sources = brave_core_public_headers + + public_headers = get_target_outputs(":brave_core_umbrella_header") + public_headers += brave_core_public_headers +} diff --git a/ios/CPPLINT.cfg b/ios/CPPLINT.cfg index 4d7e79c8741..199b733d0dd 100644 --- a/ios/CPPLINT.cfg +++ b/ios/CPPLINT.cfg @@ -1,2 +1,2 @@ # ios/app/brave_core_main.h:20: Using C-style cast. Use reinterpret_cast(...) instead [readability/casting] [4] ?? -filter=-readability/casting,-whitespace/parens +filter=-readability/casting,-whitespace/parens,-whitespace/operators diff --git a/vendor/brave-ios/Info.plist b/ios/Info.plist similarity index 85% rename from vendor/brave-ios/Info.plist rename to ios/Info.plist index 36b5a109aa7..74b1fd78012 100644 --- a/vendor/brave-ios/Info.plist +++ b/ios/Info.plist @@ -5,13 +5,13 @@ CFBundleDevelopmentRegion en CFBundleExecutable - BraveRewards + BraveCore CFBundleIdentifier - com.brave.ios.rewards + com.brave.ios.core CFBundleInfoDictionaryVersion 6.0 CFBundleName - BraveRewards + BraveCore CFBundlePackageType FMWK CFBundleShortVersionString diff --git a/ios/app/BUILD.gn b/ios/app/BUILD.gn index 39a639dad7b..c4e57ec2d4c 100644 --- a/ios/app/BUILD.gn +++ b/ios/app/BUILD.gn @@ -23,8 +23,10 @@ source_set("app") { "//brave/components/brave_sync:constants", "//brave/components/brave_wallet/common/buildflags:buildflags", "//brave/ios/browser", + "//brave/ios/browser/api/ads", "//brave/ios/browser/api/bookmarks", "//brave/ios/browser/api/history", + "//brave/ios/browser/api/ledger", "//brave/ios/browser/api/sync/driver", "//components/browser_sync", "//components/history/core/browser", diff --git a/ios/app/brave_core_main.h b/ios/app/brave_core_main.h index 52e6a7a650f..2d6af4d44d7 100644 --- a/ios/app/brave_core_main.h +++ b/ios/app/brave_core_main.h @@ -11,11 +11,16 @@ @class BraveBookmarksAPI; @class BraveHistoryAPI; @class BraveSyncProfileServiceIOS; - @class BraveWalletAPI; NS_ASSUME_NONNULL_BEGIN +typedef bool (^BraveCoreLogHandler)(int severity, + NSString* file, + int line, + size_t messageStart, + NSString* formattedMessage); + OBJC_EXPORT @interface BraveCoreMain : NSObject @@ -26,6 +31,8 @@ OBJC_EXPORT @property(nullable, nonatomic, readonly) BraveSyncProfileServiceIOS* syncProfileService; ++ (void)setLogHandler:(nullable BraveCoreLogHandler)logHandler; + - (instancetype)init; - (instancetype)initWithSyncServiceURL:(NSString*)syncServiceURL; diff --git a/ios/app/brave_core_main.mm b/ios/app/brave_core_main.mm index 5fc86200364..1ec4ce03edf 100644 --- a/ios/app/brave_core_main.mm +++ b/ios/app/brave_core_main.mm @@ -5,9 +5,11 @@ #import "brave/ios/app/brave_core_main.h" +#import #import #include "base/compiler_specific.h" +#include "base/logging.h" #include "base/strings/sys_string_conversions.h" #include "brave/components/brave_wallet/common/buildflags/buildflags.h" #include "brave/ios/app/brave_main_delegate.h" @@ -35,6 +37,10 @@ #import "brave/ios/browser/api/wallet/brave_wallet_service_factory.h" #endif +// Chromium logging is global, therefore we cannot link this to the instance in +// question +static BraveCoreLogHandler _Nullable _logHandler = nil; + @interface BraveCoreMain () { std::unique_ptr _webClient; std::unique_ptr _delegate; @@ -128,6 +134,29 @@ _webClient->SetUserAgent(base::SysNSStringToUTF8(userAgent)); } ++ (void)setLogHandler:(BraveCoreLogHandler)logHandler { + _logHandler = logHandler; + logging::SetLogMessageHandler(&CustomLogHandler); +} + +static bool CustomLogHandler(int severity, + const char* file, + int line, + size_t message_start, + const std::string& str) { + if (!_logHandler) { + return false; + } + const int vlog_level = logging::GetVlogLevelHelper(file, strlen(file)); + if (severity <= vlog_level) { + return _logHandler(severity, base::SysUTF8ToNSString(file), line, + message_start, base::SysUTF8ToNSString(str)); + } + return true; +} + +#pragma mark - + - (BraveBookmarksAPI*)bookmarksAPI { if (!_bookmarksAPI) { bookmarks::BookmarkModel* bookmark_model_ = diff --git a/ios/app/brave_main_delegate.mm b/ios/app/brave_main_delegate.mm index fa10905f943..37b1d9a2798 100644 --- a/ios/app/brave_main_delegate.mm +++ b/ios/app/brave_main_delegate.mm @@ -5,15 +5,16 @@ #include "brave/ios/app/brave_main_delegate.h" +#include "base/base_paths.h" +#include "base/base_switches.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/mac/bundle_locations.h" -#include "base/base_paths.h" #include "base/path_service.h" -#include "components/sync/driver/sync_driver_switches.h" -#include "components/sync/base/model_type.h" #include "components/browser_sync/browser_sync_switches.h" +#include "components/sync/base/model_type.h" #include "components/sync/base/sync_base_switches.h" +#include "components/sync/driver/sync_driver_switches.h" #include "ios/chrome/browser/chrome_switches.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -53,6 +54,7 @@ void BraveMainDelegate::BasicStartupComplete() { // Brave's sync protocol does not use the sync service url command_line->AppendSwitchASCII(switches::kSyncServiceURL, brave_sync_service_url_.c_str()); + command_line->AppendSwitchASCII(switches::kVModule, "*/brave/*=5"); IOSChromeMainDelegate::BasicStartupComplete(); } diff --git a/ios/app/headers.gni b/ios/app/headers.gni deleted file mode 100644 index a0814f572c5..00000000000 --- a/ios/app/headers.gni +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (c) 2020 The Brave Authors. All rights reserved. -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this file, -# You can obtain one at http://mozilla.org/MPL/2.0/. - -brave_core_public_headers = [ - "//brave/ios/app/brave_core_main.h", - "//brave/ios/browser/api/bookmarks/brave_bookmarks_api.h", - "//brave/ios/browser/api/bookmarks/brave_bookmarks_observer.h", - "//brave/ios/browser/api/bookmarks/importer/brave_bookmarks_importer.h", - "//brave/ios/browser/api/bookmarks/exporter/brave_bookmarks_exporter.h", - "//brave/ios/browser/api/history/brave_history_api.h", - "//brave/ios/browser/api/history/brave_history_observer.h", - "//brave/ios/browser/api/sync/brave_sync_api.h", - "//brave/ios/browser/api/sync/driver/brave_sync_profile_service.h", - "//brave/ios/browser/api/wallet/brave_wallet_api.h", - "//brave/ios/browser/api/wallet/hd_keyring_ios.h", - "//brave/ios/browser/api/wallet/keyring_controller_ios.h", -] diff --git a/ios/browser/api/ads/BUILD.gn b/ios/browser/api/ads/BUILD.gn new file mode 100644 index 00000000000..0f1bc0861c6 --- /dev/null +++ b/ios/browser/api/ads/BUILD.gn @@ -0,0 +1,58 @@ +# Copyright (c) 2021 The Brave Authors. All rights reserved. +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +import("//brave/build/ios/mojom/mojom_wrappers.gni") +import("//build/config/ios/rules.gni") + +config("external_config") { + visibility = [ ":*" ] + include_dirs = [ "$target_gen_dir" ] +} + +source_set("ads") { + configs += [ + ":external_config", + "//build/config/compiler:enable_arc", + ] + + sources = [ + "ad_notification_ios.h", + "ad_notification_ios.mm", + "ads_client_bridge.h", + "ads_client_ios.h", + "ads_client_ios.mm", + "brave_ads.h", + "brave_ads.mm", + "inline_content_ad_ios.h", + "inline_content_ad_ios.mm", + ] + + deps = [ + ":ads_mojom_wrappers", + ":ads_resources", + "//base", + "//brave/ios/browser/api/common", + "//brave/vendor/bat-native-ads", + ] + + frameworks = [ + "Foundation.framework", + "UIKit.framework", + "Network.framework", + ] +} + +mojom_wrappers("ads_mojom_wrappers") { + mojom_target = + "//brave/vendor/bat-native-ads/include/bat/ads/public/interfaces" + mojom_file = "//brave/vendor/bat-native-ads/include/bat/ads/public/interfaces/ads.mojom" + class_prefix = "BAT" +} + +bundle_data("ads_resources") { + sources = + [ "//brave/vendor/bat-native-ads/data/resources/catalog-schema.json" ] + outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ] +} diff --git a/vendor/brave-ios/Ads/DEPS b/ios/browser/api/ads/DEPS similarity index 100% rename from vendor/brave-ios/Ads/DEPS rename to ios/browser/api/ads/DEPS diff --git a/ios/browser/api/ads/ad_notification_ios.h b/ios/browser/api/ads/ad_notification_ios.h new file mode 100644 index 00000000000..0c00eb2c05c --- /dev/null +++ b/ios/browser/api/ads/ad_notification_ios.h @@ -0,0 +1,37 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#import + +#ifndef BRAVE_IOS_BROWSER_API_ADS_AD_NOTIFICATION_IOS_H_ +#define BRAVE_IOS_BROWSER_API_ADS_AD_NOTIFICATION_IOS_H_ + +NS_ASSUME_NONNULL_BEGIN + +OBJC_EXPORT +NS_SWIFT_NAME(AdsNotification) +@interface AdNotificationIOS : NSObject +@property(nonatomic, readonly) NSString* uuid; +@property(nonatomic, readonly) NSString* creativeInstanceID; +@property(nonatomic, readonly) NSString* creativeSetID; +@property(nonatomic, readonly) NSString* campaignID; +@property(nonatomic, readonly) NSString* advertiserID; +@property(nonatomic, readonly) NSString* segment; +@property(nonatomic, readonly) NSString* title; +@property(nonatomic, readonly) NSString* body; +@property(nonatomic, readonly) NSString* targetURL; +@end + +OBJC_EXPORT +@interface AdNotificationIOS (MyFirstAd) ++ (instancetype)customAdWithTitle:(NSString*)title + body:(NSString*)body + url:(NSString*)url + NS_SWIFT_NAME(customAd(title:body:url:)); +@end + +NS_ASSUME_NONNULL_END + +#endif // BRAVE_IOS_BROWSER_API_ADS_AD_NOTIFICATION_IOS_H_ diff --git a/ios/browser/api/ads/ad_notification_ios.mm b/ios/browser/api/ads/ad_notification_ios.mm new file mode 100644 index 00000000000..f74421e64e0 --- /dev/null +++ b/ios/browser/api/ads/ad_notification_ios.mm @@ -0,0 +1,57 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#import "ad_notification_ios.h" + +#include "base/strings/sys_string_conversions.h" +#include "bat/ads/ad_notification_info.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@interface AdNotificationIOS () +@property(nonatomic, copy) NSString* uuid; +@property(nonatomic, copy) NSString* creativeInstanceID; +@property(nonatomic, copy) NSString* creativeSetID; +@property(nonatomic, copy) NSString* campaignID; +@property(nonatomic, copy) NSString* advertiserID; +@property(nonatomic, copy) NSString* segment; +@property(nonatomic, copy) NSString* title; +@property(nonatomic, copy) NSString* body; +@property(nonatomic, copy) NSString* targetURL; +@end + +@implementation AdNotificationIOS + +- (instancetype)initWithNotificationInfo:(const ads::AdNotificationInfo&)info { + if ((self = [super init])) { + self.uuid = base::SysUTF8ToNSString(info.uuid); + self.creativeInstanceID = + base::SysUTF8ToNSString(info.creative_instance_id); + self.creativeSetID = base::SysUTF8ToNSString(info.creative_set_id); + self.campaignID = base::SysUTF8ToNSString(info.campaign_id); + self.advertiserID = base::SysUTF8ToNSString(info.advertiser_id); + self.segment = base::SysUTF8ToNSString(info.segment); + self.title = base::SysUTF8ToNSString(info.title); + self.body = base::SysUTF8ToNSString(info.body); + self.targetURL = base::SysUTF8ToNSString(info.target_url); + } + return self; +} + +@end + +@implementation AdNotificationIOS (MyFirstAd) ++ (instancetype)customAdWithTitle:(NSString*)title + body:(NSString*)body + url:(NSString*)url { + AdNotificationIOS* notification = [[AdNotificationIOS alloc] init]; + notification.title = title; + notification.body = body; + notification.targetURL = url; + return notification; +} +@end diff --git a/vendor/brave-ios/Ads/Generated/NativeAdsClientBridge.h b/ios/browser/api/ads/ads_client_bridge.h similarity index 56% rename from vendor/brave-ios/Ads/Generated/NativeAdsClientBridge.h rename to ios/browser/api/ads/ads_client_bridge.h index c944e531c21..fe8bc32cb86 100644 --- a/vendor/brave-ios/Ads/Generated/NativeAdsClientBridge.h +++ b/ios/browser/api/ads/ads_client_bridge.h @@ -1,18 +1,20 @@ -/* WARNING: THIS FILE IS GENERATED. ANY CHANGES TO THIS FILE WILL BE OVERWRITTEN - * +/* Copyright (c) 2021 The Brave Authors. All rights reserved. * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_IOS_BROWSER_API_ADS_ADS_CLIENT_BRIDGE_H_ +#define BRAVE_IOS_BROWSER_API_ADS_ADS_CLIENT_BRIDGE_H_ #import #import "bat/ads/ads_client.h" -@protocol NativeAdsClientBridge +#include +#include + +@protocol AdsClientBridge @required -- (uint64_t)getAdsPerHour; -- (bool)isAdsEnabled; -- (bool)shouldAllowAdConversionTracking; - (bool)isForeground; - (bool)isFullScreen; - (bool)canShowBackgroundNotifications; @@ -24,12 +26,16 @@ - (void)getBrowsingHistory:(const int)max_count forDays:(const int)days_ago callback:(ads::GetBrowsingHistoryCallback)callback; -- (void)load:(const std::string &)name callback:(ads::LoadCallback)callback; -- (std::string)loadResourceForId:(const std::string &)id; -- (void)log:(const char *)file line:(const int)line verboseLevel:(const int)verbose_level message:(const std::string &) message; -- (void)save:(const std::string &)name value:(const std::string &)value callback:(ads::ResultCallback)callback; -- (void)setIdleThreshold:(const int)threshold; -- (void)showNotification:(const ads::AdNotificationInfo &)info; +- (void)load:(const std::string&)name callback:(ads::LoadCallback)callback; +- (std::string)loadResourceForId:(const std::string&)id; +- (void)log:(const char*)file + line:(const int)line + verboseLevel:(const int)verbose_level + message:(const std::string&)message; +- (void)save:(const std::string&)name + value:(const std::string&)value + callback:(ads::ResultCallback)callback; +- (void)showNotification:(const ads::AdNotificationInfo&)info; - (void)closeNotification:(const std::string&)id; - (void)recordAdEvent:(const std::string&)ad_type confirmationType:(const std::string&)confirmation_type @@ -37,14 +43,10 @@ - (std::vector)getAdEvents:(const std::string&)ad_type confirmationType:(const std::string&)confirmation_type; - (void)resetAdEvents; -- (void)UrlRequest:(ads::UrlRequestPtr)url_request callback:(ads::UrlRequestCallback)callback; -- (bool)shouldAllowAdsSubdivisionTargeting; -- (void)setAllowAdsSubdivisionTargeting:(const bool)should_allow; -- (std::string)adsSubdivisionTargetingCode; -- (void)setAdsSubdivisionTargetingCode:(const std::string &)subdivision_targeting_code; -- (std::string)autoDetectedAdsSubdivisionTargetingCode; -- (void)setAutoDetectedAdsSubdivisionTargetingCode:(const std::string &)subdivision_targeting_code; -- (void)runDBTransaction:(ads::DBTransactionPtr)transaction callback:(ads::RunDBTransactionCallback)callback; +- (void)UrlRequest:(ads::UrlRequestPtr)url_request + callback:(ads::UrlRequestCallback)callback; +- (void)runDBTransaction:(ads::DBTransactionPtr)transaction + callback:(ads::RunDBTransactionCallback)callback; - (void)onAdRewardsChanged; - (void)setBooleanPref:(const std::string&)path value:(const bool)value; - (bool)getBooleanPref:(const std::string&)path; @@ -59,6 +61,10 @@ - (void)setUint64Pref:(const std::string&)path value:(const uint64_t)value; - (uint64_t)getUint64Pref:(const std::string&)path; - (void)clearPref:(const std::string&)path; -- (void)recordP2AEvent:(const std::string&)name type:(const ads::P2AEventType)type value:(const std::string&)value; +- (void)recordP2AEvent:(const std::string&)name + type:(const ads::P2AEventType)type + value:(const std::string&)value; @end + +#endif // BRAVE_IOS_BROWSER_API_ADS_ADS_CLIENT_BRIDGE_H_ diff --git a/ios/browser/api/ads/ads_client_ios.h b/ios/browser/api/ads/ads_client_ios.h new file mode 100644 index 00000000000..15a5eb40bb1 --- /dev/null +++ b/ios/browser/api/ads/ads_client_ios.h @@ -0,0 +1,77 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_IOS_BROWSER_API_ADS_ADS_CLIENT_IOS_H_ +#define BRAVE_IOS_BROWSER_API_ADS_ADS_CLIENT_IOS_H_ + +#import +#include +#include +#import "bat/ads/ads_client.h" + +@protocol AdsClientBridge; + +class AdsClientIOS : public ads::AdsClient { + public: + explicit AdsClientIOS(id bridge); + ~AdsClientIOS() override; + + private: + __unsafe_unretained id bridge_; + + bool IsNetworkConnectionAvailable() const override; + bool IsForeground() const override; + bool IsFullScreen() const override; + bool CanShowBackgroundNotifications() const override; + void ShowNotification(const ads::AdNotificationInfo& info) override; + bool ShouldShowNotifications() override; + void CloseNotification(const std::string& uuid) override; + void RecordAdEvent(const std::string& ad_type, + const std::string& confirmation_type, + const uint64_t timestamp) const override; + std::vector GetAdEvents( + const std::string& ad_type, + const std::string& confirmation_type) const override; + void ResetAdEvents() const override; + void UrlRequest(ads::UrlRequestPtr url_request, + ads::UrlRequestCallback callback) override; + void Save(const std::string& name, + const std::string& value, + ads::ResultCallback callback) override; + void Load(const std::string& name, ads::LoadCallback callback) override; + void LoadAdsResource(const std::string& id, + const int version, + ads::LoadCallback callback) override; + void GetBrowsingHistory(const int max_count, + const int days_ago, + ads::GetBrowsingHistoryCallback callback) override; + std::string LoadResourceForId(const std::string& id) override; + void Log(const char* file, + const int line, + const int verbose_level, + const std::string& message) override; + void RunDBTransaction(ads::DBTransactionPtr transaction, + ads::RunDBTransactionCallback callback) override; + void OnAdRewardsChanged() override; + void SetBooleanPref(const std::string& path, const bool value) override; + bool GetBooleanPref(const std::string& path) const override; + void SetIntegerPref(const std::string& path, const int value) override; + int GetIntegerPref(const std::string& path) const override; + void SetDoublePref(const std::string& path, const double value) override; + double GetDoublePref(const std::string& path) const override; + void SetStringPref(const std::string& path, + const std::string& value) override; + std::string GetStringPref(const std::string& path) const override; + void SetInt64Pref(const std::string& path, const int64_t value) override; + int64_t GetInt64Pref(const std::string& path) const override; + void SetUint64Pref(const std::string& path, const uint64_t value) override; + uint64_t GetUint64Pref(const std::string& path) const override; + void ClearPref(const std::string& path) override; + void RecordP2AEvent(const std::string& name, + const ads::P2AEventType type, + const std::string& value) override; +}; + +#endif // BRAVE_IOS_BROWSER_API_ADS_ADS_CLIENT_IOS_H_ diff --git a/ios/browser/api/ads/ads_client_ios.mm b/ios/browser/api/ads/ads_client_ios.mm new file mode 100644 index 00000000000..7c3b1d2a088 --- /dev/null +++ b/ios/browser/api/ads/ads_client_ios.mm @@ -0,0 +1,172 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#import "ads_client_ios.h" +#import "ads_client_bridge.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +// Constructor & Destructor +AdsClientIOS::AdsClientIOS(id bridge) : bridge_(bridge) {} + +AdsClientIOS::~AdsClientIOS() { + bridge_ = nil; +} + +bool AdsClientIOS::IsNetworkConnectionAvailable() const { + return [bridge_ isNetworkConnectionAvailable]; +} + +bool AdsClientIOS::IsForeground() const { + return [bridge_ isForeground]; +} + +bool AdsClientIOS::IsFullScreen() const { + return [bridge_ isFullScreen]; +} + +bool AdsClientIOS::CanShowBackgroundNotifications() const { + return [bridge_ canShowBackgroundNotifications]; +} + +void AdsClientIOS::ShowNotification(const ads::AdNotificationInfo& info) { + [bridge_ showNotification:info]; +} + +bool AdsClientIOS::ShouldShowNotifications() { + return [bridge_ shouldShowNotifications]; +} + +void AdsClientIOS::CloseNotification(const std::string& uuid) { + [bridge_ closeNotification:uuid]; +} + +void AdsClientIOS::RecordAdEvent(const std::string& ad_type, + const std::string& confirmation_type, + const uint64_t timestamp) const { + [bridge_ recordAdEvent:ad_type + confirmationType:confirmation_type + timestamp:timestamp]; +} + +std::vector AdsClientIOS::GetAdEvents( + const std::string& ad_type, + const std::string& confirmation_type) const { + return [bridge_ getAdEvents:ad_type confirmationType:confirmation_type]; +} + +void AdsClientIOS::ResetAdEvents() const { + [bridge_ resetAdEvents]; +} + +void AdsClientIOS::UrlRequest(ads::UrlRequestPtr url_request, + ads::UrlRequestCallback callback) { + [bridge_ UrlRequest:std::move(url_request) callback:callback]; +} + +void AdsClientIOS::Save(const std::string& name, + const std::string& value, + ads::ResultCallback callback) { + [bridge_ save:name value:value callback:callback]; +} + +void AdsClientIOS::LoadAdsResource(const std::string& id, + const int version, + ads::LoadCallback callback) { + [bridge_ loadAdsResource:id version:version callback:callback]; +} + +void AdsClientIOS::GetBrowsingHistory( + const int max_count, + const int days_ago, + ads::GetBrowsingHistoryCallback callback) { + [bridge_ getBrowsingHistory:max_count forDays:days_ago callback:callback]; +} + +void AdsClientIOS::Load(const std::string& name, ads::LoadCallback callback) { + [bridge_ load:name callback:callback]; +} + +std::string AdsClientIOS::LoadResourceForId(const std::string& id) { + return [bridge_ loadResourceForId:id]; +} + +void AdsClientIOS::Log(const char* file, + const int line, + const int verbose_level, + const std::string& message) { + [bridge_ log:file line:line verboseLevel:verbose_level message:message]; +} + +void AdsClientIOS::RunDBTransaction(ads::DBTransactionPtr transaction, + ads::RunDBTransactionCallback callback) { + [bridge_ runDBTransaction:std::move(transaction) callback:callback]; +} + +void AdsClientIOS::OnAdRewardsChanged() { + [bridge_ onAdRewardsChanged]; +} + +void AdsClientIOS::SetBooleanPref(const std::string& path, const bool value) { + [bridge_ setBooleanPref:path value:value]; +} + +bool AdsClientIOS::GetBooleanPref(const std::string& path) const { + return [bridge_ getBooleanPref:path]; +} + +void AdsClientIOS::SetIntegerPref(const std::string& path, const int value) { + [bridge_ setIntegerPref:path value:value]; +} + +int AdsClientIOS::GetIntegerPref(const std::string& path) const { + return [bridge_ getIntegerPref:path]; +} + +void AdsClientIOS::SetDoublePref(const std::string& path, const double value) { + [bridge_ setDoublePref:path value:value]; +} + +double AdsClientIOS::GetDoublePref(const std::string& path) const { + return [bridge_ getDoublePref:path]; +} + +void AdsClientIOS::SetStringPref(const std::string& path, + const std::string& value) { + [bridge_ setStringPref:path value:value]; +} + +std::string AdsClientIOS::GetStringPref(const std::string& path) const { + return [bridge_ getStringPref:path]; +} + +void AdsClientIOS::SetInt64Pref(const std::string& path, const int64_t value) { + [bridge_ setInt64Pref:path value:value]; +} + +int64_t AdsClientIOS::GetInt64Pref(const std::string& path) const { + return [bridge_ getInt64Pref:path]; +} + +void AdsClientIOS::SetUint64Pref(const std::string& path, + const uint64_t value) { + [bridge_ setUint64Pref:path value:value]; +} + +uint64_t AdsClientIOS::GetUint64Pref(const std::string& path) const { + return [bridge_ getUint64Pref:path]; +} + +void AdsClientIOS::ClearPref(const std::string& path) { + [bridge_ clearPref:path]; +} + +void AdsClientIOS::RecordP2AEvent(const std::string& name, + const ads::P2AEventType type, + const std::string& value) { + [bridge_ recordP2AEvent:name type:type value:value]; +} diff --git a/vendor/brave-ios/Ads/BATBraveAds.h b/ios/browser/api/ads/brave_ads.h similarity index 61% rename from vendor/brave-ios/Ads/BATBraveAds.h rename to ios/browser/api/ads/brave_ads.h index c84744d139c..74a6f0c85c0 100644 --- a/vendor/brave-ios/Ads/BATBraveAds.h +++ b/ios/browser/api/ads/brave_ads.h @@ -1,6 +1,10 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_IOS_BROWSER_API_ADS_BRAVE_ADS_H_ +#define BRAVE_IOS_BROWSER_API_ADS_BRAVE_ADS_H_ #import #import @@ -8,60 +12,57 @@ NS_ASSUME_NONNULL_BEGIN -@class BATAdNotification, BATBraveAds, BATBraveLedger, BATInlineContentAd; +@class AdNotificationIOS, InlineContentAdIOS; OBJC_EXPORT -NS_SWIFT_NAME(BraveAdsNotificationHandler) -@protocol BATBraveAdsNotificationHandler +@protocol BraveAdsNotificationHandler @required /// Determine whether or not the client can currently show notifications /// to the user. - (BOOL)shouldShowNotifications; /// Show the given notification to the user (or add it to the queue) -- (void)showNotification:(BATAdNotification *)notification; +- (void)showNotification:(AdNotificationIOS*)notification; /// Remove a pending notification from the queue or remove an already shown /// notification from view -- (void)clearNotificationWithIdentifier:(NSString *)identifier; +- (void)clearNotificationWithIdentifier:(NSString*)identifier; @end -OBJC_EXPORT -NS_SWIFT_NAME(BraveAds) -@interface BATBraveAds : NSObject - -@property (nonatomic, weak) BATBraveLedger *ledger; +OBJC_EXPORT +@interface BraveAds : NSObject /// The notifications handler. /// -/// @see BATSystemNotificationsHandler -@property (nonatomic, weak, nullable) id notificationsHandler; +/// @see BraveAdsNotificationHandler +@property(nonatomic, weak, nullable) id + notificationsHandler; #pragma mark - Global /// Whether or not a given locale is supported. The locale should be a standard /// locale identifier, i.e. "en_US" -+ (BOOL)isSupportedLocale:(NSString *)locale; ++ (BOOL)isSupportedLocale:(NSString*)locale; /// Whether or not a given locale is newly supported. The locale should be a /// standard locale identifier, i.e. "en_US" -+ (BOOL)isNewlySupportedLocale:(NSString *)locale; ++ (BOOL)isNewlySupportedLocale:(NSString*)locale; /// Whether or not the users current locale (by `NSLocale`) is supported + (BOOL)isCurrentLocaleSupported; /// Whether or not to use staging servers. Defaults to false -@property (nonatomic, class, getter=isDebug) BOOL debug; +@property(nonatomic, class, getter=isDebug) BOOL debug; /// The environment that ads is communicating with. See ledger's BATEnvironment /// for appropriate values. -@property (nonatomic, class) int environment; +@property(nonatomic, class) int environment; /// System info -@property (nonatomic, class) BATBraveAdsSysInfo *sysInfo; +@property(nonatomic, class) BATBraveAdsSysInfo* sysInfo; /// The build channel that ads is configured for -@property (nonatomic, class) BATBraveAdsBuildChannel *buildChannel; +@property(nonatomic, class) BATBraveAdsBuildChannel* buildChannel; #pragma mark - Initialization / Shutdown /// Initializes the ads service if ads is enabled -- (void)initializeIfAdsEnabled; +- (void)initializeIfAdsEnabled:(void (^)(bool success))completion; /// Shuts down the ads service if its running - (void)shutdown:(nullable void (^)())completion; @@ -69,31 +70,41 @@ NS_SWIFT_NAME(BraveAds) /// Whether or not the ads service is running - (BOOL)isAdsServiceRunning; +/// Update the ad library with the users current wallet +- (void)updateWalletInfo:(NSString*)paymentId base64Seed:(NSString*)base64Seed; + #pragma mark - Configuration +/// Whether or not Brave Ads is enabled +@property(nonatomic, assign, getter=isEnabled) BOOL enabled; + /// The max number of ads the user can see in an hour -@property (nonatomic, assign) NSInteger numberOfAllowableAdsPerHour NS_SWIFT_NAME(adsPerHour); +@property(nonatomic, assign) + NSInteger numberOfAllowableAdsPerHour NS_SWIFT_NAME(adsPerHour); /// Whether or not the user has opted out of subdivision ad targeting -@property (nonatomic, assign, getter=shouldAllowSubdivisionTargeting) BOOL allowSubdivisionTargeting; +@property(nonatomic, assign, getter=shouldAllowSubdivisionTargeting) + BOOL allowSubdivisionTargeting; /// Selected ads subdivision targeting option -@property (nonatomic, copy) NSString * subdivisionTargetingCode; +@property(nonatomic, copy) NSString* subdivisionTargetingCode; /// Automatically detected ads subdivision targeting code -@property (nonatomic, copy) NSString * autoDetectedSubdivisionTargetingCode; +@property(nonatomic, copy) NSString* autoDetectedSubdivisionTargetingCode; -/// Remove all cached history (should be called when the user clears their browser history) +/// Remove all cached history (should be called when the user clears their +/// browser history) - (void)removeAllHistory:(void (^)(BOOL))completion; #pragma mark - Notificiations -- (nullable BATAdNotification *)adsNotificationForIdentifier:(NSString *)identifier; +- (nullable AdNotificationIOS*)adsNotificationForIdentifier: + (NSString*)identifier; #pragma mark - History /// Get a list of dates of when the user has viewed ads -- (NSArray *)getAdsHistoryDates; +- (NSArray*)getAdsHistoryDates; /// Return true if the user has viewed ads in the previous cycle/month - (BOOL)hasViewedAdsInPreviousCycle; @@ -109,16 +120,22 @@ NS_SWIFT_NAME(BraveAds) tabId:(NSInteger)tabId; /// Report that media has started on a tab with a given id -- (void)reportMediaStartedWithTabId:(NSInteger)tabId NS_SWIFT_NAME(reportMediaStarted(tabId:)); +- (void)reportMediaStartedWithTabId:(NSInteger)tabId + NS_SWIFT_NAME(reportMediaStarted(tabId:)); /// Report that media has stopped on a tab with a given id -- (void)reportMediaStoppedWithTabId:(NSInteger)tabId NS_SWIFT_NAME(reportMediaStopped(tabId:)); +- (void)reportMediaStoppedWithTabId:(NSInteger)tabId + NS_SWIFT_NAME(reportMediaStopped(tabId:)); /// Report that a tab with a given id was updated -- (void)reportTabUpdated:(NSInteger)tabId url:(NSURL *)url isSelected:(BOOL)isSelected isPrivate:(BOOL)isPrivate; +- (void)reportTabUpdated:(NSInteger)tabId + url:(NSURL*)url + isSelected:(BOOL)isSelected + isPrivate:(BOOL)isPrivate; /// Report that a tab with a given id was closed by the user -- (void)reportTabClosedWithTabId:(NSInteger)tabId NS_SWIFT_NAME(reportTabClosed(tabId:)); +- (void)reportTabClosedWithTabId:(NSInteger)tabId + NS_SWIFT_NAME(reportTabClosed(tabId:)); /// Report that an ad notification event type was triggered for a given id - (void)reportAdNotificationEvent:(NSString*)uuid @@ -128,7 +145,7 @@ NS_SWIFT_NAME(BraveAds) - (void)inlineContentAdsWithDimensions:(NSString*)dimensions completion:(void (^)(BOOL success, NSString* dimensions, - BATInlineContentAd*))completion + InlineContentAdIOS*))completion NS_SWIFT_NAME(inlineContentAds(dimensions:completion:)); /// Report that an inline content ad event type was triggered for a given id @@ -154,22 +171,29 @@ NS_SWIFT_NAME(BraveAds) /// Reconcile ad rewards with server - (void)reconcileAdRewards; -/// Get the number of ads received and the estimated earnings of viewing said ads for this cycle -- (void)detailsForCurrentCycle:(void (^)(NSInteger adsReceived, double estimatedEarnings, NSDate * _Nullable nextPaymentDate))completion NS_SWIFT_NAME(detailsForCurrentCycle(_:)); +/// Get the number of ads received and the estimated earnings of viewing said +/// ads for this cycle +- (void)detailsForCurrentCycle: + (void (^)(NSInteger adsReceived, + double estimatedEarnings, + NSDate* _Nullable nextPaymentDate))completion + NS_SWIFT_NAME(detailsForCurrentCycle(_:)); /// Toggle that the user liked the given ad and more like it should be shown -- (void)toggleThumbsUpForAd:(NSString *)creativeInstanceId - creativeSetID:(NSString *)creativeSetID; +- (void)toggleThumbsUpForAd:(NSString*)creativeInstanceId + creativeSetID:(NSString*)creativeSetID; /// Toggle that the user disliked the given ad and it shouldn't be shown again -- (void)toggleThumbsDownForAd:(NSString *)creativeInstanceId - creativeSetID:(NSString *)creativeSetID; +- (void)toggleThumbsDownForAd:(NSString*)creativeInstanceId + creativeSetID:(NSString*)creativeSetID; #pragma mark - - (instancetype)init NS_UNAVAILABLE; -- (instancetype)initWithStateStoragePath:(NSString *)path; +- (instancetype)initWithStateStoragePath:(NSString*)path; @end NS_ASSUME_NONNULL_END + +#endif // BRAVE_IOS_BROWSER_API_ADS_BRAVE_ADS_H_ diff --git a/vendor/brave-ios/Ads/BATBraveAds.mm b/ios/browser/api/ads/brave_ads.mm similarity index 91% rename from vendor/brave-ios/Ads/BATBraveAds.mm rename to ios/browser/api/ads/brave_ads.mm index 0aa3d007392..e1a1bd03317 100644 --- a/vendor/brave-ios/Ads/BATBraveAds.mm +++ b/ios/browser/api/ads/brave_ads.mm @@ -1,36 +1,40 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include - -#import "BATAdNotification.h" -#import "BATBraveAds+Private.h" -#import "BATBraveAds.h" -#import "BATBraveLedger.h" -#import "BATInlineContentAd.h" - -#import "bat/ads/ad_event_history.h" -#import "bat/ads/ads.h" -#import "bat/ads/database.h" -#import "bat/ads/pref_names.h" - -#import "BATCommonOperations.h" -#import "CppTransformations.h" -#import "NativeAdsClient.h" -#import "NativeAdsClientBridge.h" +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ #import #import -#import "base/base64.h" +#include +#import "ad_notification_ios.h" +#import "ads_client_bridge.h" +#import "ads_client_ios.h" +#include "base/base64.h" +#include "base/logging.h" #include "base/sequenced_task_runner.h" -#import "base/strings/sys_string_conversions.h" +#include "base/strings/sys_string_conversions.h" #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "base/task_runner_util.h" +#include "bat/ads/ad_event_history.h" +#include "bat/ads/ads.h" +#include "bat/ads/database.h" +#include "bat/ads/pref_names.h" +#import "brave/build/ios/mojom/cpp_transformations.h" +#import "brave/ios/browser/api/common/common_operations.h" +#import "brave_ads.h" +#import "inline_content_ad_ios.h" -#import "RewardsLogging.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#define BLOG(verbose_level, format, ...) \ + [self log:(__FILE__) \ + line:(__LINE__)verboseLevel:(verbose_level)message \ + :base::SysNSStringToUTF8( \ + [NSString stringWithFormat:(format), ##__VA_ARGS__])] #define BATClassAdsBridge(__type, __objc_getter, __objc_setter, __cpp_var) \ +(__type)__objc_getter { \ @@ -54,13 +58,13 @@ static NSString* const kLegacyAutoDetectedAdsSubdivisionTargetingCodePrefKey = @"BATAutoDetectedAdsSubdivisionTargetingCodePrefKey"; static NSString* const kAdsEnabledPrefKey = - [NSString stringWithUTF8String:ads::prefs::kEnabled]; + base::SysUTF8ToNSString(ads::prefs::kEnabled); static NSString* const kNumberOfAdsPerHourKey = - [NSString stringWithUTF8String:ads::prefs::kAdsPerHour]; + base::SysUTF8ToNSString(ads::prefs::kAdsPerHour); static NSString* const kShouldAllowAdsSubdivisionTargetingPrefKey = [NSString stringWithUTF8String:ads::prefs::kShouldAllowAdsSubdivisionTargeting]; static NSString* const kAdsSubdivisionTargetingCodePrefKey = - [NSString stringWithUTF8String:ads::prefs::kAdsSubdivisionTargetingCode]; + base::SysUTF8ToNSString(ads::prefs::kAdsSubdivisionTargetingCode); static NSString* const kAutoDetectedAdsSubdivisionTargetingCodePrefKey = [NSString stringWithUTF8String: ads::prefs::kAutoDetectedAdsSubdivisionTargetingCode]; @@ -83,17 +87,17 @@ ads::DBCommandResponsePtr RunDBTransactionOnTaskRunner( } // namespace -@interface BATAdNotification () +@interface AdNotificationIOS () - (instancetype)initWithNotificationInfo:(const ads::AdNotificationInfo&)info; @end -@interface BATInlineContentAd () +@interface InlineContentAdIOS () - (instancetype)initWithInlineContentAdInfo: (const ads::InlineContentAdInfo&)info; @end -@interface BATBraveAds () { - NativeAdsClient* adsClient; +@interface BraveAds () { + AdsClientIOS* adsClient; ads::Ads* ads; ads::Database* adsDatabase; ads::AdEventHistory* adEventHistory; @@ -102,7 +106,7 @@ ads::DBCommandResponsePtr RunDBTransactionOnTaskRunner( nw_path_monitor_t networkMonitor; dispatch_queue_t monitorQueue; } -@property(nonatomic) BATCommonOperations* commonOps; +@property(nonatomic) BraveCommonOperations* commonOps; @property(nonatomic) BOOL networkConnectivityAvailable; @property(nonatomic, copy) NSString* storagePath; @property(nonatomic) dispatch_group_t prefsWriteGroup; @@ -114,12 +118,12 @@ ads::DBCommandResponsePtr RunDBTransactionOnTaskRunner( @property(nonatomic, readonly) NSDictionary* componentPaths; @end -@implementation BATBraveAds +@implementation BraveAds - (instancetype)initWithStateStoragePath:(NSString*)path { if ((self = [super init])) { self.storagePath = path; - self.commonOps = [[BATCommonOperations alloc] initWithStoragePath:path]; + self.commonOps = [[BraveCommonOperations alloc] initWithStoragePath:path]; adsDatabase = nullptr; adEventHistory = nullptr; @@ -191,13 +195,13 @@ ads::DBCommandResponsePtr RunDBTransactionOnTaskRunner( #pragma mark - Global + (BOOL)isSupportedLocale:(NSString*)locale { - return ads::IsSupportedLocale(std::string(locale.UTF8String)); + return ads::IsSupportedLocale(base::SysNSStringToUTF8(locale)); } + (BOOL)isNewlySupportedLocale:(NSString*)locale { // TODO(khickinson): Add support for last schema version, however for the MVP // we can safely pass 0 as all locales are newly supported - return ads::IsNewlySupportedLocale(std::string(locale.UTF8String), 0); + return ads::IsNewlySupportedLocale(base::SysNSStringToUTF8(locale), 0); } + (BOOL)isCurrentLocaleSupported { @@ -234,51 +238,43 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) + (BATBraveAdsBuildChannel*)buildChannel { auto build_channel = [[BATBraveAdsBuildChannel alloc] init]; build_channel.isRelease = ads::g_build_channel.is_release; - build_channel.name = - [NSString stringWithUTF8String:ads::g_build_channel.name.c_str()]; + build_channel.name = base::SysUTF8ToNSString(ads::g_build_channel.name); return build_channel; } + (void)setBuildChannel:(BATBraveAdsBuildChannel*)buildChannel { ads::g_build_channel.is_release = buildChannel.isRelease; - ads::g_build_channel.name = buildChannel.name.UTF8String; + ads::g_build_channel.name = base::SysNSStringToUTF8(buildChannel.name); } #pragma mark - Initialization / Shutdown -- (void)initializeIfAdsEnabled { +- (void)initializeIfAdsEnabled:(void (^)(bool))completion { if (![self isAdsServiceRunning] && self.enabled) { - const auto* dbPath = [self adsDatabasePath].UTF8String; + const auto dbPath = base::SysNSStringToUTF8([self adsDatabasePath]); adsDatabase = new ads::Database(base::FilePath(dbPath)); adEventHistory = new ads::AdEventHistory(); - adsClient = new NativeAdsClient(self); + adsClient = new AdsClientIOS(self); ads = ads::Ads::CreateInstance(adsClient); - - if (!self.ledger) { - return; - } - [self.ledger currentWalletInfo:^(BATBraveWallet* _Nullable wallet) { - if (!wallet || wallet.recoverySeed.count == 0) { - BLOG(0, @"Failed to obtain wallet information to initialize ads"); - return; - } - std::vector seed; - for (NSNumber* number in wallet.recoverySeed) { - seed.push_back(static_cast(number.unsignedCharValue)); - } - self->ads->OnWalletUpdated(wallet.paymentId.UTF8String, - base::Base64Encode(seed)); - self->ads->Initialize(^(bool) { - [self periodicallyCheckForAdsResourceUpdates]; - [self registerAdsResources]; - }); - }]; + ads->Initialize(^(ads::Result result) { + [self periodicallyCheckForAdsResourceUpdates]; + [self registerAdsResources]; + completion(result == ads::Result::SUCCESS); + }); } } +- (void)updateWalletInfo:(NSString*)paymentId base64Seed:(NSString*)base64Seed { + if (![self isAdsServiceRunning]) { + return; + } + ads->OnWalletUpdated(base::SysNSStringToUTF8(paymentId), + base::SysNSStringToUTF8(base64Seed)); +} + - (NSString*)adsDatabasePath { return [self.storagePath stringByAppendingPathComponent:@"Ads.db"]; } @@ -290,7 +286,8 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) [NSFileManager.defaultManager removeItemAtPath:[dbPath stringByAppendingString:@"-journal"] error:nil]; - adsDatabase = new ads::Database(base::FilePath(dbPath.UTF8String)); + adsDatabase = + new ads::Database(base::FilePath(base::SysNSStringToUTF8(dbPath))); } - (void)shutdown:(nullable void (^)())completion { @@ -338,10 +335,6 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) - (void)setEnabled:(BOOL)enabled { self.prefs[kAdsEnabledPrefKey] = @(enabled); [self savePref:kAdsEnabledPrefKey]; - - if (enabled) { - [self initializeIfAdsEnabled]; - } } - (BOOL)shouldAllowAdConversionTracking { @@ -390,7 +383,7 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) - (void)savePref:(NSString*)name { if ([self isAdsServiceRunning]) { - ads->OnPrefChanged(name.UTF8String); + ads->OnPrefChanged(base::SysNSStringToUTF8(name)); } [self savePrefs]; @@ -576,7 +569,7 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) if (![self isAdsServiceRunning]) { return; } - const auto urlString = std::string(url.absoluteString.UTF8String); + const auto urlString = base::SysNSStringToUTF8(url.absoluteString); ads->OnTabUpdated((int32_t)tabId, urlString, isSelected, [self isForeground], isPrivate); } @@ -595,7 +588,8 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) return; } ads->OnAdNotificationEvent( - uuid.UTF8String, static_cast(eventType)); + base::SysNSStringToUTF8(uuid), + static_cast(eventType)); } - (void)reportNewTabPageAdEvent:(NSString*)wallpaperId @@ -604,8 +598,8 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) if (![self isAdsServiceRunning]) { return; } - ads->OnNewTabPageAdEvent(wallpaperId.UTF8String, - creativeInstanceId.UTF8String, + ads->OnNewTabPageAdEvent(base::SysNSStringToUTF8(wallpaperId), + base::SysNSStringToUTF8(creativeInstanceId), static_cast(eventType)); } @@ -613,17 +607,16 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) completion: (void (^)(BOOL success, NSString* dimensions, - BATInlineContentAd* ad))completion { + InlineContentAdIOS* ad))completion { if (![self isAdsServiceRunning]) { return; } - ads->GetInlineContentAd(dimensions.UTF8String, ^( + ads->GetInlineContentAd(base::SysNSStringToUTF8(dimensions), ^( const bool success, const std::string& dimensions, const ads::InlineContentAdInfo& ad) { const auto inline_content_ad = - [[BATInlineContentAd alloc] initWithInlineContentAdInfo:ad]; - completion(success, [NSString stringWithUTF8String:dimensions.c_str()], - inline_content_ad); + [[InlineContentAdIOS alloc] initWithInlineContentAdInfo:ad]; + completion(success, base::SysUTF8ToNSString(dimensions), inline_content_ad); }); } @@ -635,7 +628,8 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) return; } ads->OnInlineContentAdEvent( - uuid.UTF8String, creativeInstanceId.UTF8String, + base::SysNSStringToUTF8(uuid), + base::SysNSStringToUTF8(creativeInstanceId), static_cast(eventType)); } @@ -647,7 +641,8 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) return; } ads->OnPromotedContentAdEvent( - uuid.UTF8String, creativeInstanceId.UTF8String, + base::SysNSStringToUTF8(uuid), + base::SysNSStringToUTF8(creativeInstanceId), static_cast(eventType)); } @@ -655,7 +650,8 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) if (![self isAdsServiceRunning]) { return; } - ads->purgeOrphanedAdEventsForType(adType.UTF8String); + ads->PurgeOrphanedAdEventsForType( + static_cast(adType)); } - (void)reconcileAdRewards { @@ -692,7 +688,8 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) if (![self isAdsServiceRunning]) { return; } - ads->ToggleAdThumbUp(creativeInstanceId.UTF8String, creativeSetID.UTF8String, + ads->ToggleAdThumbUp(base::SysNSStringToUTF8(creativeInstanceId), + base::SysNSStringToUTF8(creativeSetID), ads::AdContentInfo::LikeAction::kThumbsUp); } @@ -701,8 +698,8 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) if (![self isAdsServiceRunning]) { return; } - ads->ToggleAdThumbDown(creativeInstanceId.UTF8String, - creativeSetID.UTF8String, + ads->ToggleAdThumbDown(base::SysNSStringToUTF8(creativeInstanceId), + base::SysNSStringToUTF8(creativeSetID), ads::AdContentInfo::LikeAction::kThumbsDown); } @@ -746,8 +743,7 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) {ads::UrlRequestMethod::POST, "POST"}, {ads::UrlRequestMethod::PUT, "PUT"}}; - const auto copiedURL = - [NSString stringWithUTF8String:url_request->url.c_str()]; + const auto copiedURL = base::SysUTF8ToNSString(url_request->url); const auto __weak weakSelf = self; return [self.commonOps @@ -765,7 +761,7 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) return; } ads::UrlResponse url_response; - url_response.url = copiedURL.UTF8String; + url_response.url = base::SysNSStringToUTF8(copiedURL); url_response.status_code = statusCode; url_response.body = response; url_response.headers = headers; @@ -814,7 +810,7 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) } if (success) { const std::string bridged_language_code_adsResource_idkey = - languageCodeAdsResourceId.UTF8String; + base::SysNSStringToUTF8(languageCodeAdsResourceId); strongSelf->ads->OnResourceComponentUpdated( bridged_language_code_adsResource_idkey); } @@ -851,7 +847,7 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) } if (success) { const std::string bridged_country_code_adsResource_idkey = - countryCodeAdsResourceId.UTF8String; + base::SysNSStringToUTF8(countryCodeAdsResourceId); strongSelf->ads->OnResourceComponentUpdated( bridged_country_code_adsResource_idkey); @@ -916,22 +912,22 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) BLOG(1, @"Checking %@ ads resource for updates", key); const auto __weak weakSelf = self; - [self - downloadAdsResource:key - completion:^(BOOL success) { - const auto strongSelf = weakSelf; - if (!strongSelf) { - return; - } + [self downloadAdsResource:key + completion:^(BOOL success) { + const auto strongSelf = weakSelf; + if (!strongSelf) { + return; + } - if (!success) { - BLOG(1, @"Failed to update ads resources"); - return; - } + if (!success) { + BLOG(1, @"Failed to update ads resources"); + return; + } - BLOG(1, @"Notifying ads resource observers"); - strongSelf->ads->OnResourceComponentUpdated(key.UTF8String); - }]; + BLOG(1, @"Notifying ads resource observers"); + strongSelf->ads->OnResourceComponentUpdated( + base::SysNSStringToUTF8(key)); + }]; } } @@ -981,7 +977,7 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) NSString* manifestUrl = [baseUrl stringByAppendingPathComponent:@"resources.json"]; - [self.commonOps loadURLRequest:manifestUrl.UTF8String + [self.commonOps loadURLRequest:base::SysNSStringToUTF8(manifestUrl) headers:{} content:"" content_type:"" @@ -1006,7 +1002,7 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) return; } - NSData* data = [[NSString stringWithUTF8String:response.c_str()] + NSData* data = [base::SysUTF8ToNSString(response) dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:data options:0 @@ -1068,7 +1064,8 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) version); dispatch_group_enter(group); - [strongSelf.commonOps loadURLRequest:adsResourceUrl.UTF8String + [strongSelf.commonOps + loadURLRequest:base::SysNSStringToUTF8(adsResourceUrl) headers:{} content:"" content_type:"" @@ -1132,7 +1129,7 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) - (void)loadAdsResource:(const std::string&)id version:(const int)version callback:(ads::LoadCallback)callback { - NSString* bridgedId = [NSString stringWithUTF8String:id.c_str()]; + NSString* bridgedId = base::SysUTF8ToNSString(id); BLOG(1, @"Loading %@ ads resource", bridgedId); @@ -1158,10 +1155,9 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) } - (const std::string)loadResourceForId:(const std::string&)id { - const auto bundle = [NSBundle bundleForClass:[BATBraveAds class]]; - const auto path = - [bundle pathForResource:[NSString stringWithUTF8String:id.c_str()] - ofType:nil]; + const auto bundle = [NSBundle bundleForClass:[BraveAds class]]; + const auto path = [bundle pathForResource:base::SysUTF8ToNSString(id) + ofType:nil]; if (!path || path.length == 0) { return ""; } @@ -1199,20 +1195,22 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) line:(const int)line verboseLevel:(const int)verbose_level message:(const std::string&)message { - rewards::LogMessage(file, line, verbose_level, - [NSString stringWithUTF8String:message.c_str()]); + const int vlog_level = logging::GetVlogLevelHelper(file, strlen(file)); + if (verbose_level <= vlog_level) { + logging::LogMessage(file, line, -verbose_level).stream() << message; + } } #pragma mark - Notifications -- (nullable BATAdNotification*)adsNotificationForIdentifier: +- (nullable AdNotificationIOS*)adsNotificationForIdentifier: (NSString*)identifier { if (![self isAdsServiceRunning]) { return nil; } ads::AdNotificationInfo info; if (ads->GetAdNotification(identifier.UTF8String, &info)) { - return [[BATAdNotification alloc] initWithNotificationInfo:info]; + return [[AdNotificationIOS alloc] initWithNotificationInfo:info]; } return nil; } @@ -1223,12 +1221,12 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) - (void)showNotification:(const ads::AdNotificationInfo&)info { const auto notification = - [[BATAdNotification alloc] initWithNotificationInfo:info]; + [[AdNotificationIOS alloc] initWithNotificationInfo:info]; [self.notificationsHandler showNotification:notification]; } - (void)closeNotification:(const std::string&)id { - const auto bridgedId = [NSString stringWithUTF8String:id.c_str()]; + const auto bridgedId = base::SysUTF8ToNSString(id); [self.notificationsHandler clearNotificationWithIdentifier:bridgedId]; } @@ -1291,7 +1289,7 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) - (void)runDBTransaction:(ads::DBTransactionPtr)transaction callback:(ads::RunDBTransactionCallback)callback { - __weak BATBraveAds* weakSelf = self; + __weak BraveAds* weakSelf = self; base::PostTaskAndReplyWithResult( databaseQueue.get(), FROM_HERE, base::BindOnce(&RunDBTransactionOnTaskRunner, std::move(transaction), @@ -1310,13 +1308,13 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) } - (void)setBooleanPref:(const std::string&)path value:(const bool)value { - const auto key = [NSString stringWithUTF8String:path.c_str()]; + const auto key = base::SysUTF8ToNSString(path); self.prefs[key] = @(value); [self savePref:key]; } - (bool)getBooleanPref:(const std::string&)path { - const auto key = [NSString stringWithUTF8String:path.c_str()]; + const auto key = base::SysUTF8ToNSString(path); if (path == ads::prefs::kShouldAllowConversionTracking) { return [self shouldAllowAdConversionTracking]; } @@ -1324,35 +1322,35 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) } - (void)setIntegerPref:(const std::string&)path value:(const int)value { - const auto key = [NSString stringWithUTF8String:path.c_str()]; + const auto key = base::SysUTF8ToNSString(path); self.prefs[key] = @(value); [self savePref:key]; } - (int)getIntegerPref:(const std::string&)path { - const auto key = [NSString stringWithUTF8String:path.c_str()]; + const auto key = base::SysUTF8ToNSString(path); return [self.prefs[key] intValue]; } - (void)setDoublePref:(const std::string&)path value:(const double)value { - const auto key = [NSString stringWithUTF8String:path.c_str()]; + const auto key = base::SysUTF8ToNSString(path); self.prefs[key] = @(value); [self savePref:key]; } - (double)getDoublePref:(const std::string&)path { - const auto key = [NSString stringWithUTF8String:path.c_str()]; + const auto key = base::SysUTF8ToNSString(path); return [self.prefs[key] doubleValue]; } - (void)setStringPref:(const std::string&)path value:(const std::string&)value { - const auto key = [NSString stringWithUTF8String:path.c_str()]; - self.prefs[key] = [NSString stringWithUTF8String:value.c_str()]; + const auto key = base::SysUTF8ToNSString(path); + self.prefs[key] = base::SysUTF8ToNSString(value); [self savePref:key]; } - (std::string)getStringPref:(const std::string&)path { - const auto key = [NSString stringWithUTF8String:path.c_str()]; + const auto key = base::SysUTF8ToNSString(path); const auto value = (NSString*)self.prefs[key]; if (!value) { return ""; @@ -1361,29 +1359,29 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug) } - (void)setInt64Pref:(const std::string&)path value:(const int64_t)value { - const auto key = [NSString stringWithUTF8String:path.c_str()]; + const auto key = base::SysUTF8ToNSString(path); self.prefs[key] = @(value); [self savePref:key]; } - (int64_t)getInt64Pref:(const std::string&)path { - const auto key = [NSString stringWithUTF8String:path.c_str()]; + const auto key = base::SysUTF8ToNSString(path); return [self.prefs[key] longLongValue]; } - (void)setUint64Pref:(const std::string&)path value:(const uint64_t)value { - const auto key = [NSString stringWithUTF8String:path.c_str()]; + const auto key = base::SysUTF8ToNSString(path); self.prefs[key] = @(value); [self savePref:key]; } - (uint64_t)getUint64Pref:(const std::string&)path { - const auto key = [NSString stringWithUTF8String:path.c_str()]; + const auto key = base::SysUTF8ToNSString(path); return [self.prefs[key] unsignedLongLongValue]; } - (void)clearPref:(const std::string&)path { - const auto key = [NSString stringWithUTF8String:path.c_str()]; + const auto key = base::SysUTF8ToNSString(path); [self.prefs removeObjectForKey:key]; [self savePref:key]; } diff --git a/vendor/brave-ios/Ads/BATInlineContentAd.h b/ios/browser/api/ads/inline_content_ad_ios.h similarity index 68% rename from vendor/brave-ios/Ads/BATInlineContentAd.h rename to ios/browser/api/ads/inline_content_ad_ios.h index da4b8f0a516..32a2678eb54 100644 --- a/vendor/brave-ios/Ads/BATInlineContentAd.h +++ b/ios/browser/api/ads/inline_content_ad_ios.h @@ -1,14 +1,18 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ #import +#ifndef BRAVE_IOS_BROWSER_API_ADS_INLINE_CONTENT_AD_IOS_H_ +#define BRAVE_IOS_BROWSER_API_ADS_INLINE_CONTENT_AD_IOS_H_ + NS_ASSUME_NONNULL_BEGIN OBJC_EXPORT NS_SWIFT_NAME(InlineContentAd) -@interface BATInlineContentAd : NSObject +@interface InlineContentAdIOS : NSObject @property(nonatomic, readonly, copy) NSString* uuid; @property(nonatomic, readonly, copy) NSString* creativeInstanceID; @property(nonatomic, readonly, copy) NSString* creativeSetID; @@ -24,3 +28,5 @@ NS_SWIFT_NAME(InlineContentAd) @end NS_ASSUME_NONNULL_END + +#endif // BRAVE_IOS_BROWSER_API_ADS_INLINE_CONTENT_AD_IOS_H_ diff --git a/ios/browser/api/ads/inline_content_ad_ios.mm b/ios/browser/api/ads/inline_content_ad_ios.mm new file mode 100644 index 00000000000..9a721f2f719 --- /dev/null +++ b/ios/browser/api/ads/inline_content_ad_ios.mm @@ -0,0 +1,52 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#import "inline_content_ad_ios.h" + +#include "base/strings/sys_string_conversions.h" +#include "bat/ads/inline_content_ad_info.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@interface InlineContentAdIOS () +@property(nonatomic, copy) NSString* uuid; +@property(nonatomic, copy) NSString* creativeInstanceID; +@property(nonatomic, copy) NSString* creativeSetID; +@property(nonatomic, copy) NSString* campaignID; +@property(nonatomic, copy) NSString* advertiserID; +@property(nonatomic, copy) NSString* segment; +@property(nonatomic, copy) NSString* title; +@property(nonatomic, copy) NSString* message; +@property(nonatomic, copy) NSString* imageURL; +@property(nonatomic, copy) NSString* dimensions; +@property(nonatomic, copy) NSString* ctaText; +@property(nonatomic, copy) NSString* targetURL; +@end + +@implementation InlineContentAdIOS + +- (instancetype)initWithInlineContentAdInfo: + (const ads::InlineContentAdInfo&)info { + if ((self = [super init])) { + self.uuid = base::SysUTF8ToNSString(info.uuid); + self.creativeInstanceID = + base::SysUTF8ToNSString(info.creative_instance_id); + self.creativeSetID = base::SysUTF8ToNSString(info.creative_set_id); + self.campaignID = base::SysUTF8ToNSString(info.campaign_id); + self.advertiserID = base::SysUTF8ToNSString(info.advertiser_id); + self.segment = base::SysUTF8ToNSString(info.segment); + self.title = base::SysUTF8ToNSString(info.title); + self.message = base::SysUTF8ToNSString(info.description); + self.imageURL = base::SysUTF8ToNSString(info.image_url); + self.dimensions = base::SysUTF8ToNSString(info.dimensions); + self.ctaText = base::SysUTF8ToNSString(info.cta_text); + self.targetURL = base::SysUTF8ToNSString(info.target_url); + } + return self; +} + +@end diff --git a/ios/browser/api/common/BUILD.gn b/ios/browser/api/common/BUILD.gn new file mode 100644 index 00000000000..2edaa46a524 --- /dev/null +++ b/ios/browser/api/common/BUILD.gn @@ -0,0 +1,24 @@ +# Copyright (c) 2020 The Brave Authors. All rights reserved. +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this file, +# You can obtain one at http://mozilla.org/MPL/2.0/. + +import("//build/config/ios/rules.gni") +import("//ios/build/config.gni") + +source_set("common") { + configs += [ "//build/config/compiler:enable_arc" ] + + sources = [ + "common_operations.h", + "common_operations.mm", + ] + + deps = [ + "//base", + "//net", + "//url", + ] + + frameworks = [ "Foundation.framework" ] +} diff --git a/vendor/brave-ios/Shared/BATCommonOperations.h b/ios/browser/api/common/common_operations.h similarity index 56% rename from vendor/brave-ios/Shared/BATCommonOperations.h rename to ios/browser/api/common/common_operations.h index 105262ddb29..1127ab29e33 100644 --- a/vendor/brave-ios/Shared/BATCommonOperations.h +++ b/ios/browser/api/common/common_operations.h @@ -1,28 +1,33 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_IOS_BROWSER_API_COMMON_COMMON_OPERATIONS_H_ +#define BRAVE_IOS_BROWSER_API_COMMON_COMMON_OPERATIONS_H_ #import - -#import -#import - +#include +#include +#include #import "base/containers/flat_map.h" NS_ASSUME_NONNULL_BEGIN -/// A standard network completion block. Matches the native-ads/native-rewards signature, but -/// each library uses their own typedef from their namespaces -typedef void (^BATNetworkCompletionBlock)(const std::string& errorDescription, - int statusCode, - const std::string& response, - const base::flat_map& headers); +/// A standard network completion block. Matches the native-ads/native-rewards +/// signature, but each library uses their own typedef from their namespaces +typedef void (^BATNetworkCompletionBlock)( + const std::string& errorDescription, + int statusCode, + const std::string& response, + const base::flat_map& headers); /// A set of common operations that accept and return C++ types OBJC_EXPORT -@interface BATCommonOperations : NSObject +@interface BraveCommonOperations : NSObject -- (instancetype)initWithStoragePath:(nullable NSString *)storagePath NS_DESIGNATED_INITIALIZER; +- (instancetype)initWithStoragePath:(nullable NSString*)storagePath + NS_DESIGNATED_INITIALIZER; #pragma mark - @@ -31,7 +36,7 @@ OBJC_EXPORT #pragma mark - Network -@property (nonatomic, copy, nullable) NSString *customUserAgent; +@property(nonatomic, copy, nullable) NSString* customUserAgent; /// Loads a URL request - (void)loadURLRequest:(const std::string&)url @@ -53,3 +58,5 @@ OBJC_EXPORT @end NS_ASSUME_NONNULL_END + +#endif // BRAVE_IOS_BROWSER_API_COMMON_COMMON_OPERATIONS_H_ diff --git a/ios/browser/api/common/common_operations.mm b/ios/browser/api/common/common_operations.mm new file mode 100644 index 00000000000..a7082f65cab --- /dev/null +++ b/ios/browser/api/common/common_operations.mm @@ -0,0 +1,208 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#import "common_operations.h" +#include +#include "base/logging.h" +#include "base/strings/sys_string_conversions.h" + +@interface BraveCommonOperations () +@property(nonatomic, copy) NSString* storagePath; +@property(nonatomic, assign) uint32_t currentTimerID; +@property(nonatomic, copy) + NSMutableDictionary* timers; // {ID: Timer} +@property(nonatomic, copy) NSMutableArray* runningTasks; +@end + +@implementation BraveCommonOperations + +- (instancetype)initWithStoragePath:(NSString*)storagePath { + if ((self = [super init])) { + self.storagePath = storagePath; + _timers = [[NSMutableDictionary alloc] init]; + _runningTasks = [[NSMutableArray alloc] init]; + + // Setup the ads directory for persistant storage + if (self.storagePath.length > 0) { + if (![NSFileManager.defaultManager fileExistsAtPath:self.storagePath + isDirectory:nil]) { + [NSFileManager.defaultManager createDirectoryAtPath:self.storagePath + withIntermediateDirectories:true + attributes:nil + error:nil]; + } + } + } + return self; +} + +- (instancetype)init { + return [self initWithStoragePath:nil]; +} + +- (void)dealloc { + [self.runningTasks makeObjectsPerformSelector:@selector(cancel)]; + for (NSNumber* timerID in self.timers) { + [self.timers[timerID] invalidate]; + } +} + +- (const std::string)generateUUID { + return std::string([NSUUID UUID].UUIDString.UTF8String); +} + +- (void)loadURLRequest:(const std::string&)url + headers:(const std::vector&)headers + content:(const std::string&)content + content_type:(const std::string&)content_type + method:(const std::string&)method + callback:(BATNetworkCompletionBlock)callback { + const auto session = NSURLSession.sharedSession; + const auto nsurl = + [NSURL URLWithString:[NSString stringWithUTF8String:url.c_str()]]; + const auto request = [[NSMutableURLRequest alloc] initWithURL:nsurl]; + + for (const auto& header : headers) { + const auto bridged = [NSString stringWithUTF8String:header.c_str()]; + const auto split = [bridged componentsSeparatedByString:@":"]; + if (split.count == 2 && split.firstObject && split.lastObject) { + auto name = [split.firstObject + stringByTrimmingCharactersInSet:[NSCharacterSet + whitespaceCharacterSet]]; + auto value = [split.lastObject + stringByTrimmingCharactersInSet:[NSCharacterSet + whitespaceCharacterSet]]; + [request setValue:value forHTTPHeaderField:name]; + } + } + + if (self.customUserAgent != nil && self.customUserAgent.length > 0) { + [request setValue:self.customUserAgent forHTTPHeaderField:@"User-Agent"]; + } + + if (content_type.length() > 0) { + [request setValue:[NSString stringWithUTF8String:content_type.c_str()] + forHTTPHeaderField:@"Content-Type"]; + } + + request.HTTPMethod = [NSString stringWithUTF8String:method.c_str()]; + + if (method != "GET" && content.length() > 0) { + // Assumed http body + request.HTTPBody = [[NSString stringWithUTF8String:content.c_str()] + dataUsingEncoding:NSUTF8StringEncoding]; + } + + const auto __weak weakSelf = self; + NSURLSessionDataTask* task = nil; + task = [session + dataTaskWithRequest:request + completionHandler:^(NSData* _Nullable data, + NSURLResponse* _Nullable urlResponse, + NSError* _Nullable error) { + if (!weakSelf) { + return; + }; + const auto strongSelf = weakSelf; + + const auto response = (NSHTTPURLResponse*)urlResponse; + std::string body; + if (data && data.length > 0) { + body = + std::string(static_cast(data.bytes), data.length); + } + std::string errorDescription; + if (error) { + errorDescription = error.localizedDescription.UTF8String; + } + // For some reason I couldn't just do `base::flat_map responseHeaders;` due to base::flat_map's non-const + // key insertion + auto* responseHeaders = + new base::flat_map(); + [response.allHeaderFields + enumerateKeysAndObjectsUsingBlock:^(NSString* _Nonnull key, + NSString* _Nonnull obj, + BOOL* _Nonnull stop) { + if (![key isKindOfClass:NSString.class] || + ![obj isKindOfClass:NSString.class]) { + return; + } + std::string stringKey(key.UTF8String); + std::string stringValue(obj.UTF8String); + responseHeaders->insert(std::make_pair(stringKey, stringValue)); + }]; + auto copiedHeaders = + base::flat_map(*responseHeaders); + const auto __weak weakSelf2 = strongSelf; + dispatch_async(dispatch_get_main_queue(), ^{ + if (!weakSelf2) { + return; + } + [weakSelf2.runningTasks removeObject:task]; + callback(errorDescription, (int)response.statusCode, body, + copiedHeaders); + }); + delete responseHeaders; + }]; + // dataTaskWithRequest returns _Nonnull, so no need to worry about initialized + // variable being nil + [self.runningTasks addObject:task]; + [task resume]; +} + +#pragma mark - + +- (NSString*)dataPathForFilename:(NSString*)filename { + return [self.storagePath stringByAppendingPathComponent:filename]; +} + +- (bool)saveContents:(const std::string&)contents + name:(const std::string&)name { + const auto filename = [NSString stringWithUTF8String:name.c_str()]; + const auto nscontents = [NSString stringWithUTF8String:contents.c_str()]; + NSError* error = nil; + const auto path = [self dataPathForFilename:filename]; + const auto result = [nscontents writeToFile:path + atomically:YES + encoding:NSUTF8StringEncoding + error:&error]; + if (error) { + LOG(ERROR) << "Failed to save data for " << name << ": " + << base::SysNSStringToUTF8(error.localizedDescription); + } + return result; +} + +- (std::string)loadContentsFromFileWithName:(const std::string&)name { + const auto filename = [NSString stringWithUTF8String:name.c_str()]; + NSError* error = nil; + const auto path = [self dataPathForFilename:filename]; + // BLOG(2, @"Loading contents from file: %@", path); + const auto contents = [NSString stringWithContentsOfFile:path + encoding:NSUTF8StringEncoding + error:&error]; + if (error) { + LOG(ERROR) << "Failed to load data for " << name << ": " + << base::SysNSStringToUTF8(error.localizedDescription); + return ""; + } + return std::string(contents.UTF8String); +} + +- (bool)removeFileWithName:(const std::string&)name { + const auto filename = [NSString stringWithUTF8String:name.c_str()]; + NSError* error = nil; + const auto path = [self dataPathForFilename:filename]; + const auto result = [NSFileManager.defaultManager removeItemAtPath:path + error:&error]; + if (error) { + LOG(ERROR) << "Failed to remove data for " << name << ": " + << base::SysNSStringToUTF8(error.localizedDescription); + return false; + } + return result; +} + +@end diff --git a/ios/browser/api/ledger/BUILD.gn b/ios/browser/api/ledger/BUILD.gn new file mode 100644 index 00000000000..cd20b21a849 --- /dev/null +++ b/ios/browser/api/ledger/BUILD.gn @@ -0,0 +1,58 @@ +# Copyright (c) 2021 The Brave Authors. All rights reserved. +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +import("//brave/build/ios/coredata_model.gni") +import("//brave/build/ios/mojom/mojom_wrappers.gni") +import("//build/config/ios/rules.gni") + +config("external_config") { + visibility = [ ":*" ] + include_dirs = [ "$target_gen_dir" ] +} + +source_set("ledger") { + configs += [ + ":external_config", + "//build/config/compiler:enable_arc", + ] + + sources = [ + "brave_ledger.h", + "brave_ledger.mm", + "brave_ledger_observer.h", + "brave_ledger_observer.mm", + "ledger_client_bridge.h", + "ledger_client_ios.h", + "ledger_client_ios.mm", + "promotion_solution.h", + "promotion_solution.mm", + "rewards_notification.h", + "rewards_notification.m", + ] + + deps = [ + ":ledger_mojom_wrappers", + "//base", + "//brave/ios/browser/api/common", + "//brave/ios/browser/api/ledger/legacy_database", + "//brave/vendor/bat-native-ledger", + "//components/os_crypt", + "//net:net", + "//url", + ] + + frameworks = [ + "Foundation.framework", + "UIKit.framework", + "Network.framework", + ] +} + +mojom_wrappers("ledger_mojom_wrappers") { + mojom_target = + "//brave/vendor/bat-native-ledger/include/bat/ledger/public/interfaces" + mojom_file = "//brave/vendor/bat-native-ledger/include/bat/ledger/public/interfaces/ledger.mojom" + class_prefix = "BAT" +} diff --git a/vendor/brave-ios/Ledger/DEPS b/ios/browser/api/ledger/DEPS similarity index 100% rename from vendor/brave-ios/Ledger/DEPS rename to ios/browser/api/ledger/DEPS diff --git a/ios/browser/api/ledger/brave_ledger.h b/ios/browser/api/ledger/brave_ledger.h new file mode 100644 index 00000000000..09ef2e72082 --- /dev/null +++ b/ios/browser/api/ledger/brave_ledger.h @@ -0,0 +1,367 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_IOS_BROWSER_API_LEDGER_BRAVE_LEDGER_H_ +#define BRAVE_IOS_BROWSER_API_LEDGER_BRAVE_LEDGER_H_ + +#import +#import "ledger.mojom.objc.h" + +@class BraveLedgerObserver, PromotionSolution, RewardsNotification; + +NS_ASSUME_NONNULL_BEGIN + +typedef NSString* ExternalWalletType NS_SWIFT_NAME(ExternalWalletType) + NS_STRING_ENUM; + +static ExternalWalletType const ExternalWalletTypeUphold = @"uphold"; +static ExternalWalletType const ExternalWalletTypeAnonymous = @"anonymous"; +static ExternalWalletType const ExternalWalletTypeUnblindedTokens = @"blinded"; + +typedef void (^LedgerFaviconFetcher)( + NSURL* pageURL, + void (^completion)(NSURL* _Nullable faviconURL)); + +/// The error domain for ledger related errors +OBJC_EXPORT NSString* const BraveLedgerErrorDomain; + +OBJC_EXPORT NSNotificationName const BraveLedgerNotificationAdded + NS_SWIFT_NAME(BraveLedger.notificationAdded); + +typedef NSString* BraveGeneralLedgerNotificationID NS_STRING_ENUM; +OBJC_EXPORT BraveGeneralLedgerNotificationID const + BraveGeneralLedgerNotificationIDWalletNowVerified; +OBJC_EXPORT BraveGeneralLedgerNotificationID const + BraveGeneralLedgerNotificationIDWalletDisconnected; + +OBJC_EXPORT +@interface BraveLedger : NSObject + +@property(nonatomic, copy, nullable) LedgerFaviconFetcher faviconFetcher; + +/// Create a brave ledger that will read and write its state to the given path +- (instancetype)initWithStateStoragePath:(NSString*)path; + +- (instancetype)init NS_UNAVAILABLE; + +#pragma mark - Initialization + +/// Initialize the ledger service. +/// +/// This must be called before other methods on this class are called +- (void)initializeLedgerService:(nullable void (^)())completion; + +/// Whether or not the ledger service has been initialized already +@property(nonatomic, readonly, getter=isInitialized) BOOL initialized; + +/// Whether or not the ledger service is currently initializing +@property(nonatomic, readonly, getter=isInitializing) BOOL initializing; + +/// The result when initializing the ledger service. Should be +/// `BATResultLedgerOk` if `initialized` is `true` +/// +/// If this is not `BATResultLedgerOk`, rewards is not usable for the user +@property(nonatomic, readonly) BATResult initializationResult; + +/// Whether or not data migration failed when initializing and the user should +/// be notified. +@property(nonatomic, readonly) BOOL dataMigrationFailed; + +#pragma mark - Observers + +/// Add an interface to the list of observers +/// +/// Observers are stored weakly and do not necessarily need to be removed +- (void)addObserver:(BraveLedgerObserver*)observer; + +/// Removes an interface from the list of observers +- (void)removeObserver:(BraveLedgerObserver*)observer; + +#pragma mark - Global + +/// Whether or not to use staging servers. Defaults to false +@property(nonatomic, class, getter=isDebug) BOOL debug; +/// The environment that ledger is communicating with +@property(nonatomic, class) BATEnvironment environment; +/// Marks if this is being ran in a test environment. Defaults to false +@property(nonatomic, class, getter=isTesting) BOOL testing; +/// Number of minutes between reconciles override. Defaults to 0 (no override) +@property(nonatomic, class) int reconcileInterval; +/// Whether or not to use short contribution retries. Defaults to false +@property(nonatomic, class) BOOL useShortRetries; + +#pragma mark - Wallet + +/// Whether or not the wallet is currently in the process of being created +@property(nonatomic, readonly, getter=isInitializingWallet) + BOOL initializingWallet; + +/// Creates a cryptocurrency wallet +- (void)createWallet:(nullable void (^)(NSError* _Nullable error))completion; + +/// Get the brave wallet's payment ID and seed for ads confirmations +- (void)currentWalletInfo: + (void (^)(BATBraveWallet* _Nullable wallet))completion; + +/// Get parameters served from the server +- (void)getRewardsParameters: + (nullable void (^)(BATRewardsParameters* _Nullable))completion; + +/// The parameters send from the server +@property(nonatomic, readonly, nullable) + BATRewardsParameters* rewardsParameters; + +/// Fetch details about the users wallet (if they have one) and assigns it to +/// `balance` +- (void)fetchBalance:(nullable void (^)(BATBalance* _Nullable))completion; + +/// The users current wallet balance and related info +@property(nonatomic, readonly, nullable) BATBalance* balance; + +/// The wallet's passphrase. nil if the wallet has not been created yet +@property(nonatomic, readonly, nullable) NSString* walletPassphrase; + +/// Recover the users wallet using their passphrase +- (void)recoverWalletUsingPassphrase:(NSString*)passphrase + completion: + (nullable void (^)(NSError* _Nullable))completion; + +/// Retrieves the users most up to date balance to determin whether or not the +/// wallet has a sufficient balance to complete a reconcile +- (void)hasSufficientBalanceToReconcile:(void (^)(BOOL sufficient))completion; + +/// Returns reserved amount of pending contributions to publishers. +- (void)pendingContributionsTotal:(void (^)(double amount))completion + NS_SWIFT_NAME(pendingContributionsTotal(completion:)); + +/// Links a desktop brave wallet given some payment ID +- (void)linkBraveWalletToPaymentId:(NSString*)paymentId + completion:(void (^)(BATResult result, + NSString* drainID))completion + NS_SWIFT_NAME(linkBraveWallet(paymentId:completion:)); + +/// Obtain a drain status given some drain ID previously obtained from +/// `linkBraveWalletToPaymentId:completion:` +- (void)drainStatusForDrainId:(NSString *)drainId + completion:(void (^)(BATResult result, + BATDrainStatus status))completion + NS_SWIFT_NAME(drainStatus(for:completion:)); + +/// Get the amount of BAT that is transferrable via wallet linking +- (void)transferrableAmount:(void (^)(double amount))completion; + +#pragma mark - User Wallets + +/// The last updated external wallet if a user has hooked one up +@property(nonatomic, readonly, nullable) BATExternalWallet* upholdWallet; + +- (void)fetchUpholdWallet: + (nullable void (^)(BATExternalWallet* _Nullable wallet))completion; + +- (void)disconnectWalletOfType:(ExternalWalletType)walletType + completion:(nullable void (^)(BATResult result))completion; + +- (void)authorizeExternalWalletOfType:(ExternalWalletType)walletType + queryItems: + (NSDictionary*)queryItems + completion:(void (^)(BATResult result, + NSURL* _Nullable redirectURL)) + completion; + +#pragma mark - Publishers + +@property(nonatomic, readonly, getter=isLoadingPublisherList) + BOOL loadingPublisherList; + +/// Get publisher info & its activity based on its publisher key +/// +/// This key is _not_ always the URL's host. Use `publisherActivityFromURL` +/// instead when obtaining a publisher given a URL +/// +/// @note `completion` callback is called synchronously +- (void)listActivityInfoFromStart:(unsigned int)start + limit:(unsigned int)limit + filter:(BATActivityInfoFilter*)filter + completion: + (void (^)(NSArray*))completion; + +/// Start a fetch to get a publishers activity information given a URL +/// +/// Use `BraveLedgerObserver` to retrieve a panel publisher if one is found +- (void)fetchPublisherActivityFromURL:(NSURL*)URL + faviconURL:(nullable NSURL*)faviconURL + publisherBlob:(nullable NSString*)publisherBlob + tabId:(uint64_t)tabId; + +/// Update a publishers exclusion state +- (void)updatePublisherExclusionState:(NSString*)publisherId + state:(BATPublisherExclude)state + NS_SWIFT_NAME(updatePublisherExclusionState(withId:state:)); + +/// Restore all sites which had been previously excluded +- (void)restoreAllExcludedPublishers; + +/// Get the publisher banner given some publisher key +/// +/// This key is _not_ always the URL's host. Use `publisherActivityFromURL` +/// instead when obtaining a publisher given a URL +/// +/// @note `completion` callback is called synchronously +- (void)publisherBannerForId:(NSString*)publisherId + completion:(void (^)(BATPublisherBanner* _Nullable banner)) + completion; + +/// Refresh a publishers verification status +- (void)refreshPublisherWithId:(NSString*)publisherId + completion:(void (^)(BATPublisherStatus status))completion; + +#pragma mark - SKUs + +- (void)processSKUItems:(NSArray*)items + completion: + (void (^)(BATResult result, NSString* orderID))completion; + +#pragma mark - Tips + +/// Get a list of publishers who the user has recurring tips on +/// +/// @note `completion` callback is called synchronously +- (void)listRecurringTips:(void (^)(NSArray*))completion; + +- (void)addRecurringTipToPublisherWithId:(NSString*)publisherId + amount:(double)amount + completion:(void (^)(BOOL success))completion + NS_SWIFT_NAME(addRecurringTip(publisherId:amount:completion:)); + +- (void)removeRecurringTipForPublisherWithId:(NSString*)publisherId + NS_SWIFT_NAME(removeRecurringTip(publisherId:)); + +/// Get a list of publishers who the user has made direct tips too +/// +/// @note `completion` callback is called synchronously +- (void)listOneTimeTips:(void (^)(NSArray*))completion; + +- (void)tipPublisherDirectly:(BATPublisherInfo*)publisher + amount:(double)amount + currency:(NSString*)currency + completion:(void (^)(BATResult result))completion; + +#pragma mark - Promotions + +@property(nonatomic, readonly) NSArray* pendingPromotions; + +@property(nonatomic, readonly) NSArray* finishedPromotions; + +/// Updates `pendingPromotions` and `finishedPromotions` based on the database +- (void)updatePendingAndFinishedPromotions: + (nullable void (^)(bool shouldReconcileAds))completion; + +- (void)fetchPromotions:(nullable void (^)(NSArray* grants, + bool shouldReconcileAds))completion; + +- (void)claimPromotion:(NSString*)promotionId + publicKey:(NSString*)deviceCheckPublicKey + completion:(void (^)(BATResult result, + NSString* _Nonnull nonce))completion; + +- (void)attestPromotion:(NSString*)promotionId + solution:(PromotionSolution*)solution + completion:(nullable void (^)(BATResult result, + BATPromotion* _Nullable promotion)) + completion; + +#pragma mark - Pending Contributions + +- (void)pendingContributions: + (void (^)(NSArray* publishers))completion; + +- (void)removePendingContribution:(BATPendingContributionInfo*)info + completion:(void (^)(BATResult result))completion; + +- (void)removeAllPendingContributions:(void (^)(BATResult result))completion; + +#pragma mark - History + +- (void)balanceReportForMonth:(BATActivityMonth)month + year:(int)year + completion:(void (^)(BATBalanceReportInfo* _Nullable info)) + completion; + +@property(nonatomic, readonly) + BATAutoContributeProperties* autoContributeProperties; + +#pragma mark - Misc + ++ (bool)isMediaURL:(NSURL*)url + firstPartyURL:(nullable NSURL*)firstPartyURL + referrerURL:(nullable NSURL*)referrerURL; + +- (void)rewardsInternalInfo: + (void(NS_NOESCAPE ^)(BATRewardsInternalsInfo* _Nullable info))completion; + +- (void)allContributions: + (void (^)(NSArray* contributions))completion; + +@property(nonatomic, readonly, copy) NSString* rewardsDatabasePath; + +#pragma mark - Reporting + +@property(nonatomic) UInt32 selectedTabId; + +/// Report that a page has loaded in the current browser tab, and the HTML is +/// available for analysis +- (void)reportLoadedPageWithURL:(NSURL*)url + tabId:(UInt32)tabId + NS_SWIFT_NAME(reportLoadedPage(url:tabId:)); + +- (void)reportXHRLoad:(NSURL*)url + tabId:(UInt32)tabId + firstPartyURL:(NSURL*)firstPartyURL + referrerURL:(nullable NSURL*)referrerURL; + +- (void)reportPostData:(NSData*)postData + url:(NSURL*)url + tabId:(UInt32)tabId + firstPartyURL:(NSURL*)firstPartyURL + referrerURL:(nullable NSURL*)referrerURL; + +/// Report that a tab with a given id navigated or was closed by the user +- (void)reportTabNavigationOrClosedWithTabId:(UInt32)tabId + NS_SWIFT_NAME(reportTabNavigationOrClosed(tabId:)); + +#pragma mark - Preferences + +/// The number of seconds before a publisher is added. +@property(nonatomic, assign) int minimumVisitDuration; +/// The minimum number of visits before a publisher is added +@property(nonatomic, assign) int minimumNumberOfVisits; +/// Whether or not to allow auto contributions to unverified publishers +@property(nonatomic, assign) BOOL allowUnverifiedPublishers; +/// Whether or not to allow auto contributions to videos +@property(nonatomic, assign) BOOL allowVideoContributions; +/// The auto-contribute amount +@property(nonatomic, assign) double contributionAmount; +/// Whether or not the user will automatically contribute +@property(nonatomic, assign, getter=isAutoContributeEnabled) + BOOL autoContributeEnabled; +/// A custom user agent for network operations on ledger +@property(nonatomic, copy, nullable) NSString* customUserAgent; + +#pragma mark - Notifications + +/// Gets a list of notifications awaiting user interaction +@property(nonatomic, readonly) NSArray* notifications; + +/// Clear a given notification +- (void)clearNotification:(RewardsNotification*)notification; + +/// Clear all the notifications +- (void)clearAllNotifications; + +@end + +NS_ASSUME_NONNULL_END + +#endif // BRAVE_IOS_BROWSER_API_LEDGER_BRAVE_LEDGER_H_ diff --git a/ios/browser/api/ledger/brave_ledger.mm b/ios/browser/api/ledger/brave_ledger.mm new file mode 100644 index 00000000000..21d9d43fefb --- /dev/null +++ b/ios/browser/api/ledger/brave_ledger.mm @@ -0,0 +1,2128 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#import "brave_ledger.h" +#import + +#include "base/base64.h" +#include "base/containers/flat_map.h" +#include "base/ios/ios_util.h" +#include "base/logging.h" +#include "base/sequenced_task_runner.h" +#include "base/strings/sys_string_conversions.h" +#include "base/task/post_task.h" +#include "base/task/thread_pool.h" +#include "base/task_runner_util.h" +#include "base/time/time.h" +#include "brave/build/ios/mojom/cpp_transformations.h" +#import "brave/ios/browser/api/common/common_operations.h" +#import "brave/ios/browser/api/ledger/brave_ledger_observer.h" +#import "brave/ios/browser/api/ledger/ledger.mojom.objc+private.h" +#import "brave/ios/browser/api/ledger/ledger_client_bridge.h" +#import "brave/ios/browser/api/ledger/ledger_client_ios.h" +#import "brave/ios/browser/api/ledger/legacy_database/data_controller.h" +#import "brave/ios/browser/api/ledger/legacy_database/legacy_ledger_database.h" +#import "brave/ios/browser/api/ledger/promotion_solution.h" +#import "brave/ios/browser/api/ledger/rewards_notification.h" +#include "brave/vendor/bat-native-ledger/include/bat/ledger/global_constants.h" +#include "brave/vendor/bat-native-ledger/include/bat/ledger/ledger.h" +#include "brave/vendor/bat-native-ledger/include/bat/ledger/ledger_database.h" +#include "brave/vendor/bat-native-ledger/include/bat/ledger/option_keys.h" +#include "components/os_crypt/os_crypt.h" +#include "net/base/registry_controlled_domains/registry_controlled_domain.h" +#include "url/gurl.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#define BLOG(verbose_level, format, ...) \ + [self log:(__FILE__) \ + line:(__LINE__)verboseLevel:(verbose_level)message \ + :base::SysNSStringToUTF8( \ + [NSString stringWithFormat:(format), ##__VA_ARGS__])] + +#define BATLedgerReadonlyBridge(__type, __objc_getter, __cpp_getter) \ + -(__type)__objc_getter { \ + return ledger->__cpp_getter(); \ + } + +#define BATLedgerBridge(__type, __objc_getter, __objc_setter, __cpp_getter, \ + __cpp_setter) \ + -(__type)__objc_getter { \ + return ledger->__cpp_getter(); \ + } \ + -(void)__objc_setter : (__type)newValue { \ + ledger->__cpp_setter(newValue); \ + } + +#define BATClassLedgerBridge(__type, __objc_getter, __objc_setter, __cpp_var) \ + +(__type)__objc_getter { \ + return ledger::__cpp_var; \ + } \ + +(void)__objc_setter : (__type)newValue { \ + ledger::__cpp_var = newValue; \ + } + +NSString* const BraveLedgerErrorDomain = @"BraveLedgerErrorDomain"; +NSNotificationName const BraveLedgerNotificationAdded = + @"BATBraveLedgerNotificationAdded"; + +BraveGeneralLedgerNotificationID const + BATBraveGeneralLedgerNotificationIDWalletNowVerified = + @"wallet_new_verified"; +BraveGeneralLedgerNotificationID const + BATBraveGeneralLedgerNotificationIDWalletDisconnected = + @"wallet_disconnected"; + +static NSString* const kNextAddFundsDateNotificationKey = + @"BATNextAddFundsDateNotification"; +static NSString* const kBackupNotificationIntervalKey = + @"BATBackupNotificationInterval"; +static NSString* const kBackupNotificationFrequencyKey = + @"BATBackupNotificationFrequency"; +static NSString* const kUserHasFundedKey = @"BATRewardsUserHasFunded"; +static NSString* const kBackupSucceededKey = @"BATRewardsBackupSucceeded"; +static NSString* const kMigrationSucceeded = @"BATRewardsMigrationSucceeded"; + +static NSString* const kContributionQueueAutoincrementID = + @"BATContributionQueueAutoincrementID"; +static NSString* const kUnblindedTokenAutoincrementID = + @"BATUnblindedTokenAutoincrementID"; + +static NSString* const kExternalWalletsPrefKey = @"external_wallets"; +static NSString* const kTransferFeesPrefKey = @"transfer_fees"; + +static const auto kOneDay = + base::Time::kHoursPerDay * base::Time::kSecondsPerHour; + +/// Ledger Prefs, keys will be defined in `bat/ledger/option_keys.h` +const std::map kBoolOptions = { + {ledger::option::kClaimUGP, true}, + {ledger::option::kIsBitflyerRegion, false}}; +const std::map kIntegerOptions = {}; +const std::map kDoubleOptions = {}; +const std::map kStringOptions = {}; +const std::map kInt64Options = {}; +const std::map kUInt64Options = { + {ledger::option::kPublisherListRefreshInterval, + 7 * base::Time::kHoursPerDay* base::Time::kSecondsPerHour}}; +/// --- + +/// When initializing the ledger, what should we do when migrating +typedef NS_ENUM(NSInteger, BATLedgerDatabaseMigrationType) { + /// Attempt to migrate all rewards data if needed + BATLedgerDatabaseMigrationTypeDefault = 0, + /// Only migrate unblinded tokens if needed + BATLedgerDatabaseMigrationTypeTokensOnly, + /// Do not migrate any data (essentially resetting rewards activity & balance) + BATLedgerDatabaseMigrationTypeNone +}; + +namespace { + +ledger::type::DBCommandResponsePtr RunDBTransactionOnTaskRunner( + ledger::type::DBTransactionPtr transaction, + ledger::LedgerDatabase* database) { + auto response = ledger::type::DBCommandResponse::New(); + if (!database) { + response->status = ledger::type::DBCommandResponse::Status::RESPONSE_ERROR; + } else { + database->RunTransaction(std::move(transaction), response.get()); + } + + return response; +} + +} // namespace + +@interface BraveLedger () { + LedgerClientIOS* ledgerClient; + ledger::Ledger* ledger; + ledger::LedgerDatabase* rewardsDatabase; + scoped_refptr databaseQueue; +} + +@property(nonatomic, copy) NSString* storagePath; +@property(nonatomic) BATRewardsParameters* rewardsParameters; +@property(nonatomic) BATBalance* balance; +@property(nonatomic) BATExternalWallet* upholdWallet; +@property(nonatomic) dispatch_queue_t fileWriteThread; +@property(nonatomic) NSMutableDictionary* state; +@property(nonatomic) BraveCommonOperations* commonOps; +@property(nonatomic) NSMutableDictionary* prefs; + +@property(nonatomic) NSMutableArray* mPendingPromotions; +@property(nonatomic) NSMutableArray* mFinishedPromotions; + +@property(nonatomic) NSHashTable* observers; + +@property(nonatomic, getter=isInitialized) BOOL initialized; +@property(nonatomic) BOOL initializing; +@property(nonatomic) BOOL dataMigrationFailed; +@property(nonatomic) BATResult initializationResult; +@property(nonatomic, getter=isLoadingPublisherList) BOOL loadingPublisherList; +@property(nonatomic, getter=isInitializingWallet) BOOL initializingWallet; +@property(nonatomic) BATLedgerDatabaseMigrationType migrationType; + +/// Notifications + +@property(nonatomic) NSMutableArray* mNotifications; +@property(nonatomic) NSTimer* notificationStartupTimer; +@property(nonatomic) NSDate* lastNotificationCheckDate; + +/// Temporary blocks + +@end + +@implementation BraveLedger + +- (instancetype)initWithStateStoragePath:(NSString*)path { + if ((self = [super init])) { + self.storagePath = path; + self.commonOps = [[BraveCommonOperations alloc] initWithStoragePath:path]; + self.state = [[NSMutableDictionary alloc] + initWithContentsOfFile:self.randomStatePath] + ?: [[NSMutableDictionary alloc] init]; + self.fileWriteThread = + dispatch_queue_create("com.rewards.file-write", DISPATCH_QUEUE_SERIAL); + self.mPendingPromotions = [[NSMutableArray alloc] init]; + self.mFinishedPromotions = [[NSMutableArray alloc] init]; + self.observers = [NSHashTable weakObjectsHashTable]; + rewardsDatabase = nullptr; + + self.prefs = + [[NSMutableDictionary alloc] initWithContentsOfFile:[self prefsPath]]; + if (!self.prefs) { + self.prefs = [[NSMutableDictionary alloc] init]; + // Setup defaults + self.prefs[kNextAddFundsDateNotificationKey] = + @([[NSDate date] timeIntervalSince1970]); + self.prefs[kBackupNotificationFrequencyKey] = @(7 * kOneDay); // 7 days + self.prefs[kBackupNotificationIntervalKey] = @(7 * kOneDay); // 7 days + self.prefs[kBackupSucceededKey] = @(NO); + self.prefs[kUserHasFundedKey] = @(NO); + self.prefs[kMigrationSucceeded] = @(NO); + [self savePrefs]; + } + + const auto args = [NSProcessInfo processInfo].arguments; + const char* argv[args.count]; + for (NSUInteger i = 0; i < args.count; i++) { + argv[i] = args[i].UTF8String; + } + + databaseQueue = base::ThreadPool::CreateSequencedTaskRunner( + {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + base::TaskShutdownBehavior::BLOCK_SHUTDOWN}); + + const auto* dbPath = [self rewardsDatabasePath].UTF8String; + rewardsDatabase = + ledger::LedgerDatabase::CreateInstance(base::FilePath(dbPath)); + + ledgerClient = new LedgerClientIOS(self); + ledger = ledger::Ledger::CreateInstance(ledgerClient); + + // Add notifications for standard app foreground/background + [NSNotificationCenter.defaultCenter + addObserver:self + selector:@selector(applicationDidBecomeActive) + name:UIApplicationDidBecomeActiveNotification + object:nil]; + [NSNotificationCenter.defaultCenter + addObserver:self + selector:@selector(applicationDidBackground) + name:UIApplicationDidEnterBackgroundNotification + object:nil]; + } + return self; +} + +- (void)dealloc { + [NSNotificationCenter.defaultCenter removeObserver:self]; + [self.notificationStartupTimer invalidate]; + + if (rewardsDatabase) { + databaseQueue->DeleteSoon(FROM_HERE, rewardsDatabase); + } + delete ledger; + delete ledgerClient; +} + +- (void)initializeLedgerService:(nullable void (^)())completion { + self.migrationType = BATLedgerDatabaseMigrationTypeDefault; + [self databaseNeedsMigration:^(BOOL needsMigration) { + if (needsMigration) { + [BATLedgerDatabase deleteCoreDataServerPublisherList:nil]; + } + [self initializeLedgerService:needsMigration completion:completion]; + }]; +} + +- (void)initializeLedgerService:(BOOL)executeMigrateScript + completion:(nullable void (^)())completion { + if (self.initialized || self.initializing) { + return; + } + self.initializing = YES; + + BLOG(3, @"DB: Migrate from CoreData? %@", + (executeMigrateScript ? @"YES" : @"NO")); + ledger->Initialize(executeMigrateScript, ^(ledger::type::Result result) { + self.initialized = (result == ledger::type::Result::LEDGER_OK || + result == ledger::type::Result::NO_LEDGER_STATE || + result == ledger::type::Result::NO_PUBLISHER_STATE); + self.initializing = NO; + if (self.initialized) { + self.prefs[kMigrationSucceeded] = @(YES); + [self savePrefs]; + + [self getRewardsParameters:nil]; + [self fetchBalance:nil]; + [self fetchUpholdWallet:nil]; + + [self readNotificationsFromDisk]; + } else { + BLOG(0, @"Ledger Initialization Failed with error: %d", result); + if (result == ledger::type::Result::DATABASE_INIT_FAILED) { + // Failed to migrate data... + switch (self.migrationType) { + case BATLedgerDatabaseMigrationTypeDefault: + BLOG(0, + @"DB: Full migration failed, attempting BAT only migration."); + self.dataMigrationFailed = YES; + self.migrationType = BATLedgerDatabaseMigrationTypeTokensOnly; + [self resetRewardsDatabase]; + // attempt re-initialize without other data + [self initializeLedgerService:YES completion:completion]; + return; + case BATLedgerDatabaseMigrationTypeTokensOnly: + BLOG(0, @"DB: BAT only migration failed. Initializing without " + @"migration."); + self.dataMigrationFailed = YES; + self.migrationType = BATLedgerDatabaseMigrationTypeNone; + [self resetRewardsDatabase]; + // attempt initialize without migrating at all + [self initializeLedgerService:NO completion:completion]; + return; + default: + break; + } + } + } + self.initializationResult = static_cast(result); + if (completion) { + completion(); + } + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.walletInitalized) { + observer.walletInitalized(self.initializationResult); + } + } + }); +} + +- (void)databaseNeedsMigration:(void (^)(BOOL needsMigration))completion { + // Check if we even have a DB to migrate + if (!DataController.defaultStoreExists) { + completion(NO); + return; + } + // Have we set the pref saying ledger has alaready initialized successfully? + if ([self.prefs[kMigrationSucceeded] boolValue]) { + completion(NO); + return; + } + // Can we even check the DB + if (!rewardsDatabase) { + BLOG(3, @"DB: No rewards database object"); + completion(YES); + return; + } + // Check integrity of the new DB. Safe to assume if `publisher_info` table + // exists, then all the others do as well. + auto transaction = ledger::type::DBTransaction::New(); + const auto command = ledger::type::DBCommand::New(); + command->type = ledger::type::DBCommand::Type::READ; + command->command = "SELECT name FROM sqlite_master WHERE type = 'table' AND " + "name = 'publisher_info';"; + command->record_bindings = { + ledger::type::DBCommand::RecordBindingType::STRING_TYPE}; + transaction->commands.push_back(command->Clone()); + + [self runDBTransaction:std::move(transaction) + callback:^(ledger::type::DBCommandResponsePtr response) { + // Failed to even run the check, tables probably don't exist, + // restart from scratch + if (response->status != + ledger::type::DBCommandResponse::Status::RESPONSE_OK) { + [self resetRewardsDatabase]; + BLOG(3, @"DB: Failed to run transaction with status: %d", + response->status); + completion(YES); + return; + } + + const auto record = + std::move(response->result->get_records()); + // sqlite_master table exists, but the publisher_info table + // doesn't exist? Restart from scratch + if (record.empty() || record.front()->fields.empty()) { + [self resetRewardsDatabase]; + BLOG(3, @"DB: Migrate because we couldnt find tables in " + @"sqlite_master"); + completion(YES); + return; + } + + // Tables exist so migration has happened already, but somehow + // the flag wasn't saved. + self.prefs[kMigrationSucceeded] = @(YES); + [self savePrefs]; + + completion(NO); + }]; +} + +- (NSString*)rewardsDatabasePath { + return [self.storagePath stringByAppendingPathComponent:@"Rewards.db"]; +} + +- (void)resetRewardsDatabase { + delete rewardsDatabase; + const auto dbPath = [self rewardsDatabasePath]; + [NSFileManager.defaultManager removeItemAtPath:dbPath error:nil]; + [NSFileManager.defaultManager + removeItemAtPath:[dbPath stringByAppendingString:@"-journal"] + error:nil]; + rewardsDatabase = ledger::LedgerDatabase::CreateInstance( + base::FilePath(base::SysNSStringToUTF8(dbPath))); +} + +- (void)getCreateScript:(ledger::client::GetCreateScriptCallback)callback { + NSString* migrationScript = @""; + switch (self.migrationType) { + case BATLedgerDatabaseMigrationTypeNone: + // We shouldn't be migrating, therefore doesn't make sense that + // `getCreateScript` was called + BLOG(0, + @"DB: Attempted CoreData migration with an empty migration script"); + break; + case BATLedgerDatabaseMigrationTypeTokensOnly: + migrationScript = + [BATLedgerDatabase migrateCoreDataBATOnlyToSQLTransaction]; + break; + case BATLedgerDatabaseMigrationTypeDefault: + default: + migrationScript = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; + } + callback(base::SysNSStringToUTF8(migrationScript), 10); +} + +- (NSString*)randomStatePath { + return + [self.storagePath stringByAppendingPathComponent:@"random_state.plist"]; +} + +- (NSString*)prefsPath { + return [self.storagePath stringByAppendingPathComponent:@"ledger_pref.plist"]; +} + +- (void)savePrefs { + NSDictionary* prefs = [self.prefs copy]; + NSString* path = [[self prefsPath] copy]; + dispatch_async(self.fileWriteThread, ^{ + [prefs writeToURL:[NSURL fileURLWithPath:path isDirectory:NO] error:nil]; + }); +} + +#pragma mark - Observers + +- (void)addObserver:(BraveLedgerObserver*)observer { + [self.observers addObject:observer]; +} + +- (void)removeObserver:(BraveLedgerObserver*)observer { + [self.observers removeObject:observer]; +} + +#pragma mark - Global + +BATClassLedgerBridge(BOOL, isDebug, setDebug, is_debug) + BATClassLedgerBridge(BOOL, isTesting, setTesting, is_testing) + BATClassLedgerBridge(int, + reconcileInterval, + setReconcileInterval, + reconcile_interval) + BATClassLedgerBridge(BOOL, + useShortRetries, + setUseShortRetries, + short_retries) + + + (BATEnvironment)environment { + return static_cast(ledger::_environment); +} + ++ (void)setEnvironment:(BATEnvironment)environment { + ledger::_environment = static_cast(environment); +} + +#pragma mark - Wallet + +- (void)createWallet:(void (^)(NSError* _Nullable))completion { + const auto __weak weakSelf = self; + // Results that can come from CreateWallet(): + // - WALLET_CREATED: Good to go + // - LEDGER_ERROR: Already initialized + // - BAD_REGISTRATION_RESPONSE: Request credentials call failure or + // malformed data + // - REGISTRATION_VERIFICATION_FAILED: Missing master user token + self.initializingWallet = YES; + ledger->CreateWallet(^(ledger::type::Result result) { + const auto strongSelf = weakSelf; + if (!strongSelf) { + return; + } + NSError* error = nil; + if (result != ledger::type::Result::WALLET_CREATED) { + std::map errorDescriptions{ + {ledger::type::Result::LEDGER_ERROR, + "The wallet was already initialized"}, + {ledger::type::Result::BAD_REGISTRATION_RESPONSE, + "Request credentials call failure or malformed data"}, + {ledger::type::Result::REGISTRATION_VERIFICATION_FAILED, + "Missing master user token from registered persona"}, + }; + NSDictionary* userInfo = @{}; + const auto description = + errorDescriptions[static_cast(result)]; + if (description.length() > 0) { + userInfo = + @{NSLocalizedDescriptionKey : base::SysUTF8ToNSString(description)}; + } + error = [NSError errorWithDomain:BraveLedgerErrorDomain + code:static_cast(result) + userInfo:userInfo]; + } + + [strongSelf startNotificationTimers]; + strongSelf.initializingWallet = NO; + + dispatch_async(dispatch_get_main_queue(), ^{ + if (completion) { + completion(error); + } + + for (BraveLedgerObserver* observer in [strongSelf.observers copy]) { + if (observer.walletInitalized) { + observer.walletInitalized(static_cast(result)); + } + } + }); + }); +} + +- (void)currentWalletInfo: + (void (^)(BATBraveWallet* _Nullable wallet))completion { + ledger->GetBraveWallet(^(ledger::type::BraveWalletPtr wallet) { + if (wallet.get() == nullptr) { + completion(nil); + return; + } + const auto bridgedWallet = + [[BATBraveWallet alloc] initWithBraveWallet:*wallet]; + completion(bridgedWallet); + }); +} + +- (void)getRewardsParameters: + (void (^)(BATRewardsParameters* _Nullable))completion { + ledger->GetRewardsParameters(^(ledger::type::RewardsParametersPtr info) { + if (info) { + self.rewardsParameters = [[BATRewardsParameters alloc] + initWithRewardsParametersPtr:std::move(info)]; + } else { + self.rewardsParameters = nil; + } + const auto __weak weakSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + if (completion) { + completion(weakSelf.rewardsParameters); + } + }); + }); +} + +- (void)fetchBalance:(void (^)(BATBalance* _Nullable))completion { + const auto __weak weakSelf = self; + ledger->FetchBalance( + ^(ledger::type::Result result, ledger::type::BalancePtr balance) { + const auto strongSelf = weakSelf; + if (result == ledger::type::Result::LEDGER_OK) { + strongSelf.balance = + [[BATBalance alloc] initWithBalancePtr:std::move(balance)]; + } + dispatch_async(dispatch_get_main_queue(), ^{ + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.fetchedBalance) { + observer.fetchedBalance(); + } + } + if (completion) { + completion(strongSelf.balance); + } + }); + }); +} + +- (void)recoverWalletUsingPassphrase:(NSString*)passphrase + completion:(void (^)(NSError* _Nullable))completion { + const auto __weak weakSelf = self; + // Results that can come from CreateWallet(): + // - LEDGER_OK: Good to go + // - LEDGER_ERROR: Recovery failed + ledger->RecoverWallet(base::SysNSStringToUTF8(passphrase), ^( + const ledger::type::Result result) { + const auto strongSelf = weakSelf; + if (!strongSelf) { + return; + } + NSError* error = nil; + if (result != ledger::type::Result::LEDGER_OK) { + std::map errorDescriptions{ + {ledger::type::Result::LEDGER_ERROR, "The recovery failed"}, + }; + NSDictionary* userInfo = @{}; + const auto description = errorDescriptions[result]; + if (description.length() > 0) { + userInfo = + @{NSLocalizedDescriptionKey : base::SysUTF8ToNSString(description)}; + } + error = [NSError errorWithDomain:BraveLedgerErrorDomain + code:static_cast(result) + userInfo:userInfo]; + } + if (completion) { + completion(error); + } + }); +} + +- (void)hasSufficientBalanceToReconcile:(void (^)(BOOL))completion { + ledger->HasSufficientBalanceToReconcile(completion); +} + +- (void)pendingContributionsTotal:(void (^)(double amount))completion { + ledger->GetPendingContributionsTotal(^(double total) { + completion(total); + }); +} + +- (void)linkBraveWalletToPaymentId:(NSString*)paymentId + completion:(void (^)(BATResult result, + NSString* drainID))completion { + ledger->LinkBraveWallet(base::SysNSStringToUTF8(paymentId), + ^(ledger::type::Result result, std::string drain_id) { + completion(static_cast(result), + base::SysUTF8ToNSString(drain_id)); + }); +} + +- (void)drainStatusForDrainId:(NSString*)drainId + completion:(void (^)(BATResult result, + BATDrainStatus status))completion { + ledger->GetDrainStatus( + base::SysNSStringToUTF8(drainId), + ^(ledger::type::Result result, ledger::type::DrainStatus status) { + completion(static_cast(result), + static_cast(status)); + }); +} + +- (void)transferrableAmount:(void (^)(double amount))completion { + ledger->GetTransferableAmount(^(double amount) { + completion(amount); + }); +} + +#pragma mark - User Wallets + +- (void)fetchUpholdWallet: + (nullable void (^)(BATExternalWallet* _Nullable wallet))completion { + const auto __weak weakSelf = self; + ledger->GetExternalWallet(ledger::constant::kWalletUphold, ^( + ledger::type::Result result, + ledger::type::ExternalWalletPtr walletPtr) { + if (result == ledger::type::Result::LEDGER_OK && + walletPtr.get() != nullptr) { + const auto bridgedWallet = + [[BATExternalWallet alloc] initWithExternalWallet:*walletPtr]; + weakSelf.upholdWallet = bridgedWallet; + if (completion) { + completion(bridgedWallet); + } + } else { + if (completion) { + completion(nil); + } + } + }); +} + +- (void)disconnectWalletOfType:(ExternalWalletType)walletType + completion:(nullable void (^)(BATResult result))completion { + ledger->DisconnectWallet( + base::SysNSStringToUTF8(walletType), ^(ledger::type::Result result) { + if (completion) { + completion(static_cast(result)); + } + + for (BraveLedgerObserver* observer in self.observers) { + if (observer.externalWalletDisconnected) { + observer.externalWalletDisconnected(walletType); + } + } + }); +} + +- (void)authorizeExternalWalletOfType:(ExternalWalletType)walletType + queryItems: + (NSDictionary*)queryItems + completion:(void (^)(BATResult result, + NSURL* _Nullable redirectURL)) + completion { + ledger->ExternalWalletAuthorization( + base::SysNSStringToUTF8(walletType), MapFromNSDictionary(queryItems), + ^(ledger::type::Result result, + base::flat_map args) { + const auto it = args.find("redirect_url"); + std::string redirect; + if (it != args.end()) { + redirect = it->second; + } + NSURL* url = + redirect.empty() + ? nil + : [NSURL URLWithString:base::SysUTF8ToNSString(redirect)]; + completion(static_cast(result), url); + + if (result == ledger::type::Result::LEDGER_OK) { + for (BraveLedgerObserver* observer in self.observers) { + if (observer.externalWalletAuthorized) { + observer.externalWalletAuthorized(walletType); + } + } + } + }); +} + +- (std::string)getLegacyWallet { + NSDictionary* externalWallets = + self.prefs[kExternalWalletsPrefKey] ?: [[NSDictionary alloc] init]; + std::string wallet; + NSData* data = [NSJSONSerialization dataWithJSONObject:externalWallets + options:0 + error:nil]; + if (data != nil) { + NSString* dataString = [[NSString alloc] initWithData:data + encoding:NSUTF8StringEncoding]; + if (dataString != nil) { + wallet = base::SysNSStringToUTF8(dataString); + } + } + return wallet; +} + +#pragma mark - Publishers + +- (void)listActivityInfoFromStart:(unsigned int)start + limit:(unsigned int)limit + filter:(BATActivityInfoFilter*)filter + completion: + (void(NS_NOESCAPE ^)(NSArray*)) + completion { + auto cppFilter = + filter ? filter.cppObjPtr : ledger::type::ActivityInfoFilter::New(); + if (filter.excluded == BATExcludeFilterFilterExcluded) { + ledger->GetExcludedList(^(ledger::type::PublisherInfoList list) { + const auto publishers = NSArrayFromVector( + &list, + ^BATPublisherInfo*(const ledger::type::PublisherInfoPtr& info) { + return [[BATPublisherInfo alloc] initWithPublisherInfo:*info]; + }); + completion(publishers); + }); + } else { + ledger->GetActivityInfoList( + start, limit, std::move(cppFilter), + ^(ledger::type::PublisherInfoList list) { + const auto publishers = NSArrayFromVector( + &list, + ^BATPublisherInfo*(const ledger::type::PublisherInfoPtr& info) { + return [[BATPublisherInfo alloc] initWithPublisherInfo:*info]; + }); + completion(publishers); + }); + } +} + +- (void)fetchPublisherActivityFromURL:(NSURL*)URL + faviconURL:(nullable NSURL*)faviconURL + publisherBlob:(nullable NSString*)publisherBlob + tabId:(uint64_t)tabId { + if (!URL.absoluteString) { + return; + } + + GURL parsedUrl(base::SysNSStringToUTF8(URL.absoluteString)); + + if (!parsedUrl.is_valid()) { + return; + } + + auto origin = parsedUrl.GetOrigin(); + std::string baseDomain = GetDomainAndRegistry( + origin.host(), + net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); + + if (baseDomain == "") { + return; + } + + ledger::type::VisitDataPtr visitData = ledger::type::VisitData::New(); + visitData->domain = visitData->name = baseDomain; + visitData->path = parsedUrl.PathForRequest(); + visitData->url = origin.spec(); + + if (faviconURL.absoluteString) { + visitData->favicon_url = base::SysNSStringToUTF8(faviconURL.absoluteString); + } + + std::string blob = std::string(); + if (publisherBlob) { + blob = base::SysNSStringToUTF8(publisherBlob); + } + + ledger->GetPublisherActivityFromUrl(tabId, std::move(visitData), blob); +} + +- (void)updatePublisherExclusionState:(NSString*)publisherId + state:(BATPublisherExclude)state { + ledger->SetPublisherExclude( + base::SysNSStringToUTF8(publisherId), + (ledger::type::PublisherExclude)state, + ^(const ledger::type::Result result) { + if (result != ledger::type::Result::LEDGER_OK) { + return; + } + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.excludedSitesChanged) { + observer.excludedSitesChanged(publisherId, state); + } + } + }); +} + +- (void)restoreAllExcludedPublishers { + ledger->RestorePublishers(^(const ledger::type::Result result) { + if (result != ledger::type::Result::LEDGER_OK) { + return; + } + + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.excludedSitesChanged) { + observer.excludedSitesChanged(@"-1", + static_cast( + ledger::type::PublisherExclude::ALL)); + } + } + }); +} + +- (void)publisherBannerForId:(NSString*)publisherId + completion:(void (^)(BATPublisherBanner* _Nullable banner)) + completion { + ledger->GetPublisherBanner(base::SysNSStringToUTF8(publisherId), ^( + ledger::type::PublisherBannerPtr banner) { + auto bridgedBanner = + banner.get() != nullptr + ? [[BATPublisherBanner alloc] initWithPublisherBanner:*banner] + : nil; + // native libs prefixes the logo and background image with this URL scheme + const auto imagePrefix = @"chrome://rewards-image/"; + bridgedBanner.background = [bridgedBanner.background + stringByReplacingOccurrencesOfString:imagePrefix + withString:@""]; + bridgedBanner.logo = + [bridgedBanner.logo stringByReplacingOccurrencesOfString:imagePrefix + withString:@""]; + completion(bridgedBanner); + }); +} + +- (void)refreshPublisherWithId:(NSString*)publisherId + completion:(void (^)(BATPublisherStatus status))completion { + if (self.loadingPublisherList) { + completion(BATPublisherStatusNotVerified); + return; + } + ledger->RefreshPublisher(base::SysNSStringToUTF8(publisherId), ^( + ledger::type::PublisherStatus status) { + completion(static_cast(status)); + }); +} + +#pragma mark - SKUs + +- (void)processSKUItems:(NSArray*)items + completion: + (void (^)(BATResult result, NSString* orderID))completion { + ledger->ProcessSKU( + VectorFromNSArray(items, + ^ledger::type::SKUOrderItem(BATSKUOrderItem* item) { + return *item.cppObjPtr; + }), + ledger::constant::kWalletUnBlinded, + ^(const ledger::type::Result result, const std::string& order_id) { + completion(static_cast(result), + base::SysUTF8ToNSString(order_id)); + }); +} + +#pragma mark - Tips + +- (void)listRecurringTips:(void (^)(NSArray*))completion { + ledger->GetRecurringTips(^(ledger::type::PublisherInfoList list) { + const auto publishers = NSArrayFromVector( + &list, ^BATPublisherInfo*(const ledger::type::PublisherInfoPtr& info) { + return [[BATPublisherInfo alloc] initWithPublisherInfo:*info]; + }); + completion(publishers); + }); +} + +- (void)addRecurringTipToPublisherWithId:(NSString*)publisherId + amount:(double)amount + completion:(void (^)(BOOL success))completion { + ledger::type::RecurringTipPtr info = ledger::type::RecurringTip::New(); + info->publisher_key = base::SysNSStringToUTF8(publisherId); + info->amount = amount; + info->created_at = [[NSDate date] timeIntervalSince1970]; + ledger->SaveRecurringTip(std::move(info), ^(ledger::type::Result result) { + const auto success = (result == ledger::type::Result::LEDGER_OK); + if (success) { + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.recurringTipAdded) { + observer.recurringTipAdded(publisherId); + } + } + } + completion(success); + }); +} + +- (void)removeRecurringTipForPublisherWithId:(NSString*)publisherId { + ledger->RemoveRecurringTip( + base::SysNSStringToUTF8(publisherId), ^(ledger::type::Result result) { + if (result == ledger::type::Result::LEDGER_OK) { + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.recurringTipRemoved) { + observer.recurringTipRemoved(publisherId); + } + } + } + }); +} + +- (void)listOneTimeTips:(void (^)(NSArray*))completion { + ledger->GetOneTimeTips(^(ledger::type::PublisherInfoList list) { + const auto publishers = NSArrayFromVector( + &list, ^BATPublisherInfo*(const ledger::type::PublisherInfoPtr& info) { + return [[BATPublisherInfo alloc] initWithPublisherInfo:*info]; + }); + completion(publishers); + }); +} + +- (void)tipPublisherDirectly:(BATPublisherInfo*)publisher + amount:(double)amount + currency:(NSString*)currency + completion:(void (^)(BATResult result))completion { + ledger->OneTimeTip(base::SysNSStringToUTF8(publisher.id), amount, + ^(ledger::type::Result result) { + completion(static_cast(result)); + }); +} + +#pragma mark - Grants + +- (NSArray*)pendingPromotions { + return [self.mPendingPromotions copy]; +} + +- (NSArray*)finishedPromotions { + return [self.mFinishedPromotions copy]; +} + +- (NSString*)notificationIDForPromo:(const ledger::type::PromotionPtr)promo { + bool isUGP = promo->type == ledger::type::PromotionType::UGP; + const auto prefix = isUGP ? @"rewards_grant_" : @"rewards_grant_ads_"; + const auto promotionId = base::SysUTF8ToNSString(promo->id); + return [NSString stringWithFormat:@"%@%@", prefix, promotionId]; +} + +- (void)updatePendingAndFinishedPromotions: + (void (^)(bool shouldReconcileAds))completion { + ledger->GetAllPromotions(^(ledger::type::PromotionMap map) { + NSMutableArray* promos = [[NSMutableArray alloc] init]; + bool shouldReconcileAds = false; + for (auto it = map.begin(); it != map.end(); ++it) { + if (it->second.get() != nullptr) { + [promos addObject:[[BATPromotion alloc] initWithPromotion:*it->second]]; + } + } + for (BATPromotion* promo in [self.mPendingPromotions copy]) { + [self + clearNotificationWithID:[self + notificationIDForPromo:promo.cppObjPtr]]; + } + [self.mFinishedPromotions removeAllObjects]; + [self.mPendingPromotions removeAllObjects]; + for (BATPromotion* promotion in promos) { + if (promotion.status == BATPromotionStatusFinished) { + [self.mFinishedPromotions addObject:promotion]; + + if (promotion.type == BATPromotionTypeAds) { + shouldReconcileAds = true; + } + } else if (promotion.status == BATPromotionStatusActive || + promotion.status == BATPromotionStatusAttested) { + [self.mPendingPromotions addObject:promotion]; + bool isUGP = promotion.type == BATPromotionTypeUgp; + auto notificationKind = isUGP ? RewardsNotificationKindGrant + : RewardsNotificationKindGrantAds; + + [self addNotificationOfKind:notificationKind + userInfo:nil + notificationID:[self notificationIDForPromo:promotion + .cppObjPtr] + onlyOnce:YES]; + } + } + if (completion) { + completion(shouldReconcileAds); + } + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.promotionsAdded) { + observer.promotionsAdded(self.pendingPromotions); + } + if (observer.finishedPromotionsAdded) { + observer.finishedPromotionsAdded(self.finishedPromotions); + } + } + }); +} + +- (void)fetchPromotions:(nullable void (^)(NSArray* grants, + bool shouldReconcileAds))completion { + ledger->FetchPromotions( + ^(ledger::type::Result result, + std::vector promotions) { + if (result != ledger::type::Result::LEDGER_OK) { + return; + } + [self updatePendingAndFinishedPromotions:^(bool shouldReconcileAds) { + if (completion) { + completion(self.pendingPromotions, shouldReconcileAds); + } + }]; + }); +} + +- (void)claimPromotion:(NSString*)promotionId + publicKey:(NSString*)deviceCheckPublicKey + completion:(void (^)(BATResult result, + NSString* _Nonnull nonce))completion { + const auto payload = [NSDictionary dictionaryWithObject:deviceCheckPublicKey + forKey:@"publicKey"]; + const auto jsonData = [NSJSONSerialization dataWithJSONObject:payload + options:0 + error:nil]; + if (!jsonData) { + BLOG(0, @"Missing JSON payload while attempting to claim promotion"); + return; + } + const auto jsonString = [[NSString alloc] initWithData:jsonData + encoding:NSUTF8StringEncoding]; + ledger->ClaimPromotion( + base::SysNSStringToUTF8(promotionId), base::SysNSStringToUTF8(jsonString), + ^(const ledger::type::Result result, const std::string& nonce) { + const auto bridgedNonce = base::SysUTF8ToNSString(nonce); + dispatch_async(dispatch_get_main_queue(), ^{ + completion(static_cast(result), bridgedNonce); + }); + }); +} + +- (void)attestPromotion:(NSString*)promotionId + solution:(PromotionSolution*)solution + completion: + (void (^)(BATResult result, + BATPromotion* _Nullable promotion))completion { + ledger->AttestPromotion( + base::SysNSStringToUTF8(promotionId), + base::SysNSStringToUTF8(solution.JSONPayload), + ^(const ledger::type::Result result, + ledger::type::PromotionPtr promotion) { + if (promotion.get() == nullptr) { + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(static_cast(result), nil); + }); + } + return; + } + + const auto bridgedPromotion = + [[BATPromotion alloc] initWithPromotion:*promotion]; + if (result == ledger::type::Result::LEDGER_OK) { + [self fetchBalance:nil]; + [self clearNotificationWithID: + [self notificationIDForPromo:std::move(promotion)]]; + } + + dispatch_async(dispatch_get_main_queue(), ^{ + if (completion) { + completion(static_cast(result), bridgedPromotion); + } + if (result == ledger::type::Result::LEDGER_OK) { + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.promotionClaimed) { + observer.promotionClaimed(bridgedPromotion); + } + } + } + }); + }); +} + +#pragma mark - History + +- (void)balanceReportForMonth:(BATActivityMonth)month + year:(int)year + completion:(void (^)(BATBalanceReportInfo* _Nullable info)) + completion { + ledger->GetBalanceReport( + (ledger::type::ActivityMonth)month, year, + ^(const ledger::type::Result result, + ledger::type::BalanceReportInfoPtr info) { + auto bridgedInfo = info.get() != nullptr + ? [[BATBalanceReportInfo alloc] + initWithBalanceReportInfo:*info.get()] + : nil; + completion(result == ledger::type::Result::LEDGER_OK ? bridgedInfo + : nil); + }); +} + +- (BATAutoContributeProperties*)autoContributeProperties { + ledger::type::AutoContributePropertiesPtr props = + ledger->GetAutoContributeProperties(); + return [[BATAutoContributeProperties alloc] + initWithAutoContributePropertiesPtr:std::move(props)]; +} + +#pragma mark - Pending Contributions + +- (void)pendingContributions: + (void (^)(NSArray* publishers))completion { + ledger->GetPendingContributions( + ^(ledger::type::PendingContributionInfoList list) { + const auto convetedList = NSArrayFromVector( + &list, ^BATPendingContributionInfo*( + const ledger::type::PendingContributionInfoPtr& info) { + return [[BATPendingContributionInfo alloc] + initWithPendingContributionInfo:*info]; + }); + completion(convetedList); + }); +} + +- (void)removePendingContribution:(BATPendingContributionInfo*)info + completion:(void (^)(BATResult result))completion { + ledger->RemovePendingContribution( + info.id, ^(const ledger::type::Result result) { + completion(static_cast(result)); + }); +} + +- (void)removeAllPendingContributions:(void (^)(BATResult result))completion { + ledger->RemoveAllPendingContributions(^(const ledger::type::Result result) { + completion(static_cast(result)); + }); +} + +#pragma mark - Reconcile + +- (void)onReconcileComplete:(ledger::type::Result)result + contribution:(ledger::type::ContributionInfoPtr)contribution { + // TODO we changed from probi to amount, so from string to double + if (result == ledger::type::Result::LEDGER_OK) { + if (contribution->type == ledger::type::RewardsType::RECURRING_TIP) { + [self showTipsProcessedNotificationIfNeccessary]; + } + [self fetchBalance:nil]; + } + + if ((result == ledger::type::Result::LEDGER_OK && + contribution->type == ledger::type::RewardsType::AUTO_CONTRIBUTE) || + result == ledger::type::Result::LEDGER_ERROR || + result == ledger::type::Result::NOT_ENOUGH_FUNDS || + result == ledger::type::Result::TIP_ERROR) { + const auto contributionId = + base::SysUTF8ToNSString(contribution->contribution_id); + const auto info = @{ + @"viewingId" : contributionId, + @"result" : @((BATResult)result), + @"type" : @((BATRewardsType)contribution->type), + @"amount" : [@(contribution->amount) stringValue] + }; + + [self addNotificationOfKind:RewardsNotificationKindAutoContribute + userInfo:info + notificationID:[NSString stringWithFormat:@"contribution_%@", + contributionId]]; + } + + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.balanceReportUpdated) { + observer.balanceReportUpdated(); + } + if (observer.reconcileCompleted) { + observer.reconcileCompleted( + static_cast(result), + base::SysUTF8ToNSString(contribution->contribution_id), + static_cast(contribution->type), + [@(contribution->amount) stringValue]); + } + } +} + +#pragma mark - Misc + ++ (bool)isMediaURL:(NSURL*)url + firstPartyURL:(NSURL*)firstPartyURL + referrerURL:(NSURL*)referrerURL { + std::string referrer = + referrerURL != nil ? base::SysNSStringToUTF8(referrerURL.absoluteString) + : ""; + return ledger::Ledger::IsMediaLink( + base::SysNSStringToUTF8(url.absoluteString), + base::SysNSStringToUTF8(firstPartyURL.absoluteString), referrer); +} + +- (void)rewardsInternalInfo: + (void(NS_NOESCAPE ^)(BATRewardsInternalsInfo* _Nullable info))completion { + ledger->GetRewardsInternalsInfo( + ^(ledger::type::RewardsInternalsInfoPtr info) { + auto bridgedInfo = info.get() != nullptr + ? [[BATRewardsInternalsInfo alloc] + initWithRewardsInternalsInfo:*info.get()] + : nil; + completion(bridgedInfo); + }); +} + +- (void)allContributions: + (void (^)(NSArray* contributions))completion { + ledger->GetAllContributions(^(ledger::type::ContributionInfoList list) { + const auto convetedList = NSArrayFromVector( + &list, + ^BATContributionInfo*(const ledger::type::ContributionInfoPtr& info) { + return [[BATContributionInfo alloc] initWithContributionInfo:*info]; + }); + completion(convetedList); + }); +} + +#pragma mark - Reporting + +- (void)setSelectedTabId:(UInt32)selectedTabId { + if (!self.initialized) { + return; + } + + if (_selectedTabId != selectedTabId) { + ledger->OnHide(_selectedTabId, [[NSDate date] timeIntervalSince1970]); + } + _selectedTabId = selectedTabId; + if (_selectedTabId > 0) { + ledger->OnShow(_selectedTabId, [[NSDate date] timeIntervalSince1970]); + } +} + +- (void)applicationDidBecomeActive { + if (!self.initialized) { + return; + } + + ledger->OnForeground(self.selectedTabId, + [[NSDate date] timeIntervalSince1970]); + + // Check if the last notification check was more than a day ago + if (fabs([self.lastNotificationCheckDate timeIntervalSinceNow]) > kOneDay) { + [self checkForNotificationsAndFetchGrants]; + } +} + +- (void)applicationDidBackground { + if (!self.initialized) { + return; + } + + ledger->OnBackground(self.selectedTabId, + [[NSDate date] timeIntervalSince1970]); +} + +- (void)reportLoadedPageWithURL:(NSURL*)url tabId:(UInt32)tabId { + if (!self.initialized) { + return; + } + + GURL parsedUrl(base::SysNSStringToUTF8(url.absoluteString)); + auto origin = parsedUrl.GetOrigin(); + const std::string baseDomain = GetDomainAndRegistry( + origin.host(), + net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); + + if (baseDomain == "") { + return; + } + + const std::string publisher_url = origin.scheme() + "://" + baseDomain + "/"; + + ledger::type::VisitDataPtr data = ledger::type::VisitData::New(); + data->tld = data->name = baseDomain; + data->domain = origin.host(); + data->path = parsedUrl.path(); + data->tab_id = tabId; + data->url = publisher_url; + + ledger->OnLoad(std::move(data), [[NSDate date] timeIntervalSince1970]); +} + +- (void)reportXHRLoad:(NSURL*)url + tabId:(UInt32)tabId + firstPartyURL:(NSURL*)firstPartyURL + referrerURL:(NSURL*)referrerURL { + if (!self.initialized) { + return; + } + + base::flat_map partsMap; + const auto urlComponents = [[NSURLComponents alloc] initWithURL:url + resolvingAgainstBaseURL:NO]; + for (NSURLQueryItem* item in urlComponents.queryItems) { + std::string value = + item.value != nil ? base::SysNSStringToUTF8(item.value) : ""; + partsMap[base::SysNSStringToUTF8(item.name)] = value; + } + + auto visit = ledger::type::VisitData::New(); + visit->path = base::SysNSStringToUTF8(url.absoluteString); + visit->tab_id = tabId; + + std::string ref = referrerURL != nil + ? base::SysNSStringToUTF8(referrerURL.absoluteString) + : ""; + std::string fpu = firstPartyURL != nil + ? base::SysNSStringToUTF8(firstPartyURL.absoluteString) + : ""; + + ledger->OnXHRLoad(tabId, base::SysNSStringToUTF8(url.absoluteString), + partsMap, fpu, ref, std::move(visit)); +} + +- (void)reportPostData:(NSData*)postData + url:(NSURL*)url + tabId:(UInt32)tabId + firstPartyURL:(NSURL*)firstPartyURL + referrerURL:(NSURL*)referrerURL { + if (!self.initialized) { + return; + } + + GURL parsedUrl(base::SysNSStringToUTF8(url.absoluteString)); + if (!parsedUrl.is_valid()) { + return; + } + + const auto postDataString = [[[NSString alloc] + initWithData:postData + encoding:NSUTF8StringEncoding] stringByRemovingPercentEncoding]; + + auto visit = ledger::type::VisitData::New(); + visit->path = parsedUrl.spec(); + visit->tab_id = tabId; + + std::string ref = referrerURL != nil + ? base::SysNSStringToUTF8(referrerURL.absoluteString) + : ""; + std::string fpu = firstPartyURL != nil + ? base::SysNSStringToUTF8(firstPartyURL.absoluteString) + : ""; + + ledger->OnPostData(parsedUrl.spec(), fpu, ref, + base::SysNSStringToUTF8(postDataString), std::move(visit)); +} + +- (void)reportTabNavigationOrClosedWithTabId:(UInt32)tabId { + if (!self.initialized) { + return; + } + + ledger->OnUnload(tabId, [[NSDate date] timeIntervalSince1970]); +} + +#pragma mark - Preferences + +BATLedgerBridge(int, + minimumVisitDuration, + setMinimumVisitDuration, + GetPublisherMinVisitTime, + SetPublisherMinVisitTime) + + BATLedgerBridge(int, + minimumNumberOfVisits, + setMinimumNumberOfVisits, + GetPublisherMinVisits, + SetPublisherMinVisits) + + BATLedgerBridge(BOOL, + allowUnverifiedPublishers, + setAllowUnverifiedPublishers, + GetPublisherAllowNonVerified, + SetPublisherAllowNonVerified) + + BATLedgerBridge(BOOL, + allowVideoContributions, + setAllowVideoContributions, + GetPublisherAllowVideos, + SetPublisherAllowVideos) + + BATLedgerReadonlyBridge(double, + contributionAmount, + GetAutoContributionAmount) + + - (void)setContributionAmount : (double)contributionAmount { + ledger->SetAutoContributionAmount(contributionAmount); +} + +BATLedgerBridge(BOOL, + isAutoContributeEnabled, + setAutoContributeEnabled, + GetAutoContributeEnabled, + SetAutoContributeEnabled) + + - (void)setBooleanState : (const std::string&)name value : (bool)value { + const auto key = base::SysUTF8ToNSString(name); + self.prefs[key] = [NSNumber numberWithBool:value]; + [self savePrefs]; +} + +- (bool)getBooleanState:(const std::string&)name { + const auto key = base::SysUTF8ToNSString(name); + if (![self.prefs objectForKey:key]) { + return NO; + } + + return [self.prefs[key] boolValue]; +} + +- (void)setIntegerState:(const std::string&)name value:(int)value { + const auto key = base::SysUTF8ToNSString(name); + self.prefs[key] = [NSNumber numberWithInt:value]; + [self savePrefs]; +} + +- (int)getIntegerState:(const std::string&)name { + const auto key = base::SysUTF8ToNSString(name); + return [self.prefs[key] intValue]; +} + +- (void)setDoubleState:(const std::string&)name value:(double)value { + const auto key = base::SysUTF8ToNSString(name); + self.prefs[key] = [NSNumber numberWithDouble:value]; + [self savePrefs]; +} + +- (double)getDoubleState:(const std::string&)name { + const auto key = base::SysUTF8ToNSString(name); + return [self.prefs[key] doubleValue]; +} + +- (void)setStringState:(const std::string&)name + value:(const std::string&)value { + const auto key = base::SysUTF8ToNSString(name); + self.prefs[key] = base::SysUTF8ToNSString(value); + [self savePrefs]; +} + +- (std::string)getStringState:(const std::string&)name { + const auto key = base::SysUTF8ToNSString(name); + const auto value = (NSString*)self.prefs[key]; + if (!value) { + return ""; + } + return base::SysNSStringToUTF8(value); +} + +- (void)setInt64State:(const std::string&)name value:(int64_t)value { + const auto key = base::SysUTF8ToNSString(name); + self.prefs[key] = [NSNumber numberWithLongLong:value]; + [self savePrefs]; +} + +- (int64_t)getInt64State:(const std::string&)name { + const auto key = base::SysUTF8ToNSString(name); + return [self.prefs[key] longLongValue]; +} + +- (void)setUint64State:(const std::string&)name value:(uint64_t)value { + const auto key = base::SysUTF8ToNSString(name); + self.prefs[key] = [NSNumber numberWithUnsignedLongLong:value]; + [self savePrefs]; +} + +- (uint64_t)getUint64State:(const std::string&)name { + const auto key = base::SysUTF8ToNSString(name); + return [self.prefs[key] unsignedLongLongValue]; +} + +- (void)clearState:(const std::string&)name { + const auto key = base::SysUTF8ToNSString(name); + [self.prefs removeObjectForKey:key]; + [self savePrefs]; +} + +- (bool)getBooleanOption:(const std::string&)name { + DCHECK(!name.empty()); + + const auto it = kBoolOptions.find(name); + DCHECK(it != kBoolOptions.end()); + + return kBoolOptions.at(name); +} + +- (int)getIntegerOption:(const std::string&)name { + DCHECK(!name.empty()); + + const auto it = kIntegerOptions.find(name); + DCHECK(it != kIntegerOptions.end()); + + return kIntegerOptions.at(name); +} + +- (double)getDoubleOption:(const std::string&)name { + DCHECK(!name.empty()); + + const auto it = kDoubleOptions.find(name); + DCHECK(it != kDoubleOptions.end()); + + return kDoubleOptions.at(name); +} + +- (std::string)getStringOption:(const std::string&)name { + DCHECK(!name.empty()); + + const auto it = kStringOptions.find(name); + DCHECK(it != kStringOptions.end()); + + return kStringOptions.at(name); +} + +- (int64_t)getInt64Option:(const std::string&)name { + DCHECK(!name.empty()); + + const auto it = kInt64Options.find(name); + DCHECK(it != kInt64Options.end()); + + return kInt64Options.at(name); +} + +- (uint64_t)getUint64Option:(const std::string&)name { + DCHECK(!name.empty()); + + const auto it = kUInt64Options.find(name); + DCHECK(it != kUInt64Options.end()); + + return kUInt64Options.at(name); +} + +#pragma mark - Notifications + +- (NSArray*)notifications { + return [self.mNotifications copy]; +} + +- (void)clearNotificationWithID:(NSString*)notificationID { + for (RewardsNotification* n in self.notifications) { + if ([n.id isEqualToString:notificationID]) { + [self clearNotification:n]; + return; + } + } +} + +- (void)clearNotification:(RewardsNotification*)notification { + [self.mNotifications removeObject:notification]; + [self writeNotificationsToDisk]; + + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.notificationsRemoved) { + observer.notificationsRemoved(@[ notification ]); + } + } +} + +- (void)clearAllNotifications { + NSArray* notifications = [self.mNotifications copy]; + [self.mNotifications removeAllObjects]; + [self writeNotificationsToDisk]; + + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.notificationsRemoved) { + observer.notificationsRemoved(notifications); + } + } +} + +- (void)startNotificationTimers { + dispatch_async(dispatch_get_main_queue(), ^{ + // Startup timer, begins after 30-second delay. + self.notificationStartupTimer = + [NSTimer scheduledTimerWithTimeInterval:30 + target:self + selector:@selector + (checkForNotificationsAndFetchGrants) + userInfo:nil + repeats:NO]; + }); +} + +- (void)checkForNotificationsAndFetchGrants { + self.lastNotificationCheckDate = [NSDate date]; + + [self showBackupNotificationIfNeccessary]; + [self showAddFundsNotificationIfNeccessary]; + [self fetchPromotions:nil]; +} + +- (void)showBackupNotificationIfNeccessary { + // This is currently not required as the user cannot manage their wallet on + // mobile... yet + /* + auto bootstamp = ledger->GetCreationStamp(); + auto userFunded = [self.prefs[kUserHasFundedKey] boolValue]; + auto backupSucceeded = [self.prefs[kBackupSucceededKey] boolValue]; + if (userFunded && !backupSucceeded) { + auto frequency = 10; [self.prefs[kBackupNotificationFrequencyKey] + doubleValue]; auto interval = 10; [self.prefs[kBackupNotificationIntervalKey] + doubleValue]; auto delta = [[NSDate date] timeIntervalSinceDate:[NSDate + dateWithTimeIntervalSince1970:bootstamp]]; if (delta > interval) { auto + nextBackupNotificationInterval = frequency + interval; + self.prefs[kBackupNotificationIntervalKey] = + @(nextBackupNotificationInterval); [self savePrefs]; [self + addNotificationOfKind:RewardsNotificationKindBackupWallet arguments:nil + notificationID:@"rewards_notification_backup_wallet"]; + } + } + */ +} + +- (void)showAddFundsNotificationIfNeccessary { + const auto stamp = ledger->GetReconcileStamp(); + const auto now = [[NSDate date] timeIntervalSince1970]; + + // Show add funds notification if reconciliation will occur in the + // next 3 days and balance is too low. + if (stamp - now > 3 * kOneDay) { + return; + } + // Make sure it hasnt already been shown + const auto upcomingAddFundsNotificationTime = + [self.prefs[kNextAddFundsDateNotificationKey] doubleValue]; + if (upcomingAddFundsNotificationTime != 0.0 && + now < upcomingAddFundsNotificationTime) { + return; + } + + const auto __weak weakSelf = self; + // Make sure they don't have a sufficient balance + [self hasSufficientBalanceToReconcile:^(BOOL sufficient) { + if (sufficient) { + return; + } + const auto strongSelf = weakSelf; + + // Set next add funds notification in 3 days + const auto nextTime = [[NSDate date] timeIntervalSince1970] + (kOneDay * 3); + strongSelf.prefs[kNextAddFundsDateNotificationKey] = @(nextTime); + [strongSelf savePrefs]; + + [strongSelf + addNotificationOfKind:RewardsNotificationKindInsufficientFunds + userInfo:nil + notificationID:@"rewards_notification_insufficient_funds"]; + }]; +} + +- (void)showTipsProcessedNotificationIfNeccessary { + if (!self.autoContributeEnabled) { + return; + } + [self addNotificationOfKind:RewardsNotificationKindTipsProcessed + userInfo:nil + notificationID:@"rewards_notification_tips_processed"]; +} + +- (void)addNotificationOfKind:(RewardsNotificationKind)kind + userInfo:(nullable NSDictionary*)userInfo + notificationID:(nullable NSString*)identifier { + [self addNotificationOfKind:kind + userInfo:userInfo + notificationID:identifier + onlyOnce:NO]; +} + +- (void)addNotificationOfKind:(RewardsNotificationKind)kind + userInfo:(nullable NSDictionary*)userInfo + notificationID:(nullable NSString*)identifier + onlyOnce:(BOOL)onlyOnce { + NSParameterAssert(kind != RewardsNotificationKindInvalid); + NSString* notificationID = [identifier copy]; + if (!identifier || identifier.length == 0) { + notificationID = [NSUUID UUID].UUIDString; + } else if (onlyOnce) { + const auto idx = [self.mNotifications + indexOfObjectPassingTest:^BOOL(RewardsNotification* _Nonnull obj, + NSUInteger idx, BOOL* _Nonnull stop) { + return obj.displayed && [obj.id isEqualToString:identifier]; + }]; + if (idx != NSNotFound) { + return; + } + } + + const auto notification = [[RewardsNotification alloc] + initWithID:notificationID + dateAdded:[[NSDate date] timeIntervalSince1970] + kind:kind + userInfo:userInfo]; + if (onlyOnce) { + notification.displayed = YES; + } + + [self.mNotifications addObject:notification]; + + // Post to observers + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.notificationAdded) { + observer.notificationAdded(notification); + } + } + + [NSNotificationCenter.defaultCenter + postNotificationName:BraveLedgerNotificationAdded + object:nil]; + + [self writeNotificationsToDisk]; +} + +- (void)readNotificationsFromDisk { + const auto path = + [self.storagePath stringByAppendingPathComponent:@"notifications"]; + const auto data = [NSData dataWithContentsOfFile:path]; + if (!data) { + // Nothing to read + self.mNotifications = [[NSMutableArray alloc] init]; + return; + } + + NSError* error; + self.mNotifications = [NSKeyedUnarchiver unarchivedObjectOfClass:NSArray.self + fromData:data + error:&error]; + if (!self.mNotifications) { + self.mNotifications = [[NSMutableArray alloc] init]; + if (error) { + BLOG(0, @"Failed to unarchive notifications on disk: %@", + error.debugDescription); + } + } +} + +- (void)writeNotificationsToDisk { + const auto path = + [self.storagePath stringByAppendingPathComponent:@"notifications"]; + if (self.notifications.count == 0) { + // Nothing to write, delete anything we have stored + if ([[NSFileManager defaultManager] fileExistsAtPath:path]) { + [[NSFileManager defaultManager] removeItemAtPath:path error:nil]; + } + return; + } + + NSError* error; + const auto data = + [NSKeyedArchiver archivedDataWithRootObject:self.notifications + requiringSecureCoding:YES + error:&error]; + if (!data) { + if (error) { + BLOG(0, @"Failed to write notifications to disk: %@", + error.debugDescription); + } + return; + } + + [data writeToURL:[NSURL fileURLWithPath:path isDirectory:NO] + options:NSDataWritingAtomic + error:nil]; +} + +#pragma mark - State + +- (void)loadLedgerState:(ledger::client::OnLoadCallback)callback { + const auto contents = + [self.commonOps loadContentsFromFileWithName:"ledger_state.json"]; + if (contents.length() > 0) { + callback(ledger::type::Result::LEDGER_OK, contents); + } else { + callback(ledger::type::Result::NO_LEDGER_STATE, contents); + } + [self startNotificationTimers]; +} + +- (void)loadPublisherState:(ledger::client::OnLoadCallback)callback { + const auto contents = + [self.commonOps loadContentsFromFileWithName:"publisher_state.json"]; + if (contents.length() > 0) { + callback(ledger::type::Result::LEDGER_OK, contents); + } else { + callback(ledger::type::Result::NO_PUBLISHER_STATE, contents); + } +} + +- (void)loadState:(const std::string&)name + callback:(ledger::client::OnLoadCallback)callback { + const auto key = base::SysUTF8ToNSString(name); + const auto value = self.state[key]; + if (value) { + callback(ledger::type::Result::LEDGER_OK, base::SysNSStringToUTF8(value)); + } else { + callback(ledger::type::Result::LEDGER_ERROR, ""); + } +} + +- (void)resetState:(const std::string&)name + callback:(ledger::ResultCallback)callback { + const auto key = base::SysUTF8ToNSString(name); + self.state[key] = nil; + callback(ledger::type::Result::LEDGER_OK); + // In brave-core, failed callback returns `LEDGER_ERROR` + NSDictionary* state = [self.state copy]; + NSString* path = [self.randomStatePath copy]; + dispatch_async(self.fileWriteThread, ^{ + [state writeToURL:[NSURL fileURLWithPath:path isDirectory:NO] error:nil]; + }); +} + +- (void)saveState:(const std::string&)name + value:(const std::string&)value + callback:(ledger::ResultCallback)callback { + const auto key = base::SysUTF8ToNSString(name); + self.state[key] = base::SysUTF8ToNSString(value); + callback(ledger::type::Result::LEDGER_OK); + // In brave-core, failed callback returns `LEDGER_ERROR` + NSDictionary* state = [self.state copy]; + NSString* path = [self.randomStatePath copy]; + dispatch_async(self.fileWriteThread, ^{ + [state writeToURL:[NSURL fileURLWithPath:path isDirectory:NO] error:nil]; + }); +} + +#pragma mark - Network + +- (NSString*)customUserAgent { + return self.commonOps.customUserAgent; +} + +- (void)setCustomUserAgent:(NSString*)customUserAgent { + self.commonOps.customUserAgent = [customUserAgent + stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; +} + +- (void)loadURL:(ledger::type::UrlRequestPtr)request + callback:(ledger::client::LoadURLCallback)callback { + std::map methodMap{ + {ledger::type::UrlMethod::GET, "GET"}, + {ledger::type::UrlMethod::POST, "POST"}, + {ledger::type::UrlMethod::PUT, "PUT"}, + {ledger::type::UrlMethod::DEL, "DELETE"}}; + + if (!request) { + request = ledger::type::UrlRequest::New(); + } + + const auto copiedURL = base::SysUTF8ToNSString(request->url); + + return [self.commonOps + loadURLRequest:request->url + headers:request->headers + content:request->content + content_type:request->content_type + method:methodMap[request->method] + callback:^( + const std::string& errorDescription, int statusCode, + const std::string& response, + const base::flat_map& headers) { + ledger::type::UrlResponse url_response; + url_response.url = base::SysNSStringToUTF8(copiedURL); + url_response.error = errorDescription; + url_response.status_code = statusCode; + url_response.body = response; + url_response.headers = headers; + + callback(url_response); + }]; +} + +- (std::string)URIEncode:(const std::string&)value { + const auto allowedCharacters = + [NSMutableCharacterSet alphanumericCharacterSet]; + [allowedCharacters addCharactersInString:@"-._~"]; + const auto string = base::SysUTF8ToNSString(value); + const auto encoded = [string + stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters]; + return base::SysNSStringToUTF8(encoded); +} + +- (void)fetchFavIcon:(const std::string&)url + faviconKey:(const std::string&)favicon_key + callback:(ledger::client::FetchIconCallback)callback { + const auto pageURL = [NSURL URLWithString:base::SysUTF8ToNSString(url)]; + if (!self.faviconFetcher || !pageURL) { + dispatch_async(dispatch_get_main_queue(), ^{ + callback(NO, std::string()); + }); + return; + } + self.faviconFetcher(pageURL, ^(NSURL* _Nullable faviconURL) { + dispatch_async(dispatch_get_main_queue(), ^{ + callback(faviconURL != nil, + base::SysNSStringToUTF8(faviconURL.absoluteString)); + }); + }); +} + +#pragma mark - Logging + +- (void)log:(const char*)file + line:(const int)line + verboseLevel:(const int)verbose_level + message:(const std::string&)message { + const int vlog_level = logging::GetVlogLevelHelper(file, strlen(file)); + if (verbose_level <= vlog_level) { + logging::LogMessage(file, line, -verbose_level).stream() << message; + } +} + +#pragma mark - Publisher Database + +- (void)handlePublisherListing:(NSArray*)publishers + start:(uint32_t)start + limit:(uint32_t)limit + callback:(ledger::PublisherInfoListCallback)callback { + callback(VectorFromNSArray( + publishers, ^ledger::type::PublisherInfoPtr(BATPublisherInfo* info) { + return info.cppObjPtr; + })); +} +- (void)publisherListNormalized:(ledger::type::PublisherInfoList)list { + const auto list_converted = NSArrayFromVector( + &list, ^BATPublisherInfo*(const ledger::type::PublisherInfoPtr& info) { + return [[BATPublisherInfo alloc] initWithPublisherInfo:*info]; + }); + + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.publisherListNormalized) { + observer.publisherListNormalized(list_converted); + } + } +} + +- (void)onPanelPublisherInfo:(ledger::type::Result)result + publisherInfo:(ledger::type::PublisherInfoPtr)publisher_info + windowId:(uint64_t)windowId { + if (publisher_info.get() == nullptr || + result != ledger::type::Result::LEDGER_OK) { + return; + } + auto info = [[BATPublisherInfo alloc] initWithPublisherInfo:*publisher_info]; + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.fetchedPanelPublisher) { + observer.fetchedPanelPublisher(info, windowId); + } + } +} + +- (void)onContributeUnverifiedPublishers:(ledger::type::Result)result + publisherKey:(const std::string&)publisher_key + publisherName:(const std::string&)publisher_name { + switch (result) { + case ledger::type::Result::PENDING_NOT_ENOUGH_FUNDS: + [self addNotificationOfKind:RewardsNotificationKindPendingNotEnoughFunds + userInfo:nil + notificationID:@"not_enough_funds_for_pending"]; + break; + case ledger::type::Result::PENDING_PUBLISHER_REMOVED: { + const auto publisherID = base::SysUTF8ToNSString(publisher_key); + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.pendingContributionsRemoved) { + observer.pendingContributionsRemoved(@[ publisherID ]); + } + } + break; + } + case ledger::type::Result::VERIFIED_PUBLISHER: { + const auto notificationID = + [NSString stringWithFormat:@"verified_publisher_%@", + base::SysUTF8ToNSString(publisher_key)]; + const auto name = base::SysUTF8ToNSString(publisher_name); + [self addNotificationOfKind:RewardsNotificationKindVerifiedPublisher + userInfo:@{@"publisher_name" : name} + notificationID:notificationID]; + break; + } + default: + break; + } +} + +- (void)showNotification:(const std::string&)type + args:(const std::vector&)args + callback:(ledger::ResultCallback)callback { + const auto notificationID = base::SysUTF8ToNSString(type); + const auto info = [[NSMutableDictionary alloc] init]; + for (NSUInteger i = 0; i < args.size(); i++) { + info[@(i)] = base::SysUTF8ToNSString(args[i]); + } + [self addNotificationOfKind:RewardsNotificationKindGeneralLedger + userInfo:info + notificationID:notificationID + onlyOnce:NO]; +} +- (ledger::type::ClientInfoPtr)getClientInfo { + auto info = ledger::type::ClientInfo::New(); + info->os = ledger::type::OperatingSystem::UNDEFINED; + info->platform = ledger::type::Platform::IOS; + return info; +} + +- (void)unblindedTokensReady { + [self fetchBalance:nil]; + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.balanceReportUpdated) { + observer.balanceReportUpdated(); + } + } +} + +- (void)reconcileStampReset { + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.reconcileStampReset) { + observer.reconcileStampReset(); + } + } +} + +- (void)runDBTransaction:(ledger::type::DBTransactionPtr)transaction + callback:(ledger::client::RunDBTransactionCallback)callback { + __weak BraveLedger* weakSelf = self; + base::PostTaskAndReplyWithResult( + databaseQueue.get(), FROM_HERE, + base::BindOnce(&RunDBTransactionOnTaskRunner, std::move(transaction), + rewardsDatabase), + base::BindOnce(^(ledger::type::DBCommandResponsePtr response) { + if (weakSelf) + callback(std::move(response)); + })); +} + +- (void)pendingContributionSaved:(const ledger::type::Result)result { + for (BraveLedgerObserver* observer in [self.observers copy]) { + if (observer.pendingContributionAdded) { + observer.pendingContributionAdded(); + } + } +} + +- (void)walletDisconnected:(const std::string&)wallet_type { + const auto bridgedType = + static_cast(base::SysUTF8ToNSString(wallet_type)); + for (BraveLedgerObserver* observer in self.observers) { + if (observer.externalWalletDisconnected) { + observer.externalWalletDisconnected(bridgedType); + } + } +} + +- (void)deleteLog:(ledger::ResultCallback)callback { + callback(ledger::type::Result::LEDGER_OK); +} + +- (bool)setEncryptedStringState:(const std::string&)key + value:(const std::string&)value { + const auto bridgedKey = base::SysUTF8ToNSString(key); + + std::string encrypted_value; + if (!OSCrypt::EncryptString(value, &encrypted_value)) { + BLOG(0, @"Couldn't encrypt value for %@", bridgedKey); + return false; + } + + std::string encoded_value; + base::Base64Encode(encrypted_value, &encoded_value); + + self.prefs[bridgedKey] = base::SysUTF8ToNSString(encoded_value); + [self savePrefs]; + return true; +} + +- (std::string)getEncryptedStringState:(const std::string&)key { + const auto bridgedKey = base::SysUTF8ToNSString(key); + NSString* savedValue = self.prefs[bridgedKey]; + if (!savedValue || ![savedValue isKindOfClass:NSString.class]) { + return ""; + } + + std::string encoded_value = base::SysNSStringToUTF8(savedValue); + std::string encrypted_value; + if (!base::Base64Decode(encoded_value, &encrypted_value)) { + BLOG(0, @"base64 decode failed for %@", bridgedKey); + return ""; + } + + std::string value; + if (!OSCrypt::DecryptString(encrypted_value, &value)) { + BLOG(0, @"Decrypting failed for %@", bridgedKey); + return ""; + } + + return value; +} + +@end diff --git a/ios/browser/api/ledger/brave_ledger_observer.h b/ios/browser/api/ledger/brave_ledger_observer.h new file mode 100644 index 00000000000..4f85369cf12 --- /dev/null +++ b/ios/browser/api/ledger/brave_ledger_observer.h @@ -0,0 +1,112 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_IOS_BROWSER_API_LEDGER_BRAVE_LEDGER_OBSERVER_H_ +#define BRAVE_IOS_BROWSER_API_LEDGER_BRAVE_LEDGER_OBSERVER_H_ + +#import +#import "ledger.mojom.objc.h" + +@class BraveLedger, RewardsNotification; + +NS_ASSUME_NONNULL_BEGIN + +/// A ledger observer can get notified when certain actions happen +/// +/// Creating a LedgerObserver alone will not respond to any events. Set +/// each closure that you wish to watch based on the data being displayed on +/// screen +OBJC_EXPORT +NS_SWIFT_NAME(LedgerObserver) +@interface BraveLedgerObserver : NSObject + +@property(nonatomic, readonly, weak) BraveLedger* ledger; + +- (instancetype)initWithLedger:(BraveLedger*)ledger; + +/// Executed when the wallet is first initialized +@property(nonatomic, copy, nullable) void (^walletInitalized)(BATResult result); + +/// A publisher was fetched by its URL for a specific tab identified by tabId +@property(nonatomic, copy, nullable) void (^fetchedPanelPublisher) + (BATPublisherInfo* info, uint64_t tabId); + +@property(nonatomic, copy, nullable) void (^publisherListUpdated)(); + +/// +@property(nonatomic, copy, nullable) void (^finishedPromotionsAdded) + (NSArray* promotions); + +/// Eligable grants were added to the wallet +@property(nonatomic, copy, nullable) void (^promotionsAdded) + (NSArray* promotions); + +/// A grant was claimed +@property(nonatomic, copy, nullable) void (^promotionClaimed) + (BATPromotion* promotion); + +/// A reconcile transaction completed and the user may have an updated balance +/// and likely an updated balance report +@property(nonatomic, copy, nullable) void (^reconcileCompleted) + (BATResult result, + NSString* viewingId, + BATRewardsType type, + NSString* probi); + +/// The users balance report has been updated +@property(nonatomic, copy, nullable) void (^balanceReportUpdated)(); + +/// The exclusion state of a given publisher has been changed +@property(nonatomic, copy, nullable) void (^excludedSitesChanged) + (NSString* publisherKey, BATPublisherExclude excluded); + +/// Called when the ledger removes activity info for a given publisher +@property(nonatomic, copy, nullable) void (^activityRemoved) + (NSString* publisherKey); + +/// The publisher list was normalized and saved +@property(nonatomic, copy, nullable) void (^publisherListNormalized) + (NSArray* normalizedList); + +@property(nonatomic, copy, nullable) void (^pendingContributionAdded)(); + +@property(nonatomic, copy, nullable) void (^pendingContributionsRemoved) + (NSArray* publisherKeys); + +@property(nonatomic, copy, nullable) void (^recurringTipAdded) + (NSString* publisherKey); + +@property(nonatomic, copy, nullable) void (^recurringTipRemoved) + (NSString* publisherKey); + +// A users contribution was added +@property(nonatomic, copy, nullable) void (^contributionAdded) + (BOOL successful, BATRewardsType type); + +/// A notification was added to the wallet +@property(nonatomic, copy, nullable) void (^notificationAdded) + (RewardsNotification* notification); + +/// A notification was removed from the wallet +@property(nonatomic, copy, nullable) void (^notificationsRemoved) + (NSArray* notification); + +/// Wallet balance was fetched and updated +@property(nonatomic, copy, nullable) void (^fetchedBalance)(); + +@property(nonatomic, copy, nullable) void (^externalWalletAuthorized) + (NSString* type); + +@property(nonatomic, copy, nullable) void (^externalWalletDisconnected) + (NSString* type); + +/// The reconcile stamp reset +@property(nonatomic, copy, nullable) void (^reconcileStampReset)(); + +@end + +NS_ASSUME_NONNULL_END + +#endif // BRAVE_IOS_BROWSER_API_LEDGER_BRAVE_LEDGER_OBSERVER_H_ diff --git a/ios/browser/api/ledger/brave_ledger_observer.mm b/ios/browser/api/ledger/brave_ledger_observer.mm new file mode 100644 index 00000000000..af7dc5d6df2 --- /dev/null +++ b/ios/browser/api/ledger/brave_ledger_observer.mm @@ -0,0 +1,26 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#import "brave_ledger_observer.h" +#import "brave_ledger.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@interface BraveLedgerObserver () +@property(nonatomic, weak) BraveLedger* ledger; +@end + +@implementation BraveLedgerObserver + +- (instancetype)initWithLedger:(BraveLedger*)ledger { + if ((self = [super init])) { + self.ledger = ledger; + } + return self; +} + +@end diff --git a/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h b/ios/browser/api/ledger/ledger_client_bridge.h similarity index 53% rename from vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h rename to ios/browser/api/ledger/ledger_client_bridge.h index feb781a7a82..63ef4dfd9cd 100644 --- a/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h +++ b/ios/browser/api/ledger/ledger_client_bridge.h @@ -1,23 +1,40 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_IOS_BROWSER_API_LEDGER_LEDGER_CLIENT_BRIDGE_H_ +#define BRAVE_IOS_BROWSER_API_LEDGER_LEDGER_CLIENT_BRIDGE_H_ #import -#import "bat/ledger/ledger_client.h" +#include +#include +#include "bat/ledger/ledger_client.h" -@protocol NativeLedgerClientBridge +@protocol LedgerClientBridge @required -- (void)fetchFavIcon:(const std::string &)url faviconKey:(const std::string &)favicon_key callback:(ledger::client::FetchIconCallback)callback; +- (void)fetchFavIcon:(const std::string&)url + faviconKey:(const std::string&)favicon_key + callback:(ledger::client::FetchIconCallback)callback; - (void)loadLedgerState:(ledger::client::OnLoadCallback)callback; - (void)loadPublisherState:(ledger::client::OnLoadCallback)callback; -- (void)loadURL:(ledger::type::UrlRequestPtr)request callback:(ledger::client::LoadURLCallback)callback; -- (void)log:(const char *)file line:(const int)line verboseLevel:(const int)verbose_level message:(const std::string &) message; -- (void)onPanelPublisherInfo:(ledger::type::Result)result publisherInfo:(ledger::type::PublisherInfoPtr)publisher_info windowId:(uint64_t)windowId; -- (void)onReconcileComplete:(ledger::type::Result)result contribution:(ledger::type::ContributionInfoPtr)contribution; +- (void)loadURL:(ledger::type::UrlRequestPtr)request + callback:(ledger::client::LoadURLCallback)callback; +- (void)log:(const char*)file + line:(const int)line + verboseLevel:(const int)verbose_level + message:(const std::string&)message; +- (void)onPanelPublisherInfo:(ledger::type::Result)result + publisherInfo:(ledger::type::PublisherInfoPtr)publisher_info + windowId:(uint64_t)windowId; +- (void)onReconcileComplete:(ledger::type::Result)result + contribution:(ledger::type::ContributionInfoPtr)contribution; - (void)publisherListNormalized:(ledger::type::PublisherInfoList)list; -- (std::string)URIEncode:(const std::string &)value; -- (void)onContributeUnverifiedPublishers:(ledger::type::Result)result publisherKey:(const std::string&)publisher_key publisherName:(const std::string&)publisher_name; +- (std::string)URIEncode:(const std::string&)value; +- (void)onContributeUnverifiedPublishers:(ledger::type::Result)result + publisherKey:(const std::string&)publisher_key + publisherName:(const std::string&)publisher_name; - (void)setBooleanState:(const std::string&)name value:(bool)value; - (bool)getBooleanState:(const std::string&)name; - (void)setIntegerState:(const std::string&)name value:(int)value; @@ -32,7 +49,9 @@ - (uint64_t)getUint64State:(const std::string&)name; - (void)clearState:(const std::string&)name; - (std::string)getLegacyWallet; -- (void)showNotification:(const std::string &)type args:(const std::vector&)args callback:(ledger::client::ResultCallback)callback; +- (void)showNotification:(const std::string&)type + args:(const std::vector&)args + callback:(ledger::client::ResultCallback)callback; - (bool)getBooleanOption:(const std::string&)name; - (int)getIntegerOption:(const std::string&)name; - (double)getDoubleOption:(const std::string&)name; @@ -42,13 +61,17 @@ - (ledger::type::ClientInfoPtr)getClientInfo; - (void)unblindedTokensReady; - (void)reconcileStampReset; -- (void)runDBTransaction:(ledger::type::DBTransactionPtr)transaction callback:(ledger::client::RunDBTransactionCallback)callback; +- (void)runDBTransaction:(ledger::type::DBTransactionPtr)transaction + callback:(ledger::client::RunDBTransactionCallback)callback; - (void)getCreateScript:(ledger::client::GetCreateScriptCallback)callback; - (void)pendingContributionSaved:(const ledger::type::Result)result; - (void)clearAllNotifications; - (void)walletDisconnected:(const std::string&)wallet_type; - (void)deleteLog:(ledger::client::ResultCallback)callback; -- (bool)setEncryptedStringState:(const std::string&)key value:(const std::string&)value; +- (bool)setEncryptedStringState:(const std::string&)key + value:(const std::string&)value; - (std::string)getEncryptedStringState:(const std::string&)key; @end + +#endif // BRAVE_IOS_BROWSER_API_LEDGER_LEDGER_CLIENT_BRIDGE_H_ diff --git a/ios/browser/api/ledger/ledger_client_ios.h b/ios/browser/api/ledger/ledger_client_ios.h new file mode 100644 index 00000000000..bf23aaf14d7 --- /dev/null +++ b/ios/browser/api/ledger/ledger_client_ios.h @@ -0,0 +1,88 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_IOS_BROWSER_API_LEDGER_LEDGER_CLIENT_IOS_H_ +#define BRAVE_IOS_BROWSER_API_LEDGER_LEDGER_CLIENT_IOS_H_ + +#import +#include +#include +#import "bat/ledger/ledger_client.h" + +@protocol LedgerClientBridge; + +class LedgerClientIOS : public ledger::LedgerClient { + public: + explicit LedgerClientIOS(id bridge); + ~LedgerClientIOS() override; + + private: + __unsafe_unretained id bridge_; + + void FetchFavIcon(const std::string& url, + const std::string& favicon_key, + ledger::client::FetchIconCallback callback) override; + void LoadLedgerState(ledger::client::OnLoadCallback callback) override; + void LoadPublisherState(ledger::client::OnLoadCallback callback) override; + void LoadURL(ledger::type::UrlRequestPtr request, + ledger::client::LoadURLCallback callback) override; + void Log(const char* file, + const int line, + const int verbose_level, + const std::string& message) override; + void OnPanelPublisherInfo(ledger::type::Result result, + ledger::type::PublisherInfoPtr publisher_info, + uint64_t windowId) override; + void OnReconcileComplete( + ledger::type::Result result, + ledger::type::ContributionInfoPtr contribution) override; + void PublisherListNormalized(ledger::type::PublisherInfoList list) override; + std::string URIEncode(const std::string& value) override; + void OnContributeUnverifiedPublishers( + ledger::type::Result result, + const std::string& publisher_key, + const std::string& publisher_name) override; + void SetBooleanState(const std::string& name, bool value) override; + bool GetBooleanState(const std::string& name) const override; + void SetIntegerState(const std::string& name, int value) override; + int GetIntegerState(const std::string& name) const override; + void SetDoubleState(const std::string& name, double value) override; + double GetDoubleState(const std::string& name) const override; + void SetStringState(const std::string& name, + const std::string& value) override; + std::string GetStringState(const std::string& name) const override; + void SetInt64State(const std::string& name, int64_t value) override; + int64_t GetInt64State(const std::string& name) const override; + void SetUint64State(const std::string& name, uint64_t value) override; + uint64_t GetUint64State(const std::string& name) const override; + void ClearState(const std::string& name) override; + std::string GetLegacyWallet() override; + void ShowNotification(const std::string& type, + const std::vector& args, + ledger::client::ResultCallback callback) override; + bool GetBooleanOption(const std::string& name) const override; + int GetIntegerOption(const std::string& name) const override; + double GetDoubleOption(const std::string& name) const override; + std::string GetStringOption(const std::string& name) const override; + int64_t GetInt64Option(const std::string& name) const override; + uint64_t GetUint64Option(const std::string& name) const override; + ledger::type::ClientInfoPtr GetClientInfo() override; + void UnblindedTokensReady() override; + void ReconcileStampReset() override; + void RunDBTransaction( + ledger::type::DBTransactionPtr transaction, + ledger::client::RunDBTransactionCallback callback) override; + void GetCreateScript( + ledger::client::GetCreateScriptCallback callback) override; + void PendingContributionSaved(const ledger::type::Result result) override; + void ClearAllNotifications() override; + void WalletDisconnected(const std::string& wallet_type) override; + void DeleteLog(ledger::client::ResultCallback callback) override; + bool SetEncryptedStringState(const std::string& key, + const std::string& value) override; + std::string GetEncryptedStringState(const std::string& key) override; +}; + +#endif // BRAVE_IOS_BROWSER_API_LEDGER_LEDGER_CLIENT_IOS_H_ diff --git a/ios/browser/api/ledger/ledger_client_ios.mm b/ios/browser/api/ledger/ledger_client_ios.mm new file mode 100644 index 00000000000..186b1243a0c --- /dev/null +++ b/ios/browser/api/ledger/ledger_client_ios.mm @@ -0,0 +1,174 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#import "ledger_client_ios.h" +#import "ledger_client_bridge.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +// Constructor & Destructor +LedgerClientIOS::LedgerClientIOS(id bridge) + : bridge_(bridge) {} +LedgerClientIOS::~LedgerClientIOS() { + bridge_ = nil; +} + +void LedgerClientIOS::FetchFavIcon(const std::string& url, + const std::string& favicon_key, + ledger::client::FetchIconCallback callback) { + [bridge_ fetchFavIcon:url faviconKey:favicon_key callback:callback]; +} +void LedgerClientIOS::LoadLedgerState(ledger::client::OnLoadCallback callback) { + [bridge_ loadLedgerState:callback]; +} +void LedgerClientIOS::LoadPublisherState( + ledger::client::OnLoadCallback callback) { + [bridge_ loadPublisherState:callback]; +} +void LedgerClientIOS::LoadURL(ledger::type::UrlRequestPtr request, + ledger::client::LoadURLCallback callback) { + [bridge_ loadURL:std::move(request) callback:callback]; +} +void LedgerClientIOS::Log(const char* file, + const int line, + const int verbose_level, + const std::string& message) { + [bridge_ log:file line:line verboseLevel:verbose_level message:message]; +} +void LedgerClientIOS::OnPanelPublisherInfo( + ledger::type::Result result, + ledger::type::PublisherInfoPtr publisher_info, + uint64_t windowId) { + [bridge_ onPanelPublisherInfo:result + publisherInfo:std::move(publisher_info) + windowId:windowId]; +} +void LedgerClientIOS::OnReconcileComplete( + ledger::type::Result result, + ledger::type::ContributionInfoPtr contribution) { + [bridge_ onReconcileComplete:result contribution:std::move(contribution)]; +} +void LedgerClientIOS::PublisherListNormalized( + ledger::type::PublisherInfoList list) { + [bridge_ publisherListNormalized:std::move(list)]; +} +std::string LedgerClientIOS::URIEncode(const std::string& value) { + return [bridge_ URIEncode:value]; +} +void LedgerClientIOS::OnContributeUnverifiedPublishers( + ledger::type::Result result, + const std::string& publisher_key, + const std::string& publisher_name) { + return [bridge_ onContributeUnverifiedPublishers:result + publisherKey:publisher_key + publisherName:publisher_name]; +} +void LedgerClientIOS::SetBooleanState(const std::string& name, bool value) { + [bridge_ setBooleanState:name value:value]; +} +bool LedgerClientIOS::GetBooleanState(const std::string& name) const { + return [bridge_ getBooleanState:name]; +} +void LedgerClientIOS::SetIntegerState(const std::string& name, int value) { + [bridge_ setIntegerState:name value:value]; +} +int LedgerClientIOS::GetIntegerState(const std::string& name) const { + return [bridge_ getIntegerState:name]; +} +void LedgerClientIOS::SetDoubleState(const std::string& name, double value) { + [bridge_ setDoubleState:name value:value]; +} +double LedgerClientIOS::GetDoubleState(const std::string& name) const { + return [bridge_ getDoubleState:name]; +} +void LedgerClientIOS::SetStringState(const std::string& name, + const std::string& value) { + [bridge_ setStringState:name value:value]; +} +std::string LedgerClientIOS::GetStringState(const std::string& name) const { + return [bridge_ getStringState:name]; +} +void LedgerClientIOS::SetInt64State(const std::string& name, int64_t value) { + [bridge_ setInt64State:name value:value]; +} +int64_t LedgerClientIOS::GetInt64State(const std::string& name) const { + return [bridge_ getInt64State:name]; +} +void LedgerClientIOS::SetUint64State(const std::string& name, uint64_t value) { + [bridge_ setUint64State:name value:value]; +} +uint64_t LedgerClientIOS::GetUint64State(const std::string& name) const { + return [bridge_ getUint64State:name]; +} +void LedgerClientIOS::ClearState(const std::string& name) { + [bridge_ clearState:name]; +} +std::string LedgerClientIOS::GetLegacyWallet() { + return [bridge_ getLegacyWallet]; +} +void LedgerClientIOS::ShowNotification( + const std::string& type, + const std::vector& args, + ledger::client::ResultCallback callback) { + [bridge_ showNotification:type args:args callback:callback]; +} +bool LedgerClientIOS::GetBooleanOption(const std::string& name) const { + return [bridge_ getBooleanOption:name]; +} +int LedgerClientIOS::GetIntegerOption(const std::string& name) const { + return [bridge_ getIntegerOption:name]; +} +double LedgerClientIOS::GetDoubleOption(const std::string& name) const { + return [bridge_ getDoubleOption:name]; +} +std::string LedgerClientIOS::GetStringOption(const std::string& name) const { + return [bridge_ getStringOption:name]; +} +int64_t LedgerClientIOS::GetInt64Option(const std::string& name) const { + return [bridge_ getInt64Option:name]; +} +uint64_t LedgerClientIOS::GetUint64Option(const std::string& name) const { + return [bridge_ getUint64Option:name]; +} +ledger::type::ClientInfoPtr LedgerClientIOS::GetClientInfo() { + return [bridge_ getClientInfo]; +} +void LedgerClientIOS::UnblindedTokensReady() { + [bridge_ unblindedTokensReady]; +} +void LedgerClientIOS::ReconcileStampReset() { + [bridge_ reconcileStampReset]; +} +void LedgerClientIOS::RunDBTransaction( + ledger::type::DBTransactionPtr transaction, + ledger::client::RunDBTransactionCallback callback) { + [bridge_ runDBTransaction:std::move(transaction) callback:callback]; +} +void LedgerClientIOS::GetCreateScript( + ledger::client::GetCreateScriptCallback callback) { + [bridge_ getCreateScript:callback]; +} +void LedgerClientIOS::PendingContributionSaved( + const ledger::type::Result result) { + [bridge_ pendingContributionSaved:result]; +} +void LedgerClientIOS::ClearAllNotifications() { + [bridge_ clearAllNotifications]; +} +void LedgerClientIOS::WalletDisconnected(const std::string& wallet_type) { + [bridge_ walletDisconnected:wallet_type]; +} +void LedgerClientIOS::DeleteLog(ledger::client::ResultCallback callback) { + [bridge_ deleteLog:callback]; +} +bool LedgerClientIOS::SetEncryptedStringState(const std::string& key, + const std::string& value) { + return [bridge_ setEncryptedStringState:key value:value]; +} +std::string LedgerClientIOS::GetEncryptedStringState(const std::string& key) { + return [bridge_ getEncryptedStringState:key]; +} diff --git a/ios/browser/api/ledger/legacy_database/BUILD.gn b/ios/browser/api/ledger/legacy_database/BUILD.gn new file mode 100644 index 00000000000..e86657879d1 --- /dev/null +++ b/ios/browser/api/ledger/legacy_database/BUILD.gn @@ -0,0 +1,39 @@ +# Copyright (c) 2021 The Brave Authors. All rights reserved. +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +import("//brave/build/ios/coredata_model.gni") +import("//build/config/ios/rules.gni") + +source_set("legacy_database") { + configs += [ "//build/config/compiler:enable_arc" ] + + sources = [ + "data_controller.h", + "data_controller.mm", + "legacy_ledger_database.h", + "legacy_ledger_database.mm", + ] + + deps = [ + ":ledger_resources", + ":model", + "//base", + "//brave/ios/browser/api/ledger/legacy_database/core_data_models", + ] + + frameworks = [ + "Foundation.framework", + "CoreData.framework", + ] +} + +coredata_model("model") { + model_file = "Model.xcdatamodeld" +} + +bundle_data("ledger_resources") { + sources = [ "migrate.sql" ] + outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ] +} diff --git a/ios/browser/api/ledger/legacy_database/CPPLINT.cfg b/ios/browser/api/ledger/legacy_database/CPPLINT.cfg new file mode 100644 index 00000000000..f25ac1008a6 --- /dev/null +++ b/ios/browser/api/ledger/legacy_database/CPPLINT.cfg @@ -0,0 +1 @@ +exclude_files=core_data_models \ No newline at end of file diff --git a/vendor/brave-ios/Ledger/Data/Model.xcdatamodeld/Model.xcdatamodel/contents b/ios/browser/api/ledger/legacy_database/Model.xcdatamodeld/Model.xcdatamodel/contents similarity index 100% rename from vendor/brave-ios/Ledger/Data/Model.xcdatamodeld/Model.xcdatamodel/contents rename to ios/browser/api/ledger/legacy_database/Model.xcdatamodeld/Model.xcdatamodel/contents diff --git a/vendor/brave-ios/Ledger/Data/Model/ActivityInfo.h b/ios/browser/api/ledger/legacy_database/core_data_models/ActivityInfo.h similarity index 50% rename from vendor/brave-ios/Ledger/Data/Model/ActivityInfo.h rename to ios/browser/api/ledger/legacy_database/core_data_models/ActivityInfo.h index 436e65e94f5..f1900194237 100644 --- a/vendor/brave-ios/Ledger/Data/Model/ActivityInfo.h +++ b/ios/browser/api/ledger/legacy_database/core_data_models/ActivityInfo.h @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#import #import +#import @class PublisherInfo; @@ -12,16 +12,16 @@ NS_ASSUME_NONNULL_BEGIN OBJC_EXPORT @interface ActivityInfo : NSManagedObject -+ (NSFetchRequest *)fetchRequest; ++ (NSFetchRequest*)fetchRequest; -@property (nonatomic) int64_t duration; -@property (nonatomic) int32_t percent; -@property (nonatomic, copy) NSString *publisherID; -@property (nonatomic) int64_t reconcileStamp; -@property (nonatomic) double score; -@property (nonatomic) int32_t visits; -@property (nonatomic) double weight; -@property (nonatomic, retain) PublisherInfo *publisher; +@property(nonatomic) int64_t duration; +@property(nonatomic) int32_t percent; +@property(nonatomic, copy) NSString* publisherID; +@property(nonatomic) int64_t reconcileStamp; +@property(nonatomic) double score; +@property(nonatomic) int32_t visits; +@property(nonatomic) double weight; +@property(nonatomic, retain) PublisherInfo* publisher; @end diff --git a/vendor/brave-ios/Ledger/Data/Model/ActivityInfo.m b/ios/browser/api/ledger/legacy_database/core_data_models/ActivityInfo.m similarity index 90% rename from vendor/brave-ios/Ledger/Data/Model/ActivityInfo.m rename to ios/browser/api/ledger/legacy_database/core_data_models/ActivityInfo.m index ad2a5971cb0..99c57c481b6 100644 --- a/vendor/brave-ios/Ledger/Data/Model/ActivityInfo.m +++ b/ios/browser/api/ledger/legacy_database/core_data_models/ActivityInfo.m @@ -6,7 +6,7 @@ @implementation ActivityInfo -+ (NSFetchRequest *)fetchRequest { ++ (NSFetchRequest*)fetchRequest { return [NSFetchRequest fetchRequestWithEntityName:@"ActivityInfo"]; } diff --git a/ios/browser/api/ledger/legacy_database/core_data_models/BUILD.gn b/ios/browser/api/ledger/legacy_database/core_data_models/BUILD.gn new file mode 100644 index 00000000000..db06888b797 --- /dev/null +++ b/ios/browser/api/ledger/legacy_database/core_data_models/BUILD.gn @@ -0,0 +1,48 @@ +# Copyright (c) 2021 The Brave Authors. All rights reserved. +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +import("//build/config/ios/rules.gni") + +source_set("core_data_models") { + configs += [ "//build/config/compiler:enable_arc" ] + + sources = [ + "ActivityInfo.h", + "ActivityInfo.m", + "ContributionInfo.h", + "ContributionInfo.m", + "ContributionPublisher.h", + "ContributionPublisher.m", + "ContributionQueue.h", + "ContributionQueue.m", + "CoreDataModels.h", + "MediaPublisherInfo.h", + "MediaPublisherInfo.m", + "PendingContribution.h", + "PendingContribution.m", + "Promotion.h", + "Promotion.m", + "PromotionCredentials.h", + "PromotionCredentials.m", + "PublisherInfo.h", + "PublisherInfo.m", + "RecurringDonation.h", + "RecurringDonation.m", + "ServerPublisherAmount.h", + "ServerPublisherAmount.m", + "ServerPublisherBanner.h", + "ServerPublisherBanner.m", + "ServerPublisherInfo.h", + "ServerPublisherInfo.m", + "ServerPublisherLink.h", + "ServerPublisherLink.m", + "UnblindedToken.h", + "UnblindedToken.m", + ] + frameworks = [ + "Foundation.framework", + "CoreData.framework", + ] +} diff --git a/vendor/brave-ios/Ledger/Data/Model/ContributionInfo.h b/ios/browser/api/ledger/legacy_database/core_data_models/ContributionInfo.h similarity index 53% rename from vendor/brave-ios/Ledger/Data/Model/ContributionInfo.h rename to ios/browser/api/ledger/legacy_database/core_data_models/ContributionInfo.h index fdf33e10214..f83a93d3428 100644 --- a/vendor/brave-ios/Ledger/Data/Model/ContributionInfo.h +++ b/ios/browser/api/ledger/legacy_database/core_data_models/ContributionInfo.h @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#import #import +#import @class PublisherInfo; @@ -12,15 +12,15 @@ NS_ASSUME_NONNULL_BEGIN OBJC_EXPORT @interface ContributionInfo : NSManagedObject -+ (NSFetchRequest *)fetchRequest; ++ (NSFetchRequest*)fetchRequest; -@property (nonatomic) int32_t type; -@property (nonatomic) int64_t date; -@property (nonatomic) int32_t month; -@property (nonatomic, copy) NSString *probi; -@property (nonatomic, copy) NSString *publisherID; -@property (nonatomic) int32_t year; -@property (nonatomic, retain) PublisherInfo *publisher; +@property(nonatomic) int32_t type; +@property(nonatomic) int64_t date; +@property(nonatomic) int32_t month; +@property(nonatomic, copy) NSString* probi; +@property(nonatomic, copy) NSString* publisherID; +@property(nonatomic) int32_t year; +@property(nonatomic, retain) PublisherInfo* publisher; @end diff --git a/vendor/brave-ios/Ledger/Data/Model/ContributionInfo.m b/ios/browser/api/ledger/legacy_database/core_data_models/ContributionInfo.m similarity index 89% rename from vendor/brave-ios/Ledger/Data/Model/ContributionInfo.m rename to ios/browser/api/ledger/legacy_database/core_data_models/ContributionInfo.m index aec0f49ace0..bb26eb39b89 100644 --- a/vendor/brave-ios/Ledger/Data/Model/ContributionInfo.m +++ b/ios/browser/api/ledger/legacy_database/core_data_models/ContributionInfo.m @@ -6,7 +6,7 @@ @implementation ContributionInfo -+ (NSFetchRequest *)fetchRequest { ++ (NSFetchRequest*)fetchRequest { return [NSFetchRequest fetchRequestWithEntityName:@"ContributionInfo"]; } diff --git a/vendor/brave-ios/Ledger/Data/Model/ContributionPublisher.h b/ios/browser/api/ledger/legacy_database/core_data_models/ContributionPublisher.h similarity index 64% rename from vendor/brave-ios/Ledger/Data/Model/ContributionPublisher.h rename to ios/browser/api/ledger/legacy_database/core_data_models/ContributionPublisher.h index 0c50d3c8f1c..ab99ad744f5 100644 --- a/vendor/brave-ios/Ledger/Data/Model/ContributionPublisher.h +++ b/ios/browser/api/ledger/legacy_database/core_data_models/ContributionPublisher.h @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#import #import +#import @class ContributionQueue; @@ -12,11 +12,11 @@ NS_ASSUME_NONNULL_BEGIN OBJC_EXPORT @interface ContributionPublisher : NSManagedObject -+ (NSFetchRequest *)fetchRequest; ++ (NSFetchRequest*)fetchRequest; -@property (nullable, nonatomic, copy) NSString *publisherKey; -@property (nonatomic) double amountPercent; -@property (nullable, nonatomic, retain) ContributionQueue *queue; +@property(nullable, nonatomic, copy) NSString* publisherKey; +@property(nonatomic) double amountPercent; +@property(nullable, nonatomic, retain) ContributionQueue* queue; @end diff --git a/vendor/brave-ios/Ledger/Data/Model/ContributionPublisher.m b/ios/browser/api/ledger/legacy_database/core_data_models/ContributionPublisher.m similarity index 87% rename from vendor/brave-ios/Ledger/Data/Model/ContributionPublisher.m rename to ios/browser/api/ledger/legacy_database/core_data_models/ContributionPublisher.m index 744b067c9c9..b5a8d4735a5 100644 --- a/vendor/brave-ios/Ledger/Data/Model/ContributionPublisher.m +++ b/ios/browser/api/ledger/legacy_database/core_data_models/ContributionPublisher.m @@ -6,7 +6,7 @@ @implementation ContributionPublisher -+ (NSFetchRequest *)fetchRequest { ++ (NSFetchRequest*)fetchRequest { return [NSFetchRequest fetchRequestWithEntityName:@"ContributionPublisher"]; } diff --git a/ios/browser/api/ledger/legacy_database/core_data_models/ContributionQueue.h b/ios/browser/api/ledger/legacy_database/core_data_models/ContributionQueue.h new file mode 100644 index 00000000000..e1a74f2768a --- /dev/null +++ b/ios/browser/api/ledger/legacy_database/core_data_models/ContributionQueue.h @@ -0,0 +1,35 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#import +#import + +@class ContributionPublisher; + +NS_ASSUME_NONNULL_BEGIN + +OBJC_EXPORT +@interface ContributionQueue : NSManagedObject + ++ (NSFetchRequest*)fetchRequest; + +@property(nonatomic) int64_t id; +@property(nonatomic) int32_t type; +@property(nonatomic) double amount; +@property(nonatomic) bool partial; +@property(nullable, nonatomic, retain) + NSSet* publishers; + +@end + +@interface ContributionQueue (CoreDataGeneratedAccessors) + +- (void)addPublishersObject:(ContributionPublisher*)value; +- (void)removePublishersObject:(ContributionPublisher*)value; +- (void)addPublishers:(NSSet*)values; +- (void)removePublishers:(NSSet*)values; + +@end + +NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Data/Model/ContributionQueue.m b/ios/browser/api/ledger/legacy_database/core_data_models/ContributionQueue.m similarity index 88% rename from vendor/brave-ios/Ledger/Data/Model/ContributionQueue.m rename to ios/browser/api/ledger/legacy_database/core_data_models/ContributionQueue.m index fe9e4a0f1cd..87db8f1497f 100644 --- a/vendor/brave-ios/Ledger/Data/Model/ContributionQueue.m +++ b/ios/browser/api/ledger/legacy_database/core_data_models/ContributionQueue.m @@ -6,7 +6,7 @@ @implementation ContributionQueue -+ (NSFetchRequest *)fetchRequest { ++ (NSFetchRequest*)fetchRequest { return [NSFetchRequest fetchRequestWithEntityName:@"ContributionQueue"]; } diff --git a/vendor/brave-ios/Ledger/Data/Model/CoreDataModels.h b/ios/browser/api/ledger/legacy_database/core_data_models/CoreDataModels.h similarity index 99% rename from vendor/brave-ios/Ledger/Data/Model/CoreDataModels.h rename to ios/browser/api/ledger/legacy_database/core_data_models/CoreDataModels.h index 733d383df01..bbf27a8df8f 100644 --- a/vendor/brave-ios/Ledger/Data/Model/CoreDataModels.h +++ b/ios/browser/api/ledger/legacy_database/core_data_models/CoreDataModels.h @@ -1,27 +1,27 @@ // // Model+CoreDataModel.h -// +// // // Created by Kyle Hickinson on 2019-05-24. // // This file was automatically generated and should not be edited. // -#import #import +#import #import "ActivityInfo.h" #import "ContributionInfo.h" +#import "ContributionPublisher.h" +#import "ContributionQueue.h" #import "MediaPublisherInfo.h" #import "PendingContribution.h" -#import "PublisherInfo.h" -#import "RecurringDonation.h" -#import "ServerPublisherInfo.h" -#import "ServerPublisherAmount.h" -#import "ServerPublisherBanner.h" -#import "ServerPublisherLink.h" -#import "ContributionQueue.h" -#import "ContributionPublisher.h" #import "Promotion.h" #import "PromotionCredentials.h" +#import "PublisherInfo.h" +#import "RecurringDonation.h" +#import "ServerPublisherAmount.h" +#import "ServerPublisherBanner.h" +#import "ServerPublisherInfo.h" +#import "ServerPublisherLink.h" #import "UnblindedToken.h" diff --git a/vendor/brave-ios/Ledger/Data/Model/MediaPublisherInfo.h b/ios/browser/api/ledger/legacy_database/core_data_models/MediaPublisherInfo.h similarity index 71% rename from vendor/brave-ios/Ledger/Data/Model/MediaPublisherInfo.h rename to ios/browser/api/ledger/legacy_database/core_data_models/MediaPublisherInfo.h index ad59a155ef5..fd8a745558a 100644 --- a/vendor/brave-ios/Ledger/Data/Model/MediaPublisherInfo.h +++ b/ios/browser/api/ledger/legacy_database/core_data_models/MediaPublisherInfo.h @@ -2,18 +2,18 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#import #import +#import NS_ASSUME_NONNULL_BEGIN OBJC_EXPORT @interface MediaPublisherInfo : NSManagedObject -+ (NSFetchRequest *)fetchRequest; ++ (NSFetchRequest*)fetchRequest; -@property (nonatomic, copy) NSString *mediaKey; -@property (nonatomic, copy) NSString *publisherID; +@property(nonatomic, copy) NSString* mediaKey; +@property(nonatomic, copy) NSString* publisherID; @end diff --git a/vendor/brave-ios/Ledger/Data/Model/MediaPublisherInfo.m b/ios/browser/api/ledger/legacy_database/core_data_models/MediaPublisherInfo.m similarity index 87% rename from vendor/brave-ios/Ledger/Data/Model/MediaPublisherInfo.m rename to ios/browser/api/ledger/legacy_database/core_data_models/MediaPublisherInfo.m index f4fca6625a4..75e0f3c0ba7 100644 --- a/vendor/brave-ios/Ledger/Data/Model/MediaPublisherInfo.m +++ b/ios/browser/api/ledger/legacy_database/core_data_models/MediaPublisherInfo.m @@ -6,7 +6,7 @@ @implementation MediaPublisherInfo -+ (NSFetchRequest *)fetchRequest { ++ (NSFetchRequest*)fetchRequest { return [NSFetchRequest fetchRequestWithEntityName:@"MediaPublisherInfo"]; } diff --git a/vendor/brave-ios/Ledger/Data/Model/PendingContribution.h b/ios/browser/api/ledger/legacy_database/core_data_models/PendingContribution.h similarity index 55% rename from vendor/brave-ios/Ledger/Data/Model/PendingContribution.h rename to ios/browser/api/ledger/legacy_database/core_data_models/PendingContribution.h index fd5b4b8dfba..32ff05970eb 100644 --- a/vendor/brave-ios/Ledger/Data/Model/PendingContribution.h +++ b/ios/browser/api/ledger/legacy_database/core_data_models/PendingContribution.h @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#import #import +#import @class PublisherInfo; @@ -12,14 +12,14 @@ NS_ASSUME_NONNULL_BEGIN OBJC_EXPORT @interface PendingContribution : NSManagedObject -+ (NSFetchRequest *)fetchRequest; ++ (NSFetchRequest*)fetchRequest; -@property (nonatomic) int64_t addedDate; -@property (nonatomic) double amount; -@property (nonatomic) int32_t type; -@property (nonatomic, copy) NSString *publisherID; -@property (nonatomic, copy) NSString *viewingID; -@property (nonatomic, retain) PublisherInfo *publisher; +@property(nonatomic) int64_t addedDate; +@property(nonatomic) double amount; +@property(nonatomic) int32_t type; +@property(nonatomic, copy) NSString* publisherID; +@property(nonatomic, copy) NSString* viewingID; +@property(nonatomic, retain) PublisherInfo* publisher; @end diff --git a/vendor/brave-ios/Ledger/Data/Model/PendingContribution.m b/ios/browser/api/ledger/legacy_database/core_data_models/PendingContribution.m similarity index 89% rename from vendor/brave-ios/Ledger/Data/Model/PendingContribution.m rename to ios/browser/api/ledger/legacy_database/core_data_models/PendingContribution.m index 387556d7f4f..6969eba1057 100644 --- a/vendor/brave-ios/Ledger/Data/Model/PendingContribution.m +++ b/ios/browser/api/ledger/legacy_database/core_data_models/PendingContribution.m @@ -6,7 +6,7 @@ @implementation PendingContribution -+ (NSFetchRequest *)fetchRequest { ++ (NSFetchRequest*)fetchRequest { return [NSFetchRequest fetchRequestWithEntityName:@"PendingContribution"]; } diff --git a/ios/browser/api/ledger/legacy_database/core_data_models/Promotion.h b/ios/browser/api/ledger/legacy_database/core_data_models/Promotion.h new file mode 100644 index 00000000000..7fe33292efe --- /dev/null +++ b/ios/browser/api/ledger/legacy_database/core_data_models/Promotion.h @@ -0,0 +1,32 @@ +// +// Promotion+CoreDataClass.h +// +// +// Created by Kyle Hickinson on 2019-10-21. +// +// + +#import +#import + +@class PromotionCredentials; + +NS_ASSUME_NONNULL_BEGIN + +OBJC_EXPORT +@interface Promotion : NSManagedObject + ++ (NSFetchRequest*)fetchRequest; + +@property(nonatomic, copy) NSString* promotionID; +@property(nonatomic) int32_t version; +@property(nonatomic) int32_t type; +@property(nonatomic, copy) NSString* publicKeys; +@property(nonatomic) int32_t suggestions; +@property(nonatomic) double approximateValue; +@property(nonatomic) int32_t status; +@property(nonatomic, copy) NSDate* expiryDate; + +@end + +NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Data/Model/Promotion.m b/ios/browser/api/ledger/legacy_database/core_data_models/Promotion.m similarity index 87% rename from vendor/brave-ios/Ledger/Data/Model/Promotion.m rename to ios/browser/api/ledger/legacy_database/core_data_models/Promotion.m index 191a40c11a7..59520bd3cd1 100644 --- a/vendor/brave-ios/Ledger/Data/Model/Promotion.m +++ b/ios/browser/api/ledger/legacy_database/core_data_models/Promotion.m @@ -1,6 +1,6 @@ // // Promotion+CoreDataClass.m -// +// // // Created by Kyle Hickinson on 2019-10-21. // @@ -10,7 +10,7 @@ @implementation Promotion -+ (NSFetchRequest *)fetchRequest { ++ (NSFetchRequest*)fetchRequest { return [NSFetchRequest fetchRequestWithEntityName:@"Promotion"]; } diff --git a/ios/browser/api/ledger/legacy_database/core_data_models/PromotionCredentials.h b/ios/browser/api/ledger/legacy_database/core_data_models/PromotionCredentials.h new file mode 100644 index 00000000000..19ae1df0015 --- /dev/null +++ b/ios/browser/api/ledger/legacy_database/core_data_models/PromotionCredentials.h @@ -0,0 +1,29 @@ +// +// PromotionCredentials+CoreDataClass.h +// +// +// Created by Kyle Hickinson on 2019-10-21. +// +// + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +OBJC_EXPORT +@interface PromotionCredentials : NSManagedObject + ++ (NSFetchRequest*)fetchRequest; + +@property(nonatomic, copy) NSString* blindedCredentials; +@property(nullable, nonatomic, copy) NSString* signedCredentials; +@property(nullable, nonatomic, copy) NSString* publicKey; +@property(nullable, nonatomic, copy) NSString* batchProof; +@property(nonatomic, copy) NSString* claimID; +@property(nonatomic, copy) NSString* promotionID; +@property(nonatomic, copy) NSString* tokens; + +@end + +NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Data/Model/PromotionCredentials.m b/ios/browser/api/ledger/legacy_database/core_data_models/PromotionCredentials.m similarity index 86% rename from vendor/brave-ios/Ledger/Data/Model/PromotionCredentials.m rename to ios/browser/api/ledger/legacy_database/core_data_models/PromotionCredentials.m index 5605d567086..6da69104a79 100644 --- a/vendor/brave-ios/Ledger/Data/Model/PromotionCredentials.m +++ b/ios/browser/api/ledger/legacy_database/core_data_models/PromotionCredentials.m @@ -1,6 +1,6 @@ // // PromotionCredentials+CoreDataClass.m -// +// // // Created by Kyle Hickinson on 2019-10-21. // @@ -10,7 +10,7 @@ @implementation PromotionCredentials -+ (NSFetchRequest *)fetchRequest { ++ (NSFetchRequest*)fetchRequest { return [NSFetchRequest fetchRequestWithEntityName:@"PromotionCredentials"]; } diff --git a/ios/browser/api/ledger/legacy_database/core_data_models/PublisherInfo.h b/ios/browser/api/ledger/legacy_database/core_data_models/PublisherInfo.h new file mode 100644 index 00000000000..d4515aeca99 --- /dev/null +++ b/ios/browser/api/ledger/legacy_database/core_data_models/PublisherInfo.h @@ -0,0 +1,56 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#import +#import + +@class ActivityInfo, ContributionInfo, RecurringDonation, PendingContribution; + +NS_ASSUME_NONNULL_BEGIN + +OBJC_EXPORT +@interface PublisherInfo : NSManagedObject + ++ (NSFetchRequest*)fetchRequest; + +@property(nonatomic) int32_t excluded; +@property(nonatomic, copy) NSString* faviconURL; +@property(nonatomic, copy) NSString* name; +@property(nonatomic, copy) NSString* provider; +@property(nonatomic, copy) NSString* publisherID; +@property(nonatomic, copy) NSString* url; +@property(nullable, nonatomic, retain) NSSet* activities; +@property(nullable, nonatomic, retain) NSSet* contributions; +@property(nullable, nonatomic, retain) + NSSet* recurringDonations; +@property(nullable, nonatomic, retain) + NSSet* pendingContributions; + +@end + +@interface PublisherInfo (CoreDataGeneratedAccessors) + +- (void)addActivitiesObject:(ActivityInfo*)value; +- (void)removeActivitiesObject:(ActivityInfo*)value; +- (void)addActivities:(NSSet*)values; +- (void)removeActivities:(NSSet*)values; + +- (void)addContributionsObject:(ContributionInfo*)value; +- (void)removeContributionsObject:(ContributionInfo*)value; +- (void)addContributions:(NSSet*)values; +- (void)removeContributions:(NSSet*)values; + +- (void)addRecurringDonationsObject:(RecurringDonation*)value; +- (void)removeRecurringDonationsObject:(RecurringDonation*)value; +- (void)addRecurringDonations:(NSSet*)values; +- (void)removeRecurringDonations:(NSSet*)values; + +- (void)addPendingContributionsObject:(PendingContribution*)value; +- (void)removePendingContributionsObject:(PendingContribution*)value; +- (void)addPendingContributions:(NSSet*)values; +- (void)removePendingContributions:(NSSet*)values; + +@end + +NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Data/Model/PublisherInfo.m b/ios/browser/api/ledger/legacy_database/core_data_models/PublisherInfo.m similarity index 91% rename from vendor/brave-ios/Ledger/Data/Model/PublisherInfo.m rename to ios/browser/api/ledger/legacy_database/core_data_models/PublisherInfo.m index 9b9d781ee12..31aa4ad6063 100644 --- a/vendor/brave-ios/Ledger/Data/Model/PublisherInfo.m +++ b/ios/browser/api/ledger/legacy_database/core_data_models/PublisherInfo.m @@ -6,7 +6,7 @@ @implementation PublisherInfo -+ (NSFetchRequest *)fetchRequest { ++ (NSFetchRequest*)fetchRequest { return [NSFetchRequest fetchRequestWithEntityName:@"PublisherInfo"]; } diff --git a/vendor/brave-ios/Ledger/Data/Model/RecurringDonation.h b/ios/browser/api/ledger/legacy_database/core_data_models/RecurringDonation.h similarity index 63% rename from vendor/brave-ios/Ledger/Data/Model/RecurringDonation.h rename to ios/browser/api/ledger/legacy_database/core_data_models/RecurringDonation.h index 5354df0c3db..a83f06f37fe 100644 --- a/vendor/brave-ios/Ledger/Data/Model/RecurringDonation.h +++ b/ios/browser/api/ledger/legacy_database/core_data_models/RecurringDonation.h @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#import #import +#import @class PublisherInfo; @@ -12,12 +12,12 @@ NS_ASSUME_NONNULL_BEGIN OBJC_EXPORT @interface RecurringDonation : NSManagedObject -+ (NSFetchRequest *)fetchRequest; ++ (NSFetchRequest*)fetchRequest; -@property (nonatomic) int64_t addedDate; -@property (nonatomic) double amount; -@property (nonatomic, copy) NSString *publisherID; -@property (nonatomic, retain) PublisherInfo *publisher; +@property(nonatomic) int64_t addedDate; +@property(nonatomic) double amount; +@property(nonatomic, copy) NSString* publisherID; +@property(nonatomic, retain) PublisherInfo* publisher; @end diff --git a/vendor/brave-ios/Ledger/Data/Model/RecurringDonation.m b/ios/browser/api/ledger/legacy_database/core_data_models/RecurringDonation.m similarity index 88% rename from vendor/brave-ios/Ledger/Data/Model/RecurringDonation.m rename to ios/browser/api/ledger/legacy_database/core_data_models/RecurringDonation.m index ce1cd067af0..f5c9101b034 100644 --- a/vendor/brave-ios/Ledger/Data/Model/RecurringDonation.m +++ b/ios/browser/api/ledger/legacy_database/core_data_models/RecurringDonation.m @@ -6,7 +6,7 @@ @implementation RecurringDonation -+ (NSFetchRequest *)fetchRequest { ++ (NSFetchRequest*)fetchRequest { return [NSFetchRequest fetchRequestWithEntityName:@"RecurringDonation"]; } diff --git a/vendor/brave-ios/Ledger/Data/Model/ServerPublisherAmount.h b/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherAmount.h similarity index 62% rename from vendor/brave-ios/Ledger/Data/Model/ServerPublisherAmount.h rename to ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherAmount.h index 79d6aba6b18..f163830ef5e 100644 --- a/vendor/brave-ios/Ledger/Data/Model/ServerPublisherAmount.h +++ b/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherAmount.h @@ -11,11 +11,11 @@ NS_ASSUME_NONNULL_BEGIN OBJC_EXPORT @interface ServerPublisherAmount : NSManagedObject -+ (NSFetchRequest *)fetchRequest; ++ (NSFetchRequest*)fetchRequest; -@property (nonatomic) double amount; -@property (nonatomic, copy) NSString *publisherID; -@property (nullable, nonatomic, retain) ServerPublisherInfo *serverPublisherInfo; +@property(nonatomic) double amount; +@property(nonatomic, copy) NSString* publisherID; +@property(nullable, nonatomic, retain) ServerPublisherInfo* serverPublisherInfo; @end diff --git a/vendor/brave-ios/Ledger/Data/Model/ServerPublisherAmount.m b/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherAmount.m similarity index 87% rename from vendor/brave-ios/Ledger/Data/Model/ServerPublisherAmount.m rename to ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherAmount.m index b4665b6b171..fa6b8476402 100644 --- a/vendor/brave-ios/Ledger/Data/Model/ServerPublisherAmount.m +++ b/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherAmount.m @@ -6,7 +6,7 @@ @implementation ServerPublisherAmount -+ (NSFetchRequest *)fetchRequest { ++ (NSFetchRequest*)fetchRequest { return [NSFetchRequest fetchRequestWithEntityName:@"ServerPublisherAmount"]; } diff --git a/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherBanner.h b/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherBanner.h new file mode 100644 index 00000000000..2f12650f0ee --- /dev/null +++ b/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherBanner.h @@ -0,0 +1,25 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#import + +@class ServerPublisherInfo; + +NS_ASSUME_NONNULL_BEGIN + +OBJC_EXPORT +@interface ServerPublisherBanner : NSManagedObject + ++ (NSFetchRequest*)fetchRequest; + +@property(nonatomic, copy) NSString* publisherID; +@property(nullable, nonatomic, copy) NSString* title; +@property(nullable, nonatomic, copy) NSString* desc; +@property(nullable, nonatomic, copy) NSString* background; +@property(nullable, nonatomic, copy) NSString* logo; +@property(nullable, nonatomic, retain) ServerPublisherInfo* serverPublisherInfo; + +@end + +NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Data/Model/ServerPublisherBanner.m b/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherBanner.m similarity index 89% rename from vendor/brave-ios/Ledger/Data/Model/ServerPublisherBanner.m rename to ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherBanner.m index 943fd14e8f1..a8a284efe30 100644 --- a/vendor/brave-ios/Ledger/Data/Model/ServerPublisherBanner.m +++ b/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherBanner.m @@ -6,7 +6,7 @@ @implementation ServerPublisherBanner -+ (NSFetchRequest *)fetchRequest { ++ (NSFetchRequest*)fetchRequest { return [NSFetchRequest fetchRequestWithEntityName:@"ServerPublisherBanner"]; } diff --git a/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherInfo.h b/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherInfo.h new file mode 100644 index 00000000000..bd9251a2bc3 --- /dev/null +++ b/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherInfo.h @@ -0,0 +1,38 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#import + +@class ServerPublisherBanner, ServerPublisherAmount, ServerPublisherLink; + +NS_ASSUME_NONNULL_BEGIN + +OBJC_EXPORT +@interface ServerPublisherInfo : NSManagedObject + ++ (NSFetchRequest*)fetchRequest; + +@property(nonatomic, copy) NSString* publisherID; +@property(nonatomic) int32_t status; +@property(nonatomic) BOOL excluded; +@property(nonatomic, copy) NSString* address; +@property(nullable, nonatomic, retain) ServerPublisherBanner* banner; +@property(nullable, nonatomic, retain) NSSet* amounts; +@property(nullable, nonatomic, retain) NSSet* links; + +@end + +@interface ServerPublisherInfo (CoreDataGeneratedAccessors) +- (void)addAmountsObject:(ServerPublisherAmount*)value; +- (void)removeAmountsObject:(ServerPublisherAmount*)value; +- (void)addAmounts:(NSSet*)values; +- (void)removeAmounts:(NSSet*)values; + +- (void)addLinksObject:(ServerPublisherLink*)value; +- (void)removeLinksObject:(ServerPublisherLink*)value; +- (void)addLinks:(NSSet*)values; +- (void)removeLinks:(NSSet*)values; +@end + +NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Data/Model/ServerPublisherInfo.m b/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherInfo.m similarity index 89% rename from vendor/brave-ios/Ledger/Data/Model/ServerPublisherInfo.m rename to ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherInfo.m index cd5a38f88f7..6f597044fd7 100644 --- a/vendor/brave-ios/Ledger/Data/Model/ServerPublisherInfo.m +++ b/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherInfo.m @@ -6,7 +6,7 @@ @implementation ServerPublisherInfo -+ (NSFetchRequest *)fetchRequest { ++ (NSFetchRequest*)fetchRequest { return [NSFetchRequest fetchRequestWithEntityName:@"ServerPublisherInfo"]; } diff --git a/vendor/brave-ios/Ledger/Data/Model/ServerPublisherLink.h b/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherLink.h similarity index 55% rename from vendor/brave-ios/Ledger/Data/Model/ServerPublisherLink.h rename to ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherLink.h index 8fd98e0ee76..1f4bd63aa88 100644 --- a/vendor/brave-ios/Ledger/Data/Model/ServerPublisherLink.h +++ b/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherLink.h @@ -11,12 +11,12 @@ NS_ASSUME_NONNULL_BEGIN OBJC_EXPORT @interface ServerPublisherLink : NSManagedObject -+ (NSFetchRequest *)fetchRequest; ++ (NSFetchRequest*)fetchRequest; -@property (nonatomic, copy) NSString *publisherID; -@property (nullable, nonatomic, copy) NSString *provider; -@property (nullable, nonatomic, copy) NSString *link; -@property (nullable, nonatomic, retain) ServerPublisherInfo *serverPublisherInfo; +@property(nonatomic, copy) NSString* publisherID; +@property(nullable, nonatomic, copy) NSString* provider; +@property(nullable, nonatomic, copy) NSString* link; +@property(nullable, nonatomic, retain) ServerPublisherInfo* serverPublisherInfo; @end diff --git a/vendor/brave-ios/Ledger/Data/Model/ServerPublisherLink.m b/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherLink.m similarity index 88% rename from vendor/brave-ios/Ledger/Data/Model/ServerPublisherLink.m rename to ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherLink.m index e75fabff1bb..fadc904f2fe 100644 --- a/vendor/brave-ios/Ledger/Data/Model/ServerPublisherLink.m +++ b/ios/browser/api/ledger/legacy_database/core_data_models/ServerPublisherLink.m @@ -6,7 +6,7 @@ @implementation ServerPublisherLink -+ (NSFetchRequest *)fetchRequest { ++ (NSFetchRequest*)fetchRequest { return [NSFetchRequest fetchRequestWithEntityName:@"ServerPublisherLink"]; } diff --git a/ios/browser/api/ledger/legacy_database/core_data_models/UnblindedToken.h b/ios/browser/api/ledger/legacy_database/core_data_models/UnblindedToken.h new file mode 100644 index 00000000000..5d3490914d9 --- /dev/null +++ b/ios/browser/api/ledger/legacy_database/core_data_models/UnblindedToken.h @@ -0,0 +1,29 @@ +// +// UnblindedToken+CoreDataClass.h +// +// +// Created by Kyle Hickinson on 2019-10-21. +// +// + +#import +#import + +@class Promotion; + +NS_ASSUME_NONNULL_BEGIN + +OBJC_EXPORT +@interface UnblindedToken : NSManagedObject + ++ (NSFetchRequest*)fetchRequest; + +@property(nonatomic) int64_t tokenID; +@property(nullable, nonatomic, copy) NSString* publicKey; +@property(nonatomic) double value; +@property(nullable, nonatomic, copy) NSString* promotionID; +@property(nullable, nonatomic, copy) NSString* tokenValue; + +@end + +NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Data/Model/UnblindedToken.m b/ios/browser/api/ledger/legacy_database/core_data_models/UnblindedToken.m similarity index 85% rename from vendor/brave-ios/Ledger/Data/Model/UnblindedToken.m rename to ios/browser/api/ledger/legacy_database/core_data_models/UnblindedToken.m index f2130f3385d..e1e2f340e39 100644 --- a/vendor/brave-ios/Ledger/Data/Model/UnblindedToken.m +++ b/ios/browser/api/ledger/legacy_database/core_data_models/UnblindedToken.m @@ -1,6 +1,6 @@ // // UnblindedToken+CoreDataClass.m -// +// // // Created by Kyle Hickinson on 2019-10-21. // @@ -10,7 +10,7 @@ @implementation UnblindedToken -+ (NSFetchRequest *)fetchRequest { ++ (NSFetchRequest*)fetchRequest { return [NSFetchRequest fetchRequestWithEntityName:@"UnblindedToken"]; } diff --git a/ios/browser/api/ledger/legacy_database/data_controller.h b/ios/browser/api/ledger/legacy_database/data_controller.h new file mode 100644 index 00000000000..d69f52537ce --- /dev/null +++ b/ios/browser/api/ledger/legacy_database/data_controller.h @@ -0,0 +1,40 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_IOS_BROWSER_API_LEDGER_LEGACY_DATABASE_DATA_CONTROLLER_H_ +#define BRAVE_IOS_BROWSER_API_LEDGER_LEGACY_DATABASE_DATA_CONTROLLER_H_ + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +OBJC_EXPORT +@interface DataController : NSObject + ++ (BOOL)defaultStoreExists; + +@property(nonatomic, class) DataController* shared; + +/// File URL to the folder containing all data files +@property(nonatomic, readonly) NSURL* storeDirectoryURL; +/// File URL to the SQLite store +@property(nonatomic, readonly) NSURL* storeURL; + +- (void)addPersistentStoreForContainer:(NSPersistentContainer*)container; + +@property(nonatomic, readonly) NSPersistentContainer* container; + +/// Context object also allows us access to all persistent container data if +/// needed. ++ (NSManagedObjectContext*)viewContext; + ++ (NSManagedObjectContext*)newBackgroundContext; + +@end + +NS_ASSUME_NONNULL_END + +#endif // BRAVE_IOS_BROWSER_API_LEDGER_LEGACY_DATABASE_DATA_CONTROLLER_H_ diff --git a/ios/browser/api/ledger/legacy_database/data_controller.mm b/ios/browser/api/ledger/legacy_database/data_controller.mm new file mode 100644 index 00000000000..5a0f22b0e8e --- /dev/null +++ b/ios/browser/api/ledger/legacy_database/data_controller.mm @@ -0,0 +1,119 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#import "data_controller.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@interface DataController () +@property(nonatomic) NSOperationQueue* operationQueue; +@property(nonatomic) NSPersistentContainer* container; +@end + +@implementation DataController + +static DataController* _dataController = nil; + ++ (DataController*)shared { + if (!_dataController) { + _dataController = [[DataController alloc] init]; + } + return _dataController; +} + ++ (void)setShared:(DataController*)shared { + _dataController = shared; +} + +- (NSURL*)storeDirectoryURL { + const auto urls = NSSearchPathForDirectoriesInDomains( + NSApplicationSupportDirectory, NSUserDomainMask, YES); + const auto documentURL = urls.lastObject; + if (!documentURL) { + return nil; + } + return [NSURL + fileURLWithPath:[documentURL stringByAppendingPathComponent:@"rewards"]]; +} + +- (NSURL*)storeURL { + return [[self storeDirectoryURL] + URLByAppendingPathComponent:@"BraveRewards.sqlite"]; +} + ++ (BOOL)defaultStoreExists { + const auto urls = NSSearchPathForDirectoriesInDomains( + NSApplicationSupportDirectory, NSUserDomainMask, YES); + const auto documentURL = urls.lastObject; + if (!documentURL) { + return NO; + } + const auto directoryURL = [NSURL + fileURLWithPath:[documentURL stringByAppendingPathComponent:@"rewards"]]; + const auto storeURL = + [directoryURL URLByAppendingPathComponent:@"BraveRewards.sqlite"]; + return [NSFileManager.defaultManager fileExistsAtPath:storeURL.path]; +} + +- (instancetype)init { + if ((self = [super init])) { + self.operationQueue = [[NSOperationQueue alloc] init]; + self.operationQueue.maxConcurrentOperationCount = 1; + + [[NSFileManager defaultManager] + createDirectoryAtURL:[self storeDirectoryURL] + withIntermediateDirectories:YES + attributes:nil + error:nil]; + + // Setup container + const auto bundle = [NSBundle bundleForClass:DataController.class]; + const auto modelURL = [bundle URLForResource:@"Model" + withExtension:@"momd"]; + NSAssert(modelURL != nil, @"Error loading model from bundle"); + const auto model = + [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; + NSAssert(model != nil, @"Error initializing managed object model from: %@", + modelURL); + self.container = [[NSPersistentContainer alloc] initWithName:@"Model" + managedObjectModel:model]; + [self addPersistentStoreForContainer:self.container]; + [self.container + loadPersistentStoresWithCompletionHandler:^( + NSPersistentStoreDescription* _Nonnull, NSError* _Nullable error) { + NSAssert(error == nil, @"Load persistent store error: %@", error); + }]; + self.container.viewContext.automaticallyMergesChangesFromParent = YES; + } + return self; +} + +- (void)addPersistentStoreForContainer:(NSPersistentContainer*)container { + // This makes the database file encrypted until device is unlocked. + const auto storeDescription = + [[NSPersistentStoreDescription alloc] initWithURL:self.storeURL]; + [storeDescription setOption:NSFileProtectionComplete + forKey:NSPersistentStoreFileProtectionKey]; + self.container.persistentStoreDescriptions = @[ storeDescription ]; +} + ++ (NSManagedObjectContext*)newBackgroundContext { + const auto backgroundContext = + [DataController.shared.container newBackgroundContext]; + // In theory, the merge policy should not matter + // since all operations happen on a synchronized operation queue. + // But in case of any bugs it's better to have one, so the app won't crash for + // users. + backgroundContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy; + return backgroundContext; +} + ++ (NSManagedObjectContext*)viewContext { + return DataController.shared.container.viewContext; +} + +@end diff --git a/ios/browser/api/ledger/legacy_database/legacy_ledger_database.h b/ios/browser/api/ledger/legacy_database/legacy_ledger_database.h new file mode 100644 index 00000000000..2fca9541e21 --- /dev/null +++ b/ios/browser/api/ledger/legacy_database/legacy_ledger_database.h @@ -0,0 +1,61 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_IOS_BROWSER_API_LEDGER_LEGACY_DATABASE_LEGACY_LEDGER_DATABASE_H_ +#define BRAVE_IOS_BROWSER_API_LEDGER_LEGACY_DATABASE_LEGACY_LEDGER_DATABASE_H_ + +#import +#import "brave/ios/browser/api/ledger/legacy_database/core_data_models/CoreDataModels.h" // NOLINT + +NS_ASSUME_NONNULL_BEGIN + +typedef void (^BATLedgerDatabaseWriteCompletion)(BOOL success); + +/// An interface into the ledger database +/// +/// This class mirrors brave-core's `publisher_info_database.h/cc` file. This +/// file will actually likely be removed at a future date when database +/// managment happens in the ledger library +OBJC_EXPORT +@interface BATLedgerDatabase : NSObject + +/// Generates a SQL migration transaction that will move all data in the users +/// CoreData storage into version 10 of the brave-core's database schema to +/// then run and have ledger take over +/// +/// Return's nil if the migration template cannot be found ++ (nullable NSString*)migrateCoreDataToSQLTransaction; + +/// Generates a SQL migration transaction that will move token related tables +/// only (promos, promo creds, unblinded tokens) to version 10 of brave-core's +/// database schema. +/// +/// Return's nil if the migration template cannot be found ++ (nullable NSString*)migrateCoreDataBATOnlyToSQLTransaction; + +/// Deletes the server publisher list from the CoreData DB ++ (void)deleteCoreDataServerPublisherList: + (nullable void (^)(NSError* _Nullable error))completion; + ++ (NSString*)activityInfoInsertFor:(ActivityInfo*)info; ++ (NSString*)contributionInfoInsertFor:(ContributionInfo*)info; ++ (NSString*)contributionQueueInsertFor:(ContributionQueue*)obj; ++ (NSString*)contributionQueuePublisherInsertFor:(ContributionPublisher*)obj; ++ (NSString*)mediaPublisherInfoInsertFor:(MediaPublisherInfo*)obj; ++ (NSString*)pendingContributionInsertFor:(PendingContribution*)obj; ++ (NSString*)promotionInsertFor:(Promotion*)obj; ++ (NSString*)promotionCredsInsertFor:(PromotionCredentials*)obj; ++ (NSString*)publisherInfoInsertFor:(PublisherInfo*)obj; ++ (NSString*)recurringDonationInsertFor:(RecurringDonation*)obj; ++ (NSString*)unblindedTokenInsertFor:(UnblindedToken*)obj; + +- (instancetype)init NS_UNAVAILABLE; +- (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END + +#endif // BRAVE_IOS_BROWSER_API_LEDGER_LEGACY_DATABASE_LEGACY_LEDGER_DATABASE_H_ diff --git a/ios/browser/api/ledger/legacy_database/legacy_ledger_database.mm b/ios/browser/api/ledger/legacy_database/legacy_ledger_database.mm new file mode 100644 index 00000000000..dcdcac8a8dd --- /dev/null +++ b/ios/browser/api/ledger/legacy_database/legacy_ledger_database.mm @@ -0,0 +1,455 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#import + +#include "base/logging.h" +#include "base/strings/sys_string_conversions.h" +#import "data_controller.h" +#import "legacy_ledger_database.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@implementation BATLedgerDatabase + ++ (nullable NSString*)migrateCoreDataToSQLTransaction { + const auto bundlePath = [[NSBundle bundleForClass:BATLedgerDatabase.class] + pathForResource:@"migrate" + ofType:@"sql"]; + NSError* error = nil; + const auto migrationScript = + [NSString stringWithContentsOfFile:bundlePath + encoding:NSUTF8StringEncoding + error:&error]; + if (error) { + LOG(ERROR) << "Failed to load migration script from path: " + << base::SysNSStringToUTF8(bundlePath); + return nil; + } + + const auto statements = [[NSMutableArray alloc] init]; + + // activity_info + [statements + addObjectsFromArray:MapFetchedObjectsToInsertsForClass( + ActivityInfo.class, ^(ActivityInfo* info) { + return [self activityInfoInsertFor:info]; + })]; + + // contribution_info + [statements addObjectsFromArray:MapFetchedObjectsToInsertsForClass( + ContributionInfo.class, + ^(ContributionInfo* info) { + return [self + contributionInfoInsertFor:info]; + })]; + + // contribution_queue + __block int64_t contributionQueueMaxID = 0; + [statements addObjectsFromArray:MapFetchedObjectsToInsertsForClass( + ContributionQueue.class, + ^(ContributionQueue* obj) { + contributionQueueMaxID = + MAX(obj.id, contributionQueueMaxID); + return [self + contributionQueueInsertFor:obj]; + })]; + if (contributionQueueMaxID > 0) { + [statements + addObject:[NSString + stringWithFormat:@"UPDATE SQLITE_SEQUENCE SET seq = %lld " + @"WHERE name = 'contribution_queue';", + contributionQueueMaxID]]; + } + + // contribution_queue_publishers + [statements + addObjectsFromArray:MapFetchedObjectsToInsertsForClass( + ContributionPublisher.class, + ^(ContributionPublisher* obj) { + return [self + contributionQueuePublisherInsertFor:obj]; + })]; + + // media_publisher_info + [statements addObjectsFromArray:MapFetchedObjectsToInsertsForClass( + MediaPublisherInfo.class, + ^(MediaPublisherInfo* obj) { + return [self + mediaPublisherInfoInsertFor:obj]; + })]; + + // pending_contribution + [statements addObjectsFromArray:MapFetchedObjectsToInsertsForClass( + PendingContribution.class, + ^(PendingContribution* obj) { + return [self + pendingContributionInsertFor:obj]; + })]; + + // promotion + [statements addObjectsFromArray:MapFetchedObjectsToInsertsForClass( + Promotion.class, ^(Promotion* obj) { + return [self promotionInsertFor:obj]; + })]; + + // promotion_creds + [statements addObjectsFromArray:MapFetchedObjectsToInsertsForClass( + PromotionCredentials.class, + ^(PromotionCredentials* obj) { + return + [self promotionCredsInsertFor:obj]; + })]; + + // publisher_info + [statements + addObjectsFromArray:MapFetchedObjectsToInsertsForClass( + PublisherInfo.class, ^(PublisherInfo* obj) { + return [self publisherInfoInsertFor:obj]; + })]; + + // recurring_donation + [statements addObjectsFromArray:MapFetchedObjectsToInsertsForClass( + RecurringDonation.class, + ^(RecurringDonation* obj) { + return [self + recurringDonationInsertFor:obj]; + })]; + + // unblinded_tokens + __block int64_t unblindedTokenMaxID = 0; + [statements + addObjectsFromArray:MapFetchedObjectsToInsertsForClass( + UnblindedToken.class, ^(UnblindedToken* obj) { + unblindedTokenMaxID = + MAX(obj.tokenID, unblindedTokenMaxID); + return [self unblindedTokenInsertFor:obj]; + })]; + if (unblindedTokenMaxID > 0) { + [statements + addObject:[NSString + stringWithFormat:@"UPDATE SQLITE_SEQUENCE SET seq = %lld " + @"WHERE name = 'unblinded_tokens';", + unblindedTokenMaxID]]; + } + + return [migrationScript + stringByReplacingOccurrencesOfString:@"# {statements}" + withString:[statements + componentsJoinedByString:@"\n"]]; +} + ++ (nullable NSString*)migrateCoreDataBATOnlyToSQLTransaction { + const auto bundlePath = [[NSBundle bundleForClass:BATLedgerDatabase.class] + pathForResource:@"migrate" + ofType:@"sql"]; + NSError* error = nil; + const auto migrationScript = + [NSString stringWithContentsOfFile:bundlePath + encoding:NSUTF8StringEncoding + error:&error]; + if (error) { + LOG(ERROR) << "Failed to load migration script from path: " + << base::SysNSStringToUTF8(bundlePath); + return nil; + } + + const auto statements = [[NSMutableArray alloc] init]; + + // promotion + [statements addObjectsFromArray:MapFetchedObjectsToInsertsForClass( + Promotion.class, ^(Promotion* obj) { + return [self promotionInsertFor:obj]; + })]; + + // promotion_creds + [statements addObjectsFromArray:MapFetchedObjectsToInsertsForClass( + PromotionCredentials.class, + ^(PromotionCredentials* obj) { + return + [self promotionCredsInsertFor:obj]; + })]; + + // unblinded_tokens + __block int64_t unblindedTokenMaxID = 0; + [statements + addObjectsFromArray:MapFetchedObjectsToInsertsForClass( + UnblindedToken.class, ^(UnblindedToken* obj) { + unblindedTokenMaxID = + MAX(obj.tokenID, unblindedTokenMaxID); + return [self unblindedTokenInsertFor:obj]; + })]; + if (unblindedTokenMaxID > 0) { + [statements + addObject:[NSString + stringWithFormat:@"UPDATE SQLITE_SEQUENCE SET seq = %lld " + @"WHERE name = 'unblinded_tokens';", + unblindedTokenMaxID]]; + } + + return [migrationScript + stringByReplacingOccurrencesOfString:@"# {statements}" + withString:[statements + componentsJoinedByString:@"\n"]]; +} + +#pragma mark - + ++ (NSString*)activityInfoInsertFor:(ActivityInfo*)info { + const auto activityInfoInsert = + @"INSERT INTO \"activity_info\" " + "(publisher_id, duration, visits, score, percent, weight, " + "reconcile_stamp) VALUES (" + "%@," // publisher_id LONGVARCHAR NOT NULL + "%lld," // duration INTEGER DEFAULT 0 NOT NULL, + "%d," // visits INTEGER DEFAULT 0 NOT NULL, + "%f," // score DOUBLE DEFAULT 0 NOT NULL + "%d," // percent INTEGER DEFAULT 0 NOT NULL + "%f," // weight DOUBLE DEFAULT 0 NOT NULL, + "%lld" // reconcile_stamp INTEGER DEFAULT 0 NOT NULL + ");"; + return [NSString stringWithFormat:activityInfoInsert, + SQLString(info.publisherID), info.duration, + info.visits, info.score, info.percent, + info.weight, info.reconcileStamp]; +} + ++ (NSString*)contributionInfoInsertFor:(ContributionInfo*)info { + const auto contributionInfoInsert = + @"INSERT INTO \"contribution_info\" " + "(publisher_id, probi, date, type, month, year) VALUES (" + "%@," // publisher_id LONGVARCHAR + "%@," // probi TEXT "0" NOT NULL + "%lld," // date INTEGER NOT NULL + "%d," // type INTEGER NOT NULL + "%d," // month INTEGER NOT NULL + "%d" // year INTEGER NOT NULL + ");"; + return [NSString stringWithFormat:contributionInfoInsert, + SQLString(info.publisherID), + SQLString(info.probi), info.date, info.type, + info.month, info.year]; +} + ++ (NSString*)contributionQueueInsertFor:(ContributionQueue*)obj { + const auto contributionQueueInsert = + @"INSERT INTO \"contribution_queue\" " + "(contribution_queue_id, type, amount, partial) VALUES (" + "%lld," // contribution_queue_id INTEGER PRIMARY KEY AUTOINCREMENT NOT + // NULL + "%d," // type INTEGER NOT NULL + "%f," // amount DOUBLE NOT NULL + "%d" // partial INTEGER NOT NULL DEFAULT 0 + ");"; + return [NSString stringWithFormat:contributionQueueInsert, obj.id, obj.type, + obj.amount, obj.partial]; +} + ++ (NSString*)contributionQueuePublisherInsertFor:(ContributionPublisher*)obj { + const auto contributionQueuePublisherInsert = + @"INSERT INTO \"contribution_queue_publishers\" " + "(contribution_queue_id, publisher_key, amount_percent) VALUES (" + "%lld," // contribution_queue_id INTEGER NOT NULL + "%@," // publisher_key TEXT NOT NULL + "%f" // amount_percent DOUBLE NOT NULL + ");"; + return [NSString stringWithFormat:contributionQueuePublisherInsert, + obj.queue.id, SQLString(obj.publisherKey), + obj.amountPercent]; +} + ++ (NSString*)mediaPublisherInfoInsertFor:(MediaPublisherInfo*)obj { + const auto mediaPublisherInfoInsert = + @"INSERT INTO \"media_publisher_info\" " + "(media_key, publisher_id) VALUES (" + "%@," // media_key TEXT NOT NULL PRIMARY KEY UNIQUE + "%@" // publisher_id LONGVARCHAR NOT NULL + ");"; + return [NSString stringWithFormat:mediaPublisherInfoInsert, + SQLString(obj.mediaKey), + SQLString(obj.publisherID)]; +} + ++ (NSString*)pendingContributionInsertFor:(PendingContribution*)obj { + const auto pendingContributionInsert = + @"INSERT INTO \"pending_contribution\" " + "(publisher_id, amount, added_date, viewing_id, type) VALUES (" + "%@," // publisher_id LONGVARCHAR NOT NULL + "%f," // amount DOUBLE DEFAULT 0 NOT NULL + "%lld," // added_date INTEGER DEFAULT 0 NOT NULL + "%@," // viewing_id LONGVARCHAR NOT NULL + "%d" // type INTEGER NOT NULL + ");"; + return [NSString stringWithFormat:pendingContributionInsert, + SQLString(obj.publisherID), obj.amount, + obj.addedDate, SQLString(obj.viewingID), + obj.type]; +} + ++ (NSString*)promotionInsertFor:(Promotion*)obj { + const auto promotionInsert = + @"INSERT INTO \"promotion\" " + "(promotion_id, version, type, public_keys, suggestions, " + "approximate_value, status, expires_at) VALUES (" + "%@," // promotion_id TEXT NOT NULL + "%d," // version INTEGER NOT NULL + "%d," // type INTEGER NOT NULL + "%@," // public_keys TEXT NOT NULL + "%d," // suggestions INTEGER NOT NULL DEFAULT 0 + "%f," // approximate_value DOUBLE NOT NULL DEFAULT 0 + "%d," // status INTEGER NOT NULL DEFAULT 0 + "%lld" // expires_at TIMESTAMP NOT NULL + ");"; + return [NSString stringWithFormat:promotionInsert, SQLString(obj.promotionID), + obj.version, obj.type, + SQLString(obj.publicKeys), obj.suggestions, + obj.approximateValue, obj.status, + static_cast( + obj.expiryDate.timeIntervalSince1970)]; +} + ++ (NSString*)promotionCredsInsertFor:(PromotionCredentials*)obj { + const auto promotionCredsInsert = + @"INSERT INTO \"promotion_creds\" " + "(promotion_id, tokens, blinded_creds, signed_creds, public_key, " + "batch_proof, claim_id) VALUES (" + "%@," // promotion_id TEXT UNIQUE NOT NULL + "%@," // tokens TEXT NOT NULL + "%@," // blinded_creds TEXT NOT NULL + "%@," // signed_creds TEXT + "%@," // public_key TEXT + "%@," // batch_proof TEXT + "%@" // claim_id TEXT + ");"; + return [NSString + stringWithFormat:promotionCredsInsert, SQLString(obj.promotionID), + SQLString(obj.tokens), SQLString(obj.blindedCredentials), + SQLNullableString(obj.signedCredentials), + SQLNullableString(obj.publicKey), + SQLNullableString(obj.batchProof), + SQLNullableString(obj.claimID)]; +} + ++ (NSString*)publisherInfoInsertFor:(PublisherInfo*)obj { + const auto publisherInfoInsert = + @"INSERT INTO \"publisher_info\" " + "(publisher_id, excluded, name, favIcon, url, provider) VALUES (" + "%@," // publisher_id LONGVARCHAR PRIMARY KEY NOT NULL UNIQUE + "%d," // excluded INTEGER DEFAULT 0 NOT NULL + "%@," // name TEXT NOT NULL + "%@," // favIcon TEXT NOT NULL + "%@," // url TEXT NOT NULL + "%@" // provider TEXT NOT NULL + ");"; + return + [NSString stringWithFormat:publisherInfoInsert, + SQLString(obj.publisherID), obj.excluded, + SQLString(obj.name), SQLString(obj.faviconURL), + SQLString(obj.url), SQLString(obj.provider)]; +} + ++ (NSString*)recurringDonationInsertFor:(RecurringDonation*)obj { + const auto recurringDonationInsert = + @"INSERT INTO \"recurring_donation\" " + "(publisher_id, amount, added_date) VALUES (" + "%@," // publisher_id LONGVARCHAR NOT NULL PRIMARY KEY UNIQUE + "%f," // amount DOUBLE DEFAULT 0 NOT NULL + "%lld" // added_date INTEGER DEFAULT 0 NOT NULL + ");"; + return [NSString stringWithFormat:recurringDonationInsert, + SQLString(obj.publisherID), obj.amount, + obj.addedDate]; +} + ++ (NSString*)unblindedTokenInsertFor:(UnblindedToken*)obj { + const auto unblindedTokenInsert = + @"INSERT INTO \"unblinded_tokens\" " + "(token_id, token_value, public_key, value, promotion_id) VALUES (" + "%lld," // token_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL + "%@," // token_value TEXT + "%@," // public_key TEXT + "%f," // value DOUBLE NOT NULL DEFAULT 0 + "%@" // promotion_id TEXT + ");"; + return [NSString stringWithFormat:unblindedTokenInsert, obj.tokenID, + SQLNullableString(obj.tokenValue), + SQLNullableString(obj.publicKey), obj.value, + SQLNullableString(obj.promotionID)]; +} + ++ (void)deleteCoreDataServerPublisherList: + (nullable void (^)(NSError* _Nullable error))completion { + const auto context = [DataController newBackgroundContext]; + + LOG(INFO) << "CoreData: Deleting publisher list"; + [context performBlock:^{ + const auto fetchRequest = ServerPublisherInfo.fetchRequest; + fetchRequest.entity = [NSEntityDescription + entityForName:NSStringFromClass(ServerPublisherInfo.class) + inManagedObjectContext:context]; + NSError* error = nil; + const auto deleteRequest = + [[NSBatchDeleteRequest alloc] initWithFetchRequest:fetchRequest]; + [context executeRequest:deleteRequest error:&error]; + + if (!error && context.hasChanges) { + [context save:&error]; + } + + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(error); + }); + } + }]; +} + +#pragma mark - + +NS_INLINE NSString* SQLNullableString(NSString* _Nullable value) { + return (value == nil ? @"NULL" : SQLString(value)); +} + +NS_INLINE NSString* SQLString(NSString* _Nonnull value) { + // Obj-C doesn't enforce nullability, therefore adding an extra check + if (value == nil) { + return @"''"; + } + // Have to make sure to escape any apostrophies + return [NSString + stringWithFormat:@"'%@'", + [value stringByReplacingOccurrencesOfString:@"'" + withString:@"''"]]; +} + +static NSArray* MapFetchedObjectsToInsertsForClass( + Class clazz, + NSString*(NS_NOESCAPE ^ block)(__kindof NSManagedObject* obj)) { + const auto context = DataController.viewContext; + const auto fetchRequest = [clazz fetchRequest]; + fetchRequest.entity = + [NSEntityDescription entityForName:NSStringFromClass(clazz) + inManagedObjectContext:context]; + NSError* error; + const auto fetchedObjects = [context executeFetchRequest:fetchRequest + error:&error]; + if (error) { + return @[]; + } + const auto statements = [[NSMutableArray alloc] init]; + [fetchedObjects + enumerateObjectsUsingBlock:^(NSManagedObject* _Nonnull obj, + NSUInteger idx, BOOL* _Nonnull stop) { + if (![obj isKindOfClass:clazz]) { + return; + } + [statements addObject:block(obj)]; + }]; + return statements; +} + +@end diff --git a/vendor/brave-ios/Ledger/Data/migrate.sql b/ios/browser/api/ledger/legacy_database/migrate.sql similarity index 100% rename from vendor/brave-ios/Ledger/Data/migrate.sql rename to ios/browser/api/ledger/legacy_database/migrate.sql diff --git a/ios/browser/api/ledger/promotion_solution.h b/ios/browser/api/ledger/promotion_solution.h new file mode 100644 index 00000000000..dd679872675 --- /dev/null +++ b/ios/browser/api/ledger/promotion_solution.h @@ -0,0 +1,30 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_IOS_BROWSER_API_LEDGER_PROMOTION_SOLUTION_H_ +#define BRAVE_IOS_BROWSER_API_LEDGER_PROMOTION_SOLUTION_H_ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/// The solution to claiming a promotion on iOS. Obtain the `nonce` through +/// `[BraveLedger claimPromotion:completion:]` method, and obtain the +/// blob and signature from the users keychain +OBJC_EXPORT +NS_SWIFT_NAME(PromotionSolution) +@interface PromotionSolution : NSObject + +@property(nonatomic, copy) NSString* nonce; +@property(nonatomic, copy) NSString* blob; +@property(nonatomic, copy) NSString* signature; + +- (NSString*)JSONPayload; + +@end + +NS_ASSUME_NONNULL_END + +#endif // BRAVE_IOS_BROWSER_API_LEDGER_PROMOTION_SOLUTION_H_ diff --git a/ios/browser/api/ledger/promotion_solution.mm b/ios/browser/api/ledger/promotion_solution.mm new file mode 100644 index 00000000000..345fc72dbd3 --- /dev/null +++ b/ios/browser/api/ledger/promotion_solution.mm @@ -0,0 +1,33 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#import "promotion_solution.h" + +#include "base/logging.h" +#import "ledger.mojom.objc.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@implementation PromotionSolution + +- (NSString*)JSONPayload { + NSDictionary* payload = @{ + @"nonce" : self.nonce, + @"blob" : self.blob, + @"signature" : self.signature + }; + NSData* jsonData = [NSJSONSerialization dataWithJSONObject:payload + options:0 + error:nil]; + if (!jsonData) { + LOG(INFO) << "Missing JSON payload while attempting to attest promotion"; + return @""; + } + return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; +} + +@end diff --git a/ios/browser/api/ledger/rewards_notification.h b/ios/browser/api/ledger/rewards_notification.h new file mode 100644 index 00000000000..d5dfffa7c41 --- /dev/null +++ b/ios/browser/api/ledger/rewards_notification.h @@ -0,0 +1,46 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_IOS_BROWSER_API_LEDGER_REWARDS_NOTIFICATION_H_ +#define BRAVE_IOS_BROWSER_API_LEDGER_REWARDS_NOTIFICATION_H_ + +#import + +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSInteger, RewardsNotificationKind) { + RewardsNotificationKindInvalid, + RewardsNotificationKindAutoContribute, + RewardsNotificationKindGrant, + RewardsNotificationKindGrantAds, + RewardsNotificationKindFailedContribution, + RewardsNotificationKindInsufficientFunds, + RewardsNotificationKindBackupWallet, + RewardsNotificationKindTipsProcessed, + RewardsNotificationKindAdsLaunch, // Unused + RewardsNotificationKindVerifiedPublisher, + RewardsNotificationKindPendingNotEnoughFunds, + RewardsNotificationKindGeneralLedger // Comes from ledger +} NS_SWIFT_NAME(RewardsNotification.Kind); + +OBJC_EXPORT +@interface RewardsNotification : NSObject + +@property(nonatomic, copy) NSString* id; +@property(nonatomic) NSTimeInterval dateAdded; +@property(nonatomic) RewardsNotificationKind kind; +@property(nonatomic, copy) NSDictionary* userInfo; +@property(nonatomic) BOOL displayed; + +- (instancetype)initWithID:(NSString*)notificationID + dateAdded:(NSTimeInterval)dateAdded + kind:(RewardsNotificationKind)kind + userInfo:(nullable NSDictionary*)userInfo; + +@end + +NS_ASSUME_NONNULL_END + +#endif // BRAVE_IOS_BROWSER_API_LEDGER_REWARDS_NOTIFICATION_H_ diff --git a/ios/browser/api/ledger/rewards_notification.m b/ios/browser/api/ledger/rewards_notification.m new file mode 100644 index 00000000000..e30339b93e2 --- /dev/null +++ b/ios/browser/api/ledger/rewards_notification.m @@ -0,0 +1,52 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#import "rewards_notification.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@implementation RewardsNotification + +- (instancetype)initWithID:(NSString*)notificationID + dateAdded:(NSTimeInterval)dateAdded + kind:(RewardsNotificationKind)kind + userInfo:(NSDictionary*)userInfo { + if ((self = [super init])) { + self.id = notificationID; + self.dateAdded = dateAdded; + self.kind = kind; + self.userInfo = userInfo; + self.displayed = NO; + } + return self; +} + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder*)aDecoder { + if ((self = [super init])) { + self.id = [aDecoder decodeObjectOfClass:NSString.class forKey:@"id"]; + self.dateAdded = [aDecoder decodeDoubleForKey:@"dateAdded"]; + self.kind = (RewardsNotificationKind)[aDecoder decodeIntegerForKey:@"kind"]; + self.userInfo = + [aDecoder decodeObjectOfClass:NSDictionary.class forKey:@"userInfo"]; + self.displayed = [aDecoder decodeBoolForKey:@"displayed"]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder*)aCoder { + [aCoder encodeObject:self.id forKey:@"id"]; + [aCoder encodeDouble:self.dateAdded forKey:@"dateAdded"]; + [aCoder encodeInteger:self.kind forKey:@"kind"]; + [aCoder encodeObject:self.userInfo forKey:@"userInfo"]; + [aCoder encodeBool:self.displayed forKey:@"displayed"]; +} + +@end diff --git a/ios/testing/BUILD.gn b/ios/testing/BUILD.gn new file mode 100644 index 00000000000..a185c39b245 --- /dev/null +++ b/ios/testing/BUILD.gn @@ -0,0 +1,19 @@ +# Copyright (c) 2019 The Brave Authors. All rights reserved. +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +import("//build/config/ios/rules.gni") +import("//testing/test.gni") + +ios_xctest_test("brave_core_ios_tests") { + configs += [ "//build/config/compiler:enable_arc" ] + sources = [ + "dictionary_transform_test.mm", + "main.mm", + "test_foo.h", + "test_foo.mm", + "vector_transform_test.mm", + ] + deps = [ "//base" ] +} diff --git a/vendor/brave-ios/tests/dictionary_transform_test.mm b/ios/testing/dictionary_transform_test.mm similarity index 72% rename from vendor/brave-ios/tests/dictionary_transform_test.mm rename to ios/testing/dictionary_transform_test.mm index c7d26a79351..f12ebeec275 100644 --- a/vendor/brave-ios/tests/dictionary_transform_test.mm +++ b/ios/testing/dictionary_transform_test.mm @@ -5,7 +5,7 @@ #import #import "base/containers/flat_map.h" -#import "CppTransformations.h" +#import "brave/build/ios/mojom/cpp_transformations.h" #import "test_foo.h" @interface DictionaryTransformTest : XCTestCase @@ -14,11 +14,10 @@ @implementation DictionaryTransformTest -- (void)testStringPrimitiveMapToDictionary -{ - std::map m { {"0", 0}, {"1", 1}, {"2", 2} }; +- (void)testStringPrimitiveMapToDictionary { + std::map m{{"0", 0}, {"1", 1}, {"2", 2}}; const auto dict = NSDictionaryFromMap(m); - XCTAssertEqual(dict.count, 3); + XCTAssertEqual(dict.count, static_cast(3)); const auto keys = @[ @"0", @"1", @"2" ]; const auto values = @[ @(0), @(1), @(2) ]; XCTAssertTrue([dict.allKeys isEqualToArray:keys]); @@ -28,11 +27,11 @@ XCTAssertEqual(dict[@"2"].integerValue, 2); } -- (void)testStringStringMapToDictionary -{ - std::map m { {"0", "test0"}, {"1", "test1"}, {"2", "test2"} }; +- (void)testStringStringMapToDictionary { + std::map m{ + {"0", "test0"}, {"1", "test1"}, {"2", "test2"}}; const auto dict = NSDictionaryFromMap(m); - XCTAssertEqual(dict.count, 3); + XCTAssertEqual(dict.count, static_cast(3)); const auto keys = @[ @"0", @"1", @"2" ]; const auto values = @[ @"test0", @"test1", @"test2" ]; XCTAssertTrue([dict.allKeys isEqualToArray:keys]); @@ -42,17 +41,16 @@ XCTAssertTrue([dict[@"2"] isEqualToString:@"test2"]); } -- (void)testStringCppStructToDictionary -{ - std::map m { - { "0", CppFoo(true, 10, "test", { 1.0, 2.0, 3.0 }) }, - { "1", CppFoo(false, 7, "test2", { 3.0, 2.0, 1.0 }) }, +- (void)testStringCppStructToDictionary { + std::map m{ + {"0", CppFoo(true, 10, "test", {1.0, 2.0, 3.0})}, + {"1", CppFoo(false, 7, "test2", {3.0, 2.0, 1.0})}, }; - const auto dict = NSDictionaryFromMap(m, ^TestFoo *(CppFoo foo) { + const auto dict = NSDictionaryFromMap(m, ^TestFoo*(CppFoo foo) { return [[TestFoo alloc] initWithCppFoo:foo]; }); - XCTAssertEqual(dict.count, 2); + XCTAssertEqual(dict.count, static_cast(2)); const auto keys = @[ @"0", @"1" ]; XCTAssertTrue([dict.allKeys isEqualToArray:keys]); @@ -73,12 +71,8 @@ XCTAssertTrue([foo1.numbers isEqualToArray:numbers2]); } -- (void)testStringNSDictionaryToStringMap -{ - const auto d = @{ - @"1": @"2", - @"3": @"4" - }; +- (void)testStringNSDictionaryToStringMap { + const auto d = @{@"1" : @"2", @"3" : @"4"}; base::flat_map map = MapFromNSDictionary(d); XCTAssert(map["1"] == "2"); XCTAssert(map["3"] == "4"); diff --git a/vendor/brave-ios/tests/main.mm b/ios/testing/main.mm similarity index 94% rename from vendor/brave-ios/tests/main.mm rename to ios/testing/main.mm index b36f663b2a1..86f0a6557c0 100644 --- a/vendor/brave-ios/tests/main.mm +++ b/ios/testing/main.mm @@ -2,7 +2,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#import #import #if !defined(__has_feature) || !__has_feature(objc_arc) diff --git a/ios/testing/test_foo.h b/ios/testing/test_foo.h new file mode 100644 index 00000000000..8c855c7d9ed --- /dev/null +++ b/ios/testing/test_foo.h @@ -0,0 +1,36 @@ +/* Copyright (c) 2021 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_IOS_TESTING_TEST_FOO_H_ +#define BRAVE_IOS_TESTING_TEST_FOO_H_ + +#import +#include +#include + +NS_ASSUME_NONNULL_BEGIN + +struct CppFoo { + CppFoo(const CppFoo&); + CppFoo(bool b, int i, std::string s, std::vector ds); + ~CppFoo(); + + bool boolean; + int integer; + std::string stringObject; + std::vector numbers; +}; + +@interface TestFoo : NSObject +@property(nonatomic, assign) BOOL boolean; +@property(nonatomic, assign) int integer; +@property(nonatomic, copy) NSString* stringObject; +@property(nonatomic, copy) NSArray* numbers; +- (instancetype)initWithCppFoo:(const CppFoo&)foo; +@end + +NS_ASSUME_NONNULL_END + +#endif // BRAVE_IOS_TESTING_TEST_FOO_H_ diff --git a/vendor/brave-ios/tests/test_foo.mm b/ios/testing/test_foo.mm similarity index 52% rename from vendor/brave-ios/tests/test_foo.mm rename to ios/testing/test_foo.mm index f9299a5f43d..be37622f65c 100644 --- a/vendor/brave-ios/tests/test_foo.mm +++ b/ios/testing/test_foo.mm @@ -3,22 +3,26 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #import "test_foo.h" -#import "CppTransformations.h" +#import "brave/build/ios/mojom/cpp_transformations.h" -CppFoo::CppFoo(const CppFoo & foo) : boolean(foo.boolean), integer(foo.integer), stringObject(foo.stringObject), numbers(foo.numbers) { } -CppFoo::CppFoo(bool b, int i, std::string s, std::vector ds) : -boolean(b), integer(i), stringObject(s), numbers(ds) { } -CppFoo::~CppFoo() { } +CppFoo::CppFoo(const CppFoo& foo) + : boolean(foo.boolean), + integer(foo.integer), + stringObject(foo.stringObject), + numbers(foo.numbers) {} +CppFoo::CppFoo(bool b, int i, std::string s, std::vector ds) + : boolean(b), integer(i), stringObject(s), numbers(ds) {} +CppFoo::~CppFoo() {} @implementation TestFoo -- (instancetype)initWithCppFoo:(const CppFoo&)foo -{ +- (instancetype)initWithCppFoo:(const CppFoo&)foo { if ((self = [super init])) { self.boolean = foo.boolean; self.integer = foo.integer; self.numbers = NSArrayFromVector(foo.numbers); - self.stringObject = [NSString stringWithUTF8String:foo.stringObject.c_str()]; + self.stringObject = + [NSString stringWithUTF8String:foo.stringObject.c_str()]; } return self; } diff --git a/vendor/brave-ios/tests/vector_transform_test.mm b/ios/testing/vector_transform_test.mm similarity index 59% rename from vendor/brave-ios/tests/vector_transform_test.mm rename to ios/testing/vector_transform_test.mm index fe351a91c21..74c36cf5b5f 100644 --- a/vendor/brave-ios/tests/vector_transform_test.mm +++ b/ios/testing/vector_transform_test.mm @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #import -#import "CppTransformations.h" +#import "brave/build/ios/mojom/cpp_transformations.h" #import "test_foo.h" @interface VectorTransformTest : XCTestCase @@ -11,27 +11,23 @@ @implementation VectorTransformTest -- (void)testPrimitiveVectorToNSNumberArray -{ - std::vector v { 1, 2, 3 }; +- (void)testPrimitiveVectorToNSNumberArray { + std::vector v{1, 2, 3}; auto array = NSArrayFromVector(v); XCTAssertTrue(array.count == 3); - XCTAssertTrue(array[0].intValue == 1 && - array[1].intValue == 2 && + XCTAssertTrue(array[0].intValue == 1 && array[1].intValue == 2 && array[2].intValue == 3); } -- (void)testNSNumberArrayToPrimitiveVector -{ - NSArray *a = @[ @(1), @(2), @(3) ]; +- (void)testNSNumberArrayToPrimitiveVector { + NSArray* a = @[ @(1), @(2), @(3) ]; std::vector v = VectorFromNSArray(a); XCTAssertTrue(v.size() == 3); XCTAssertTrue(v[0] == 1 && v[1] == 2 && v[2] == 3); } -- (void)testStringVectorToStringArray -{ - std::vector v { "1", "2", "3" }; +- (void)testStringVectorToStringArray { + std::vector v{"1", "2", "3"}; auto array = NSArrayFromVector(v); XCTAssertTrue(array.count == 3); XCTAssertTrue([array[0] isEqualToString:@"1"] && @@ -39,30 +35,26 @@ [array[2] isEqualToString:@"3"]); } -- (void)testStringArrayToStringVector -{ - NSArray *a = @[ @"1", @"2", @"3" ]; +- (void)testStringArrayToStringVector { + NSArray* a = @[ @"1", @"2", @"3" ]; std::vector v = VectorFromNSArray(a); XCTAssertTrue(v.size() == 3); XCTAssertTrue(v[0] == "1" && v[1] == "2" && v[2] == "3"); } -- (void)testVectorObjectsToArrayObjects -{ - std::vector foos { - CppFoo(true, 10, "test", { 1.0, 2.0, 3.0 }), - CppFoo(false, 7, "tset", { 3.0, 2.0, 1.0 }), +- (void)testVectorObjectsToArrayObjects { + std::vector foos{ + CppFoo(true, 10, "test", {1.0, 2.0, 3.0}), + CppFoo(false, 7, "tset", {3.0, 2.0, 1.0}), }; - const auto array = NSArrayFromVector(foos, ^TestFoo *(const CppFoo& foo) { + const auto array = NSArrayFromVector(foos, ^TestFoo*(const CppFoo& foo) { return [[TestFoo alloc] initWithCppFoo:foo]; }); XCTAssertTrue(array.count == 2); - XCTAssertTrue(array[0].boolean == true && - array[0].integer == 10 && + XCTAssertTrue(array[0].boolean == true && array[0].integer == 10 && [array[0].stringObject isEqualToString:@"test"] && array[0].numbers.count == 3); - XCTAssertTrue(array[1].boolean == false && - array[1].integer == 7 && + XCTAssertTrue(array[1].boolean == false && array[1].integer == 7 && [array[1].stringObject isEqualToString:@"tset"] && array[1].numbers.count == 3); } diff --git a/vendor/CPPLINT.cfg b/vendor/CPPLINT.cfg deleted file mode 100644 index 5e181a1503b..00000000000 --- a/vendor/CPPLINT.cfg +++ /dev/null @@ -1 +0,0 @@ -exclude_files=brave-ios diff --git a/vendor/brave-ios/Ads/BATAdNotification.h b/vendor/brave-ios/Ads/BATAdNotification.h deleted file mode 100644 index 5c256e3ef49..00000000000 --- a/vendor/brave-ios/Ads/BATAdNotification.h +++ /dev/null @@ -1,30 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import - -NS_ASSUME_NONNULL_BEGIN - -OBJC_EXPORT -NS_SWIFT_NAME(AdsNotification) -@interface BATAdNotification : NSObject -@property (nonatomic, readonly, copy) NSString *uuid; -@property (nonatomic, readonly, copy) NSString *creativeInstanceID; -@property (nonatomic, readonly, copy) NSString *creativeSetID; -@property (nonatomic, readonly, copy) NSString *campaignID; -@property (nonatomic, readonly, copy) NSString *advertiserID; -@property (nonatomic, readonly, copy) NSString *segment; -@property (nonatomic, readonly, copy) NSString *title; -@property (nonatomic, readonly, copy) NSString *body; -@property (nonatomic, readonly, copy) NSString *targetURL; -@end - -OBJC_EXPORT -@interface BATAdNotification (MyFirstAd) -+ (instancetype)customAdWithTitle:(NSString *)title - body:(NSString *)body - url:(NSString *)url NS_SWIFT_NAME(customAd(title:body:url:)); -@end - -NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ads/BATAdNotification.mm b/vendor/brave-ios/Ads/BATAdNotification.mm deleted file mode 100644 index 1eba0ac24fa..00000000000 --- a/vendor/brave-ios/Ads/BATAdNotification.mm +++ /dev/null @@ -1,50 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import "BATAdNotification.h" -#include "bat/ads/ad_notification_info.h" -#import - -@interface BATAdNotification () -@property (nonatomic, copy) NSString *uuid; -@property (nonatomic, copy) NSString *creativeInstanceID; -@property (nonatomic, copy) NSString *creativeSetID; -@property (nonatomic, copy) NSString *campaignID; -@property (nonatomic, copy) NSString *advertiserID; -@property (nonatomic, copy) NSString *segment; -@property (nonatomic, copy) NSString *title; -@property (nonatomic, copy) NSString *body; -@property (nonatomic, copy) NSString *targetURL; -@end - -@implementation BATAdNotification - -- (instancetype)initWithNotificationInfo:(const ads::AdNotificationInfo &)info -{ - if ((self = [super init])) { - self.uuid = [NSString stringWithUTF8String:info.uuid.c_str()]; - self.creativeInstanceID = [NSString stringWithUTF8String:info.creative_instance_id.c_str()]; - self.creativeSetID = [NSString stringWithUTF8String:info.creative_set_id.c_str()]; - self.campaignID = [NSString stringWithUTF8String:info.campaign_id.c_str()]; - self.advertiserID = [NSString stringWithUTF8String:info.advertiser_id.c_str()]; - self.segment = [NSString stringWithUTF8String:info.segment.c_str()]; - self.title = [NSString stringWithUTF8String:info.title.c_str()]; - self.body = [NSString stringWithUTF8String:info.body.c_str()]; - self.targetURL = [NSString stringWithUTF8String:info.target_url.c_str()]; - } - return self; -} - -@end - -@implementation BATAdNotification (MyFirstAd) -+ (instancetype)customAdWithTitle:(NSString *)title body:(NSString *)body url:(NSString *)url -{ - BATAdNotification *notification = [[BATAdNotification alloc] init]; - notification.title = title; - notification.body = body; - notification.targetURL = url; - return notification; -} -@end diff --git a/vendor/brave-ios/Ads/BATBraveAds+Private.h b/vendor/brave-ios/Ads/BATBraveAds+Private.h deleted file mode 100644 index 7b4e82c9e44..00000000000 --- a/vendor/brave-ios/Ads/BATBraveAds+Private.h +++ /dev/null @@ -1,12 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import "BATBraveAds.h" - -@interface BATBraveAds (Private) - -/// Whether or not Brave Ads is enabled -@property (nonatomic, assign, getter=isEnabled) BOOL enabled; - -@end diff --git a/vendor/brave-ios/Ads/BATInlineContentAd.mm b/vendor/brave-ios/Ads/BATInlineContentAd.mm deleted file mode 100644 index 8bcee9a52f2..00000000000 --- a/vendor/brave-ios/Ads/BATInlineContentAd.mm +++ /dev/null @@ -1,47 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import "BATInlineContentAd.h" -#include "bat/ads/inline_content_ad_info.h" - -@interface BATInlineContentAd () -@property(nonatomic, copy) NSString* uuid; -@property(nonatomic, copy) NSString* creativeInstanceID; -@property(nonatomic, copy) NSString* creativeSetID; -@property(nonatomic, copy) NSString* campaignID; -@property(nonatomic, copy) NSString* advertiserID; -@property(nonatomic, copy) NSString* segment; -@property(nonatomic, copy) NSString* title; -@property(nonatomic, copy) NSString* message; -@property(nonatomic, copy) NSString* imageURL; -@property(nonatomic, copy) NSString* dimensions; -@property(nonatomic, copy) NSString* ctaText; -@property(nonatomic, copy) NSString* targetURL; -@end - -@implementation BATInlineContentAd - -- (instancetype)initWithInlineContentAdInfo: - (const ads::InlineContentAdInfo&)info { - if ((self = [super init])) { - self.uuid = [NSString stringWithUTF8String:info.uuid.c_str()]; - self.creativeInstanceID = - [NSString stringWithUTF8String:info.creative_instance_id.c_str()]; - self.creativeSetID = - [NSString stringWithUTF8String:info.creative_set_id.c_str()]; - self.campaignID = [NSString stringWithUTF8String:info.campaign_id.c_str()]; - self.advertiserID = - [NSString stringWithUTF8String:info.advertiser_id.c_str()]; - self.segment = [NSString stringWithUTF8String:info.segment.c_str()]; - self.title = [NSString stringWithUTF8String:info.title.c_str()]; - self.message = [NSString stringWithUTF8String:info.description.c_str()]; - self.imageURL = [NSString stringWithUTF8String:info.image_url.c_str()]; - self.dimensions = [NSString stringWithUTF8String:info.dimensions.c_str()]; - self.ctaText = [NSString stringWithUTF8String:info.cta_text.c_str()]; - self.targetURL = [NSString stringWithUTF8String:info.target_url.c_str()]; - } - return self; -} - -@end diff --git a/vendor/brave-ios/Ads/Generated/NativeAdsClient.h b/vendor/brave-ios/Ads/Generated/NativeAdsClient.h deleted file mode 100644 index 327d8b599ea..00000000000 --- a/vendor/brave-ios/Ads/Generated/NativeAdsClient.h +++ /dev/null @@ -1,61 +0,0 @@ -/* WARNING: THIS FILE IS GENERATED. ANY CHANGES TO THIS FILE WILL BE OVERWRITTEN - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import -#import "bat/ads/ads_client.h" - -@protocol NativeAdsClientBridge; - -class NativeAdsClient : public ads::AdsClient { - public: - NativeAdsClient(id bridge); - ~NativeAdsClient() override; - - private: - __unsafe_unretained id bridge_; - - bool IsNetworkConnectionAvailable() const override; - bool IsForeground() const override; - bool IsFullScreen() const override; - bool CanShowBackgroundNotifications() const override; - void ShowNotification(const ads::AdNotificationInfo& info) override; - bool ShouldShowNotifications() override; - void CloseNotification(const std::string & uuid) override; - void RecordAdEvent(const std::string& ad_type, - const std::string& confirmation_type, - const uint64_t timestamp) const override; - std::vector GetAdEvents( - const std::string& ad_type, - const std::string& confirmation_type) const override; - void ResetAdEvents() const override; - void UrlRequest(ads::UrlRequestPtr url_request, ads::UrlRequestCallback callback) override; - void Save(const std::string & name, const std::string & value, ads::ResultCallback callback) override; - void Load(const std::string & name, ads::LoadCallback callback) override; - void LoadAdsResource(const std::string& id, - const int version, - ads::LoadCallback callback) override; - void GetBrowsingHistory(const int max_count, - const int days_ago, - ads::GetBrowsingHistoryCallback callback) override; - std::string LoadResourceForId(const std::string & id) override; - void Log(const char * file, const int line, const int verbose_level, const std::string & message) override; - void RunDBTransaction(ads::DBTransactionPtr transaction, ads::RunDBTransactionCallback callback) override; - void OnAdRewardsChanged() override; - void SetBooleanPref(const std::string & path, const bool value) override; - bool GetBooleanPref(const std::string & path) const override; - void SetIntegerPref(const std::string & path, const int value) override; - int GetIntegerPref(const std::string & path) const override; - void SetDoublePref(const std::string & path, const double value) override; - double GetDoublePref(const std::string & path) const override; - void SetStringPref(const std::string & path, const std::string& value) override; - std::string GetStringPref(const std::string & path) const override; - void SetInt64Pref(const std::string & path, const int64_t value) override; - int64_t GetInt64Pref(const std::string & path) const override; - void SetUint64Pref(const std::string & path, const uint64_t value) override; - uint64_t GetUint64Pref(const std::string & path) const override; - void ClearPref(const std::string & path) override; - void RecordP2AEvent(const std::string& name, const ads::P2AEventType type, const std::string& value) override; -}; diff --git a/vendor/brave-ios/Ads/Generated/NativeAdsClient.mm b/vendor/brave-ios/Ads/Generated/NativeAdsClient.mm deleted file mode 100644 index 24a2a04d17d..00000000000 --- a/vendor/brave-ios/Ads/Generated/NativeAdsClient.mm +++ /dev/null @@ -1,159 +0,0 @@ -/* WARNING: THIS FILE IS GENERATED. ANY CHANGES TO THIS FILE WILL BE OVERWRITTEN - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import "NativeAdsClient.h" -#import "NativeAdsClientBridge.h" - -// Constructor & Destructor -NativeAdsClient::NativeAdsClient(id bridge) : bridge_(bridge) { -} - -NativeAdsClient::~NativeAdsClient() { - bridge_ = nil; -} - -bool NativeAdsClient::IsNetworkConnectionAvailable() const { - return [bridge_ isNetworkConnectionAvailable]; -} - -bool NativeAdsClient::IsForeground() const { - return [bridge_ isForeground]; -} - -bool NativeAdsClient::IsFullScreen() const { - return [bridge_ isFullScreen]; -} - -bool NativeAdsClient::CanShowBackgroundNotifications() const { - return [bridge_ canShowBackgroundNotifications]; -} - -void NativeAdsClient::ShowNotification(const ads::AdNotificationInfo & info) { - [bridge_ showNotification:info]; -} - -bool NativeAdsClient::ShouldShowNotifications() { - return [bridge_ shouldShowNotifications]; -} - -void NativeAdsClient::CloseNotification(const std::string & uuid) { - [bridge_ closeNotification:uuid]; -} - -void NativeAdsClient::RecordAdEvent(const std::string& ad_type, - const std::string& confirmation_type, - const uint64_t timestamp) const { - [bridge_ recordAdEvent:ad_type - confirmationType:confirmation_type - timestamp:timestamp]; -} - -std::vector NativeAdsClient::GetAdEvents( - const std::string& ad_type, - const std::string& confirmation_type) const { - return [bridge_ getAdEvents:ad_type confirmationType:confirmation_type]; -} - -void NativeAdsClient::ResetAdEvents() const { - [bridge_ resetAdEvents]; -} - -void NativeAdsClient::UrlRequest(ads::UrlRequestPtr url_request, ads::UrlRequestCallback callback) { - [bridge_ UrlRequest:std::move(url_request) callback:callback]; -} - -void NativeAdsClient::Save(const std::string & name, const std::string & value, ads::ResultCallback callback) { - [bridge_ save:name value:value callback:callback]; -} - -void NativeAdsClient::LoadAdsResource(const std::string& id, - const int version, - ads::LoadCallback callback) { - [bridge_ loadAdsResource:id version:version callback:callback]; -} - -void NativeAdsClient::GetBrowsingHistory( - const int max_count, - const int days_ago, - ads::GetBrowsingHistoryCallback callback) { - [bridge_ getBrowsingHistory:max_count forDays:days_ago callback:callback]; -} - -void NativeAdsClient::Load(const std::string & name, ads::LoadCallback callback) { - [bridge_ load:name callback:callback]; -} - -std::string NativeAdsClient::LoadResourceForId(const std::string & id) { - return [bridge_ loadResourceForId:id]; -} - -void NativeAdsClient::Log(const char * file, const int line, const int verbose_level, const std::string & message) { - [bridge_ log:file line:line verboseLevel:verbose_level message:message]; -} - -void NativeAdsClient::RunDBTransaction(ads::DBTransactionPtr transaction, ads::RunDBTransactionCallback callback) { - [bridge_ runDBTransaction:std::move(transaction) callback:callback]; -} - -void NativeAdsClient::OnAdRewardsChanged() { - [bridge_ onAdRewardsChanged]; -} - -void NativeAdsClient::SetBooleanPref(const std::string & path, const bool value) { - [bridge_ setBooleanPref:path value:value]; -} - -bool NativeAdsClient::GetBooleanPref(const std::string & path) const { - return [bridge_ getBooleanPref:path]; -} - -void NativeAdsClient::SetIntegerPref(const std::string & path, const int value) { - [bridge_ setIntegerPref:path value:value]; -} - -int NativeAdsClient::GetIntegerPref(const std::string & path) const { - return [bridge_ getIntegerPref:path]; -} - -void NativeAdsClient::SetDoublePref(const std::string & path, const double value) { - [bridge_ setDoublePref:path value:value]; -} - -double NativeAdsClient::GetDoublePref(const std::string & path) const { - return [bridge_ getDoublePref:path]; -} - -void NativeAdsClient::SetStringPref(const std::string & path, const std::string & value) { - [bridge_ setStringPref:path value:value]; -} - -std::string NativeAdsClient::GetStringPref(const std::string& path) const { - return [bridge_ getStringPref:path]; -} - -void NativeAdsClient::SetInt64Pref(const std::string& path, const int64_t value) { - [bridge_ setInt64Pref:path value:value]; -} - -int64_t NativeAdsClient::GetInt64Pref(const std::string& path) const { - return [bridge_ getInt64Pref:path]; -} - -void NativeAdsClient::SetUint64Pref(const std::string& path, const uint64_t value) { - [bridge_ setUint64Pref:path value:value]; -} - -uint64_t NativeAdsClient::GetUint64Pref(const std::string& path) const { - return [bridge_ getUint64Pref:path]; -} - -void NativeAdsClient::ClearPref(const std::string & path) { - [bridge_ clearPref:path]; -} - -void NativeAdsClient::RecordP2AEvent(const std::string& name, const ads::P2AEventType type, const std::string& value) { - [bridge_ recordP2AEvent:name type:type value:value]; -} diff --git a/vendor/brave-ios/BATBraveRewards.h b/vendor/brave-ios/BATBraveRewards.h deleted file mode 100644 index 429b8d40693..00000000000 --- a/vendor/brave-ios/BATBraveRewards.h +++ /dev/null @@ -1,146 +0,0 @@ -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. - -#import - -#import "BATBraveAds.h" -#import "BATBraveLedger.h" - -NS_ASSUME_NONNULL_BEGIN - -/// Configuration around brave rewards for ads & ledger -OBJC_EXPORT -NS_SWIFT_NAME(BraveRewardsConfiguration) -@interface BATBraveRewardsConfiguration : NSObject - -/// Whether or not rewards is being tested -@property (nonatomic, getter=isTesting) BOOL testing; -//@property (nonatomic, getter=isDebug) BOOL debug; -/// The rewards environment -@property (nonatomic) BATEnvironment environment; -/// The rewards build channel -@property (nonatomic, nullable) BATBraveAdsBuildChannel *buildChannel; -/// Where ledger and ads should save their state -@property (nonatomic, copy) NSString *stateStoragePath; -/// The number of seconds between overrides. Defaults to 0 (no override) which means reconciles -/// occur every 30 days (see: bat-native-ledger/static_values.h/_reconcile_default_interval) -@property (nonatomic) int overridenNumberOfSecondsBetweenReconcile; -/// Whether or not to enable short retries between contribution attempts -@property (nonatomic) BOOL useShortRetries; - -/// The default configuration. Environment is dev, no changes to ads or ledger configuration -/// -/// State is stored in Application Support -@property (nonatomic, class, readonly) BATBraveRewardsConfiguration *defaultConfiguration NS_SWIFT_NAME(default); -/// The staging configuration. Environment is staging, no changes to ads or ledger configuration -/// -/// State is stored in Application Support -@property (nonatomic, class, readonly) BATBraveRewardsConfiguration *stagingConfiguration NS_SWIFT_NAME(staging); -/// The production configuration. Environment is production, no changes to ads or ledger configuration -/// -/// State is stored in Application Support -@property (nonatomic, class, readonly) BATBraveRewardsConfiguration *productionConfiguration NS_SWIFT_NAME(production); -/// The testing configuration. Environment is development & is_testing is set to true. Short retries are enabled, -/// number of seconds between reconciles is set to 30 seconds instead of 30 days. -/// -/// State is saved to a directory created in /tmp -@property (nonatomic, class, readonly) BATBraveRewardsConfiguration *testingConfiguration NS_SWIFT_NAME(testing); - -@end - -OBJC_EXPORT -NS_SWIFT_NAME(BraveRewardsDelegate) -@protocol BATBraveRewardsDelegate -@required - -- (void)logMessageWithFilename:(NSString *)file - lineNumber:(int)lineNumber - verbosity:(int)verbosity - message:(NSString *)message; - -/// A notification that the ledger service did start -- (void)ledgerServiceDidStart:(BATBraveLedger *)ledger; - -/// Obtain the favicon URL given some page's URL. The client can then choose -/// to download said favicon and cache it for later when `retrieveFavicon` is -/// called. -/// -/// If the favicon URL cannot be obtained, call completion with `nil` -- (void)faviconURLFromPageURL:(NSURL *)pageURL - completion:(void (^)(NSURL * _Nullable faviconURL))completion; - -@end - -/// A container for handling Brave Rewards. Use `ads` to handle how many ads the users see, -/// when to display them. Use `ledger` to manage interactions between the users wallet & publishers -OBJC_EXPORT -NS_SWIFT_NAME(BraveRewards) -@interface BATBraveRewards : NSObject - -@property (nonatomic, readonly) BATBraveAds *ads; -/// Whether or not Brave Ads is enabled -@property (nonatomic, assign, getter=isAdsEnabled) BOOL adsEnabled; -@property (nonatomic, readonly, nullable) BATBraveLedger *ledger; -@property (nonatomic, weak) id delegate; - -/// Resets the ads & ledger (by purging its data). This should likely never be used in production. -- (void)reset; - -/// Create a BraveRewards instance with a given configuration -- (instancetype)initWithConfiguration:(BATBraveRewardsConfiguration *)configuration; -/// Create a BraveRewards instance with a given configuration and custom ledger classes for mocking -- (instancetype)initWithConfiguration:(BATBraveRewardsConfiguration *)configuration - delegate:(nullable id)delegate - ledgerClass:(nullable Class)ledgerClass - adsClass:(nullable Class)adsClass NS_DESIGNATED_INITIALIZER; -- (instancetype)init NS_UNAVAILABLE; - -/// Starts the ledger service if it hadn't already been started and calls a completion handler -/// after it has been initialized -- (void)startLedgerService:(nullable void (^)())completion; - -@end - -OBJC_EXPORT -@interface BATBraveRewards (Reporting) - -/// Report that a tab with a given id was updated -- (void)reportTabUpdated:(NSInteger)tabId - url:(NSURL *)url - faviconURL:(nullable NSURL *)faviconURL - isSelected:(BOOL)isSelected - isPrivate:(BOOL)isPrivate; -/// Report that a page has loaded in the current browser tab, and the HTML is available for analysis -/// -/// @note Send nil for `adsInnerText` if the load happened due to tabs restoring -/// after app launch -- (void)reportLoadedPageWithURL:(NSURL *)url - redirectedFromURLs:(NSArray *)redirectionURLs - faviconURL:(nullable NSURL *)faviconURL - tabId:(UInt32)tabId - html:(NSString *)html - adsInnerText:(nullable NSString *)adsInnerText NS_SWIFT_NAME(reportLoadedPage(url:redirectionURLs:faviconUrl:tabId:html:adsInnerText:)); -/// Report any XHR load happening in the page -- (void)reportXHRLoad:(NSURL *)url - tabId:(UInt32)tabId - firstPartyURL:(nullable NSURL *)firstPartyURL - referrerURL:(nullable NSURL *)referrerURL NS_SWIFT_NAME(reportXHRLoad(url:tabId:firstPartyURL:referrerURL:)); -/// Report posting data to a form? -- (void)reportPostData:(NSData *)postData - url:(NSURL *)url - tabId:(UInt32)tabId - firstPartyURL:(nullable NSURL *)firstPartyURL - referrerURL:(nullable NSURL *)referrerURL NS_SWIFT_NAME(reportPostData(_:url:tabId:firstPartyURL:referrerURL:));; -/// Report that media has started on a tab with a given id -- (void)reportMediaStartedWithTabId:(UInt32)tabId NS_SWIFT_NAME(reportMediaStarted(tabId:)); -/// Report that media has stopped on a tab with a given id -- (void)reportMediaStoppedWithTabId:(UInt32)tabId NS_SWIFT_NAME(reportMediaStopped(tabId:)); -/// Report that a tab with a given id navigated to a new page in the same tab -- (void)reportTabNavigationWithTabId:(UInt32)tabId NS_SWIFT_NAME(reportTabNavigation(tabId:)); -/// Report that a tab with a given id was closed by the user -- (void)reportTabClosedWithTabId:(UInt32)tabId NS_SWIFT_NAME(reportTabClosed(tabId:)); - -@end - -NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/BATBraveRewards.mm b/vendor/brave-ios/BATBraveRewards.mm deleted file mode 100644 index 686e8281fde..00000000000 --- a/vendor/brave-ios/BATBraveRewards.mm +++ /dev/null @@ -1,258 +0,0 @@ -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. - -#import "BATBraveRewards.h" -#import "DataController.h" -#import "RewardsLogging.h" -#import "BATBraveAds+Private.h" - -#include "base/task/current_thread.h" -#include "base/task/single_thread_task_executor.h" - -base::SingleThreadTaskExecutor* g_task_executor = nullptr; - -@implementation BATBraveRewardsConfiguration - -+ (BATBraveRewardsConfiguration *)defaultConfiguration -{ - __auto_type config = [[BATBraveRewardsConfiguration alloc] init]; - config.environment = BATEnvironmentDevelopment; - config.stateStoragePath = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES).firstObject; - return config; -} - -+ (BATBraveRewardsConfiguration *)stagingConfiguration -{ - __auto_type config = [self defaultConfiguration]; - config.environment = BATEnvironmentStaging; - return config; -} - -+ (BATBraveRewardsConfiguration *)productionConfiguration -{ - __auto_type config = [self defaultConfiguration]; - config.environment = BATEnvironmentProduction; - return config; -} - -+ (BATBraveRewardsConfiguration *)testingConfiguration -{ - __auto_type config = [self defaultConfiguration]; - config.stateStoragePath = NSTemporaryDirectory(); - config.testing = YES; - config.useShortRetries = YES; - config.overridenNumberOfSecondsBetweenReconcile = 30; - return config; -} - -- (id)copyWithZone:(NSZone *)zone -{ - __auto_type config = [[BATBraveRewardsConfiguration alloc] init]; - config.stateStoragePath = self.stateStoragePath; - config.environment = self.environment; - config.testing = self.testing; - config.useShortRetries = self.useShortRetries; - config.overridenNumberOfSecondsBetweenReconcile = self.overridenNumberOfSecondsBetweenReconcile; - return config; -} - -@end - -@interface BATBraveRewards () -@property (nonatomic) BATBraveAds *ads; -@property (nonatomic, nullable) BATBraveLedger *ledger; -@property (nonatomic, copy) BATBraveRewardsConfiguration *configuration; -@property (nonatomic, assign) Class ledgerClass; -@property (nonatomic, assign) Class adsClass; -@end - -@implementation BATBraveRewards - -- (void)reset -{ - [[NSFileManager defaultManager] removeItemAtPath:[self.configuration.stateStoragePath stringByAppendingPathComponent:@"ledger"] error:nil]; - [[NSFileManager defaultManager] removeItemAtPath:[self.configuration.stateStoragePath stringByAppendingPathComponent:@"ads"] error:nil]; - if (DataController.defaultStoreExists) { - [[NSFileManager defaultManager] removeItemAtURL:DataController.shared.storeDirectoryURL error:nil]; - DataController.shared = [[DataController alloc] init]; - } - - [self startAdsService]; -} - -- (instancetype)initWithConfiguration:(BATBraveRewardsConfiguration *)configuration -{ - return [self initWithConfiguration:configuration delegate:nil ledgerClass:nil adsClass:nil]; -} - -- (instancetype)initWithConfiguration:(BATBraveRewardsConfiguration *)configuration - delegate:(nullable id)delegate - ledgerClass:(nullable Class)ledgerClass - adsClass:(nullable Class)adsClass -{ - if ((self = [super init])) { - if (!base::CurrentThread::Get()) { - g_task_executor = new base::SingleThreadTaskExecutor(base::MessagePumpType::UI); - } - - rewards::set_rewards_client_for_logging(self); - - self.configuration = configuration; - self.delegate = delegate; - self.ledgerClass = ledgerClass ?: BATBraveLedger.class; - self.adsClass = adsClass ?: BATBraveAds.class; - - BATBraveAds.debug = configuration.environment != BATEnvironmentProduction; - BATBraveAds.environment = configuration.environment; - if (configuration.buildChannel != nil) { - BATBraveAds.buildChannel = configuration.buildChannel; - } - - BATBraveLedger.debug = configuration.environment != BATEnvironmentProduction; - BATBraveLedger.environment = configuration.environment; - BATBraveLedger.testing = configuration.testing; - BATBraveLedger.useShortRetries = configuration.useShortRetries; - BATBraveLedger.reconcileInterval = configuration.overridenNumberOfSecondsBetweenReconcile; - - [self startAdsService]; - } - return self; -} - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wobjc-messaging-id" - -- (void)startAdsService -{ - NSString *adsStorage = [self.configuration.stateStoragePath stringByAppendingPathComponent:@"ads"]; - self.ads = [[self.adsClass alloc] initWithStateStoragePath:adsStorage]; -} - -- (void)startLedgerService:(nullable void (^)())completion -{ - if (self.ledger != nil) { - // Already started - if (completion) { - completion(); - } - return; - } - NSString *ledgerStorage = [self.configuration.stateStoragePath stringByAppendingPathComponent:@"ledger"]; - self.ledger = [[self.ledgerClass alloc] initWithStateStoragePath:ledgerStorage]; - __auto_type __weak weakSelf = self; - self.ads.ledger = self.ledger; - self.ledger.ads = self.ads; - self.ledger.faviconFetcher = ^(NSURL *pageURL, void (^completion)(NSURL * _Nullable)) { - [weakSelf.delegate faviconURLFromPageURL:pageURL completion:completion]; - }; - - [self.ledger initializeLedgerService:^{ - if (!weakSelf || !weakSelf.ledger) { - return; - } - [weakSelf.delegate ledgerServiceDidStart:weakSelf.ledger]; - if (completion) { - completion(); - } - }]; -} - -#pragma clang diagnostic push - -- (BOOL)isAdsEnabled -{ - return self.ads.enabled; -} - -- (void)setAdsEnabled:(BOOL)adsEnabled -{ - if (self.ads.enabled && !adsEnabled) { - const auto __weak weakSelf = self; - self.ads.enabled = adsEnabled; - [self.ads shutdown:^{ - const auto strongSelf = weakSelf; - if (!strongSelf) { return; } - NSString *adsStorage = [strongSelf.configuration.stateStoragePath stringByAppendingPathComponent:@"ads"]; - strongSelf.ads = [[strongSelf.adsClass alloc] initWithStateStoragePath:adsStorage]; - strongSelf.ads.ledger = strongSelf.ledger; - strongSelf.ledger.ads = strongSelf.ads; - }]; - } else { - self.ads.enabled = adsEnabled; - } -} - -@end - -@implementation BATBraveRewards (Reporting) - -- (void)reportTabUpdated:(NSInteger)tabId - url:(NSURL *)url - faviconURL:(nullable NSURL *)faviconURL - isSelected:(BOOL)isSelected - isPrivate:(BOOL)isPrivate -{ - if (isSelected) { - self.ledger.selectedTabId = (UInt32)tabId; - [self onTabRetrieved:tabId url:url faviconURL:faviconURL html:nil]; - } - [self.ads reportTabUpdated:tabId url:url isSelected:isSelected isPrivate:isPrivate]; -} - -- (void)reportLoadedPageWithURL:(NSURL *)url - redirectedFromURLs:(NSArray *)redirectionURLs - faviconURL:(nullable NSURL *)faviconURL - tabId:(UInt32)tabId - html:(NSString *)html - adsInnerText:(nullable NSString *)adsInnerText -{ - [self onTabRetrieved:tabId url:url faviconURL:faviconURL html:html]; - if (adsInnerText != nil) { - [self.ads reportLoadedPageWithURL:url - redirectedFromURLs:redirectionURLs - html:html - innerText:adsInnerText - tabId:tabId]; - } - [self.ledger reportLoadedPageWithURL:url tabId:tabId]; -} - -- (void)onTabRetrieved:(NSInteger)tabId url:(NSURL *)url faviconURL:(nullable NSURL *)faviconURL html:(nullable NSString *)html -{ - // New publisher database entry will be created if the pub doesn't exist. - [self.ledger fetchPublisherActivityFromURL:url faviconURL:faviconURL publisherBlob:html tabId:tabId]; -} - -- (void)reportXHRLoad:(NSURL *)url tabId:(UInt32)tabId firstPartyURL:(NSURL *)firstPartyURL referrerURL:(NSURL *)referrerURL -{ - [self.ledger reportXHRLoad:url tabId:tabId firstPartyURL:firstPartyURL referrerURL:referrerURL]; -} - -- (void)reportPostData:(NSData *)postData url:(NSURL *)url tabId:(UInt32)tabId firstPartyURL:(NSURL *)firstPartyURL referrerURL:(NSURL *)referrerURL -{ - [self.ledger reportPostData:postData url:url tabId:tabId firstPartyURL:firstPartyURL referrerURL:referrerURL]; -} - -- (void)reportTabNavigationWithTabId:(UInt32)tabId -{ - [self.ledger reportTabNavigationOrClosedWithTabId:tabId]; -} - -- (void)reportTabClosedWithTabId:(UInt32)tabId -{ - [self.ads reportTabClosedWithTabId:tabId]; - [self.ledger reportTabNavigationOrClosedWithTabId:tabId]; -} - -- (void)reportMediaStartedWithTabId:(UInt32)tabId -{ - [self.ads reportMediaStartedWithTabId:tabId]; -} - -- (void)reportMediaStoppedWithTabId:(UInt32)tabId -{ - [self.ads reportMediaStoppedWithTabId:tabId]; -} - -@end diff --git a/vendor/brave-ios/BUILD.gn b/vendor/brave-ios/BUILD.gn deleted file mode 100644 index 979c21a5608..00000000000 --- a/vendor/brave-ios/BUILD.gn +++ /dev/null @@ -1,278 +0,0 @@ -# Copyright (c) 2019 The Brave Authors. All rights reserved. -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. - -import("//brave/ios/app/headers.gni") -import("//build/config/ios/rules.gni") - -config("internal_config") { - visibility = [ - ":*", - "tests:*", - "//brave/test:*", - ] - - cflags = [ - "-fobjc-weak", - "-fobjc-abi-version=2", - "-fobjc-legacy-dispatch", - "-Wno-objc-property-synthesis", - "-Wno-sign-compare", - ] - ldflags = [ "-Wl,-no_compact_unwind,-rpath,/usr/lib/swift,-rpath,@executable_path/../Frameworks" ] - include_dirs = [ - ".", - "Ads", - "Ads/Generated", - "Ledger", - "Ledger/Generated", - "Ledger/Data", - "Ledger/Data/Model", - "Ledger/Models", - "Shared", - "objc-gen", - "$target_gen_dir", - ] -} - -group("brave-ios") { - public_deps = [ ":brave_rewards_ios_framework" ] -} - -group("brave_ios_tests") { - testonly = true - public_deps = [ "tests:brave_rewards_ios_tests" ] -} - -ios_framework_bundle("brave_rewards_ios_framework") { - output_name = "BraveRewards" - output_dir = root_out_dir - - info_plist = "Info.plist" - - configs += [ ":internal_config" ] - configs += [ "//build/config/compiler:enable_arc" ] - - deps = [ - ":ads_mojo_gen_wrappers", - ":coredata", - ":ledger_mojo_gen_wrappers", - ":resources", - "//brave/ios/app", - "//brave/vendor/bat-native-ads", - "//brave/vendor/bat-native-ledger", - "//components/os_crypt", - "//net:net", - "//sql", - "//url", - ] - - sources = [ - "$target_gen_dir/ads.mojom.objc+private.h", - "$target_gen_dir/ads.mojom.objc.h", - "$target_gen_dir/ads.mojom.objc.mm", - "$target_gen_dir/ledger.mojom.objc+private.h", - "$target_gen_dir/ledger.mojom.objc.h", - "$target_gen_dir/ledger.mojom.objc.mm", - "Ads/BATAdNotification.h", - "Ads/BATAdNotification.mm", - "Ads/BATBraveAds+Private.h", - "Ads/BATBraveAds.h", - "Ads/BATBraveAds.mm", - "Ads/BATInlineContentAd.h", - "Ads/BATInlineContentAd.mm", - "Ads/Generated/NativeAdsClient.h", - "Ads/Generated/NativeAdsClient.mm", - "Ads/Generated/NativeAdsClientBridge.h", - "BATBraveRewards.h", - "BATBraveRewards.mm", - "Ledger/BATBraveLedger.h", - "Ledger/BATBraveLedger.mm", - "Ledger/BATBraveLedgerObserver.h", - "Ledger/BATBraveLedgerObserver.mm", - "Ledger/Data/BATLedgerDatabase.h", - "Ledger/Data/BATLedgerDatabase.mm", - "Ledger/Data/DataController.h", - "Ledger/Data/DataController.mm", - "Ledger/Data/Model/ActivityInfo.h", - "Ledger/Data/Model/ActivityInfo.m", - "Ledger/Data/Model/ContributionInfo.h", - "Ledger/Data/Model/ContributionInfo.m", - "Ledger/Data/Model/ContributionPublisher.h", - "Ledger/Data/Model/ContributionPublisher.m", - "Ledger/Data/Model/ContributionQueue.h", - "Ledger/Data/Model/ContributionQueue.m", - "Ledger/Data/Model/CoreDataModels.h", - "Ledger/Data/Model/MediaPublisherInfo.h", - "Ledger/Data/Model/MediaPublisherInfo.m", - "Ledger/Data/Model/PendingContribution.h", - "Ledger/Data/Model/PendingContribution.m", - "Ledger/Data/Model/Promotion.h", - "Ledger/Data/Model/Promotion.m", - "Ledger/Data/Model/PromotionCredentials.h", - "Ledger/Data/Model/PromotionCredentials.m", - "Ledger/Data/Model/PublisherInfo.h", - "Ledger/Data/Model/PublisherInfo.m", - "Ledger/Data/Model/RecurringDonation.h", - "Ledger/Data/Model/RecurringDonation.m", - "Ledger/Data/Model/ServerPublisherAmount.h", - "Ledger/Data/Model/ServerPublisherAmount.m", - "Ledger/Data/Model/ServerPublisherBanner.h", - "Ledger/Data/Model/ServerPublisherBanner.m", - "Ledger/Data/Model/ServerPublisherInfo.h", - "Ledger/Data/Model/ServerPublisherInfo.m", - "Ledger/Data/Model/ServerPublisherLink.h", - "Ledger/Data/Model/ServerPublisherLink.m", - "Ledger/Data/Model/UnblindedToken.h", - "Ledger/Data/Model/UnblindedToken.m", - "Ledger/Generated/NativeLedgerClient.h", - "Ledger/Generated/NativeLedgerClient.mm", - "Ledger/Generated/NativeLedgerClientBridge.h", - "Ledger/Models/BATPromotionSolution.h", - "Ledger/Models/BATPromotionSolution.mm", - "Ledger/Models/BATRewardsNotification.h", - "Ledger/Models/BATRewardsNotification.m", - "Shared/BATCommonOperations.h", - "Shared/BATCommonOperations.mm", - "Shared/NSURL+Extensions.h", - "Shared/NSURL+Extensions.mm", - "Shared/RewardsLogging.h", - "Shared/RewardsLogging.mm", - "objc-gen/CppTransformations.h", - ] - - public_headers = [ - "BraveRewards.h", - "BATBraveRewards.h", - "Ledger/BATBraveLedger.h", - "Ledger/BATBraveLedgerObserver.h", - "Ledger/Generated/Enums.h", - "Ledger/Models/BATRewardsNotification.h", - "Ledger/Models/BATPromotionSolution.h", - "Ads/BATBraveAds.h", - "Ads/BATAdNotification.h", - "Ads/BATInlineContentAd.h", - "$target_gen_dir/ledger.mojom.objc.h", - "$target_gen_dir/ads.mojom.objc.h", - ] - - public_headers += brave_core_public_headers - - frameworks = [ - "Foundation.framework", - "UIKit.framework", - "Security.framework", - "CoreData.framework", - "SystemConfiguration.framework", - "Network.framework", - "CoreImage.framework", - ] -} - -bundle_data("resources") { - ads_dir = "//brave/vendor/bat-native-ads" - sources = [ - "$ads_dir/data/resources/catalog-schema.json", - "Ledger/Data/migrate.sql", - ] - outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ] -} - -bundle_data("coredata") { - sources = [ - "$root_gen_dir/Model.momd/Model.mom", - "$root_gen_dir/Model.momd/VersionInfo.plist", - ] - - outputs = [ "{{bundle_resources_dir}}/Model.momd/{{source_file_part}}" ] - - public_deps = [ ":compile_coredata" ] -} - -action("compile_coredata") { - script = "scripts/compile-model.py" - - inputs = [ "Ledger/Data/Model.xcdatamodeld" ] - - outputs = [ - "$root_gen_dir/Model.momd/Model.mom", - "$root_gen_dir/Model.momd/VersionInfo.plist", - ] - - model = rebase_path("Ledger/Data/Model.xcdatamodeld") - out_dir = rebase_path(root_gen_dir) - - args = [ - "--model=$model", - "--output=$out_dir", - ] -} - -action("ledger_mojo_gen_wrappers") { - script = "scripts/mojo/gen_model_wrappers.py" - mojom_module = rebase_path( - "$root_gen_dir/brave/vendor/bat-native-ledger/include/bat/ledger/public/interfaces/ledger.mojom-module") - mojom_idl = rebase_path( - "//brave/vendor/bat-native-ledger/include/bat/ledger/public/interfaces/ledger.mojom") - inputs = [ - mojom_module, - mojom_idl, - "scripts/mojo/mojom_objc_generator.py", - "scripts/mojo/objc_templates/enum.tmpl", - "scripts/mojo/objc_templates/module.h.tmpl", - "scripts/mojo/objc_templates/module+private.h.tmpl", - "scripts/mojo/objc_templates/module.mm.tmpl", - "scripts/mojo/objc_templates/interface_declaration.tmpl", - "scripts/mojo/objc_templates/private_interface_declaration.tmpl", - "scripts/mojo/objc_templates/private_interface_implementation.tmpl", - ] - outputs = [ - "$target_gen_dir/ledger.mojom.objc.h", - "$target_gen_dir/ledger.mojom.objc+private.h", - "$target_gen_dir/ledger.mojom.objc.mm", - "$target_gen_dir/objc_templates_bytecode/ledger_objc_templates.zip", - ] - output_dir = rebase_path(target_gen_dir) - args = [ - "--mojom-module=$mojom_module", - "--module-include-path=bat/ledger/public/interfaces", - "--mojom-file=$mojom_idl", - "--output-dir=$output_dir", - ] - deps = [ "//brave/vendor/bat-native-ledger/include/bat/ledger/public/interfaces:interfaces__parser" ] -} - -action("ads_mojo_gen_wrappers") { - script = "scripts/mojo/gen_model_wrappers.py" - mojom_module = rebase_path( - "$root_gen_dir/brave/vendor/bat-native-ads/include/bat/ads/public/interfaces/ads.mojom-module") - mojom_idl = rebase_path( - "//brave/vendor/bat-native-ads/include/bat/ads/public/interfaces/ads.mojom") - inputs = [ - mojom_module, - mojom_idl, - "scripts/mojo/mojom_objc_generator.py", - "scripts/mojo/objc_templates/enum.tmpl", - "scripts/mojo/objc_templates/module.h.tmpl", - "scripts/mojo/objc_templates/module+private.h.tmpl", - "scripts/mojo/objc_templates/module.mm.tmpl", - "scripts/mojo/objc_templates/interface_declaration.tmpl", - "scripts/mojo/objc_templates/private_interface_declaration.tmpl", - "scripts/mojo/objc_templates/private_interface_implementation.tmpl", - ] - outputs = [ - "$target_gen_dir/ads.mojom.objc.h", - "$target_gen_dir/ads.mojom.objc+private.h", - "$target_gen_dir/ads.mojom.objc.mm", - "$target_gen_dir/objc_templates_bytecode/ads_objc_templates.zip", - ] - output_dir = rebase_path(target_gen_dir) - args = [ - "--mojom-module=$mojom_module", - "--module-include-path=bat/ads/public/interfaces", - "--mojom-file=$mojom_idl", - "--output-dir=$output_dir", - ] - deps = [ "//brave/vendor/bat-native-ads/include/bat/ads/public/interfaces:interfaces__parser" ] -} diff --git a/vendor/brave-ios/BraveRewards.h b/vendor/brave-ios/BraveRewards.h deleted file mode 100644 index a18a6e8981a..00000000000 --- a/vendor/brave-ios/BraveRewards.h +++ /dev/null @@ -1,45 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import - -//! Project version number for Ledger. -FOUNDATION_EXPORT double BraveRewardsVersionNumber; - -//! Project version string for Ledger. -FOUNDATION_EXPORT const unsigned char BraveRewardsVersionString[]; - -#import - -// Ads -#import -#import - -// Ledger -#import -#import -#import -#import - -// brave-core -#import - -// Sync -#import -#import - -// Bookmarks -#import -#import -#import -#import - -// History -#import -#import - -// Wallet -#import -#import -#import diff --git a/vendor/brave-ios/Ledger/BATBraveLedger.h b/vendor/brave-ios/Ledger/BATBraveLedger.h deleted file mode 100644 index a39deaa76b4..00000000000 --- a/vendor/brave-ios/Ledger/BATBraveLedger.h +++ /dev/null @@ -1,323 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import -#import "ledger.mojom.objc.h" -#import "BATRewardsNotification.h" -#import "BATBraveLedgerObserver.h" -#import "BATPromotionSolution.h" - -@class BATBraveAds; - -NS_ASSUME_NONNULL_BEGIN - -typedef void (^BATFaviconFetcher)(NSURL *pageURL, void (^completion)(NSURL * _Nullable faviconURL)); - -/// The error domain for ledger related errors -OBJC_EXPORT NSString * const BATBraveLedgerErrorDomain NS_SWIFT_NAME(BraveLedgerErrorDomain); - -OBJC_EXPORT NSNotificationName const BATBraveLedgerNotificationAdded NS_SWIFT_NAME(BraveLedger.NotificationAdded); - -typedef NSString *BATBraveGeneralLedgerNotificationID NS_SWIFT_NAME(GeneralLedgerNotificationID) NS_STRING_ENUM; -OBJC_EXPORT BATBraveGeneralLedgerNotificationID const BATBraveGeneralLedgerNotificationIDWalletNowVerified; -OBJC_EXPORT BATBraveGeneralLedgerNotificationID const BATBraveGeneralLedgerNotificationIDWalletDisconnected; - -OBJC_EXPORT -NS_SWIFT_NAME(BraveLedger) -@interface BATBraveLedger : NSObject - -@property (nonatomic, weak) BATBraveAds *ads; - -@property (nonatomic, copy, nullable) BATFaviconFetcher faviconFetcher; - -/// Create a brave ledger that will read and write its state to the given path -- (instancetype)initWithStateStoragePath:(NSString *)path; - -- (instancetype)init NS_UNAVAILABLE; - -#pragma mark - Initialization - -/// Initialize the ledger service. -/// -/// This must be called before other methods on this class are called -- (void)initializeLedgerService:(nullable void (^)())completion; - -/// Whether or not the ledger service has been initialized already -@property (nonatomic, readonly, getter=isInitialized) BOOL initialized; - -/// Whether or not the ledger service is currently initializing -@property (nonatomic, readonly, getter=isInitializing) BOOL initializing; - -/// The result when initializing the ledger service. Should be -/// `BATResultLedgerOk` if `initialized` is `true` -/// -/// If this is not `BATResultLedgerOk`, rewards is not usable for the user -@property (nonatomic, readonly) BATResult initializationResult; - -/// Whether or not data migration failed when initializing and the user should -/// be notified. -@property (nonatomic, readonly) BOOL dataMigrationFailed; - -#pragma mark - Observers - -/// Add an interface to the list of observers -/// -/// Observers are stored weakly and do not necessarily need to be removed -- (void)addObserver:(BATBraveLedgerObserver *)observer; - -/// Removes an interface from the list of observers -- (void)removeObserver:(BATBraveLedgerObserver *)observer; - -#pragma mark - Global - -/// Whether or not to use staging servers. Defaults to false -@property (nonatomic, class, getter=isDebug) BOOL debug; -/// The environment that ledger is communicating with -@property (nonatomic, class) BATEnvironment environment; -/// Marks if this is being ran in a test environment. Defaults to false -@property (nonatomic, class, getter=isTesting) BOOL testing; -/// Number of minutes between reconciles override. Defaults to 0 (no override) -@property (nonatomic, class) int reconcileInterval; -/// Whether or not to use short contribution retries. Defaults to false -@property (nonatomic, class) BOOL useShortRetries; - -#pragma mark - Wallet - -/// Whether or not the wallet is currently in the process of being created -@property (nonatomic, readonly, getter=isInitializingWallet) BOOL initializingWallet; - -/// Creates a cryptocurrency wallet -- (void)createWallet:(nullable void (^)(NSError * _Nullable error))completion; - -/// Get the brave wallet's payment ID and seed for ads confirmations -- (void)currentWalletInfo:(void (^)(BATBraveWallet *_Nullable wallet))completion; - -/// Get parameters served from the server -- (void)getRewardsParameters:(nullable void (^)(BATRewardsParameters * _Nullable))completion; - -/// The parameters send from the server -@property (nonatomic, readonly, nullable) BATRewardsParameters *rewardsParameters; - -/// Fetch details about the users wallet (if they have one) and assigns it to `balance` -- (void)fetchBalance:(nullable void (^)(BATBalance * _Nullable))completion; - -/// The users current wallet balance and related info -@property (nonatomic, readonly, nullable) BATBalance *balance; - -/// The wallet's passphrase. nil if the wallet has not been created yet -@property (nonatomic, readonly, nullable) NSString *walletPassphrase; - -/// Recover the users wallet using their passphrase -- (void)recoverWalletUsingPassphrase:(NSString *)passphrase - completion:(nullable void (^)(NSError * _Nullable))completion; - -/// Retrieves the users most up to date balance to determin whether or not the -/// wallet has a sufficient balance to complete a reconcile -- (void)hasSufficientBalanceToReconcile:(void (^)(BOOL sufficient))completion; - -/// Returns reserved amount of pending contributions to publishers. -- (void)pendingContributionsTotal:(void (^)(double amount))completion NS_SWIFT_NAME(pendingContributionsTotal(completion:)); - -/// Links a desktop brave wallet given some payment ID -- (void)linkBraveWalletToPaymentId:(NSString *)paymentId - completion:(void (^)(BATResult result, NSString *drainID))completion - NS_SWIFT_NAME(linkBraveWallet(paymentId:completion:)); - -/// Obtain a drain status given some drain ID previously obtained from -/// `linkBraveWalletToPaymentId:completion:` -- (void)drainStatusForDrainId:(NSString *)drainId - completion:(void (^)(BATResult result, BATDrainStatus status))completion - NS_SWIFT_NAME(drainStatus(for:completion:)); - -/// Get the amount of BAT that is transferrable via wallet linking -- (void)transferrableAmount:(void (^)(double amount))completion; - -#pragma mark - User Wallets - -/// The last updated external wallet if a user has hooked one up -@property(nonatomic, readonly, nullable) BATExternalWallet* upholdWallet; - -- (void)fetchUpholdWallet: - (nullable void (^)(BATExternalWallet* _Nullable wallet))completion; - -- (void)disconnectWalletOfType:(BATWalletType)walletType - completion:(nullable void (^)(BATResult result))completion; - -- (void)authorizeExternalWalletOfType:(BATWalletType)walletType - queryItems:(NSDictionary *)queryItems - completion:(void (^)(BATResult result, NSURL * _Nullable redirectURL))completion; - -#pragma mark - Publishers - -@property (nonatomic, readonly, getter=isLoadingPublisherList) BOOL loadingPublisherList; - -/// Get publisher info & its activity based on its publisher key -/// -/// This key is _not_ always the URL's host. Use `publisherActivityFromURL` -/// instead when obtaining a publisher given a URL -/// -/// @note `completion` callback is called synchronously -- (void)listActivityInfoFromStart:(unsigned int)start - limit:(unsigned int)limit - filter:(BATActivityInfoFilter *)filter - completion:(void (^)(NSArray *))completion; - -/// Start a fetch to get a publishers activity information given a URL -/// -/// Use `BATBraveLedgerObserver` to retrieve a panel publisher if one is found -- (void)fetchPublisherActivityFromURL:(NSURL *)URL - faviconURL:(nullable NSURL *)faviconURL - publisherBlob:(nullable NSString *)publisherBlob - tabId:(uint64_t)tabId; - -/// Update a publishers exclusion state -- (void)updatePublisherExclusionState:(NSString *)publisherId - state:(BATPublisherExclude)state - NS_SWIFT_NAME(updatePublisherExclusionState(withId:state:)); - -/// Restore all sites which had been previously excluded -- (void)restoreAllExcludedPublishers; - -/// Get the publisher banner given some publisher key -/// -/// This key is _not_ always the URL's host. Use `publisherActivityFromURL` -/// instead when obtaining a publisher given a URL -/// -/// @note `completion` callback is called synchronously -- (void)publisherBannerForId:(NSString *)publisherId - completion:(void (^)(BATPublisherBanner * _Nullable banner))completion; - -/// Refresh a publishers verification status -- (void)refreshPublisherWithId:(NSString *)publisherId - completion:(void (^)(BATPublisherStatus status))completion; - -#pragma mark - SKUs - -- (void)processSKUItems:(NSArray *)items - completion:(void (^)(BATResult result, NSString *orderID))completion; - -#pragma mark - Tips - -/// Get a list of publishers who the user has recurring tips on -/// -/// @note `completion` callback is called synchronously -- (void)listRecurringTips:(void (^)(NSArray *))completion; - -- (void)addRecurringTipToPublisherWithId:(NSString *)publisherId - amount:(double)amount - completion:(void (^)(BOOL success))completion NS_SWIFT_NAME(addRecurringTip(publisherId:amount:completion:)); - -- (void)removeRecurringTipForPublisherWithId:(NSString *)publisherId NS_SWIFT_NAME(removeRecurringTip(publisherId:)); - -/// Get a list of publishers who the user has made direct tips too -/// -/// @note `completion` callback is called synchronously -- (void)listOneTimeTips:(void (^)(NSArray *))completion; - -- (void)tipPublisherDirectly:(BATPublisherInfo *)publisher - amount:(double)amount - currency:(NSString *)currency - completion:(void (^)(BATResult result))completion; - - -#pragma mark - Promotions - -@property (nonatomic, readonly) NSArray *pendingPromotions; - -@property (nonatomic, readonly) NSArray *finishedPromotions; - -/// Updates `pendingPromotions` and `finishedPromotions` based on the database -- (void)updatePendingAndFinishedPromotions:(nullable void (^)())completion; - -- (void)fetchPromotions:(nullable void (^)(NSArray *grants))completion; - -- (void)claimPromotion:(NSString *)promotionId - publicKey:(NSString *)deviceCheckPublicKey - completion:(void (^)(BATResult result, NSString * _Nonnull nonce))completion; - -- (void)attestPromotion:(NSString *)promotionId - solution:(BATPromotionSolution *)solution - completion:(nullable void (^)(BATResult result, BATPromotion * _Nullable promotion))completion; - -#pragma mark - Pending Contributions - -- (void)pendingContributions:(void (^)(NSArray *publishers))completion; - -- (void)removePendingContribution:(BATPendingContributionInfo *)info - completion:(void (^)(BATResult result))completion; - -- (void)removeAllPendingContributions:(void (^)(BATResult result))completion; - -#pragma mark - History - -- (void)balanceReportForMonth:(BATActivityMonth)month - year:(int)year - completion:(void (^)(BATBalanceReportInfo * _Nullable info))completion; - -@property (nonatomic, readonly) BATAutoContributeProperties *autoContributeProperties; - -#pragma mark - Misc - -+ (bool)isMediaURL:(NSURL *)url - firstPartyURL:(nullable NSURL *)firstPartyURL - referrerURL:(nullable NSURL *)referrerURL; - -- (void)rewardsInternalInfo:(void (NS_NOESCAPE ^)(BATRewardsInternalsInfo * _Nullable info))completion; - -- (void)allContributions:(void (^)(NSArray *contributions))completion; - -@property (nonatomic, readonly, copy) NSString *rewardsDatabasePath; - -#pragma mark - Reporting - -@property (nonatomic) UInt32 selectedTabId; - -/// Report that a page has loaded in the current browser tab, and the HTML is available for analysis -- (void)reportLoadedPageWithURL:(NSURL *)url tabId:(UInt32)tabId NS_SWIFT_NAME(reportLoadedPage(url:tabId:)); - -- (void)reportXHRLoad:(NSURL *)url - tabId:(UInt32)tabId - firstPartyURL:(NSURL *)firstPartyURL - referrerURL:(nullable NSURL *)referrerURL; - -- (void)reportPostData:(NSData *)postData - url:(NSURL *)url - tabId:(UInt32)tabId - firstPartyURL:(NSURL *)firstPartyURL - referrerURL:(nullable NSURL *)referrerURL; - -/// Report that a tab with a given id navigated or was closed by the user -- (void)reportTabNavigationOrClosedWithTabId:(UInt32)tabId NS_SWIFT_NAME(reportTabNavigationOrClosed(tabId:)); - -#pragma mark - Preferences - -/// The number of seconds before a publisher is added. -@property (nonatomic, assign) int minimumVisitDuration; -/// The minimum number of visits before a publisher is added -@property (nonatomic, assign) int minimumNumberOfVisits; -/// Whether or not to allow auto contributions to unverified publishers -@property (nonatomic, assign) BOOL allowUnverifiedPublishers; -/// Whether or not to allow auto contributions to videos -@property (nonatomic, assign) BOOL allowVideoContributions; -/// The auto-contribute amount -@property (nonatomic, assign) double contributionAmount; -/// Whether or not the user will automatically contribute -@property (nonatomic, assign, getter=isAutoContributeEnabled) BOOL autoContributeEnabled; -/// A custom user agent for network operations on ledger -@property (nonatomic, copy, nullable) NSString *customUserAgent; - -#pragma mark - Notifications - -/// Gets a list of notifications awaiting user interaction -@property (nonatomic, readonly) NSArray *notifications; - -/// Clear a given notification -- (void)clearNotification:(BATRewardsNotification *)notification; - -/// Clear all the notifications -- (void)clearAllNotifications; - -@end - -NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/BATBraveLedger.mm b/vendor/brave-ios/Ledger/BATBraveLedger.mm deleted file mode 100644 index 6314d08cf34..00000000000 --- a/vendor/brave-ios/Ledger/BATBraveLedger.mm +++ /dev/null @@ -1,1940 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import -#import "bat/ledger/ledger.h" -#import "bat/ledger/ledger_database.h" -#import "bat/ledger/global_constants.h" -#import "bat/ledger/option_keys.h" - -#import "ledger.mojom.objc+private.h" - -#import "BATBraveLedger.h" -#import "BATBraveAds.h" -#import "BATBraveAds+Private.h" -#import "BATCommonOperations.h" -#import "NSURL+Extensions.h" - -#import "NativeLedgerClient.h" -#import "NativeLedgerClientBridge.h" -#import "CppTransformations.h" - -#import - -#import "BATLedgerDatabase.h" -#import "DataController.h" - -#import "base/containers/flat_map.h" -#import "base/time/time.h" -#import "url/gurl.h" -#import "net/base/registry_controlled_domains/registry_controlled_domain.h" -#import "base/strings/sys_string_conversions.h" -#import "components/os_crypt/os_crypt.h" - -#import "base/base64.h" -#import "base/command_line.h" -#import "base/i18n/icu_util.h" -#import "base/ios/ios_util.h" -#include "base/sequenced_task_runner.h" -#include "base/task/post_task.h" -#include "base/task/thread_pool.h" -#include "base/task_runner_util.h" - -#import "RewardsLogging.h" - -#define BATLedgerReadonlyBridge(__type, __objc_getter, __cpp_getter) \ -- (__type)__objc_getter { return ledger->__cpp_getter(); } - -#define BATLedgerBridge(__type, __objc_getter, __objc_setter, __cpp_getter, __cpp_setter) \ -- (__type)__objc_getter { return ledger->__cpp_getter(); } \ -- (void)__objc_setter:(__type)newValue { ledger->__cpp_setter(newValue); } - -#define BATClassLedgerBridge(__type, __objc_getter, __objc_setter, __cpp_var) \ -+ (__type)__objc_getter { return ledger::__cpp_var; } \ -+ (void)__objc_setter:(__type)newValue { ledger::__cpp_var = newValue; } - -NSString * const BATBraveLedgerErrorDomain = @"BATBraveLedgerErrorDomain"; -NSNotificationName const BATBraveLedgerNotificationAdded = @"BATBraveLedgerNotificationAdded"; - -BATBraveGeneralLedgerNotificationID const BATBraveGeneralLedgerNotificationIDWalletNowVerified = @"wallet_new_verified"; -BATBraveGeneralLedgerNotificationID const BATBraveGeneralLedgerNotificationIDWalletDisconnected = @"wallet_disconnected"; - -static NSString * const kNextAddFundsDateNotificationKey = @"BATNextAddFundsDateNotification"; -static NSString * const kBackupNotificationIntervalKey = @"BATBackupNotificationInterval"; -static NSString * const kBackupNotificationFrequencyKey = @"BATBackupNotificationFrequency"; -static NSString * const kUserHasFundedKey = @"BATRewardsUserHasFunded"; -static NSString * const kBackupSucceededKey = @"BATRewardsBackupSucceeded"; -static NSString * const kMigrationSucceeded = @"BATRewardsMigrationSucceeded"; - -static NSString * const kContributionQueueAutoincrementID = @"BATContributionQueueAutoincrementID"; -static NSString * const kUnblindedTokenAutoincrementID = @"BATUnblindedTokenAutoincrementID"; - -static NSString * const kExternalWalletsPrefKey = @"external_wallets"; -static NSString * const kTransferFeesPrefKey = @"transfer_fees"; - -static const auto kOneDay = base::Time::kHoursPerDay * base::Time::kSecondsPerHour; - -/// Ledger Prefs, keys will be defined in `bat/ledger/option_keys.h` -const std::map kBoolOptions = { - {ledger::option::kClaimUGP, true}, - {ledger::option::kIsBitflyerRegion, false}}; -const std::map kIntegerOptions = {}; -const std::map kDoubleOptions = {}; -const std::map kStringOptions = {}; -const std::map kInt64Options = {}; -const std::map kUInt64Options = { - {ledger::option::kPublisherListRefreshInterval, - 7 * base::Time::kHoursPerDay * base::Time::kSecondsPerHour} -}; -/// --- - -/// When initializing the ledger, what should we do when migrating -typedef NS_ENUM(NSInteger, BATLedgerDatabaseMigrationType) { - /// Attempt to migrate all rewards data if needed - BATLedgerDatabaseMigrationTypeDefault = 0, - /// Only migrate unblinded tokens if needed - BATLedgerDatabaseMigrationTypeTokensOnly, - /// Do not migrate any data (essentially resetting rewards activity & balance) - BATLedgerDatabaseMigrationTypeNone -}; - -namespace { - -ledger::type::DBCommandResponsePtr RunDBTransactionOnTaskRunner( - ledger::type::DBTransactionPtr transaction, - ledger::LedgerDatabase* database) { - auto response = ledger::type::DBCommandResponse::New(); - if (!database) { - response->status = ledger::type::DBCommandResponse::Status::RESPONSE_ERROR; - } else { - database->RunTransaction(std::move(transaction), response.get()); - } - - return response; -} - -} // namespace - -@interface BATBraveLedger () { - NativeLedgerClient *ledgerClient; - ledger::Ledger *ledger; - ledger::LedgerDatabase *rewardsDatabase; - scoped_refptr databaseQueue; -} - -@property (nonatomic, copy) NSString *storagePath; -@property (nonatomic) BATRewardsParameters *rewardsParameters; -@property (nonatomic) BATBalance *balance; -@property(nonatomic) BATExternalWallet* upholdWallet; -@property (nonatomic) dispatch_queue_t fileWriteThread; -@property (nonatomic) NSMutableDictionary *state; -@property (nonatomic) BATCommonOperations *commonOps; -@property (nonatomic) NSMutableDictionary *prefs; - -@property (nonatomic) NSMutableArray *mPendingPromotions; -@property (nonatomic) NSMutableArray *mFinishedPromotions; - -@property (nonatomic) NSHashTable *observers; - -@property (nonatomic, getter=isInitialized) BOOL initialized; -@property (nonatomic) BOOL initializing; -@property (nonatomic) BOOL dataMigrationFailed; -@property (nonatomic) BATResult initializationResult; -@property (nonatomic, getter=isLoadingPublisherList) BOOL loadingPublisherList; -@property (nonatomic, getter=isInitializingWallet) BOOL initializingWallet; -@property (nonatomic) BATLedgerDatabaseMigrationType migrationType; - -/// Notifications - -@property (nonatomic) NSMutableArray *mNotifications; -@property (nonatomic) NSTimer *notificationStartupTimer; -@property (nonatomic) NSDate *lastNotificationCheckDate; - -/// Temporary blocks - -@end - -@implementation BATBraveLedger - -- (instancetype)initWithStateStoragePath:(NSString *)path -{ - if ((self = [super init])) { - self.storagePath = path; - self.commonOps = [[BATCommonOperations alloc] initWithStoragePath:path]; - self.state = [[NSMutableDictionary alloc] initWithContentsOfFile:self.randomStatePath] ?: [[NSMutableDictionary alloc] init]; - self.fileWriteThread = dispatch_queue_create("com.rewards.file-write", DISPATCH_QUEUE_SERIAL); - self.mPendingPromotions = [[NSMutableArray alloc] init]; - self.mFinishedPromotions = [[NSMutableArray alloc] init]; - self.observers = [NSHashTable weakObjectsHashTable]; - rewardsDatabase = nullptr; - - self.prefs = [[NSMutableDictionary alloc] initWithContentsOfFile:[self prefsPath]]; - if (!self.prefs) { - self.prefs = [[NSMutableDictionary alloc] init]; - // Setup defaults - self.prefs[kNextAddFundsDateNotificationKey] = @([[NSDate date] timeIntervalSince1970]); - self.prefs[kBackupNotificationFrequencyKey] = @(7 * kOneDay); // 7 days - self.prefs[kBackupNotificationIntervalKey] = @(7 * kOneDay); // 7 days - self.prefs[kBackupSucceededKey] = @(NO); - self.prefs[kUserHasFundedKey] = @(NO); - self.prefs[kMigrationSucceeded] = @(NO); - [self savePrefs]; - } - - const auto args = [NSProcessInfo processInfo].arguments; - const char *argv[args.count]; - for (NSInteger i = 0; i < args.count; i++) { - argv[i] = args[i].UTF8String; - } - - databaseQueue = base::ThreadPool::CreateSequencedTaskRunner( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, - base::TaskShutdownBehavior::BLOCK_SHUTDOWN}); - - const auto* dbPath = [self rewardsDatabasePath].UTF8String; - rewardsDatabase = ledger::LedgerDatabase::CreateInstance(base::FilePath(dbPath)); - - ledgerClient = new NativeLedgerClient(self); - ledger = ledger::Ledger::CreateInstance(ledgerClient); - - // Add notifications for standard app foreground/background - [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(applicationDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil]; - [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(applicationDidBackground) name:UIApplicationDidEnterBackgroundNotification object:nil]; - } - return self; -} - -- (void)dealloc -{ - [NSNotificationCenter.defaultCenter removeObserver:self]; - [self.notificationStartupTimer invalidate]; - - if (rewardsDatabase) { - databaseQueue->DeleteSoon(FROM_HERE, rewardsDatabase); - } - delete ledger; - delete ledgerClient; -} - -- (void)initializeLedgerService:(nullable void (^)())completion -{ - self.migrationType = BATLedgerDatabaseMigrationTypeDefault; - [self databaseNeedsMigration:^(BOOL needsMigration) { - if (needsMigration) { - [BATLedgerDatabase deleteCoreDataServerPublisherList:nil]; - } - [self initializeLedgerService:needsMigration completion:completion]; - }]; -} - -- (void)initializeLedgerService:(BOOL)executeMigrateScript completion:(nullable void (^)())completion -{ - if (self.initialized || self.initializing) { - return; - } - self.initializing = YES; - - BLOG(3, @"DB: Migrate from CoreData? %@", (executeMigrateScript ? @"YES" : @"NO")); - ledger->Initialize(executeMigrateScript, ^(ledger::type::Result result){ - self.initialized = (result == ledger::type::Result::LEDGER_OK || - result == ledger::type::Result::NO_LEDGER_STATE || - result == ledger::type::Result::NO_PUBLISHER_STATE); - self.initializing = NO; - if (self.initialized) { - self.prefs[kMigrationSucceeded] = @(YES); - [self savePrefs]; - - [self getRewardsParameters:nil]; - [self fetchBalance:nil]; - [self fetchUpholdWallet:nil]; - - [self readNotificationsFromDisk]; - - [self.ads initializeIfAdsEnabled]; - } else { - BLOG(0, @"Ledger Initialization Failed with error: %d", result); - if (result == ledger::type::Result::DATABASE_INIT_FAILED) { - // Failed to migrate data... - switch (self.migrationType) { - case BATLedgerDatabaseMigrationTypeDefault: - BLOG(0, @"DB: Full migration failed, attempting BAT only migration."); - self.dataMigrationFailed = YES; - self.migrationType = BATLedgerDatabaseMigrationTypeTokensOnly; - [self resetRewardsDatabase]; - // attempt re-initialize without other data - [self initializeLedgerService:YES completion:completion]; - return; - case BATLedgerDatabaseMigrationTypeTokensOnly: - BLOG(0, @"DB: BAT only migration failed. Initializing without migration."); - self.dataMigrationFailed = YES; - self.migrationType = BATLedgerDatabaseMigrationTypeNone; - [self resetRewardsDatabase]; - // attempt initialize without migrating at all - [self initializeLedgerService:NO completion:completion]; - return; - default: - break; - } - } - } - self.initializationResult = static_cast(result); - if (completion) { - completion(); - } - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.walletInitalized) { - observer.walletInitalized(self.initializationResult); - } - } - }); -} - -- (void)databaseNeedsMigration:(void (^)(BOOL needsMigration))completion -{ - // Check if we even have a DB to migrate - if (!DataController.defaultStoreExists) { - completion(NO); - return; - } - // Have we set the pref saying ledger has alaready initialized successfully? - if ([self.prefs[kMigrationSucceeded] boolValue]) { - completion(NO); - return; - } - // Can we even check the DB - if (!rewardsDatabase) { - BLOG(3, @"DB: No rewards database object"); - completion(YES); - return; - } - // Check integrity of the new DB. Safe to assume if `publisher_info` table - // exists, then all the others do as well. - auto transaction = ledger::type::DBTransaction::New(); - const auto command = ledger::type::DBCommand::New(); - command->type = ledger::type::DBCommand::Type::READ; - command->command = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'publisher_info';"; - command->record_bindings = { ledger::type::DBCommand::RecordBindingType::STRING_TYPE }; - transaction->commands.push_back(command->Clone()); - - [self runDBTransaction:std::move(transaction) callback:^(ledger::type::DBCommandResponsePtr response){ - // Failed to even run the check, tables probably don't exist, - // restart from scratch - if (response->status != ledger::type::DBCommandResponse::Status::RESPONSE_OK) { - [self resetRewardsDatabase]; - BLOG(3, @"DB: Failed to run transaction with status: %d", response->status); - completion(YES); - return; - } - - const auto record = std::move(response->result->get_records()); - // sqlite_master table exists, but the publisher_info table doesn't exist? - // Restart from scratch - if (record.empty() || record.front()->fields.empty()) { - [self resetRewardsDatabase]; - BLOG(3, @"DB: Migrate because we couldnt find tables in sqlite_master"); - completion(YES); - return; - } - - // Tables exist so migration has happened already, but somehow the flag wasn't - // saved. - self.prefs[kMigrationSucceeded] = @(YES); - [self savePrefs]; - - completion(NO); - }]; -} - -- (NSString *)rewardsDatabasePath -{ - return [self.storagePath stringByAppendingPathComponent:@"Rewards.db"]; -} - -- (void)resetRewardsDatabase -{ - delete rewardsDatabase; - const auto dbPath = [self rewardsDatabasePath]; - [NSFileManager.defaultManager removeItemAtPath:dbPath error:nil]; - [NSFileManager.defaultManager removeItemAtPath:[dbPath stringByAppendingString:@"-journal"] error:nil]; - rewardsDatabase = ledger::LedgerDatabase::CreateInstance(base::FilePath(dbPath.UTF8String)); -} - -- (void)getCreateScript:(ledger::client::GetCreateScriptCallback)callback -{ - NSString *migrationScript = @""; - switch (self.migrationType) { - case BATLedgerDatabaseMigrationTypeNone: - // We shouldn't be migrating, therefore doesn't make sense that - // `getCreateScript` was called - BLOG(0, @"DB: Attempted CoreData migration with an empty migration script"); - break; - case BATLedgerDatabaseMigrationTypeTokensOnly: - migrationScript = [BATLedgerDatabase migrateCoreDataBATOnlyToSQLTransaction]; - break; - case BATLedgerDatabaseMigrationTypeDefault: - default: - migrationScript = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - } - callback(migrationScript.UTF8String, 10); -} - -- (NSString *)randomStatePath -{ - return [self.storagePath stringByAppendingPathComponent:@"random_state.plist"]; -} - -- (NSString *)prefsPath -{ - return [self.storagePath stringByAppendingPathComponent:@"ledger_pref.plist"]; -} - -- (void)savePrefs -{ - NSDictionary *prefs = [self.prefs copy]; - NSString *path = [[self prefsPath] copy]; - dispatch_async(self.fileWriteThread, ^{ - [prefs writeToURL:[NSURL fileURLWithPath:path isDirectory:NO] error:nil]; - }); -} - -#pragma mark - Observers - -- (void)addObserver:(BATBraveLedgerObserver *)observer -{ - [self.observers addObject:observer]; -} - -- (void)removeObserver:(BATBraveLedgerObserver *)observer -{ - [self.observers removeObject:observer]; -} - -#pragma mark - Global - -BATClassLedgerBridge(BOOL, isDebug, setDebug, is_debug) -BATClassLedgerBridge(BOOL, isTesting, setTesting, is_testing) -BATClassLedgerBridge(int, reconcileInterval, setReconcileInterval, reconcile_interval) -BATClassLedgerBridge(BOOL, useShortRetries, setUseShortRetries, short_retries) - -+ (BATEnvironment)environment -{ - return static_cast(ledger::_environment); -} - -+ (void)setEnvironment:(BATEnvironment)environment -{ - ledger::_environment = static_cast(environment); -} - -#pragma mark - Wallet - -- (void)createWallet:(void (^)(NSError * _Nullable))completion -{ - const auto __weak weakSelf = self; - // Results that can come from CreateWallet(): - // - WALLET_CREATED: Good to go - // - LEDGER_ERROR: Already initialized - // - BAD_REGISTRATION_RESPONSE: Request credentials call failure or malformed data - // - REGISTRATION_VERIFICATION_FAILED: Missing master user token - self.initializingWallet = YES; - ledger->CreateWallet(^(ledger::type::Result result) { - const auto strongSelf = weakSelf; - if (!strongSelf) { return; } - NSError *error = nil; - if (result != ledger::type::Result::WALLET_CREATED) { - std::map errorDescriptions { - { ledger::type::Result::LEDGER_ERROR, "The wallet was already initialized" }, - { ledger::type::Result::BAD_REGISTRATION_RESPONSE, "Request credentials call failure or malformed data" }, - { ledger::type::Result::REGISTRATION_VERIFICATION_FAILED, "Missing master user token from registered persona" }, - }; - NSDictionary *userInfo = @{}; - const auto description = errorDescriptions[static_cast(result)]; - if (description.length() > 0) { - userInfo = @{ NSLocalizedDescriptionKey: [NSString stringWithUTF8String:description.c_str()] }; - } - error = [NSError errorWithDomain:BATBraveLedgerErrorDomain code:static_cast(result) userInfo:userInfo]; - } - - [strongSelf startNotificationTimers]; - strongSelf.initializingWallet = NO; - - dispatch_async(dispatch_get_main_queue(), ^{ - if (completion) { - completion(error); - } - - for (BATBraveLedgerObserver *observer in [strongSelf.observers copy]) { - if (observer.walletInitalized) { - observer.walletInitalized(static_cast(result)); - } - } - }); - }); -} - -- (void)currentWalletInfo:(void (^)(BATBraveWallet *_Nullable wallet))completion -{ - ledger->GetBraveWallet(^(ledger::type::BraveWalletPtr wallet){ - if (wallet.get() == nullptr) { - completion(nil); - return; - } - const auto bridgedWallet = [[BATBraveWallet alloc] initWithBraveWallet:*wallet]; - completion(bridgedWallet); - }); -} - -- (void)getRewardsParameters:(void (^)(BATRewardsParameters * _Nullable))completion -{ - ledger->GetRewardsParameters(^(ledger::type::RewardsParametersPtr info) { - if (info) { - self.rewardsParameters = [[BATRewardsParameters alloc] initWithRewardsParametersPtr:std::move(info)]; - } else { - self.rewardsParameters = nil; - } - const auto __weak weakSelf = self; - dispatch_async(dispatch_get_main_queue(), ^{ - if (completion) { - completion(weakSelf.rewardsParameters); - } - }); - }); -} - -- (void)fetchBalance:(void (^)(BATBalance * _Nullable))completion -{ - const auto __weak weakSelf = self; - ledger->FetchBalance(^(ledger::type::Result result, ledger::type::BalancePtr balance) { - const auto strongSelf = weakSelf; - if (result == ledger::type::Result::LEDGER_OK) { - strongSelf.balance = [[BATBalance alloc] initWithBalancePtr:std::move(balance)]; - } - dispatch_async(dispatch_get_main_queue(), ^{ - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.fetchedBalance) { - observer.fetchedBalance(); - } - } - if (completion) { - completion(strongSelf.balance); - } - }); - }); -} - -- (void)recoverWalletUsingPassphrase:(NSString *)passphrase completion:(void (^)(NSError *_Nullable))completion -{ - const auto __weak weakSelf = self; - // Results that can come from CreateWallet(): - // - LEDGER_OK: Good to go - // - LEDGER_ERROR: Recovery failed - ledger->RecoverWallet(std::string(passphrase.UTF8String), - ^(const ledger::type::Result result) { - const auto strongSelf = weakSelf; - if (!strongSelf) { return; } - NSError *error = nil; - if (result != ledger::type::Result::LEDGER_OK) { - std::map errorDescriptions { - { ledger::type::Result::LEDGER_ERROR, "The recovery failed" }, - }; - NSDictionary *userInfo = @{}; - const auto description = errorDescriptions[result]; - if (description.length() > 0) { - userInfo = @{ NSLocalizedDescriptionKey: [NSString stringWithUTF8String:description.c_str()] }; - } - error = [NSError errorWithDomain:BATBraveLedgerErrorDomain code:static_cast(result) userInfo:userInfo]; - } - if (completion) { - completion(error); - } - } - ); -} - -- (void)hasSufficientBalanceToReconcile:(void (^)(BOOL))completion -{ - ledger->HasSufficientBalanceToReconcile(completion); -} - -- (void)pendingContributionsTotal:(void (^)(double amount))completion -{ - ledger->GetPendingContributionsTotal(^(double total){ - completion(total); - }); -} - -- (void)linkBraveWalletToPaymentId:(NSString *)paymentId completion:(void (^)(BATResult result, NSString *drainID))completion -{ - ledger->LinkBraveWallet(paymentId.UTF8String, ^(ledger::type::Result result, std::string drain_id) { - completion(static_cast(result), [NSString stringWithUTF8String:drain_id.c_str()]); - }); -} - -- (void)drainStatusForDrainId:(NSString *)drainId completion:(void (^)(BATResult result, BATDrainStatus status))completion -{ - ledger->GetDrainStatus(drainId.UTF8String, ^(ledger::type::Result result, ledger::type::DrainStatus status) { - completion(static_cast(result), - static_cast(status)); - }); -} - -- (void)transferrableAmount:(void (^)(double amount))completion -{ - ledger->GetTransferableAmount(^(double amount) { - completion(amount); - }); -} - -#pragma mark - User Wallets - -- (void)fetchUpholdWallet: - (nullable void (^)(BATExternalWallet* _Nullable wallet))completion { - const auto __weak weakSelf = self; - ledger->GetExternalWallet(ledger::constant::kWalletUphold, ^( - ledger::type::Result result, - ledger::type::ExternalWalletPtr walletPtr) { - if (result == ledger::type::Result::LEDGER_OK && - walletPtr.get() != nullptr) { - const auto bridgedWallet = - [[BATExternalWallet alloc] initWithExternalWallet:*walletPtr]; - weakSelf.upholdWallet = bridgedWallet; - if (completion) { - completion(bridgedWallet); - } - } else { - if (completion) { - completion(nil); - } - } - }); -} - -- (void)disconnectWalletOfType:(BATWalletType)walletType - completion:(nullable void (^)(BATResult result))completion -{ - ledger->DisconnectWallet(walletType.UTF8String, ^(ledger::type::Result result){ - if (completion) { - completion(static_cast(result)); - } - - for (BATBraveLedgerObserver *observer in self.observers) { - if (observer.externalWalletDisconnected) { - observer.externalWalletDisconnected(walletType); - } - } - }); -} - -- (void)authorizeExternalWalletOfType:(BATWalletType)walletType - queryItems:(NSDictionary *)queryItems - completion:(void (^)(BATResult result, NSURL * _Nullable redirectURL))completion -{ - ledger->ExternalWalletAuthorization(walletType.UTF8String, - MapFromNSDictionary(queryItems), - ^(ledger::type::Result result, base::flat_map args) { - const auto it = args.find("redirect_url"); - std::string redirect; - if (it != args.end()) { - redirect = it->second; - } - NSURL *url = redirect.empty() ? nil : [NSURL URLWithString:[NSString stringWithUTF8String:redirect.c_str()]]; - completion(static_cast(result), url); - - if (result == ledger::type::Result::LEDGER_OK) { - for (BATBraveLedgerObserver *observer in self.observers) { - if (observer.externalWalletAuthorized) { - observer.externalWalletAuthorized(walletType); - } - } - } - }); -} - -- (std::string)getLegacyWallet -{ - NSDictionary *externalWallets = self.prefs[kExternalWalletsPrefKey] ?: [[NSDictionary alloc] init]; - std::string wallet; - NSData *data = [NSJSONSerialization dataWithJSONObject:externalWallets options:0 error:nil]; - if (data != nil) { - NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - if (dataString.UTF8String != nil) { - wallet = dataString.UTF8String; - } - } - return wallet; -} - -#pragma mark - Publishers - -- (void)listActivityInfoFromStart:(unsigned int)start - limit:(unsigned int)limit - filter:(BATActivityInfoFilter *)filter - completion:(void (NS_NOESCAPE ^)(NSArray *))completion -{ - auto cppFilter = filter ? filter.cppObjPtr : ledger::type::ActivityInfoFilter::New(); - if (filter.excluded == BATExcludeFilterFilterExcluded) { - ledger->GetExcludedList(^(ledger::type::PublisherInfoList list) { - const auto publishers = NSArrayFromVector(&list, ^BATPublisherInfo *(const ledger::type::PublisherInfoPtr& info){ - return [[BATPublisherInfo alloc] initWithPublisherInfo:*info]; - }); - completion(publishers); - }); - } else { - ledger->GetActivityInfoList(start, limit, std::move(cppFilter), ^(ledger::type::PublisherInfoList list) { - const auto publishers = NSArrayFromVector(&list, ^BATPublisherInfo *(const ledger::type::PublisherInfoPtr& info){ - return [[BATPublisherInfo alloc] initWithPublisherInfo:*info]; - }); - completion(publishers); - }); - } -} - -- (void)fetchPublisherActivityFromURL:(NSURL *)URL - faviconURL:(nullable NSURL *)faviconURL - publisherBlob:(nullable NSString *)publisherBlob - tabId:(uint64_t)tabId -{ - if (!URL.absoluteString) { - return; - } - - GURL parsedUrl(base::SysNSStringToUTF8(URL.absoluteString)); - - if (!parsedUrl.is_valid()) { - return; - } - - auto origin = parsedUrl.GetOrigin(); - std::string baseDomain = - GetDomainAndRegistry(origin.host(), net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); - - if (baseDomain == "") { - return; - } - - ledger::type::VisitDataPtr visitData = ledger::type::VisitData::New(); - visitData->domain = visitData->name = baseDomain; - visitData->path = parsedUrl.PathForRequest(); - visitData->url = origin.spec(); - - if (faviconURL.absoluteString) { - visitData->favicon_url = base::SysNSStringToUTF8(faviconURL.absoluteString); - } - - std::string blob = std::string(); - if (publisherBlob) { - blob = base::SysNSStringToUTF8(publisherBlob); - } - - ledger->GetPublisherActivityFromUrl(tabId, std::move(visitData), blob); -} - -- (void)updatePublisherExclusionState:(NSString *)publisherId state:(BATPublisherExclude)state -{ - ledger->SetPublisherExclude(std::string(publisherId.UTF8String), (ledger::type::PublisherExclude)state, ^(const ledger::type::Result result) { - if (result != ledger::type::Result::LEDGER_OK) { - return; - } - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.excludedSitesChanged) { - observer.excludedSitesChanged(publisherId, - state); - } - } - }); -} - -- (void)restoreAllExcludedPublishers -{ - ledger->RestorePublishers(^(const ledger::type::Result result) { - if (result != ledger::type::Result::LEDGER_OK) { - return; - } - - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.excludedSitesChanged) { - observer.excludedSitesChanged(@"-1", - static_cast(ledger::type::PublisherExclude::ALL)); - } - } - }); -} - -- (void)publisherBannerForId:(NSString *)publisherId completion:(void (^)(BATPublisherBanner * _Nullable banner))completion -{ - ledger->GetPublisherBanner(std::string(publisherId.UTF8String), ^(ledger::type::PublisherBannerPtr banner) { - auto bridgedBanner = banner.get() != nullptr ? [[BATPublisherBanner alloc] initWithPublisherBanner:*banner] : nil; - // native libs prefixes the logo and background image with this URL scheme - const auto imagePrefix = @"chrome://rewards-image/"; - bridgedBanner.background = [bridgedBanner.background stringByReplacingOccurrencesOfString:imagePrefix withString:@""]; - bridgedBanner.logo = [bridgedBanner.logo stringByReplacingOccurrencesOfString:imagePrefix withString:@""]; - completion(bridgedBanner); - }); -} - -- (void)refreshPublisherWithId:(NSString *)publisherId completion:(void (^)(BATPublisherStatus status))completion -{ - if (self.loadingPublisherList) { - completion(BATPublisherStatusNotVerified); - return; - } - ledger->RefreshPublisher(std::string(publisherId.UTF8String), ^(ledger::type::PublisherStatus status) { - completion(static_cast(status)); - }); -} - -#pragma mark - SKUs - -- (void)processSKUItems:(NSArray *)items - completion:(void (^)(BATResult result, NSString *orderID))completion -{ - ledger->ProcessSKU(VectorFromNSArray(items, ^ledger::type::SKUOrderItem(BATSKUOrderItem *item) { - return *item.cppObjPtr; - }), ledger::constant::kWalletUnBlinded, ^(const ledger::type::Result result, const std::string& order_id) { - completion(static_cast(result), [NSString stringWithUTF8String:order_id.c_str()]); - }); -} - -#pragma mark - Tips - -- (void)listRecurringTips:(void (^)(NSArray *))completion -{ - ledger->GetRecurringTips(^(ledger::type::PublisherInfoList list){ - const auto publishers = NSArrayFromVector(&list, ^BATPublisherInfo *(const ledger::type::PublisherInfoPtr& info){ - return [[BATPublisherInfo alloc] initWithPublisherInfo:*info]; - }); - completion(publishers); - }); -} - -- (void)addRecurringTipToPublisherWithId:(NSString *)publisherId amount:(double)amount completion:(void (^)(BOOL success))completion -{ - ledger::type::RecurringTipPtr info = ledger::type::RecurringTip::New(); - info->publisher_key = publisherId.UTF8String; - info->amount = amount; - info->created_at = [[NSDate date] timeIntervalSince1970]; - ledger->SaveRecurringTip(std::move(info), ^(ledger::type::Result result){ - const auto success = (result == ledger::type::Result::LEDGER_OK); - if (success) { - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.recurringTipAdded) { - observer.recurringTipAdded(publisherId); - } - } - } - completion(success); - }); -} - -- (void)removeRecurringTipForPublisherWithId:(NSString *)publisherId -{ - ledger->RemoveRecurringTip(std::string(publisherId.UTF8String), ^(ledger::type::Result result){ - if (result == ledger::type::Result::LEDGER_OK) { - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.recurringTipRemoved) { - observer.recurringTipRemoved(publisherId); - } - } - } - }); -} - -- (void)listOneTimeTips:(void (^)(NSArray *))completion -{ - ledger->GetOneTimeTips(^(ledger::type::PublisherInfoList list){ - const auto publishers = NSArrayFromVector(&list, ^BATPublisherInfo *(const ledger::type::PublisherInfoPtr& info){ - return [[BATPublisherInfo alloc] initWithPublisherInfo:*info]; - }); - completion(publishers); - }); -} - -- (void)tipPublisherDirectly:(BATPublisherInfo *)publisher amount:(double)amount currency:(NSString *)currency completion:(void (^)(BATResult result))completion -{ - ledger->OneTimeTip(std::string(publisher.id.UTF8String), amount, ^(ledger::type::Result result) { - completion(static_cast(result)); - }); -} - -#pragma mark - Grants - -- (NSArray *)pendingPromotions -{ - return [self.mPendingPromotions copy]; -} - -- (NSArray *)finishedPromotions -{ - return [self.mFinishedPromotions copy]; -} - -- (NSString *)notificationIDForPromo:(const ledger::type::PromotionPtr)promo -{ - bool isUGP = promo->type == ledger::type::PromotionType::UGP; - const auto prefix = isUGP ? @"rewards_grant_" : @"rewards_grant_ads_"; - const auto promotionId = [NSString stringWithUTF8String:promo->id.c_str()]; - return [NSString stringWithFormat:@"%@%@", prefix, promotionId]; -} - -- (void)updatePendingAndFinishedPromotions:(void (^)())completion -{ - ledger->GetAllPromotions(^(ledger::type::PromotionMap map) { - NSMutableArray *promos = [[NSMutableArray alloc] init]; - for (auto it = map.begin(); it != map.end(); ++it) { - if (it->second.get() != nullptr) { - [promos addObject:[[BATPromotion alloc] initWithPromotion:*it->second]]; - } - } - for (BATPromotion *promo in [self.mPendingPromotions copy]) { - [self clearNotificationWithID:[self notificationIDForPromo:promo.cppObjPtr]]; - } - [self.mFinishedPromotions removeAllObjects]; - [self.mPendingPromotions removeAllObjects]; - for (BATPromotion *promotion in promos) { - if (promotion.status == BATPromotionStatusFinished) { - [self.mFinishedPromotions addObject:promotion]; - - if (promotion.type == BATPromotionTypeAds) { - [self.ads reconcileAdRewards]; - } - } else if (promotion.status == BATPromotionStatusActive || - promotion.status == BATPromotionStatusAttested) { - [self.mPendingPromotions addObject:promotion]; - bool isUGP = promotion.type == BATPromotionTypeUgp; - auto notificationKind = isUGP ? BATRewardsNotificationKindGrant : BATRewardsNotificationKindGrantAds; - - [self addNotificationOfKind:notificationKind - userInfo:nil - notificationID:[self notificationIDForPromo:promotion.cppObjPtr] - onlyOnce:YES]; - } - } - if (completion) { - completion(); - } - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.promotionsAdded) { - observer.promotionsAdded(self.pendingPromotions); - } - if (observer.finishedPromotionsAdded) { - observer.finishedPromotionsAdded(self.finishedPromotions); - } - } - }); -} - -- (void)fetchPromotions:(nullable void (^)(NSArray *grants))completion -{ - ledger->FetchPromotions(^(ledger::type::Result result, std::vector promotions) { - if (result != ledger::type::Result::LEDGER_OK) { - return; - } - [self updatePendingAndFinishedPromotions:^{ - if (completion) { - completion(self.pendingPromotions); - } - }]; - }); -} - -- (void)claimPromotion:(NSString *)promotionId publicKey:(NSString *)deviceCheckPublicKey completion:(void (^)(BATResult result, NSString * _Nonnull nonce))completion -{ - const auto payload = [NSDictionary dictionaryWithObject:deviceCheckPublicKey forKey:@"publicKey"]; - const auto jsonData = [NSJSONSerialization dataWithJSONObject:payload options:0 error:nil]; - if (!jsonData) { - BLOG(0, @"Missing JSON payload while attempting to claim promotion"); - return; - } - const auto jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; - ledger->ClaimPromotion(promotionId.UTF8String, jsonString.UTF8String, ^(const ledger::type::Result result, const std::string& nonce) { - const auto bridgedNonce = [NSString stringWithUTF8String:nonce.c_str()]; - dispatch_async(dispatch_get_main_queue(), ^{ - completion(static_cast(result), bridgedNonce); - }); - }); -} - -- (void)attestPromotion:(NSString *)promotionId solution:(BATPromotionSolution *)solution completion:(void (^)(BATResult result, BATPromotion * _Nullable promotion))completion -{ - ledger->AttestPromotion(std::string(promotionId.UTF8String), solution.JSONPayload.UTF8String, ^(const ledger::type::Result result, ledger::type::PromotionPtr promotion) { - if (promotion.get() == nullptr) { - if (completion) { - dispatch_async(dispatch_get_main_queue(), ^{ - completion(static_cast(result), nil); - }); - } - return; - } - - const auto bridgedPromotion = [[BATPromotion alloc] initWithPromotion:*promotion]; - if (result == ledger::type::Result::LEDGER_OK) { - [self fetchBalance:nil]; - [self clearNotificationWithID:[self notificationIDForPromo:std::move(promotion)]]; - } - - dispatch_async(dispatch_get_main_queue(), ^{ - if (completion) { - completion(static_cast(result), bridgedPromotion); - } - if (result == ledger::type::Result::LEDGER_OK) { - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.promotionClaimed) { - observer.promotionClaimed(bridgedPromotion); - } - } - } - }); - }); -} - -#pragma mark - History - -- (void)balanceReportForMonth:(BATActivityMonth)month year:(int)year completion:(void (^)(BATBalanceReportInfo * _Nullable info))completion -{ - ledger->GetBalanceReport((ledger::type::ActivityMonth)month, year, ^(const ledger::type::Result result, ledger::type::BalanceReportInfoPtr info) { - auto bridgedInfo = info.get() != nullptr ? [[BATBalanceReportInfo alloc] initWithBalanceReportInfo:*info.get()] : nil; - completion(result == ledger::type::Result::LEDGER_OK ? bridgedInfo : nil); - }); -} - -- (BATAutoContributeProperties *)autoContributeProperties -{ - ledger::type::AutoContributePropertiesPtr props = ledger->GetAutoContributeProperties(); - return [[BATAutoContributeProperties alloc] initWithAutoContributePropertiesPtr:std::move(props)]; -} - -#pragma mark - Pending Contributions - -- (void)pendingContributions:(void (^)(NSArray *publishers))completion -{ - ledger->GetPendingContributions(^(ledger::type::PendingContributionInfoList list){ - const auto convetedList = NSArrayFromVector(&list, ^BATPendingContributionInfo *(const ledger::type::PendingContributionInfoPtr& info){ - return [[BATPendingContributionInfo alloc] initWithPendingContributionInfo:*info]; - }); - completion(convetedList); - }); -} - -- (void)removePendingContribution:(BATPendingContributionInfo *)info completion:(void (^)(BATResult result))completion -{ - ledger->RemovePendingContribution(info.id, - ^(const ledger::type::Result result){ - completion(static_cast(result)); - }); -} - -- (void)removeAllPendingContributions:(void (^)(BATResult result))completion -{ - ledger->RemoveAllPendingContributions(^(const ledger::type::Result result){ - completion(static_cast(result)); - }); -} - -#pragma mark - Reconcile - -- (void)onReconcileComplete:(ledger::type::Result)result contribution:(ledger::type::ContributionInfoPtr)contribution -{ - // TODO we changed from probi to amount, so from string to double - if (result == ledger::type::Result::LEDGER_OK) { - if (contribution->type == ledger::type::RewardsType::RECURRING_TIP) { - [self showTipsProcessedNotificationIfNeccessary]; - } - [self fetchBalance:nil]; - } - - if ((result == ledger::type::Result::LEDGER_OK && contribution->type == ledger::type::RewardsType::AUTO_CONTRIBUTE) || - result == ledger::type::Result::LEDGER_ERROR || - result == ledger::type::Result::NOT_ENOUGH_FUNDS || - result == ledger::type::Result::TIP_ERROR) { - const auto contributionId = [NSString stringWithUTF8String:contribution->contribution_id.c_str()]; - const auto info = @{ @"viewingId": contributionId, - @"result": @((BATResult)result), - @"type": @((BATRewardsType)contribution->type), - @"amount": [@(contribution->amount) stringValue] }; - - [self addNotificationOfKind:BATRewardsNotificationKindAutoContribute - userInfo:info - notificationID:[NSString stringWithFormat:@"contribution_%@", contributionId]]; - } - - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.balanceReportUpdated) { - observer.balanceReportUpdated(); - } - if (observer.reconcileCompleted) { - observer.reconcileCompleted(static_cast(result), - [NSString stringWithUTF8String:contribution->contribution_id.c_str()], - static_cast(contribution->type), - [@(contribution->amount) stringValue]); - } - } -} - -#pragma mark - Misc - -+ (bool)isMediaURL:(NSURL *)url firstPartyURL:(NSURL *)firstPartyURL referrerURL:(NSURL *)referrerURL -{ - std::string referrer = referrerURL != nil ? referrerURL.absoluteString.UTF8String : ""; - return ledger::Ledger::IsMediaLink(url.absoluteString.UTF8String, - firstPartyURL.absoluteString.UTF8String, - referrer); -} - -- (void)rewardsInternalInfo:(void (NS_NOESCAPE ^)(BATRewardsInternalsInfo * _Nullable info))completion -{ - ledger->GetRewardsInternalsInfo(^(ledger::type::RewardsInternalsInfoPtr info) { - auto bridgedInfo = info.get() != nullptr ? [[BATRewardsInternalsInfo alloc] initWithRewardsInternalsInfo:*info.get()] : nil; - completion(bridgedInfo); - }); -} - -- (void)allContributions:(void (^)(NSArray *contributions))completion -{ - ledger->GetAllContributions(^(ledger::type::ContributionInfoList list) { - const auto convetedList = NSArrayFromVector(&list, ^BATContributionInfo *(const ledger::type::ContributionInfoPtr& info){ - return [[BATContributionInfo alloc] initWithContributionInfo:*info]; - }); - completion(convetedList); - }); -} - -#pragma mark - Reporting - -- (void)setSelectedTabId:(UInt32)selectedTabId -{ - if (!self.initialized) { return; } - - if (_selectedTabId != selectedTabId) { - ledger->OnHide(_selectedTabId, [[NSDate date] timeIntervalSince1970]); - } - _selectedTabId = selectedTabId; - if (_selectedTabId > 0) { - ledger->OnShow(_selectedTabId, [[NSDate date] timeIntervalSince1970]); - } -} - -- (void)applicationDidBecomeActive -{ - if (!self.initialized) { return; } - - ledger->OnForeground(self.selectedTabId, [[NSDate date] timeIntervalSince1970]); - - // Check if the last notification check was more than a day ago - if (fabs([self.lastNotificationCheckDate timeIntervalSinceNow]) > kOneDay) { - [self checkForNotificationsAndFetchGrants]; - } -} - -- (void)applicationDidBackground -{ - if (!self.initialized) { return; } - - ledger->OnBackground(self.selectedTabId, [[NSDate date] timeIntervalSince1970]); -} - -- (void)reportLoadedPageWithURL:(NSURL *)url tabId:(UInt32)tabId -{ - if (!self.initialized) { return; } - - GURL parsedUrl(url.absoluteString.UTF8String); - auto origin = parsedUrl.GetOrigin(); - const std::string baseDomain = - GetDomainAndRegistry(origin.host(), net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); - - if (baseDomain == "") { - return; - } - - const std::string publisher_url = origin.scheme() + "://" + baseDomain + "/"; - - ledger::type::VisitDataPtr data = ledger::type::VisitData::New(); - data->tld = data->name = baseDomain; - data->domain = origin.host(); - data->path = parsedUrl.path(); - data->tab_id = tabId; - data->url = publisher_url; - - ledger->OnLoad(std::move(data), [[NSDate date] timeIntervalSince1970]); -} - -- (void)reportXHRLoad:(NSURL *)url tabId:(UInt32)tabId firstPartyURL:(NSURL *)firstPartyURL referrerURL:(NSURL *)referrerURL -{ - if (!self.initialized) { return; } - - base::flat_map partsMap; - const auto urlComponents = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:NO]; - for (NSURLQueryItem *item in urlComponents.queryItems) { - std::string value = item.value != nil ? item.value.UTF8String : ""; - partsMap[std::string(item.name.UTF8String)] = value; - } - - auto visit = ledger::type::VisitData::New(); - visit->path = url.absoluteString.UTF8String; - visit->tab_id = tabId; - - std::string ref = referrerURL != nil ? referrerURL.absoluteString.UTF8String : ""; - std::string fpu = firstPartyURL != nil ? firstPartyURL.absoluteString.UTF8String : ""; - - ledger->OnXHRLoad(tabId, - url.absoluteString.UTF8String, - partsMap, - fpu, - ref, - std::move(visit)); -} - -- (void)reportPostData:(NSData *)postData url:(NSURL *)url tabId:(UInt32)tabId firstPartyURL:(NSURL *)firstPartyURL referrerURL:(NSURL *)referrerURL -{ - if (!self.initialized) { return; } - - GURL parsedUrl(url.absoluteString.UTF8String); - if (!parsedUrl.is_valid()) { - return; - } - - const auto postDataString = [[[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding] stringByRemovingPercentEncoding]; - - auto visit = ledger::type::VisitData::New(); - visit->path = parsedUrl.spec(); - visit->tab_id = tabId; - - std::string ref = referrerURL != nil ? referrerURL.absoluteString.UTF8String : ""; - std::string fpu = firstPartyURL != nil ? firstPartyURL.absoluteString.UTF8String : ""; - - ledger->OnPostData(parsedUrl.spec(), - fpu, - ref, - postDataString.UTF8String, - std::move(visit)); -} - -- (void)reportTabNavigationOrClosedWithTabId:(UInt32)tabId -{ - if (!self.initialized) { return; } - - ledger->OnUnload(tabId, [[NSDate date] timeIntervalSince1970]); -} - -#pragma mark - Preferences - -BATLedgerBridge(int, - minimumVisitDuration, setMinimumVisitDuration, - GetPublisherMinVisitTime, SetPublisherMinVisitTime) - -BATLedgerBridge(int, - minimumNumberOfVisits, setMinimumNumberOfVisits, - GetPublisherMinVisits, SetPublisherMinVisits) - -BATLedgerBridge(BOOL, - allowUnverifiedPublishers, setAllowUnverifiedPublishers, - GetPublisherAllowNonVerified, SetPublisherAllowNonVerified) - -BATLedgerBridge(BOOL, - allowVideoContributions, setAllowVideoContributions, - GetPublisherAllowVideos, SetPublisherAllowVideos) - -BATLedgerReadonlyBridge(double, contributionAmount, GetAutoContributionAmount) - -- (void)setContributionAmount:(double)contributionAmount -{ - ledger->SetAutoContributionAmount(contributionAmount); -} - -BATLedgerBridge(BOOL, - isAutoContributeEnabled, setAutoContributeEnabled, - GetAutoContributeEnabled, SetAutoContributeEnabled) - -- (void)setBooleanState:(const std::string&)name value:(bool)value -{ - const auto key = [NSString stringWithUTF8String:name.c_str()]; - self.prefs[key] = [NSNumber numberWithBool:value]; - [self savePrefs]; -} - -- (bool)getBooleanState:(const std::string&)name -{ - const auto key = [NSString stringWithUTF8String:name.c_str()]; - if (![self.prefs objectForKey:key]) { - return NO; - } - - return [self.prefs[key] boolValue]; -} - -- (void)setIntegerState:(const std::string&)name value:(int)value -{ - const auto key = [NSString stringWithUTF8String:name.c_str()]; - self.prefs[key] = [NSNumber numberWithInt:value]; - [self savePrefs]; -} - -- (int)getIntegerState:(const std::string&)name -{ - const auto key = [NSString stringWithUTF8String:name.c_str()]; - return [self.prefs[key] intValue]; -} - -- (void)setDoubleState:(const std::string&)name value:(double)value -{ - const auto key = [NSString stringWithUTF8String:name.c_str()]; - self.prefs[key] = [NSNumber numberWithDouble:value]; - [self savePrefs]; -} - -- (double)getDoubleState:(const std::string&)name -{ - const auto key = [NSString stringWithUTF8String:name.c_str()]; - return [self.prefs[key] doubleValue]; -} - -- (void)setStringState:(const std::string&)name value:(const std::string&)value -{ - const auto key = [NSString stringWithUTF8String:name.c_str()]; - self.prefs[key] = [NSString stringWithUTF8String:value.c_str()]; - [self savePrefs]; -} - -- (std::string)getStringState:(const std::string&)name -{ - const auto key = [NSString stringWithUTF8String:name.c_str()]; - const auto value = (NSString *)self.prefs[key]; - if (!value) { return ""; } - return value.UTF8String; -} - -- (void)setInt64State:(const std::string&)name value:(int64_t)value -{ - const auto key = [NSString stringWithUTF8String:name.c_str()]; - self.prefs[key] = [NSNumber numberWithLongLong:value]; - [self savePrefs]; -} - -- (int64_t)getInt64State:(const std::string&)name -{ - const auto key = [NSString stringWithUTF8String:name.c_str()]; - return [self.prefs[key] longLongValue]; -} - -- (void)setUint64State:(const std::string&)name value:(uint64_t)value -{ - const auto key = [NSString stringWithUTF8String:name.c_str()]; - self.prefs[key] = [NSNumber numberWithUnsignedLongLong:value]; - [self savePrefs]; -} - -- (uint64_t)getUint64State:(const std::string&)name -{ - const auto key = [NSString stringWithUTF8String:name.c_str()]; - return [self.prefs[key] unsignedLongLongValue]; -} - -- (void)clearState:(const std::string&)name -{ - const auto key = [NSString stringWithUTF8String:name.c_str()]; - [self.prefs removeObjectForKey:key]; - [self savePrefs]; -} - -- (bool)getBooleanOption:(const std::string&)name -{ - DCHECK(!name.empty()); - - const auto it = kBoolOptions.find(name); - DCHECK(it != kBoolOptions.end()); - - return kBoolOptions.at(name); -} - -- (int)getIntegerOption:(const std::string&)name -{ - DCHECK(!name.empty()); - - const auto it = kIntegerOptions.find(name); - DCHECK(it != kIntegerOptions.end()); - - return kIntegerOptions.at(name); -} - -- (double)getDoubleOption:(const std::string&)name -{ - DCHECK(!name.empty()); - - const auto it = kDoubleOptions.find(name); - DCHECK(it != kDoubleOptions.end()); - - return kDoubleOptions.at(name); -} - -- (std::string)getStringOption:(const std::string&)name -{ - DCHECK(!name.empty()); - - const auto it = kStringOptions.find(name); - DCHECK(it != kStringOptions.end()); - - return kStringOptions.at(name); -} - -- (int64_t)getInt64Option:(const std::string&)name -{ - DCHECK(!name.empty()); - - const auto it = kInt64Options.find(name); - DCHECK(it != kInt64Options.end()); - - return kInt64Options.at(name); -} - -- (uint64_t)getUint64Option:(const std::string&)name -{ - DCHECK(!name.empty()); - - const auto it = kUInt64Options.find(name); - DCHECK(it != kUInt64Options.end()); - - return kUInt64Options.at(name); -} - -#pragma mark - Notifications - -- (NSArray *)notifications -{ - return [self.mNotifications copy]; -} - -- (void)clearNotificationWithID:(NSString *)notificationID -{ - for (BATRewardsNotification *n in self.notifications) { - if ([n.id isEqualToString:notificationID]) { - [self clearNotification:n]; - return; - } - } -} - -- (void)clearNotification:(BATRewardsNotification *)notification -{ - [self.mNotifications removeObject:notification]; - [self writeNotificationsToDisk]; - - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.notificationsRemoved) { - observer.notificationsRemoved(@[notification]); - } - } -} - -- (void)clearAllNotifications -{ - NSArray *notifications = [self.mNotifications copy]; - [self.mNotifications removeAllObjects]; - [self writeNotificationsToDisk]; - - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.notificationsRemoved) { - observer.notificationsRemoved(notifications); - } - } -} - -- (void)startNotificationTimers -{ - dispatch_async(dispatch_get_main_queue(), ^{ - // Startup timer, begins after 30-second delay. - self.notificationStartupTimer = - [NSTimer scheduledTimerWithTimeInterval:30 - target:self - selector:@selector(checkForNotificationsAndFetchGrants) - userInfo:nil - repeats:NO]; - }); - -} - -- (void)checkForNotificationsAndFetchGrants -{ - self.lastNotificationCheckDate = [NSDate date]; - - [self showBackupNotificationIfNeccessary]; - [self showAddFundsNotificationIfNeccessary]; - [self fetchPromotions:nil]; -} - -- (void)showBackupNotificationIfNeccessary -{ - // This is currently not required as the user cannot manage their wallet on mobile... yet - /* - auto bootstamp = ledger->GetCreationStamp(); - auto userFunded = [self.prefs[kUserHasFundedKey] boolValue]; - auto backupSucceeded = [self.prefs[kBackupSucceededKey] boolValue]; - if (userFunded && !backupSucceeded) { - auto frequency = 10; [self.prefs[kBackupNotificationFrequencyKey] doubleValue]; - auto interval = 10; [self.prefs[kBackupNotificationIntervalKey] doubleValue]; - auto delta = [[NSDate date] timeIntervalSinceDate:[NSDate dateWithTimeIntervalSince1970:bootstamp]]; - if (delta > interval) { - auto nextBackupNotificationInterval = frequency + interval; - self.prefs[kBackupNotificationIntervalKey] = @(nextBackupNotificationInterval); - [self savePrefs]; - [self addNotificationOfKind:BATRewardsNotificationKindBackupWallet - arguments:nil - notificationID:@"rewards_notification_backup_wallet"]; - } - } - */ -} - -- (void)showAddFundsNotificationIfNeccessary -{ - const auto stamp = ledger->GetReconcileStamp(); - const auto now = [[NSDate date] timeIntervalSince1970]; - - // Show add funds notification if reconciliation will occur in the - // next 3 days and balance is too low. - if (stamp - now > 3 * kOneDay) { - return; - } - // Make sure it hasnt already been shown - const auto upcomingAddFundsNotificationTime = [self.prefs[kNextAddFundsDateNotificationKey] doubleValue]; - if (upcomingAddFundsNotificationTime != 0.0 && - now < upcomingAddFundsNotificationTime) { - return; - } - - const auto __weak weakSelf = self; - // Make sure they don't have a sufficient balance - [self hasSufficientBalanceToReconcile:^(BOOL sufficient) { - if (sufficient) { - return; - } - const auto strongSelf = weakSelf; - - // Set next add funds notification in 3 days - const auto nextTime = [[NSDate date] timeIntervalSince1970] + (kOneDay * 3); - strongSelf.prefs[kNextAddFundsDateNotificationKey] = @(nextTime); - [strongSelf savePrefs]; - - [strongSelf addNotificationOfKind:BATRewardsNotificationKindInsufficientFunds - userInfo:nil - notificationID:@"rewards_notification_insufficient_funds"]; - }]; -} - -- (void)showTipsProcessedNotificationIfNeccessary -{ - if (!self.autoContributeEnabled) { - return; - } - [self addNotificationOfKind:BATRewardsNotificationKindTipsProcessed - userInfo:nil - notificationID:@"rewards_notification_tips_processed"]; -} - -- (void)addNotificationOfKind:(BATRewardsNotificationKind)kind - userInfo:(nullable NSDictionary *)userInfo - notificationID:(nullable NSString *)identifier -{ - [self addNotificationOfKind:kind userInfo:userInfo notificationID:identifier onlyOnce:NO]; -} - -- (void)addNotificationOfKind:(BATRewardsNotificationKind)kind - userInfo:(nullable NSDictionary *)userInfo - notificationID:(nullable NSString *)identifier - onlyOnce:(BOOL)onlyOnce -{ - NSParameterAssert(kind != BATRewardsNotificationKindInvalid); - NSString *notificationID = [identifier copy]; - if (!identifier || identifier.length == 0) { - notificationID = [NSUUID UUID].UUIDString; - } else if (onlyOnce) { - const auto idx = [self.mNotifications indexOfObjectPassingTest:^BOOL(BATRewardsNotification * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { - return obj.displayed && [obj.id isEqualToString:identifier]; - }]; - if (idx != NSNotFound) { - return; - } - } - - const auto notification = [[BATRewardsNotification alloc] initWithID:notificationID - dateAdded:[[NSDate date] timeIntervalSince1970] - kind:kind - userInfo:userInfo]; - if (onlyOnce) { - notification.displayed = YES; - } - - [self.mNotifications addObject:notification]; - - // Post to observers - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.notificationAdded) { - observer.notificationAdded(notification); - } - } - - [NSNotificationCenter.defaultCenter postNotificationName:BATBraveLedgerNotificationAdded object:nil]; - - [self writeNotificationsToDisk]; -} - -- (void)readNotificationsFromDisk -{ - const auto path = [self.storagePath stringByAppendingPathComponent:@"notifications"]; - const auto data = [NSData dataWithContentsOfFile:path]; - if (!data) { - // Nothing to read - self.mNotifications = [[NSMutableArray alloc] init]; - return; - } - - NSError *error; - self.mNotifications = [NSKeyedUnarchiver unarchivedObjectOfClass:NSArray.self fromData:data error:&error]; - if (!self.mNotifications) { - self.mNotifications = [[NSMutableArray alloc] init]; - if (error) { - BLOG(0, @"Failed to unarchive notifications on disk: %@", error.debugDescription); - } - } -} - -- (void)writeNotificationsToDisk -{ - const auto path = [self.storagePath stringByAppendingPathComponent:@"notifications"]; - if (self.notifications.count == 0) { - // Nothing to write, delete anything we have stored - if ([[NSFileManager defaultManager] fileExistsAtPath:path]) { - [[NSFileManager defaultManager] removeItemAtPath:path error:nil]; - } - return; - } - - NSError *error; - const auto data = [NSKeyedArchiver archivedDataWithRootObject:self.notifications - requiringSecureCoding:YES - error:&error]; - if (!data) { - if (error) { - BLOG(0, @"Failed to write notifications to disk: %@", error.debugDescription); - } - return; - } - - [data writeToURL:[NSURL fileURLWithPath:path isDirectory:NO] options:NSDataWritingAtomic error:nil]; -} - -#pragma mark - State - -- (void)loadLedgerState:(ledger::client::OnLoadCallback)callback -{ - const auto contents = [self.commonOps loadContentsFromFileWithName:"ledger_state.json"]; - if (contents.length() > 0) { - callback(ledger::type::Result::LEDGER_OK, contents); - } else { - callback(ledger::type::Result::NO_LEDGER_STATE, contents); - } - [self startNotificationTimers]; -} - -- (void)loadPublisherState:(ledger::client::OnLoadCallback)callback -{ - const auto contents = [self.commonOps loadContentsFromFileWithName:"publisher_state.json"]; - if (contents.length() > 0) { - callback(ledger::type::Result::LEDGER_OK, contents); - } else { - callback(ledger::type::Result::NO_PUBLISHER_STATE, contents); - } -} - -- (void)loadState:(const std::string &)name callback:(ledger::client::OnLoadCallback)callback -{ - const auto key = [NSString stringWithUTF8String:name.c_str()]; - const auto value = self.state[key]; - if (value) { - callback(ledger::type::Result::LEDGER_OK, std::string(value.UTF8String)); - } else { - callback(ledger::type::Result::LEDGER_ERROR, ""); - } -} - -- (void)resetState:(const std::string &)name callback:(ledger::ResultCallback)callback -{ - const auto key = [NSString stringWithUTF8String:name.c_str()]; - self.state[key] = nil; - callback(ledger::type::Result::LEDGER_OK); - // In brave-core, failed callback returns `LEDGER_ERROR` - NSDictionary *state = [self.state copy]; - NSString *path = [self.randomStatePath copy]; - dispatch_async(self.fileWriteThread, ^{ - [state writeToURL:[NSURL fileURLWithPath:path isDirectory:NO] error:nil]; - }); -} - -- (void)saveState:(const std::string &)name value:(const std::string &)value callback:(ledger::ResultCallback)callback -{ - const auto key = [NSString stringWithUTF8String:name.c_str()]; - self.state[key] = [NSString stringWithUTF8String:value.c_str()]; - callback(ledger::type::Result::LEDGER_OK); - // In brave-core, failed callback returns `LEDGER_ERROR` - NSDictionary *state = [self.state copy]; - NSString *path = [self.randomStatePath copy]; - dispatch_async(self.fileWriteThread, ^{ - [state writeToURL:[NSURL fileURLWithPath:path isDirectory:NO] error:nil]; - }); -} - -#pragma mark - Network - -- (NSString *)customUserAgent -{ - return self.commonOps.customUserAgent; -} - -- (void)setCustomUserAgent:(NSString *)customUserAgent -{ - self.commonOps.customUserAgent = [customUserAgent stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; -} - -- (void)loadURL:(ledger::type::UrlRequestPtr)request callback:(ledger::client::LoadURLCallback)callback -{ - std::map methodMap{ - {ledger::type::UrlMethod::GET, "GET"}, - {ledger::type::UrlMethod::POST, "POST"}, - {ledger::type::UrlMethod::PUT, "PUT"}, - {ledger::type::UrlMethod::DEL, "DELETE"}}; - - if (!request) { - request = ledger::type::UrlRequest::New(); - } - - const auto copiedURL = [NSString stringWithUTF8String:request->url.c_str()]; - - return [self.commonOps loadURLRequest:request->url headers:request->headers content:request->content content_type:request->content_type method:methodMap[request->method] callback:^(const std::string& errorDescription, int statusCode, const std::string &response, const base::flat_map &headers) { - ledger::type::UrlResponse url_response; - url_response.url = copiedURL.UTF8String; - url_response.error = errorDescription; - url_response.status_code = statusCode; - url_response.body = response; - url_response.headers = headers; - - callback(url_response); - }]; -} - -- (std::string)URIEncode:(const std::string &)value -{ - const auto allowedCharacters = [NSMutableCharacterSet alphanumericCharacterSet]; - [allowedCharacters addCharactersInString:@"-._~"]; - const auto string = [NSString stringWithUTF8String:value.c_str()]; - const auto encoded = [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters]; - return std::string(encoded.UTF8String); -} - -- (void)fetchFavIcon:(const std::string &)url faviconKey:(const std::string &)favicon_key callback:(ledger::client::FetchIconCallback)callback -{ - const auto pageURL = [NSURL URLWithString:[NSString stringWithUTF8String:url.c_str()]]; - if (!self.faviconFetcher || !pageURL) { - dispatch_async(dispatch_get_main_queue(), ^{ - callback(NO, std::string()); - }); - return; - } - self.faviconFetcher(pageURL, ^(NSURL * _Nullable faviconURL) { - dispatch_async(dispatch_get_main_queue(), ^{ - callback(faviconURL != nil, - faviconURL.absoluteString.UTF8String); - }); - }); -} - -#pragma mark - Logging - -- (void)log:(const char *)file line:(const int)line verboseLevel:(const int)verbose_level message:(const std::string &) message -{ - rewards::LogMessage(file, line, verbose_level, [NSString stringWithUTF8String:message.c_str()]); -} - -#pragma mark - Publisher Database - -- (void)handlePublisherListing:(NSArray *)publishers start:(uint32_t)start limit:(uint32_t)limit callback:(ledger::PublisherInfoListCallback)callback -{ - callback(VectorFromNSArray(publishers, ^ledger::type::PublisherInfoPtr(BATPublisherInfo *info){ - return info.cppObjPtr; - })); -} -- (void)publisherListNormalized:(ledger::type::PublisherInfoList)list -{ - const auto list_converted = NSArrayFromVector(&list, ^BATPublisherInfo *(const ledger::type::PublisherInfoPtr& info) { - return [[BATPublisherInfo alloc] initWithPublisherInfo:*info]; - }); - - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.publisherListNormalized) { - observer.publisherListNormalized(list_converted); - } - } -} - -- (void)onPanelPublisherInfo:(ledger::type::Result)result publisherInfo:(ledger::type::PublisherInfoPtr)publisher_info windowId:(uint64_t)windowId -{ - if (publisher_info.get() == nullptr || result != ledger::type::Result::LEDGER_OK) { - return; - } - auto info = [[BATPublisherInfo alloc] initWithPublisherInfo:*publisher_info]; - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.fetchedPanelPublisher) { - observer.fetchedPanelPublisher(info, windowId); - } - } -} - -- (void)onContributeUnverifiedPublishers:(ledger::type::Result)result publisherKey:(const std::string &)publisher_key publisherName:(const std::string &)publisher_name -{ - switch (result) { - case ledger::type::Result::PENDING_NOT_ENOUGH_FUNDS: - [self addNotificationOfKind:BATRewardsNotificationKindPendingNotEnoughFunds - userInfo:nil - notificationID:@"not_enough_funds_for_pending"]; - break; - case ledger::type::Result::PENDING_PUBLISHER_REMOVED: { - const auto publisherID = [NSString stringWithUTF8String:publisher_key.c_str()]; - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.pendingContributionsRemoved) { - observer.pendingContributionsRemoved(@[publisherID]); - } - } - break; - } - case ledger::type::Result::VERIFIED_PUBLISHER: { - const auto notificationID = [NSString stringWithFormat:@"verified_publisher_%@", - [NSString stringWithUTF8String:publisher_key.c_str()]]; - const auto name = [NSString stringWithUTF8String:publisher_name.c_str()]; - [self addNotificationOfKind:BATRewardsNotificationKindVerifiedPublisher - userInfo:@{ @"publisher_name": name } - notificationID:notificationID]; - break; - } - default: - break; - } -} - -- (void)showNotification:(const std::string &)type args:(const std::vector&)args callback:(ledger::ResultCallback)callback -{ - const auto notificationID = [NSString stringWithUTF8String:type.c_str()]; - const auto info = [[NSMutableDictionary alloc] init]; - for (NSInteger i = 0; i < args.size(); i++) { - info[@(i)] = [NSString stringWithUTF8String:args[i].c_str()]; - } - [self addNotificationOfKind:BATRewardsNotificationKindGeneralLedger - userInfo:info - notificationID:notificationID - onlyOnce:NO]; -} -- (ledger::type::ClientInfoPtr)getClientInfo -{ - auto info = ledger::type::ClientInfo::New(); - info->os = ledger::type::OperatingSystem::UNDEFINED; - info->platform = ledger::type::Platform::IOS; - return info; -} - -- (void)unblindedTokensReady -{ - [self fetchBalance:nil]; - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.balanceReportUpdated) { - observer.balanceReportUpdated(); - } - } -} - -- (void)reconcileStampReset -{ - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.reconcileStampReset) { - observer.reconcileStampReset(); - } - } -} - -- (void)runDBTransaction:(ledger::type::DBTransactionPtr)transaction - callback:(ledger::client::RunDBTransactionCallback)callback -{ - __weak BATBraveLedger* weakSelf = self; - base::PostTaskAndReplyWithResult( - databaseQueue.get(), FROM_HERE, - base::BindOnce(&RunDBTransactionOnTaskRunner, std::move(transaction), - rewardsDatabase), - base::BindOnce(^(ledger::type::DBCommandResponsePtr response) { - if (weakSelf) - callback(std::move(response)); - })); -} - -- (void)pendingContributionSaved:(const ledger::type::Result)result -{ - for (BATBraveLedgerObserver *observer in [self.observers copy]) { - if (observer.pendingContributionAdded) { - observer.pendingContributionAdded(); - } - } -} - -- (void)walletDisconnected:(const std::string &)wallet_type -{ - const auto bridgedType = static_cast([NSString stringWithUTF8String:wallet_type.c_str()]); - for (BATBraveLedgerObserver *observer in self.observers) { - if (observer.externalWalletDisconnected) { - observer.externalWalletDisconnected(bridgedType); - } - } -} - -- (void)deleteLog:(ledger::ResultCallback)callback -{ - callback(ledger::type::Result::LEDGER_OK); -} - -- (bool)setEncryptedStringState:(const std::string&)key value:(const std::string&)value -{ - const auto bridgedKey = [NSString stringWithUTF8String:key.c_str()]; - - std::string encrypted_value; - if (!OSCrypt::EncryptString(value, &encrypted_value)) { - BLOG(0, @"Couldn't encrypt value for %@", bridgedKey); - return false; - } - - std::string encoded_value; - base::Base64Encode(encrypted_value, &encoded_value); - - self.prefs[bridgedKey] = [NSString stringWithUTF8String:encoded_value.c_str()]; - [self savePrefs]; - return true; -} - -- (std::string)getEncryptedStringState:(const std::string&)key -{ - const auto bridgedKey = [NSString stringWithUTF8String:key.c_str()]; - NSString *savedValue = self.prefs[bridgedKey]; - if (!savedValue || ![savedValue isKindOfClass:NSString.class]) { - return ""; - } - - std::string encoded_value = savedValue.UTF8String; - std::string encrypted_value; - if (!base::Base64Decode(encoded_value, &encrypted_value)) { - BLOG(0, @"base64 decode failed for %@", bridgedKey); - return ""; - } - - std::string value; - if (!OSCrypt::DecryptString(encrypted_value, &value)) { - BLOG(0, @"Decrypting failed for %@", bridgedKey); - return ""; - } - - return value; -} - -@end diff --git a/vendor/brave-ios/Ledger/BATBraveLedgerObserver.h b/vendor/brave-ios/Ledger/BATBraveLedgerObserver.h deleted file mode 100644 index 25f481b49d4..00000000000 --- a/vendor/brave-ios/Ledger/BATBraveLedgerObserver.h +++ /dev/null @@ -1,91 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import -#import "ledger.mojom.objc.h" -#import "Enums.h" - -@class BATBraveLedger, BATRewardsNotification; - -NS_ASSUME_NONNULL_BEGIN - -/// A ledger observer can get notified when certain actions happen -/// -/// Creating a LedgerObserver alone will not respond to any events. Set -/// each closure that you wish to watch based on the data being displayed on -/// screen -OBJC_EXPORT -NS_SWIFT_NAME(LedgerObserver) -@interface BATBraveLedgerObserver : NSObject - -@property (nonatomic, readonly, weak) BATBraveLedger *ledger; - -- (instancetype)initWithLedger:(BATBraveLedger *)ledger; - -/// Executed when the wallet is first initialized -@property (nonatomic, copy, nullable) void (^walletInitalized)(BATResult result); - -/// A publisher was fetched by its URL for a specific tab identified by tabId -@property (nonatomic, copy, nullable) void (^fetchedPanelPublisher)(BATPublisherInfo *info, uint64_t tabId); - -@property (nonatomic, copy, nullable) void (^publisherListUpdated)(); - -/// -@property (nonatomic, copy, nullable) void (^finishedPromotionsAdded)(NSArray *promotions); - -/// Eligable grants were added to the wallet -@property (nonatomic, copy, nullable) void (^promotionsAdded)(NSArray *promotions); - -/// A grant was claimed -@property (nonatomic, copy, nullable) void (^promotionClaimed)(BATPromotion *promotion); - -/// A reconcile transaction completed and the user may have an updated balance -/// and likely an updated balance report -@property (nonatomic, copy, nullable) void (^reconcileCompleted)(BATResult result, - NSString *viewingId, - BATRewardsType type, - NSString *probi); - -/// The users balance report has been updated -@property (nonatomic, copy, nullable) void (^balanceReportUpdated)(); - -/// The exclusion state of a given publisher has been changed -@property (nonatomic, copy, nullable) void (^excludedSitesChanged)(NSString *publisherKey, BATPublisherExclude excluded); - -/// Called when the ledger removes activity info for a given publisher -@property (nonatomic, copy, nullable) void (^activityRemoved)(NSString *publisherKey); - -/// The publisher list was normalized and saved -@property (nonatomic, copy, nullable) void (^publisherListNormalized)(NSArray *normalizedList); - -@property (nonatomic, copy, nullable) void (^pendingContributionAdded)(); - -@property (nonatomic, copy, nullable) void (^pendingContributionsRemoved)(NSArray *publisherKeys); - -@property (nonatomic, copy, nullable) void (^recurringTipAdded)(NSString *publisherKey); - -@property (nonatomic, copy, nullable) void (^recurringTipRemoved)(NSString *publisherKey); - -// A users contribution was added -@property (nonatomic, copy, nullable) void (^contributionAdded)(BOOL successful, BATRewardsType type); - -/// A notification was added to the wallet -@property (nonatomic, copy, nullable) void (^notificationAdded)(BATRewardsNotification *notification); - -/// A notification was removed from the wallet -@property (nonatomic, copy, nullable) void (^notificationsRemoved)(NSArray *notification); - -/// Wallet balance was fetched and updated -@property (nonatomic, copy, nullable) void (^fetchedBalance)(); - -@property (nonatomic, copy, nullable) void (^externalWalletAuthorized)(BATWalletType type); - -@property (nonatomic, copy, nullable) void (^externalWalletDisconnected)(BATWalletType type); - -/// The reconcile stamp reset -@property (nonatomic, copy, nullable) void (^reconcileStampReset)(); - -@end - -NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/BATBraveLedgerObserver.mm b/vendor/brave-ios/Ledger/BATBraveLedgerObserver.mm deleted file mode 100644 index 80a5487d556..00000000000 --- a/vendor/brave-ios/Ledger/BATBraveLedgerObserver.mm +++ /dev/null @@ -1,22 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import -#import "BATBraveLedgerObserver.h" -#import "BATBraveLedger.h" - -@interface BATBraveLedgerObserver () -@property (nonatomic, weak) BATBraveLedger *ledger; -@end - -@implementation BATBraveLedgerObserver - -- (instancetype)initWithLedger:(BATBraveLedger *)ledger { - if ((self = [super init])) { - self.ledger = ledger; - } - return self; -} - -@end diff --git a/vendor/brave-ios/Ledger/Data/BATLedgerDatabase.h b/vendor/brave-ios/Ledger/Data/BATLedgerDatabase.h deleted file mode 100644 index ef0fc7c7b70..00000000000 --- a/vendor/brave-ios/Ledger/Data/BATLedgerDatabase.h +++ /dev/null @@ -1,54 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import -#import "ledger.mojom.objc.h" -#import "CoreDataModels.h" - -NS_ASSUME_NONNULL_BEGIN - -typedef void (^BATLedgerDatabaseWriteCompletion)(BOOL success); - -/// An interface into the ledger database -/// -/// This class mirrors brave-core's `publisher_info_database.h/cc` file. This file will actually -/// likely be removed at a future date when database managment happens in the ledger library -OBJC_EXPORT -@interface BATLedgerDatabase : NSObject - -/// Generates a SQL migration transaction that will move all data in the users -/// CoreData storage into version 10 of the brave-core's database schema to -/// then run and have ledger take over -/// -/// Return's nil if the migration template cannot be found -+ (nullable NSString *)migrateCoreDataToSQLTransaction; - -/// Generates a SQL migration transaction that will move token related tables -/// only (promos, promo creds, unblinded tokens) to version 10 of brave-core's -/// database schema. -/// -/// Return's nil if the migration template cannot be found -+ (nullable NSString *)migrateCoreDataBATOnlyToSQLTransaction; - -/// Deletes the server publisher list from the CoreData DB -+ (void)deleteCoreDataServerPublisherList:(nullable void (^)(NSError * _Nullable error))completion; - -+ (NSString *)activityInfoInsertFor:(ActivityInfo *)info; -+ (NSString *)contributionInfoInsertFor:(ContributionInfo *)info; -+ (NSString *)contributionQueueInsertFor:(ContributionQueue *)obj; -+ (NSString *)contributionQueuePublisherInsertFor:(ContributionPublisher *)obj; -+ (NSString *)mediaPublisherInfoInsertFor:(MediaPublisherInfo *)obj; -+ (NSString *)pendingContributionInsertFor:(PendingContribution *)obj; -+ (NSString *)promotionInsertFor:(Promotion *)obj; -+ (NSString *)promotionCredsInsertFor:(PromotionCredentials *)obj; -+ (NSString *)publisherInfoInsertFor:(PublisherInfo *)obj; -+ (NSString *)recurringDonationInsertFor:(RecurringDonation *)obj; -+ (NSString *)unblindedTokenInsertFor:(UnblindedToken *)obj; - -- (instancetype)init NS_UNAVAILABLE; -- (instancetype)initWithCoder:(NSCoder *)aDecoder NS_UNAVAILABLE; - -@end - -NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Data/BATLedgerDatabase.mm b/vendor/brave-ios/Ledger/Data/BATLedgerDatabase.mm deleted file mode 100644 index cb11e02fbb5..00000000000 --- a/vendor/brave-ios/Ledger/Data/BATLedgerDatabase.mm +++ /dev/null @@ -1,391 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import -#import "BATLedgerDatabase.h" - -#import "DataController.h" -#import "bat/ledger/global_constants.h" -#import "RewardsLogging.h" - -@implementation BATLedgerDatabase - -+ (nullable NSString *)migrateCoreDataToSQLTransaction -{ - const auto bundlePath = [[NSBundle bundleForClass:BATLedgerDatabase.class] pathForResource:@"migrate" ofType:@"sql"]; - NSError *error = nil; - const auto migrationScript = [NSString stringWithContentsOfFile:bundlePath encoding:NSUTF8StringEncoding error:&error]; - if (error) { - BLOG(0, @"Failed to load migration script from path: %@", bundlePath); - return nil; - } - - const auto statements = [[NSMutableArray alloc] init]; - - // activity_info - [statements addObjectsFromArray: - MapFetchedObjectsToInsertsForClass(ActivityInfo.class, ^(ActivityInfo *info){ - return [self activityInfoInsertFor:info]; - })]; - - // contribution_info - [statements addObjectsFromArray: - MapFetchedObjectsToInsertsForClass(ContributionInfo.class, ^(ContributionInfo *info){ - return [self contributionInfoInsertFor:info]; - })]; - - // contribution_queue - __block int64_t contributionQueueMaxID = 0; - [statements addObjectsFromArray: - MapFetchedObjectsToInsertsForClass(ContributionQueue.class, ^(ContributionQueue *obj){ - contributionQueueMaxID = MAX(obj.id, contributionQueueMaxID); - return [self contributionQueueInsertFor:obj]; - })]; - if (contributionQueueMaxID > 0) { - [statements addObject: - [NSString stringWithFormat:@"UPDATE SQLITE_SEQUENCE SET seq = %lld WHERE name = 'contribution_queue';", contributionQueueMaxID] - ]; - } - - // contribution_queue_publishers - [statements addObjectsFromArray: - MapFetchedObjectsToInsertsForClass(ContributionPublisher.class, ^(ContributionPublisher *obj){ - return [self contributionQueuePublisherInsertFor:obj]; - })]; - - // media_publisher_info - [statements addObjectsFromArray: - MapFetchedObjectsToInsertsForClass(MediaPublisherInfo.class, ^(MediaPublisherInfo *obj){ - return [self mediaPublisherInfoInsertFor:obj]; - })]; - - // pending_contribution - [statements addObjectsFromArray: - MapFetchedObjectsToInsertsForClass(PendingContribution.class, ^(PendingContribution *obj){ - return [self pendingContributionInsertFor:obj]; - })]; - - // promotion - [statements addObjectsFromArray: - MapFetchedObjectsToInsertsForClass(Promotion.class, ^(Promotion *obj){ - return [self promotionInsertFor:obj]; - })]; - - // promotion_creds - [statements addObjectsFromArray: - MapFetchedObjectsToInsertsForClass(PromotionCredentials.class, ^(PromotionCredentials *obj){ - return [self promotionCredsInsertFor:obj]; - })]; - - // publisher_info - [statements addObjectsFromArray: - MapFetchedObjectsToInsertsForClass(PublisherInfo.class, ^(PublisherInfo *obj){ - return [self publisherInfoInsertFor:obj]; - })]; - - // recurring_donation - [statements addObjectsFromArray: - MapFetchedObjectsToInsertsForClass(RecurringDonation.class, ^(RecurringDonation *obj){ - return [self recurringDonationInsertFor:obj]; - })]; - - // unblinded_tokens - __block int64_t unblindedTokenMaxID = 0; - [statements addObjectsFromArray: - MapFetchedObjectsToInsertsForClass(UnblindedToken.class, ^(UnblindedToken *obj){ - unblindedTokenMaxID = MAX(obj.tokenID, unblindedTokenMaxID); - return [self unblindedTokenInsertFor:obj]; - })]; - if (unblindedTokenMaxID > 0) { - [statements addObject: - [NSString stringWithFormat:@"UPDATE SQLITE_SEQUENCE SET seq = %lld WHERE name = 'unblinded_tokens';", unblindedTokenMaxID] - ]; - } - - return [migrationScript stringByReplacingOccurrencesOfString:@"# {statements}" withString:[statements componentsJoinedByString:@"\n"]]; -} - -+ (nullable NSString *)migrateCoreDataBATOnlyToSQLTransaction -{ - const auto bundlePath = [[NSBundle bundleForClass:BATLedgerDatabase.class] pathForResource:@"migrate" ofType:@"sql"]; - NSError *error = nil; - const auto migrationScript = [NSString stringWithContentsOfFile:bundlePath encoding:NSUTF8StringEncoding error:&error]; - if (error) { - BLOG(0, @"Failed to load migration script from path: %@", bundlePath); - return nil; - } - - const auto statements = [[NSMutableArray alloc] init]; - - // promotion - [statements addObjectsFromArray: - MapFetchedObjectsToInsertsForClass(Promotion.class, ^(Promotion *obj){ - return [self promotionInsertFor:obj]; - })]; - - // promotion_creds - [statements addObjectsFromArray: - MapFetchedObjectsToInsertsForClass(PromotionCredentials.class, ^(PromotionCredentials *obj){ - return [self promotionCredsInsertFor:obj]; - })]; - - // unblinded_tokens - __block int64_t unblindedTokenMaxID = 0; - [statements addObjectsFromArray: - MapFetchedObjectsToInsertsForClass(UnblindedToken.class, ^(UnblindedToken *obj){ - unblindedTokenMaxID = MAX(obj.tokenID, unblindedTokenMaxID); - return [self unblindedTokenInsertFor:obj]; - })]; - if (unblindedTokenMaxID > 0) { - [statements addObject: - [NSString stringWithFormat:@"UPDATE SQLITE_SEQUENCE SET seq = %lld WHERE name = 'unblinded_tokens';", unblindedTokenMaxID] - ]; - } - - return [migrationScript stringByReplacingOccurrencesOfString:@"# {statements}" withString:[statements componentsJoinedByString:@"\n"]]; -} - -#pragma mark - - -+ (NSString *)activityInfoInsertFor:(ActivityInfo *)info -{ - const auto activityInfoInsert = - @"INSERT INTO \"activity_info\" " - "(publisher_id, duration, visits, score, percent, weight, reconcile_stamp) VALUES (" - "%@," // publisher_id LONGVARCHAR NOT NULL - "%lld," // duration INTEGER DEFAULT 0 NOT NULL, - "%d," // visits INTEGER DEFAULT 0 NOT NULL, - "%f," // score DOUBLE DEFAULT 0 NOT NULL - "%d," // percent INTEGER DEFAULT 0 NOT NULL - "%f," // weight DOUBLE DEFAULT 0 NOT NULL, - "%lld" // reconcile_stamp INTEGER DEFAULT 0 NOT NULL - ");"; - return [NSString stringWithFormat:activityInfoInsert, - SQLString(info.publisherID), info.duration, info.visits, info.score, - info.percent, info.weight, info.reconcileStamp]; -} - -+ (NSString *)contributionInfoInsertFor:(ContributionInfo *)info -{ - const auto contributionInfoInsert = - @"INSERT INTO \"contribution_info\" " - "(publisher_id, probi, date, type, month, year) VALUES (" - "%@," // publisher_id LONGVARCHAR - "%@," // probi TEXT "0" NOT NULL - "%lld," // date INTEGER NOT NULL - "%d," // type INTEGER NOT NULL - "%d," // month INTEGER NOT NULL - "%d" // year INTEGER NOT NULL - ");"; - return [NSString stringWithFormat:contributionInfoInsert, - SQLString(info.publisherID), SQLString(info.probi), info.date, - info.type, info.month, info.year]; -} - -+ (NSString *)contributionQueueInsertFor:(ContributionQueue *)obj -{ - const auto contributionQueueInsert = - @"INSERT INTO \"contribution_queue\" " - "(contribution_queue_id, type, amount, partial) VALUES (" - "%lld," // contribution_queue_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL - "%d," // type INTEGER NOT NULL - "%f," // amount DOUBLE NOT NULL - "%d" // partial INTEGER NOT NULL DEFAULT 0 - ");"; - return [NSString stringWithFormat:contributionQueueInsert, - obj.id, obj.type, obj.amount, obj.partial]; -} - -+ (NSString *)contributionQueuePublisherInsertFor:(ContributionPublisher *)obj -{ - const auto contributionQueuePublisherInsert = - @"INSERT INTO \"contribution_queue_publishers\" " - "(contribution_queue_id, publisher_key, amount_percent) VALUES (" - "%lld," // contribution_queue_id INTEGER NOT NULL - "%@," // publisher_key TEXT NOT NULL - "%f" // amount_percent DOUBLE NOT NULL - ");"; - return [NSString stringWithFormat:contributionQueuePublisherInsert, - obj.queue.id, SQLString(obj.publisherKey), obj.amountPercent]; -} - -+ (NSString *)mediaPublisherInfoInsertFor:(MediaPublisherInfo *)obj -{ - const auto mediaPublisherInfoInsert = - @"INSERT INTO \"media_publisher_info\" " - "(media_key, publisher_id) VALUES (" - "%@," // media_key TEXT NOT NULL PRIMARY KEY UNIQUE - "%@" // publisher_id LONGVARCHAR NOT NULL - ");"; - return [NSString stringWithFormat:mediaPublisherInfoInsert, - SQLString(obj.mediaKey), SQLString(obj.publisherID)]; -} - -+ (NSString *)pendingContributionInsertFor:(PendingContribution *)obj -{ - const auto pendingContributionInsert = - @"INSERT INTO \"pending_contribution\" " - "(publisher_id, amount, added_date, viewing_id, type) VALUES (" - "%@," // publisher_id LONGVARCHAR NOT NULL - "%f," // amount DOUBLE DEFAULT 0 NOT NULL - "%lld," // added_date INTEGER DEFAULT 0 NOT NULL - "%@," // viewing_id LONGVARCHAR NOT NULL - "%d" // type INTEGER NOT NULL - ");"; - return [NSString stringWithFormat:pendingContributionInsert, - SQLString(obj.publisherID), obj.amount, obj.addedDate, - SQLString(obj.viewingID), obj.type]; -} - -+ (NSString *)promotionInsertFor:(Promotion *)obj -{ - const auto promotionInsert = - @"INSERT INTO \"promotion\" " - "(promotion_id, version, type, public_keys, suggestions, " - "approximate_value, status, expires_at) VALUES (" - "%@," // promotion_id TEXT NOT NULL - "%d," // version INTEGER NOT NULL - "%d," // type INTEGER NOT NULL - "%@," // public_keys TEXT NOT NULL - "%d," // suggestions INTEGER NOT NULL DEFAULT 0 - "%f," // approximate_value DOUBLE NOT NULL DEFAULT 0 - "%d," // status INTEGER NOT NULL DEFAULT 0 - "%lld" // expires_at TIMESTAMP NOT NULL - ");"; - return [NSString stringWithFormat:promotionInsert, - SQLString(obj.promotionID), obj.version, obj.type, SQLString(obj.publicKeys), - obj.suggestions, obj.approximateValue, obj.status, - static_cast(obj.expiryDate.timeIntervalSince1970)]; -} - -+ (NSString *)promotionCredsInsertFor:(PromotionCredentials *)obj -{ - const auto promotionCredsInsert = - @"INSERT INTO \"promotion_creds\" " - "(promotion_id, tokens, blinded_creds, signed_creds, public_key, " - "batch_proof, claim_id) VALUES (" - "%@," // promotion_id TEXT UNIQUE NOT NULL - "%@," // tokens TEXT NOT NULL - "%@," // blinded_creds TEXT NOT NULL - "%@," // signed_creds TEXT - "%@," // public_key TEXT - "%@," // batch_proof TEXT - "%@" // claim_id TEXT - ");"; - return [NSString stringWithFormat:promotionCredsInsert, - SQLString(obj.promotionID), SQLString(obj.tokens), SQLString(obj.blindedCredentials), - SQLNullableString(obj.signedCredentials), SQLNullableString(obj.publicKey), - SQLNullableString(obj.batchProof), SQLNullableString(obj.claimID)]; -} - -+ (NSString *)publisherInfoInsertFor:(PublisherInfo *)obj -{ - const auto publisherInfoInsert = - @"INSERT INTO \"publisher_info\" " - "(publisher_id, excluded, name, favIcon, url, provider) VALUES (" - "%@," // publisher_id LONGVARCHAR PRIMARY KEY NOT NULL UNIQUE - "%d," // excluded INTEGER DEFAULT 0 NOT NULL - "%@," // name TEXT NOT NULL - "%@," // favIcon TEXT NOT NULL - "%@," // url TEXT NOT NULL - "%@" // provider TEXT NOT NULL - ");"; - return [NSString stringWithFormat:publisherInfoInsert, - SQLString(obj.publisherID), obj.excluded, SQLString(obj.name), - SQLString(obj.faviconURL), SQLString(obj.url), SQLString(obj.provider)]; -} - -+ (NSString *)recurringDonationInsertFor:(RecurringDonation *)obj -{ - const auto recurringDonationInsert = - @"INSERT INTO \"recurring_donation\" " - "(publisher_id, amount, added_date) VALUES (" - "%@," // publisher_id LONGVARCHAR NOT NULL PRIMARY KEY UNIQUE - "%f," // amount DOUBLE DEFAULT 0 NOT NULL - "%lld" // added_date INTEGER DEFAULT 0 NOT NULL - ");"; - return [NSString stringWithFormat:recurringDonationInsert, - SQLString(obj.publisherID), obj.amount, obj.addedDate]; -} - -+ (NSString *)unblindedTokenInsertFor:(UnblindedToken *)obj -{ - const auto unblindedTokenInsert = - @"INSERT INTO \"unblinded_tokens\" " - "(token_id, token_value, public_key, value, promotion_id) VALUES (" - "%lld," // token_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL - "%@," // token_value TEXT - "%@," // public_key TEXT - "%f," // value DOUBLE NOT NULL DEFAULT 0 - "%@" // promotion_id TEXT - ");"; - return [NSString stringWithFormat:unblindedTokenInsert, - obj.tokenID, SQLNullableString(obj.tokenValue), - SQLNullableString(obj.publicKey), obj.value, - SQLNullableString(obj.promotionID)]; -} - -+ (void)deleteCoreDataServerPublisherList:(nullable void (^)(NSError * _Nullable error))completion -{ - const auto context = [DataController newBackgroundContext]; - - BLOG(1, @"CoreData: Deleting publisher list"); - [context performBlock:^{ - const auto fetchRequest = ServerPublisherInfo.fetchRequest; - fetchRequest.entity = [NSEntityDescription entityForName:NSStringFromClass(ServerPublisherInfo.class) - inManagedObjectContext:context]; - NSError *error = nil; - const auto deleteRequest = [[NSBatchDeleteRequest alloc] initWithFetchRequest:fetchRequest]; - [context executeRequest:deleteRequest error:&error]; - - if (!error && context.hasChanges) { - [context save:&error]; - } - - if (completion) { - dispatch_async(dispatch_get_main_queue(), ^{ - completion(error); - }); - } - }]; -} - -#pragma mark - - -NS_INLINE NSString *SQLNullableString(NSString * _Nullable value) { - return (value == nil ? @"NULL" : SQLString(value)); -} - -NS_INLINE NSString *SQLString(NSString * _Nonnull value) { - // Obj-C doesn't enforce nullability, therefore adding an extra check - if (value == nil) { - return @"''"; - } - // Have to make sure to escape any apostrophies - return [NSString stringWithFormat:@"'%@'", - [value stringByReplacingOccurrencesOfString:@"'" withString:@"''"]]; -} - -static NSArray * -MapFetchedObjectsToInsertsForClass(Class clazz, - NSString * (NS_NOESCAPE ^block)(__kindof NSManagedObject* obj)) -{ - const auto context = DataController.viewContext; - const auto fetchRequest = [clazz fetchRequest]; - fetchRequest.entity = [NSEntityDescription entityForName:NSStringFromClass(clazz) - inManagedObjectContext:context]; - NSError *error; - const auto fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; - if (error) { - return @[]; - } - const auto statements = [[NSMutableArray alloc] init]; - [fetchedObjects enumerateObjectsUsingBlock:^(NSManagedObject *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { - if (![obj isKindOfClass:clazz]) { return; } - [statements addObject:block(obj)]; - }]; - return statements; -} - -@end diff --git a/vendor/brave-ios/Ledger/Data/DataController.h b/vendor/brave-ios/Ledger/Data/DataController.h deleted file mode 100644 index 5f46f5760dd..00000000000 --- a/vendor/brave-ios/Ledger/Data/DataController.h +++ /dev/null @@ -1,33 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -OBJC_EXPORT -@interface DataController : NSObject - -+ (BOOL)defaultStoreExists; - -@property (nonatomic, class) DataController *shared; - -/// File URL to the folder containing all data files -@property (nonatomic, readonly) NSURL *storeDirectoryURL; -/// File URL to the SQLite store -@property (nonatomic, readonly) NSURL *storeURL; - -- (void)addPersistentStoreForContainer:(NSPersistentContainer *)container; - -@property (nonatomic, readonly) NSPersistentContainer *container; - -/// Context object also allows us access to all persistent container data if needed. -+ (NSManagedObjectContext *)viewContext; - -+ (NSManagedObjectContext *)newBackgroundContext; - -@end - -NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Data/DataController.mm b/vendor/brave-ios/Ledger/Data/DataController.mm deleted file mode 100644 index 59ea8b1915c..00000000000 --- a/vendor/brave-ios/Ledger/Data/DataController.mm +++ /dev/null @@ -1,108 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import "DataController.h" - -#import "ledger.mojom.objc.h" - -@interface DataController () -@property (nonatomic) NSOperationQueue *operationQueue; -@property (nonatomic) NSPersistentContainer *container; -@end - -@implementation DataController - -static DataController *_dataController = nil; - -+ (DataController *)shared -{ - if (!_dataController) { - _dataController = [[DataController alloc] init]; - } - return _dataController; -} - -+ (void)setShared:(DataController *)shared -{ - _dataController = shared; -} - -- (NSURL *)storeDirectoryURL -{ - const auto urls = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); - const auto documentURL = urls.lastObject; - if (!documentURL) { - return nil; - } - return [NSURL fileURLWithPath:[documentURL stringByAppendingPathComponent:@"rewards"]]; -} - -- (NSURL *)storeURL -{ - return [[self storeDirectoryURL] URLByAppendingPathComponent:@"BraveRewards.sqlite"]; -} - -+ (BOOL)defaultStoreExists -{ - const auto urls = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); - const auto documentURL = urls.lastObject; - if (!documentURL) { - return NO; - } - const auto directoryURL = [NSURL fileURLWithPath:[documentURL stringByAppendingPathComponent:@"rewards"]]; - const auto storeURL = [directoryURL URLByAppendingPathComponent:@"BraveRewards.sqlite"]; - return [NSFileManager.defaultManager fileExistsAtPath:storeURL.path]; -} - -- (instancetype)init -{ - if ((self = [super init])) { - self.operationQueue = [[NSOperationQueue alloc] init]; - self.operationQueue.maxConcurrentOperationCount = 1; - - [[NSFileManager defaultManager] createDirectoryAtURL:[self storeDirectoryURL] - withIntermediateDirectories:YES - attributes:nil - error:nil]; - - // Setup container - const auto bundle = [NSBundle bundleForClass:DataController.class]; - const auto modelURL = [bundle URLForResource:@"Model" withExtension:@"momd"]; - NSAssert(modelURL != nil, @"Error loading model from bundle"); - const auto model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; - NSAssert(model != nil, @"Error initializing managed object model from: %@", modelURL); - self.container = [[NSPersistentContainer alloc] initWithName:@"Model" - managedObjectModel:model]; - [self addPersistentStoreForContainer:self.container]; - [self.container loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription * _Nonnull, NSError * _Nullable error) { - NSAssert(error == nil, @"Load persistent store error: %@", error); - }]; - self.container.viewContext.automaticallyMergesChangesFromParent = YES; - } - return self; -} - -- (void)addPersistentStoreForContainer:(NSPersistentContainer *)container -{ - // This makes the database file encrypted until device is unlocked. - const auto storeDescription = [[NSPersistentStoreDescription alloc] initWithURL:self.storeURL]; - [storeDescription setOption:NSFileProtectionComplete forKey:NSPersistentStoreFileProtectionKey]; - self.container.persistentStoreDescriptions = @[storeDescription]; -} - -+ (NSManagedObjectContext *)newBackgroundContext -{ - const auto backgroundContext = [DataController.shared.container newBackgroundContext]; - // In theory, the merge policy should not matter - // since all operations happen on a synchronized operation queue. - // But in case of any bugs it's better to have one, so the app won't crash for users. - backgroundContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy; - return backgroundContext; -} - -+ (NSManagedObjectContext *)viewContext { - return DataController.shared.container.viewContext; -} - -@end diff --git a/vendor/brave-ios/Ledger/Data/Model/ContributionQueue.h b/vendor/brave-ios/Ledger/Data/Model/ContributionQueue.h deleted file mode 100644 index 747a8d61b13..00000000000 --- a/vendor/brave-ios/Ledger/Data/Model/ContributionQueue.h +++ /dev/null @@ -1,34 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import -#import - -@class ContributionPublisher; - -NS_ASSUME_NONNULL_BEGIN - -OBJC_EXPORT -@interface ContributionQueue : NSManagedObject - -+ (NSFetchRequest *)fetchRequest; - -@property (nonatomic) int64_t id; -@property (nonatomic) int32_t type; -@property (nonatomic) double amount; -@property (nonatomic) bool partial; -@property (nullable, nonatomic, retain) NSSet *publishers; - -@end - -@interface ContributionQueue (CoreDataGeneratedAccessors) - -- (void)addPublishersObject:(ContributionPublisher *)value; -- (void)removePublishersObject:(ContributionPublisher *)value; -- (void)addPublishers:(NSSet *)values; -- (void)removePublishers:(NSSet *)values; - -@end - -NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Data/Model/Promotion.h b/vendor/brave-ios/Ledger/Data/Model/Promotion.h deleted file mode 100644 index 44440284cee..00000000000 --- a/vendor/brave-ios/Ledger/Data/Model/Promotion.h +++ /dev/null @@ -1,32 +0,0 @@ -// -// Promotion+CoreDataClass.h -// -// -// Created by Kyle Hickinson on 2019-10-21. -// -// - -#import -#import - -@class PromotionCredentials; - -NS_ASSUME_NONNULL_BEGIN - -OBJC_EXPORT -@interface Promotion : NSManagedObject - -+ (NSFetchRequest *)fetchRequest; - -@property (nonatomic, copy) NSString *promotionID; -@property (nonatomic) int32_t version; -@property (nonatomic) int32_t type; -@property (nonatomic, copy) NSString *publicKeys; -@property (nonatomic) int32_t suggestions; -@property (nonatomic) double approximateValue; -@property (nonatomic) int32_t status; -@property (nonatomic, copy) NSDate *expiryDate; - -@end - -NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Data/Model/PromotionCredentials.h b/vendor/brave-ios/Ledger/Data/Model/PromotionCredentials.h deleted file mode 100644 index 1543118742e..00000000000 --- a/vendor/brave-ios/Ledger/Data/Model/PromotionCredentials.h +++ /dev/null @@ -1,29 +0,0 @@ -// -// PromotionCredentials+CoreDataClass.h -// -// -// Created by Kyle Hickinson on 2019-10-21. -// -// - -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -OBJC_EXPORT -@interface PromotionCredentials : NSManagedObject - -+ (NSFetchRequest *)fetchRequest; - -@property (nonatomic, copy) NSString *blindedCredentials; -@property (nullable, nonatomic, copy) NSString *signedCredentials; -@property (nullable, nonatomic, copy) NSString *publicKey; -@property (nullable, nonatomic, copy) NSString *batchProof; -@property (nonatomic, copy) NSString *claimID; -@property (nonatomic, copy) NSString *promotionID; -@property (nonatomic, copy) NSString *tokens; - -@end - -NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Data/Model/PublisherInfo.h b/vendor/brave-ios/Ledger/Data/Model/PublisherInfo.h deleted file mode 100644 index b85ac78b36e..00000000000 --- a/vendor/brave-ios/Ledger/Data/Model/PublisherInfo.h +++ /dev/null @@ -1,54 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import -#import - -@class ActivityInfo, ContributionInfo, RecurringDonation, PendingContribution; - -NS_ASSUME_NONNULL_BEGIN - -OBJC_EXPORT -@interface PublisherInfo : NSManagedObject - -+ (NSFetchRequest *)fetchRequest; - -@property (nonatomic) int32_t excluded; -@property (nonatomic, copy) NSString *faviconURL; -@property (nonatomic, copy) NSString *name; -@property (nonatomic, copy) NSString *provider; -@property (nonatomic, copy) NSString *publisherID; -@property (nonatomic, copy) NSString *url; -@property (nullable, nonatomic, retain) NSSet *activities; -@property (nullable, nonatomic, retain) NSSet *contributions; -@property (nullable, nonatomic, retain) NSSet *recurringDonations; -@property (nullable, nonatomic, retain) NSSet *pendingContributions; - -@end - -@interface PublisherInfo (CoreDataGeneratedAccessors) - -- (void)addActivitiesObject:(ActivityInfo *)value; -- (void)removeActivitiesObject:(ActivityInfo *)value; -- (void)addActivities:(NSSet *)values; -- (void)removeActivities:(NSSet *)values; - -- (void)addContributionsObject:(ContributionInfo *)value; -- (void)removeContributionsObject:(ContributionInfo *)value; -- (void)addContributions:(NSSet *)values; -- (void)removeContributions:(NSSet *)values; - -- (void)addRecurringDonationsObject:(RecurringDonation *)value; -- (void)removeRecurringDonationsObject:(RecurringDonation *)value; -- (void)addRecurringDonations:(NSSet *)values; -- (void)removeRecurringDonations:(NSSet *)values; - -- (void)addPendingContributionsObject:(PendingContribution *)value; -- (void)removePendingContributionsObject:(PendingContribution *)value; -- (void)addPendingContributions:(NSSet *)values; -- (void)removePendingContributions:(NSSet *)values; - -@end - -NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Data/Model/ServerPublisherBanner.h b/vendor/brave-ios/Ledger/Data/Model/ServerPublisherBanner.h deleted file mode 100644 index f26b9846c46..00000000000 --- a/vendor/brave-ios/Ledger/Data/Model/ServerPublisherBanner.h +++ /dev/null @@ -1,25 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import - -@class ServerPublisherInfo; - -NS_ASSUME_NONNULL_BEGIN - -OBJC_EXPORT -@interface ServerPublisherBanner : NSManagedObject - -+ (NSFetchRequest *)fetchRequest; - -@property (nonatomic, copy) NSString *publisherID; -@property (nullable, nonatomic, copy) NSString *title; -@property (nullable, nonatomic, copy) NSString *desc; -@property (nullable, nonatomic, copy) NSString *background; -@property (nullable, nonatomic, copy) NSString *logo; -@property (nullable, nonatomic, retain) ServerPublisherInfo *serverPublisherInfo; - -@end - -NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Data/Model/ServerPublisherInfo.h b/vendor/brave-ios/Ledger/Data/Model/ServerPublisherInfo.h deleted file mode 100644 index c8cfe3d1373..00000000000 --- a/vendor/brave-ios/Ledger/Data/Model/ServerPublisherInfo.h +++ /dev/null @@ -1,38 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import - -@class ServerPublisherBanner, ServerPublisherAmount, ServerPublisherLink; - -NS_ASSUME_NONNULL_BEGIN - -OBJC_EXPORT -@interface ServerPublisherInfo : NSManagedObject - -+ (NSFetchRequest *)fetchRequest; - -@property (nonatomic, copy) NSString *publisherID; -@property (nonatomic) int32_t status; -@property (nonatomic) BOOL excluded; -@property (nonatomic, copy) NSString *address; -@property (nullable, nonatomic, retain) ServerPublisherBanner *banner; -@property (nullable, nonatomic, retain) NSSet *amounts; -@property (nullable, nonatomic, retain) NSSet *links; - -@end - -@interface ServerPublisherInfo (CoreDataGeneratedAccessors) -- (void)addAmountsObject:(ServerPublisherAmount *)value; -- (void)removeAmountsObject:(ServerPublisherAmount *)value; -- (void)addAmounts:(NSSet *)values; -- (void)removeAmounts:(NSSet *)values; - -- (void)addLinksObject:(ServerPublisherLink *)value; -- (void)removeLinksObject:(ServerPublisherLink *)value; -- (void)addLinks:(NSSet *)values; -- (void)removeLinks:(NSSet *)values; -@end - -NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Data/Model/UnblindedToken.h b/vendor/brave-ios/Ledger/Data/Model/UnblindedToken.h deleted file mode 100644 index cede2f6c725..00000000000 --- a/vendor/brave-ios/Ledger/Data/Model/UnblindedToken.h +++ /dev/null @@ -1,29 +0,0 @@ -// -// UnblindedToken+CoreDataClass.h -// -// -// Created by Kyle Hickinson on 2019-10-21. -// -// - -#import -#import - -@class Promotion; - -NS_ASSUME_NONNULL_BEGIN - -OBJC_EXPORT -@interface UnblindedToken : NSManagedObject - -+ (NSFetchRequest *)fetchRequest; - -@property (nonatomic) int64_t tokenID; -@property (nullable, nonatomic, copy) NSString *publicKey; -@property (nonatomic) double value; -@property (nullable, nonatomic, copy) NSString *promotionID; -@property (nullable, nonatomic, copy) NSString *tokenValue; - -@end - -NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Generated/Enums.h b/vendor/brave-ios/Ledger/Generated/Enums.h deleted file mode 100644 index f8b3e47e1fa..00000000000 --- a/vendor/brave-ios/Ledger/Generated/Enums.h +++ /dev/null @@ -1,12 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import - -typedef NSString *BATWalletType NS_SWIFT_NAME(WalletType) NS_STRING_ENUM; - -static BATWalletType const BATWalletTypeUphold = @"uphold"; -static BATWalletType const BATWalletTypeAnonymous = @"anonymous"; -static BATWalletType const BATWalletTypeUnblindedTokens = @"blinded"; - diff --git a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h deleted file mode 100644 index b8b1fa9995b..00000000000 --- a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h +++ /dev/null @@ -1,60 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import -#import "bat/ledger/ledger_client.h" - -@protocol NativeLedgerClientBridge; - -class NativeLedgerClient : public ledger::LedgerClient { -public: - NativeLedgerClient(id bridge); - ~NativeLedgerClient() override; - -private: - __unsafe_unretained id bridge_; - - void FetchFavIcon(const std::string & url, const std::string & favicon_key, ledger::client::FetchIconCallback callback) override; - void LoadLedgerState(ledger::client::OnLoadCallback callback) override; - void LoadPublisherState(ledger::client::OnLoadCallback callback) override; - void LoadURL(ledger::type::UrlRequestPtr request, ledger::client::LoadURLCallback callback) override; - void Log(const char * file, const int line, const int verbose_level, const std::string & message) override; - void OnPanelPublisherInfo(ledger::type::Result result, ledger::type::PublisherInfoPtr publisher_info, uint64_t windowId) override; - void OnReconcileComplete(ledger::type::Result result, ledger::type::ContributionInfoPtr contribution) override; - void PublisherListNormalized(ledger::type::PublisherInfoList list) override; - std::string URIEncode(const std::string & value) override; - void OnContributeUnverifiedPublishers(ledger::type::Result result, const std::string& publisher_key, const std::string& publisher_name) override; - void SetBooleanState(const std::string& name, bool value) override; - bool GetBooleanState(const std::string& name) const override; - void SetIntegerState(const std::string& name, int value) override; - int GetIntegerState(const std::string& name) const override; - void SetDoubleState(const std::string& name, double value) override; - double GetDoubleState(const std::string& name) const override; - void SetStringState(const std::string& name, const std::string& value) override; - std::string GetStringState(const std::string& name) const override; - void SetInt64State(const std::string& name, int64_t value) override; - int64_t GetInt64State(const std::string& name) const override; - void SetUint64State(const std::string& name, uint64_t value) override; - uint64_t GetUint64State(const std::string& name) const override; - void ClearState(const std::string& name) override; - std::string GetLegacyWallet() override; - void ShowNotification(const std::string& type, const std::vector& args, ledger::client::ResultCallback callback) override; - bool GetBooleanOption(const std::string& name) const override; - int GetIntegerOption(const std::string& name) const override; - double GetDoubleOption(const std::string& name) const override; - std::string GetStringOption(const std::string& name) const override; - int64_t GetInt64Option(const std::string& name) const override; - uint64_t GetUint64Option(const std::string& name) const override; - ledger::type::ClientInfoPtr GetClientInfo() override; - void UnblindedTokensReady() override; - void ReconcileStampReset() override; - void RunDBTransaction(ledger::type::DBTransactionPtr transaction, ledger::client::RunDBTransactionCallback callback) override; - void GetCreateScript(ledger::client::GetCreateScriptCallback callback) override; - void PendingContributionSaved(const ledger::type::Result result) override; - void ClearAllNotifications() override; - void WalletDisconnected(const std::string& wallet_type) override; - void DeleteLog(ledger::client::ResultCallback callback) override; - bool SetEncryptedStringState(const std::string& key, const std::string& value) override; - std::string GetEncryptedStringState(const std::string& key) override; -}; diff --git a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm deleted file mode 100644 index 373f714306f..00000000000 --- a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm +++ /dev/null @@ -1,139 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import "NativeLedgerClient.h" -#import "NativeLedgerClientBridge.h" - -// Constructor & Destructor -NativeLedgerClient::NativeLedgerClient(id bridge) : bridge_(bridge) { } -NativeLedgerClient::~NativeLedgerClient() { - bridge_ = nil; -} - -void NativeLedgerClient::FetchFavIcon(const std::string & url, const std::string & favicon_key, ledger::client::FetchIconCallback callback) { - [bridge_ fetchFavIcon:url faviconKey:favicon_key callback:callback]; -} -void NativeLedgerClient::LoadLedgerState(ledger::client::OnLoadCallback callback) { - [bridge_ loadLedgerState:callback]; -} -void NativeLedgerClient::LoadPublisherState(ledger::client::OnLoadCallback callback) { - [bridge_ loadPublisherState:callback]; -} -void NativeLedgerClient::LoadURL(ledger::type::UrlRequestPtr request, ledger::client::LoadURLCallback callback) { - [bridge_ loadURL:std::move(request) callback:callback]; -} -void NativeLedgerClient::Log(const char * file, const int line, const int verbose_level, const std::string & message) { - [bridge_ log:file line:line verboseLevel:verbose_level message:message]; -} -void NativeLedgerClient::OnPanelPublisherInfo(ledger::type::Result result, ledger::type::PublisherInfoPtr publisher_info, uint64_t windowId) { - [bridge_ onPanelPublisherInfo:result publisherInfo:std::move(publisher_info) windowId:windowId]; -} -void NativeLedgerClient::OnReconcileComplete(ledger::type::Result result, ledger::type::ContributionInfoPtr contribution) { - [bridge_ onReconcileComplete:result contribution:std::move(contribution)]; -} -void NativeLedgerClient::PublisherListNormalized(ledger::type::PublisherInfoList list) { - [bridge_ publisherListNormalized:std::move(list)]; -} -std::string NativeLedgerClient::URIEncode(const std::string & value) { - return [bridge_ URIEncode:value]; -} -void NativeLedgerClient::OnContributeUnverifiedPublishers(ledger::type::Result result, const std::string& publisher_key, const std::string& publisher_name) { - return [bridge_ onContributeUnverifiedPublishers:result publisherKey:publisher_key publisherName:publisher_name]; -} -void NativeLedgerClient::SetBooleanState(const std::string& name, bool value) { - [bridge_ setBooleanState:name value:value]; -} -bool NativeLedgerClient::GetBooleanState(const std::string& name) const { - return [bridge_ getBooleanState:name]; -} -void NativeLedgerClient::SetIntegerState(const std::string& name, int value) { - [bridge_ setIntegerState:name value:value]; -} -int NativeLedgerClient::GetIntegerState(const std::string& name) const { - return [bridge_ getIntegerState:name]; -} -void NativeLedgerClient::SetDoubleState(const std::string& name, double value) { - [bridge_ setDoubleState:name value:value]; -} -double NativeLedgerClient::GetDoubleState(const std::string& name) const { - return [bridge_ getDoubleState:name]; -} -void NativeLedgerClient::SetStringState(const std::string& name, const std::string& value) { - [bridge_ setStringState:name value:value]; -} -std::string NativeLedgerClient::GetStringState(const std::string& name) const { - return [bridge_ getStringState:name]; -} -void NativeLedgerClient::SetInt64State(const std::string& name, int64_t value) { - [bridge_ setInt64State:name value:value]; -} -int64_t NativeLedgerClient::GetInt64State(const std::string& name) const { - return [bridge_ getInt64State:name]; -} -void NativeLedgerClient::SetUint64State(const std::string& name, uint64_t value) { - [bridge_ setUint64State:name value:value]; -} -uint64_t NativeLedgerClient::GetUint64State(const std::string& name) const { - return [bridge_ getUint64State:name]; -} -void NativeLedgerClient::ClearState(const std::string& name) { - [bridge_ clearState:name]; -} -std::string NativeLedgerClient::GetLegacyWallet() { - return [bridge_ getLegacyWallet]; -} -void NativeLedgerClient::ShowNotification(const std::string& type, const std::vector& args, ledger::client::ResultCallback callback) { - [bridge_ showNotification:type args:args callback:callback]; -} -bool NativeLedgerClient::GetBooleanOption(const std::string& name) const { - return [bridge_ getBooleanOption:name]; -} -int NativeLedgerClient::GetIntegerOption(const std::string& name) const { - return [bridge_ getIntegerOption:name]; -} -double NativeLedgerClient::GetDoubleOption(const std::string& name) const { - return [bridge_ getDoubleOption:name]; -} -std::string NativeLedgerClient::GetStringOption(const std::string& name) const { - return [bridge_ getStringOption:name]; -} -int64_t NativeLedgerClient::GetInt64Option(const std::string& name) const { - return [bridge_ getInt64Option:name]; -} -uint64_t NativeLedgerClient::GetUint64Option(const std::string& name) const { - return [bridge_ getUint64Option:name]; -} -ledger::type::ClientInfoPtr NativeLedgerClient::GetClientInfo() { - return [bridge_ getClientInfo]; -} -void NativeLedgerClient::UnblindedTokensReady() { - [bridge_ unblindedTokensReady]; -} -void NativeLedgerClient::ReconcileStampReset() { - [bridge_ reconcileStampReset]; -} -void NativeLedgerClient::RunDBTransaction(ledger::type::DBTransactionPtr transaction, ledger::client::RunDBTransactionCallback callback) { - [bridge_ runDBTransaction:std::move(transaction) callback:callback]; -} -void NativeLedgerClient::GetCreateScript(ledger::client::GetCreateScriptCallback callback) { - [bridge_ getCreateScript:callback]; -} -void NativeLedgerClient::PendingContributionSaved(const ledger::type::Result result) { - [bridge_ pendingContributionSaved:result]; -} -void NativeLedgerClient::ClearAllNotifications() { - [bridge_ clearAllNotifications]; -} -void NativeLedgerClient::WalletDisconnected(const std::string& wallet_type) { - [bridge_ walletDisconnected:wallet_type]; -} -void NativeLedgerClient::DeleteLog(ledger::client::ResultCallback callback) { - [bridge_ deleteLog:callback]; -} -bool NativeLedgerClient::SetEncryptedStringState(const std::string& key, const std::string& value) { - return [bridge_ setEncryptedStringState:key value:value]; -} -std::string NativeLedgerClient::GetEncryptedStringState(const std::string& key) { - return [bridge_ getEncryptedStringState:key]; -} diff --git a/vendor/brave-ios/Ledger/Models/BATPromotionSolution.h b/vendor/brave-ios/Ledger/Models/BATPromotionSolution.h deleted file mode 100644 index 6fd26b6356d..00000000000 --- a/vendor/brave-ios/Ledger/Models/BATPromotionSolution.h +++ /dev/null @@ -1,24 +0,0 @@ -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. - -#import - -NS_ASSUME_NONNULL_BEGIN - -/// The solution to claiming a promotion on iOS. Obtain the `nonce` through -/// `[BATBraveLedger claimPromotion:completion:]` method, and obtain the -/// blob and signature from the users keychain -OBJC_EXPORT -NS_SWIFT_NAME(PromotionSolution) -@interface BATPromotionSolution : NSObject - -@property (nonatomic, copy) NSString *nonce; -@property (nonatomic, copy) NSString *blob; -@property (nonatomic, copy) NSString *signature; - -- (NSString *)JSONPayload; - -@end - -NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Models/BATPromotionSolution.mm b/vendor/brave-ios/Ledger/Models/BATPromotionSolution.mm deleted file mode 100644 index 8528e6affdd..00000000000 --- a/vendor/brave-ios/Ledger/Models/BATPromotionSolution.mm +++ /dev/null @@ -1,27 +0,0 @@ -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. - -#import "BATPromotionSolution.h" - -#import "ledger.mojom.objc.h" -#import "RewardsLogging.h" - -@implementation BATPromotionSolution - -- (NSString *)JSONPayload -{ - NSDictionary *payload = @{ - @"nonce": self.nonce, - @"blob": self.blob, - @"signature": self.signature - }; - NSData *jsonData = [NSJSONSerialization dataWithJSONObject:payload options:0 error:nil]; - if (!jsonData) { - BLOG(1, @"Missing JSON payload while attempting to attest promotion"); - return @""; - } - return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; -} - -@end diff --git a/vendor/brave-ios/Ledger/Models/BATRewardsNotification.h b/vendor/brave-ios/Ledger/Models/BATRewardsNotification.h deleted file mode 100644 index 948fb4ef637..00000000000 --- a/vendor/brave-ios/Ledger/Models/BATRewardsNotification.h +++ /dev/null @@ -1,41 +0,0 @@ -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. - -#import - -NS_ASSUME_NONNULL_BEGIN - -typedef NS_ENUM(NSInteger, BATRewardsNotificationKind) { - BATRewardsNotificationKindInvalid, - BATRewardsNotificationKindAutoContribute, - BATRewardsNotificationKindGrant, - BATRewardsNotificationKindGrantAds, - BATRewardsNotificationKindFailedContribution, - BATRewardsNotificationKindInsufficientFunds, - BATRewardsNotificationKindBackupWallet, - BATRewardsNotificationKindTipsProcessed, - BATRewardsNotificationKindAdsLaunch, // Unused - BATRewardsNotificationKindVerifiedPublisher, - BATRewardsNotificationKindPendingNotEnoughFunds, - BATRewardsNotificationKindGeneralLedger // Comes from ledger -} NS_SWIFT_NAME(RewardsNotification.Kind); - -OBJC_EXPORT -NS_SWIFT_NAME(RewardsNotification) -@interface BATRewardsNotification : NSObject - -@property (nonatomic, copy) NSString *id; -@property (nonatomic) NSTimeInterval dateAdded; -@property (nonatomic) BATRewardsNotificationKind kind; -@property (nonatomic, copy) NSDictionary *userInfo; -@property (nonatomic) BOOL displayed; - -- (instancetype)initWithID:(NSString *)notificationID - dateAdded:(NSTimeInterval)dateAdded - kind:(BATRewardsNotificationKind)kind - userInfo:(nullable NSDictionary *)userInfo; - -@end - -NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Ledger/Models/BATRewardsNotification.m b/vendor/brave-ios/Ledger/Models/BATRewardsNotification.m deleted file mode 100644 index 258a9e3adc1..00000000000 --- a/vendor/brave-ios/Ledger/Models/BATRewardsNotification.m +++ /dev/null @@ -1,50 +0,0 @@ -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. - -#import "BATRewardsNotification.h" - -@implementation BATRewardsNotification - -- (instancetype)initWithID:(NSString *)notificationID - dateAdded:(NSTimeInterval)dateAdded - kind:(BATRewardsNotificationKind)kind - userInfo:(NSDictionary *)userInfo -{ - if ((self = [super init])) { - self.id = notificationID; - self.dateAdded = dateAdded; - self.kind = kind; - self.userInfo = userInfo; - self.displayed = NO; - } - return self; -} - -+ (BOOL)supportsSecureCoding -{ - return YES; -} - -- (instancetype)initWithCoder:(NSCoder *)aDecoder -{ - if ((self = [super init])) { - self.id = [aDecoder decodeObjectOfClass:NSString.class forKey:@"id"]; - self.dateAdded = [aDecoder decodeDoubleForKey:@"dateAdded"]; - self.kind = (BATRewardsNotificationKind)[aDecoder decodeIntegerForKey:@"kind"]; - self.userInfo = [aDecoder decodeObjectOfClass:NSDictionary.class forKey:@"userInfo"]; - self.displayed = [aDecoder decodeBoolForKey:@"displayed"]; - } - return self; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder -{ - [aCoder encodeObject:self.id forKey:@"id"]; - [aCoder encodeDouble:self.dateAdded forKey:@"dateAdded"]; - [aCoder encodeInteger:self.kind forKey:@"kind"]; - [aCoder encodeObject:self.userInfo forKey:@"userInfo"]; - [aCoder encodeBool:self.displayed forKey:@"displayed"]; -} - -@end diff --git a/vendor/brave-ios/Shared/BATCommonOperations.mm b/vendor/brave-ios/Shared/BATCommonOperations.mm deleted file mode 100644 index 01370582910..00000000000 --- a/vendor/brave-ios/Shared/BATCommonOperations.mm +++ /dev/null @@ -1,175 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import "BATCommonOperations.h" -#include - -#import "ledger.mojom.objc.h" -#import "RewardsLogging.h" - -@interface BATCommonOperations () -@property (nonatomic, copy) NSString *storagePath; -@property (nonatomic, assign) uint32_t currentTimerID; -@property (nonatomic, copy) NSMutableDictionary *timers; // {ID: Timer} -@property (nonatomic, copy) NSMutableArray *runningTasks; -@end - -@implementation BATCommonOperations - -- (instancetype)initWithStoragePath:(NSString *)storagePath -{ - if ((self = [super init])) { - self.storagePath = storagePath; - _timers = [[NSMutableDictionary alloc] init]; - _runningTasks = [[NSMutableArray alloc] init]; - - // Setup the ads directory for persistant storage - if (self.storagePath.length > 0) { - if (![NSFileManager.defaultManager fileExistsAtPath:self.storagePath isDirectory:nil]) { - [NSFileManager.defaultManager createDirectoryAtPath:self.storagePath - withIntermediateDirectories:true - attributes:nil - error:nil]; - } - } - } - return self; -} - -- (instancetype)init -{ - return [self initWithStoragePath:nil]; -} - -- (void)dealloc -{ - [self.runningTasks makeObjectsPerformSelector:@selector(cancel)]; - for (NSNumber *timerID in self.timers) { - [self.timers[timerID] invalidate]; - } -} - -- (const std::string)generateUUID -{ - return std::string([NSUUID UUID].UUIDString.UTF8String); -} - -- (void)loadURLRequest:(const std::string &)url headers:(const std::vector &)headers content:(const std::string &)content content_type:(const std::string &)content_type method:(const std::string &)method callback:(BATNetworkCompletionBlock)callback -{ - const auto session = NSURLSession.sharedSession; - const auto nsurl = [NSURL URLWithString:[NSString stringWithUTF8String:url.c_str()]]; - const auto request = [[NSMutableURLRequest alloc] initWithURL:nsurl]; - - for (const auto& header : headers) { - const auto bridged = [NSString stringWithUTF8String:header.c_str()]; - const auto split = [bridged componentsSeparatedByString:@":"]; - if (split.count == 2 && split.firstObject && split.lastObject) { - auto name = [split.firstObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; - auto value = [split.lastObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; - [request setValue:value forHTTPHeaderField:name]; - } - } - - if (self.customUserAgent != nil && - self.customUserAgent.length > 0) { - [request setValue:self.customUserAgent forHTTPHeaderField:@"User-Agent"]; - } - - if (content_type.length() > 0) { - [request setValue:[NSString stringWithUTF8String:content_type.c_str()] forHTTPHeaderField:@"Content-Type"]; - } - - request.HTTPMethod = [NSString stringWithUTF8String:method.c_str()]; - - if (method != "GET" && content.length() > 0) { - // Assumed http body - request.HTTPBody = [[NSString stringWithUTF8String:content.c_str()] dataUsingEncoding:NSUTF8StringEncoding]; - } - - const auto __weak weakSelf = self; - NSURLSessionDataTask *task = nil; - task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable urlResponse, NSError * _Nullable error) { - if (!weakSelf) { return; }; - const auto strongSelf = weakSelf; - - const auto response = (NSHTTPURLResponse *)urlResponse; - std::string body; - if (data && data.length > 0) { - body = std::string(static_cast(data.bytes), data.length); - } - std::string errorDescription; - if (error) { - errorDescription = error.localizedDescription.UTF8String; - } - // For some reason I couldn't just do `base::flat_map - // responseHeaders;` due to base::flat_map's non-const key insertion - auto* responseHeaders = new base::flat_map(); - [response.allHeaderFields enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSString * _Nonnull obj, BOOL * _Nonnull stop) { - if (![key isKindOfClass:NSString.class] || ![obj isKindOfClass:NSString.class]) { return; } - std::string stringKey(key.UTF8String); - std::string stringValue(obj.UTF8String); - responseHeaders->insert(std::make_pair(stringKey, stringValue)); - }]; - auto copiedHeaders = base::flat_map(*responseHeaders); - const auto __weak weakSelf2 = strongSelf; - dispatch_async(dispatch_get_main_queue(), ^{ - if (!weakSelf2) { return; } - [weakSelf2.runningTasks removeObject:task]; - callback(errorDescription, (int)response.statusCode, body, copiedHeaders); - }); - delete responseHeaders; - }]; - // dataTaskWithRequest returns _Nonnull, so no need to worry about initialized variable being nil - [self.runningTasks addObject:task]; - [task resume]; -} - -#pragma mark - - -- (NSString *)dataPathForFilename:(NSString *)filename -{ - return [self.storagePath stringByAppendingPathComponent:filename]; -} - -- (bool)saveContents:(const std::string &)contents name:(const std::string &)name -{ - const auto filename = [NSString stringWithUTF8String:name.c_str()]; - const auto nscontents = [NSString stringWithUTF8String:contents.c_str()]; - NSError *error = nil; - const auto path = [self dataPathForFilename:filename]; - const auto result = [nscontents writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error]; - if (error) { - BLOG(0, @"Failed to save data for %@: %@", filename, error.debugDescription); - } - return result; -} - -- (std::string)loadContentsFromFileWithName:(const std::string &)name -{ - const auto filename = [NSString stringWithUTF8String:name.c_str()]; - NSError *error = nil; - const auto path = [self dataPathForFilename:filename]; - BLOG(2, @"Loading contents from file: %@", path); - const auto contents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error]; - if (error) { - BLOG(0, @"Failed to load data for %@: %@", filename, error.debugDescription); - return ""; - } - return std::string(contents.UTF8String); -} - -- (bool)removeFileWithName:(const std::string &)name -{ - const auto filename = [NSString stringWithUTF8String:name.c_str()]; - NSError *error = nil; - const auto path = [self dataPathForFilename:filename]; - const auto result = [NSFileManager.defaultManager removeItemAtPath:path error:&error]; - if (error) { - BLOG(0, @"Failed to remove data for filename: %@", filename); - return false; - } - return result; -} - -@end diff --git a/vendor/brave-ios/Shared/NSURL+Extensions.h b/vendor/brave-ios/Shared/NSURL+Extensions.h deleted file mode 100644 index f6042a475a1..00000000000 --- a/vendor/brave-ios/Shared/NSURL+Extensions.h +++ /dev/null @@ -1,16 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import - -NS_ASSUME_NONNULL_BEGIN - -OBJC_EXPORT -@interface NSURL (Extensions) - -@property (nonatomic, nullable, readonly) NSString *bat_normalizedHost; - -@end - -NS_ASSUME_NONNULL_END diff --git a/vendor/brave-ios/Shared/NSURL+Extensions.mm b/vendor/brave-ios/Shared/NSURL+Extensions.mm deleted file mode 100644 index 5db68cf79c7..00000000000 --- a/vendor/brave-ios/Shared/NSURL+Extensions.mm +++ /dev/null @@ -1,19 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import "NSURL+Extensions.h" - -@implementation NSURL (Extensions) - -- (NSString *)bat_normalizedHost -{ - const auto host = self.host; - const auto range = [host rangeOfString:@"^(www|mobile|m)\\." options:NSRegularExpressionSearch]; - if (range.length > 0) { - return [host stringByReplacingCharactersInRange:range withString:@""]; - } - return host; -} - -@end diff --git a/vendor/brave-ios/Shared/RewardsLogging.h b/vendor/brave-ios/Shared/RewardsLogging.h deleted file mode 100644 index 630b08c2620..00000000000 --- a/vendor/brave-ios/Shared/RewardsLogging.h +++ /dev/null @@ -1,37 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef RewardsLogging_h -#define RewardsLogging_h - -#include -#include -#include - -#import - -@class BATBraveRewards; - -namespace rewards { - -void set_rewards_client_for_logging(BATBraveRewards *rewards); - -void LogMessage(const char* file, - int line, - int verbose_level, - NSString *message); - -void Log(const char* file, - int line, - int verbose_level, - NSString *format, - ...) NS_FORMAT_FUNCTION(4,5); - -#define BLOG(verbose_level, format, ...) rewards::Log(__FILE__, __LINE__, \ - verbose_level, format, ##__VA_ARGS__); - -} // namespace rewards - -#endif // RewardsLogging_h diff --git a/vendor/brave-ios/Shared/RewardsLogging.mm b/vendor/brave-ios/Shared/RewardsLogging.mm deleted file mode 100644 index 83a2ac256aa..00000000000 --- a/vendor/brave-ios/Shared/RewardsLogging.mm +++ /dev/null @@ -1,51 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "RewardsLogging.h" -#import "BATBraveRewards.h" - -namespace rewards { - -__weak BATBraveRewards* g_rewards_client = nil; - -void set_rewards_client_for_logging(BATBraveRewards *rewards) { - g_rewards_client = rewards; -} - -void LogMessage(const char* file, - int line, - int verbose_level, - NSString *message) { - if (!g_rewards_client) { - return; - } - - const auto filename = [NSString stringWithUTF8String:file]; - - [g_rewards_client.delegate logMessageWithFilename:filename - lineNumber:line - verbosity:verbose_level - message:message]; -} - -void Log(const char* file, int line, int verbose_level, NSString *format, ...) { - if (!g_rewards_client) { - return; - } - - const auto filename = [NSString stringWithUTF8String:file]; - - va_list args; - va_start(args, format); - NSString *message = [[NSString alloc] initWithFormat:format arguments:args]; - va_end(args); - - [g_rewards_client.delegate logMessageWithFilename:filename - lineNumber:line - verbosity:verbose_level - message:message]; -} - -} // namespace rewards diff --git a/vendor/brave-ios/objc-gen/Clang/Info.plist b/vendor/brave-ios/objc-gen/Clang/Info.plist deleted file mode 100644 index f13e0d0ccb1..00000000000 --- a/vendor/brave-ios/objc-gen/Clang/Info.plist +++ /dev/null @@ -1,24 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - FMWK - CFBundleShortVersionString - 1.0 - CFBundleVersion - $(CURRENT_PROJECT_VERSION) - NSHumanReadableCopyright - Copyright ยฉ 2019 Brave. All rights reserved. - - diff --git a/vendor/brave-ios/objc-gen/Clang/link_clang.xcconfig b/vendor/brave-ios/objc-gen/Clang/link_clang.xcconfig deleted file mode 100644 index 5e1c48c8bb9..00000000000 --- a/vendor/brave-ios/objc-gen/Clang/link_clang.xcconfig +++ /dev/null @@ -1,3 +0,0 @@ -LIBRARY_SEARCH_PATHS = /usr/local/opt/llvm/lib -HEADER_SEARCH_PATHS = /usr/local/opt/llvm/include -OTHER_LDFLAGS = -lclang diff --git a/vendor/brave-ios/objc-gen/Clang/module.modulemap b/vendor/brave-ios/objc-gen/Clang/module.modulemap deleted file mode 100644 index fd47489478f..00000000000 --- a/vendor/brave-ios/objc-gen/Clang/module.modulemap +++ /dev/null @@ -1,4 +0,0 @@ -module Clang [extern_c] { - header "/usr/local/opt/llvm/include/clang-c/Index.h" - export * -} diff --git a/vendor/brave-ios/objc-gen/CppTransformations.h b/vendor/brave-ios/objc-gen/CppTransformations.h deleted file mode 100644 index 0044f44e0fa..00000000000 --- a/vendor/brave-ios/objc-gen/CppTransformations.h +++ /dev/null @@ -1,270 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import -#import -#import -#import -#import -#import "base/containers/flat_map.h" - -static std::map numberInitMap = { - { @encode(bool), @selector(numberWithBool:) }, - { @encode(char), @selector(numberWithChar:) }, - { @encode(double), @selector(numberWithDouble:) }, - { @encode(float), @selector(numberWithFloat:) }, - { @encode(int), @selector(numberWithInt:) }, - { @encode(NSInteger), @selector(numberWithInteger:) }, - { @encode(long), @selector(numberWithLong:) }, - { @encode(long long), @selector(numberWithLongLong:) }, - { @encode(short), @selector(numberWithShort:) }, - { @encode(unsigned char), @selector(numberWithUnsignedChar:) }, - { @encode(unsigned int), @selector(numberWithUnsignedInt:) }, - { @encode(NSUInteger), @selector(numberWithUnsignedInteger:) }, - { @encode(unsigned long), @selector(numberWithUnsignedLong:) }, - { @encode(unsigned long long), @selector(numberWithUnsignedLongLong:) }, - { @encode(unsigned short), @selector(numberWithUnsignedShort:) }, -}; - -static std::map numberGetterMap = { - { @encode(bool), @selector(boolValue) }, - { @encode(char), @selector(charValue) }, - { @encode(double), @selector(doubleValue) }, - { @encode(float), @selector(floatValue) }, - { @encode(int), @selector(intValue) }, - { @encode(NSInteger), @selector(integerValue) }, - { @encode(long), @selector(longValue) }, - { @encode(long long), @selector(longLongValue) }, - { @encode(short), @selector(shortValue) }, - { @encode(unsigned char), @selector(unsignedCharValue) }, - { @encode(unsigned int), @selector(unsignedIntValue) }, - { @encode(NSUInteger), @selector(unsignedIntegerValue) }, - { @encode(unsigned long), @selector(unsignedLongValue) }, - { @encode(unsigned long long), @selector(unsignedLongLongValue) }, - { @encode(unsigned short), @selector(unsignedShortValue) }, -}; - -#pragma mark - Vectors - -/// Convert a vector storing primatives to an array of NSNumber's -template -NS_INLINE NSArray *NSArrayFromVector(std::vector v) { - const auto a = [NSMutableArray new]; - if (v.empty()) { - return @[]; - } - // Since vector's are uniformly typed, we can just use v[0] - const auto encode = @encode(__typeof__(v[0])); - const auto selector = numberInitMap[encode]; - if (selector == nullptr) { return @[]; } - const auto method = class_getClassMethod(NSNumber.class, selector); - typedef NSNumber *(*NSNumberCall)(id,SEL,T); - NSNumberCall call = (NSNumberCall)method_getImplementation(method); - - for (auto t : v) { - NSNumber *number = (NSNumber *)call(NSNumber.class, selector, t); - [a addObject:number]; - } - return a; -} - -/// Convert an NSArray storing NSNumber's to a std::vector storing primatives -template -NS_INLINE std::vector VectorFromNSArray(NSArray *a) { - std::vector v; - if (a.count == 0) { - return v; - } - const auto encode = @encode(__typeof__(T)); - const auto selector = numberGetterMap[encode]; - if (selector == nullptr) { return v; } - const auto method = class_getInstanceMethod(NSNumber.class, selector); - typedef T(*NSNumberCall)(id,SEL); - NSNumberCall call = (NSNumberCall)method_getImplementation(method); - - for (NSNumber *number in a) { - v.push_back(call(number, selector)); - } - return v; -} - -/// Convert a vector storing strings to an array of NSString's -NS_INLINE NSArray *NSArrayFromVector(std::vector v) { - const auto a = [NSMutableArray new]; - for (auto s : v) { - [a addObject:[NSString stringWithCString:s.c_str() encoding:NSUTF8StringEncoding]]; - } - return a; -} - -/// Convert an NSArray storing strings to an vector of std::string's -NS_INLINE std::vector VectorFromNSArray(NSArray *a) { - std::vector v; - for (NSString *str in a) { - v.push_back(std::string(str.UTF8String)); - } - return v; -} - -/// Convert a vector storing objects to an array of transformed objects's -template -NS_INLINE NSArray *NSArrayFromVector(std::vector v, T(^transform)(const U&)) { - const auto a = [NSMutableArray new]; - for (const auto& o : v) { - [a addObject:transform(o)]; - } - return a; -} - -/// Convert a vector storing objects to an array of transformed objects's -template -NS_INLINE NSArray *NSArrayFromVector(const std::vector *v, T(^transform)(const U&)) { - const auto a = [NSMutableArray new]; - if (v == nullptr) { return a; } - for (const auto& o : *v) { - [a addObject:transform(o)]; - } - return a; -} - -/// Convert a NSArray storing objects to an std::vector of transformed objects's -template -NS_INLINE std::vector VectorFromNSArray(NSArray *a, U(^transform)(T)) { - std::vector v; - for (id t in a) { - v.push_back(transform(t)); - } - return v; -} - -#pragma mark - Maps - -/// Get an NSNumber object from a primitive type (int, bool, etc.) -template -NS_INLINE NSNumber* NumberFromPrimitive(T t) { - const auto encode = @encode(__typeof__(t)); - const auto selector = numberInitMap[encode]; - if (selector == nullptr) { return nil; } - const auto method = class_getClassMethod(NSNumber.class, selector); - typedef NSNumber *(*NSNumberCall)(id,SEL,T); - NSNumberCall call = (NSNumberCall)method_getImplementation(method); - return (NSNumber *)call(NSNumber.class, selector, t); -} - -/// Convert a String's to primitives mapping to an NSDictionary -template -NS_INLINE NSDictionary *NSDictionaryFromMap(std::map m) { - const auto d = [NSMutableDictionary new]; - if (m.empty()) { - return @{}; - } - for (auto item : m) { - d[[NSString stringWithCString:item.first.c_str() encoding:NSUTF8StringEncoding]] = - NumberFromPrimitive(item.second); - } - return d; -} - -/// Convert a String's to primitives mapping to an NSDictionary -template -NS_INLINE NSDictionary *NSDictionaryFromMap(base::flat_map m) { - const auto d = [NSMutableDictionary new]; - if (m.empty()) { - return @{}; - } - for (auto item : m) { - d[[NSString stringWithCString:item.first.c_str() encoding:NSUTF8StringEncoding]] = - NumberFromPrimitive(item.second); - } - return d; -} - -/// Convert a String to String mapping to an NSDictionary -NS_INLINE NSDictionary *NSDictionaryFromMap(std::map m) { - const auto d = [NSMutableDictionary new]; - if (m.empty()) { - return @{}; - } - for (auto item : m) { - d[[NSString stringWithCString:item.first.c_str() encoding:NSUTF8StringEncoding]] = - [NSString stringWithCString:item.second.c_str() encoding:NSUTF8StringEncoding]; - } - return d; -} - -/// Convert a String to String mapping to an NSDictionary -NS_INLINE NSDictionary *NSDictionaryFromMap(base::flat_map m) { - const auto d = [NSMutableDictionary new]; - if (m.empty()) { - return @{}; - } - for (auto item : m) { - d[[NSString stringWithCString:item.first.c_str() encoding:NSUTF8StringEncoding]] = - [NSString stringWithCString:item.second.c_str() encoding:NSUTF8StringEncoding]; - } - return d; -} - -/// Convert a String to C++ object mapping to an NSDictionary of String to Obj-C objects -template -NS_INLINE NSDictionary *NSDictionaryFromMap(std::map m, ObjCObj(^transform)(V)) { - const auto d = [NSMutableDictionary new]; - if (m.empty()) { - return @{}; - } - for (auto item : m) { - d[[NSString stringWithCString:item.first.c_str() encoding:NSUTF8StringEncoding]] = transform(item.second); - } - return d; -} - -/// Convert a String to C++ object mapping to an NSDictionary of String to Obj-C objects -template -NS_INLINE NSDictionary *NSDictionaryFromMap(base::flat_map m, ObjCObj(^transform)(V)) { - const auto d = [NSMutableDictionary new]; - if (m.empty()) { - return @{}; - } - for (auto item : m) { - d[[NSString stringWithCString:item.first.c_str() encoding:NSUTF8StringEncoding]] = transform(item.second); - } - return d; -} - -/// Convert any mapping to an NSDictionary of Obj-C objects by transforming both the key and the value types to Obj-C -/// types -template -NS_INLINE NSDictionary *NSDictionaryFromMap(std::map m, KObjC(^transformKey)(K), VObjC(^transformValue)(V)) { - const auto d = [NSMutableDictionary new]; - if (m.empty()) { - return @{}; - } - for (auto item : m) { - d[transformKey(item.first)] = transformValue(item.second); - } - return d; -} - -/// Convert any mapping to an NSDictionary of Obj-C objects by transforming both the key and the value types to Obj-C -/// types -template -NS_INLINE NSDictionary *NSDictionaryFromMap(base::flat_map m, KObjC(^transformKey)(K), VObjC(^transformValue)(V)) { - const auto d = [NSMutableDictionary new]; - if (m.empty()) { - return @{}; - } - for (auto item : m) { - d[transformKey(item.first)] = transformValue(item.second); - } - return d; -} - -/// Converts an NSDictionary that has NSString keys & values to a base::flat_map with std::string keys & values -NS_INLINE base::flat_map MapFromNSDictionary(NSDictionary *d) { - base::flat_map map; - for (NSString *key in d) { - map.insert(std::make_pair(key.UTF8String, d[key].UTF8String)); - } - return map; -} diff --git a/vendor/brave-ios/objc-gen/objc-gen/Bridge.swift b/vendor/brave-ios/objc-gen/objc-gen/Bridge.swift deleted file mode 100644 index f7ac84364d7..00000000000 --- a/vendor/brave-ios/objc-gen/objc-gen/Bridge.swift +++ /dev/null @@ -1,195 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import Foundation -import Clang - -extension Cursor { - var isConstCXXMethod: Bool { - return clang_CXXMethod_isConst(cursor) == 1 - } - - var isPureVirtualCXXMethod: Bool { - return clang_CXXMethod_isPureVirtual(cursor) == 1 - } - - var resultType: CXType { - return clang_getResultType(type) - } -} - -struct Method: Hashable, Comparable { - struct Argument: Hashable { - let type: String - let typeIsUniquePtr: Bool - let name: String - var objcProtocolFormattedName: String { - return Interface.Property.formatted(name: name) - } - } - - let resultType: String - let resultIsVoid: Bool - let name: String - let isConst: Bool - let arguments: [Argument] - - private static func typeStringFixingLackingNamespace(_ type: CXType) -> String { - let numberOfTemplateArgs = clang_Type_getNumTemplateArguments(type) - let typeString = clang_getTypeSpelling(type).stringAndDisposeAfter - if numberOfTemplateArgs > 0 { - if typeString.hasPrefix("std::unique_ptr") { - return "std::unique_ptr<\(clang_Type_getTemplateArgumentAsType(type, 0))>" - } - } - return typeString - } - - init(cursor: Cursor) { - self.resultType = Method.typeStringFixingLackingNamespace(cursor.resultType) - self.resultIsVoid = cursor.resultType.kind == CXType_Void - self.name = clang_getCursorSpelling(cursor.cursor).stringAndDisposeAfter - self.isConst = clang_CXXMethod_isConst(cursor.cursor) == 1 - self.arguments = (0.. String { - var s = "\(resultType) \(parentClass)::\(name)(\(arguments.map { "\($0.type) \($0.name)" }.joined(separator: ", ")))" - if isConst { - s.append(" const") - } - return s - } - - var generatedProtocolMethodCall: String { - if name.isEmpty { return "" } - var s: String - if name.hasPrefix("URL") || name.hasPrefix("URI") { - s = name - } else { - s = "\(name.first!.lowercased() + String(name.dropFirst()))" - } - if !arguments.isEmpty { - let args = arguments.map { - let value = $0.typeIsUniquePtr ? "std::move(\($0.name))" : $0.name - return $0 == arguments.first ? value : "\($0.objcProtocolFormattedName):\(value)" - }.joined(separator: " ") - s.append(":\(args)") - } - return s - } - - var generatedProtocolMethodDecleration: String { - if name.isEmpty { return "" } - var s = "- (\(resultType))" - if name.hasPrefix("URL") || name.hasPrefix("URI") { - s.append(name) - } else { - s.append("\(name.first!.lowercased() + String(name.dropFirst()))") - } - if !arguments.isEmpty { - s.append(":\(arguments.map { $0 == arguments.first ? "(\($0.type))\($0.name)" : "\($0.objcProtocolFormattedName):(\($0.type))\($0.name)" }.joined(separator: " "))") - } - s.append(";") - return s - } - - static func < (lhs: Method, rhs: Method) -> Bool { - return lhs.name < rhs.name - } -} - -/// Create a generated Obj-C bridge from the a abstract client class (i.e. `ledger_client` or -/// `ads_client`) -/// -/// Outputs: -/// _Assuming that className was "LedgerClient"_ -/// - `NativeLedgerClient.h`: The C++ header class, redefines all methods as non-virtual overrides -/// - `NativeLedgerClient.mm`: The C++ class which will accept a `Native[ClassName]Bridge` and -/// redirect all callbacks to said bridge -/// - `NativeLedgerClientBridge.h`: An Obj-C++ header defining a protocol with all -/// `NativeLedgerClient` callbacks -func createBridge(from clientFile: String, className: String, includePaths: [String], outputDirectory: String) { - let idx = clang_createIndex(0, 1) - defer { clang_disposeIndex(idx) } - // Have to define "LEDGER_EXPORT" so we don't get parsing errors. - // I assume its because we are parsing headers and not source files - let args: [String] = ["-x", "c++", "-std=c++14", "-DLEDGER_EXPORT= ", "-iframework", "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks"] + - (Config.systemIncludes.flatMap { ["-isystem", $0] }) + - (includePaths.flatMap { ["-I", $0] }) - var unit: CXTranslationUnit! - let errorCode = clang_parseTranslationUnit2(idx, clientFile, args.map { ($0 as NSString).utf8String }, Int32(args.count), nil, 0, 0, &unit) - if errorCode.rawValue != 0 { - print("Couldn't parse \(clientFile)") - } - - var methods: Set = [] - var namespace: String = "" - - func _traverse(nodes: [Cursor]) { - for node in nodes where !node.children.isEmpty && node.isFromMainFile { - switch node.kind { - case CXCursor_Namespace: - _traverse(nodes: node.children) - case CXCursor_ClassDecl where node.name == className: - namespace = Cursor(clang_getCursorLexicalParent(node.cursor)).name - methods.formUnion( - node.children - .filter { $0.kind == CXCursor_CXXMethod && $0.isPureVirtualCXXMethod } - .map(Method.init) - ) - default: - continue - } - } - } - - _traverse(nodes: Cursor(clang_getTranslationUnitCursor(unit)).children) - - var updatedPath = clientFile - includePaths.forEach { - updatedPath = updatedPath.replacingOccurrences(of: $0, with: "") - } - if updatedPath.hasPrefix("/") { - updatedPath = String(updatedPath.dropFirst()) - } - - let sortedMethods = methods.sorted() - let outputedFiles: [TemplateOutput] = [ - NativeClientHeaderOutput(namespace: namespace, className: className, includeHeader: updatedPath, methods: sortedMethods), - NativeClientSourceOutput(className: className, methods: sortedMethods), - NativeClientBridgeProtocolOutput(className: className, includeHeader: updatedPath, methods: sortedMethods) - ] - - do { - try FileManager.default.createDirectory(atPath: outputDirectory, withIntermediateDirectories: true, attributes: nil) - try outputedFiles.forEach { - try $0.generated.write(toFile: "\(outputDirectory)/\($0.filename)", atomically: true, encoding: .utf8) - } - } catch { - print("Failed to write generated files to output directory: \(String(describing: error))") - } -} - diff --git a/vendor/brave-ios/objc-gen/objc-gen/BridgeOutput.swift b/vendor/brave-ios/objc-gen/objc-gen/BridgeOutput.swift deleted file mode 100644 index 06c989b9485..00000000000 --- a/vendor/brave-ios/objc-gen/objc-gen/BridgeOutput.swift +++ /dev/null @@ -1,126 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import Foundation -import Clang - -final class NativeClientHeaderOutput: TemplateOutput { - let namespace: String - let className: String - let methods: [Method] - let includeHeader: String - - init(namespace: String, className: String, includeHeader: String, methods: [Method]) { - self.namespace = namespace - self.className = className - self.includeHeader = includeHeader - self.methods = methods - } - - var filename: String { - return "Native\(className).h" - } - var generated: String { - let nativeClassName = "Native\(className)" - let protocolName = "\(nativeClassName)Bridge" - - return """ - \(thisFileIsGeneratedString) - - #import - #import "\(includeHeader)" - - @protocol \(protocolName); - - class \(nativeClassName) : public \(namespace)::\(className) { - public: - \(nativeClassName)(id<\(protocolName)> bridge); - ~\(nativeClassName)() override; - - private: - __unsafe_unretained id<\(protocolName)> bridge_; - - \(methods.map { " \($0.generatedPublicDecleration)" }.joined(separator: "\n")) - }; - - """ - } -} - -final class NativeClientSourceOutput: TemplateOutput { - let className: String - let methods: [Method] - - init(className: String, methods: [Method]) { - self.className = className - self.methods = methods - } - - var filename: String { - return "Native\(className).mm" - } - var generated: String { - let nativeClassName = "Native\(className)" - let protocolName = "\(nativeClassName)Bridge" - - return """ - \(thisFileIsGeneratedString) - - #import "\(nativeClassName).h" - #import "\(protocolName).h" - - // Constructor & Destructor - \(nativeClassName)::\(nativeClassName)(id<\(protocolName)> bridge) : bridge_(bridge) { } - \(nativeClassName)::~\(nativeClassName)() { - bridge_ = nil; - } - - \(methods.map { (method) -> String in - let definition = method.generatedSourceImplementation(parentClass: nativeClassName) - return """ - \(definition) { - \(method.resultIsVoid ? "" : "return ")[bridge_ \(method.generatedProtocolMethodCall)]; - } - """ - }.joined(separator: "\n")) - - """ - } -} - -final class NativeClientBridgeProtocolOutput: TemplateOutput { - let className: String - let methods: [Method] - let includeHeader: String - - init(className: String, includeHeader: String, methods: [Method]) { - self.className = className - self.includeHeader = includeHeader - self.methods = methods - } - - var filename: String { - return "Native\(className)Bridge.h" - } - - var generated: String { - let nativeClassName = "Native\(className)" - let protocolName = "\(nativeClassName)Bridge" - - return """ - \(thisFileIsGeneratedString) - - #import - #import "\(includeHeader)" - - @protocol \(protocolName) - @required - - \(methods.map { $0.generatedProtocolMethodDecleration }.joined(separator: "\n")) - - @end - - """ - } -} diff --git a/vendor/brave-ios/objc-gen/objc-gen/Cursor+ObjC.swift b/vendor/brave-ios/objc-gen/objc-gen/Cursor+ObjC.swift deleted file mode 100644 index d8a6de8f0dd..00000000000 --- a/vendor/brave-ios/objc-gen/objc-gen/Cursor+ObjC.swift +++ /dev/null @@ -1,157 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import Foundation -import Clang - -// MARK: - Obj-C -extension Cursor { - /// Thrown when there is no Obj-C type that can be used in place of some C++ type - struct NoObjCTypeError: Error, CustomStringConvertible { - let cursor: CXCursor - let type: CXType - var description: String { - return "No Obj-C type to use for the given type: \"\(String(describing: type))\"" - } - } - /// Thrown when there is no Obj-C transform available between certain C++ types and an Obj-C type - /// for an r-value assignment. - /// - /// Example transforming between an `std::map` where we haven't written a supported - /// transformer for its given key/value types - struct NoObjCTransformError: Error { - let cursor: Cursor - } - - private func _objCType(for type: CXType, inObject: Bool) throws -> String { - let typeString = clang_getTypeSpelling(type).stringAndDisposeAfter - switch type.kind { - case CXType_Record: - // C++ struct - let name = clang_getCursorDisplayName(clang_getTypeDeclaration(type)).stringAndDisposeAfter - return "\(Config.classPrefix)\(name) *" - case CXType_Enum: - let name = clang_getCursorDisplayName(clang_getTypeDeclaration(type)).stringAndDisposeAfter - return "\(Config.classPrefix)\(Enum.formatted(name: name))" - case CXType_Typedef: - return try _objCType(for: clang_getCanonicalType(type), inObject: inObject) - case CXType_Bool, - CXType_Char_U, - CXType_UChar, - CXType_Char16, - CXType_Char32, - CXType_UShort, - CXType_UInt, - CXType_ULong, - CXType_ULongLong, - CXType_UInt128, - CXType_Char_S, - CXType_SChar, - CXType_WChar, - CXType_Short, - CXType_Int, - CXType_Long, - CXType_LongLong, - CXType_Int128, - CXType_Float, - CXType_Double, - CXType_LongDouble, - CXType_Float128: - return inObject ? "NSNumber *" : typeString - case CXType_Elaborated: - if typeString.hasPrefix("std::vector") { - // Get the type - let templateType = clang_Type_getTemplateArgumentAsType(type, 0) - return "NSArray<\(try _objCType(for: templateType, inObject: true))> *" - } else if typeString.hasPrefix("std::map") { - // Get the types - let keyType = clang_Type_getTemplateArgumentAsType(type, 0) - let valueType = clang_Type_getTemplateArgumentAsType(type, 1) - return "NSDictionary<\(try _objCType(for: keyType, inObject: true)), \(try _objCType(for: valueType, inObject: true))> *" - } else if typeString.hasPrefix("std::string") { - return "NSString *"; - } - default: - break - } - throw NoObjCTypeError(cursor: cursor, type: type) - } - - /// Get the type to be used in an Obj-C interface. The type used may differ depending on if the - /// type is used within an object (I.e. A property can be an `int`, but stored within an Obj-C - /// storage type (i.e. `NSArray`), it must be an NSNumber - /// - throws: NoObjCTypeError - func objCType(inObject: Bool = false) throws -> String { - let type = clang_getCursorType(cursor) - return try _objCType(for: type, inObject: inObject) - } - - /// Get an Obj-C implementation property assignment r-value string for this cursor. - /// - throws: NoObjCTypeError - func objCAssignmentRValueString(_ accessingObjName: String = "obj") throws -> String { - switch type.kind { - case CXType_Record: - // C++ struct - let name = clang_getCursorDisplayName(clang_getTypeDeclaration(type)).stringAndDisposeAfter - return "[[\(Config.classPrefix)\(name) alloc] initWith\(name): \(accessingObjName).\(name)];" - case CXType_Enum: - let name = clang_getCursorDisplayName(clang_getTypeDeclaration(type)).stringAndDisposeAfter - return "(\(Config.classPrefix)\(Enum.formatted(name: name)))\(accessingObjName).\(self.name)" - case CXType_Typedef, - CXType_Bool, - CXType_Char_U, - CXType_UChar, - CXType_Char16, - CXType_Char32, - CXType_UShort, - CXType_UInt, - CXType_ULong, - CXType_ULongLong, - CXType_UInt128, - CXType_Char_S, - CXType_SChar, - CXType_WChar, - CXType_Short, - CXType_Int, - CXType_Long, - CXType_LongLong, - CXType_Int128, - CXType_Float, - CXType_Double, - CXType_LongDouble, - CXType_Float128: - return "\(accessingObjName).\(name)" - case CXType_Elaborated: - let typeString = clang_getTypeSpelling(type).stringAndDisposeAfter - if typeString.hasPrefix("std::vector") { - // Get the type - let templateType = clang_Type_getTemplateArgumentAsType(type, 0) - switch templateType.kind { - case CXType_Record: - let objcType = try _objCType(for: templateType, inObject: true) - let cppTypeSpelling = clang_getTypeSpelling(templateType).stringAndDisposeAfter - let templateTypeString = clang_getCursorSpelling(clang_getTypeDeclaration(templateType)).stringAndDisposeAfter - return "NSArrayFromVector(\(accessingObjName).\(name), ^\(objcType)(const \(cppTypeSpelling)& o){ return [[\(Config.classPrefix)\(templateTypeString) alloc] initWith\(templateTypeString): o]; })" - default: - return "NSArrayFromVector(\(accessingObjName).\(name))" - } - } else if typeString.hasPrefix("std::map") { - // Get the types - // At the moment we only support [String: AnyObject] dictionaries - let valueType = clang_Type_getTemplateArgumentAsType(type, 1) - if valueType.kind == CXType_Record { - let cppTypeSpelling = clang_getTypeSpelling(valueType) // Includes namespace - let valueTypeString = clang_getCursorSpelling(clang_getTypeDeclaration(valueType)).stringAndDisposeAfter - return "NSDictionaryFromMap(\(accessingObjName).\(name), ^\(Config.classPrefix)\(valueTypeString) *(\(cppTypeSpelling) o){ return [[\(Config.classPrefix)\(valueTypeString) alloc] initWith\(valueTypeString):o]; })" - } - return "NSDictionaryFromMap(\(accessingObjName).\(name))" - } else if typeString.hasPrefix("std::string") { - return "[NSString stringWithUTF8String:\(accessingObjName).\(name).c_str()]"; - } - default: - break - } - throw NoObjCTransformError(cursor: self) - } -} diff --git a/vendor/brave-ios/objc-gen/objc-gen/Cursor.swift b/vendor/brave-ios/objc-gen/objc-gen/Cursor.swift deleted file mode 100644 index 8db0dc6cc09..00000000000 --- a/vendor/brave-ios/objc-gen/objc-gen/Cursor.swift +++ /dev/null @@ -1,80 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import Foundation -import Clang - -/// Simple wrapper around CXCursor -final class Cursor { - /// The underlying cursor - let cursor: CXCursor - init(_ cursor: CXCursor) { - self.cursor = cursor - } - /// The display name for this cursor - var name: String { - return clang_getCursorDisplayName(cursor).stringAndDisposeAfter - } - /// The cursor kind (struct, enum, etc.) - var kind: CXCursorKind { - return clang_getCursorKind(cursor) - } - /// The cursor's type (void, bool, int, etc.) - var type: CXType { - return clang_getCursorType(cursor) - } - /// Whether or not this cursor belongs to the main file being parsed - var isFromMainFile: Bool { - return clang_Location_isFromMainFile(clang_getCursorLocation(cursor)) == 1 - } - /// The cursor's children - lazy private(set) var children: [Cursor] = { - var cursors: [Cursor] = [] - clang_visitChildrenWithBlock(cursor, { (cursor, parent) -> CXChildVisitResult in - cursors.append(Cursor(cursor)) - return CXChildVisit_Continue - }) - return cursors - }() -} - -extension CXString { - /// Obtain a Swift string and dispose the underlying CXString - var stringAndDisposeAfter: String { - defer { clang_disposeString(self) } - if data == nil { return "" } - return String(cString: clang_getCString(self)) - } -} - -// MARK: - Debug Descriptions - -extension CXString: CustomDebugStringConvertible { - public var debugDescription: String { - return self.stringAndDisposeAfter - } -} - -extension Cursor: CustomDebugStringConvertible { - var debugDescription: String { - let prettyPrinted = clang_getCursorPrettyPrinted(cursor, nil).stringAndDisposeAfter - if prettyPrinted.count > 0 { - return prettyPrinted - } - return "\(clang_getCursorKindSpelling(kind).stringAndDisposeAfter) \(clang_getCursorDisplayName(cursor).stringAndDisposeAfter)" - } -} - -extension CXType: CustomDebugStringConvertible { - public var debugDescription: String { - return clang_getTypeSpelling(self).stringAndDisposeAfter - } -} - -extension CXCursorKind: CustomDebugStringConvertible { - public var debugDescription: String { - return clang_getCursorKindSpelling(self).stringAndDisposeAfter - } -} - diff --git a/vendor/brave-ios/objc-gen/objc-gen/Enum.swift b/vendor/brave-ios/objc-gen/objc-gen/Enum.swift deleted file mode 100644 index f2e9873e671..00000000000 --- a/vendor/brave-ios/objc-gen/objc-gen/Enum.swift +++ /dev/null @@ -1,59 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import Foundation -import Clang - -/// An Obj-C enum to generate -struct Enum: Hashable, Comparable { - /// Convert a snake case enum name into an Obj-C capitalized one (i.e. "LOG_LEVEL" returns - /// "LogLevel") - static func formatted(name: String) -> String { - let items = name.components(separatedBy: "_") - if items.count > 1 { - // Probably all-caps - return items.map { $0.lowercased() == "url" ? $0.uppercased() : $0.capitalized }.joined() - } - return name // Likely already fine - } - /// Converts a snake enum case name into an Obj-C capitalized one (i.e. "LEDGER_OK" returns - /// "LedgerOk") - func formatted(caseName: String) -> String { - let c = caseName.components(separatedBy: "_").map { $0.capitalized }.joined() - return "\(Enum.formatted(name: name))\(c)" - } - /// The enum name (unformatted) - var name: String - /// The list of cases and their values (unformatted) - var cases: [(String, Int64)] - /// The generated Obj-C enum output - var generated: String { - let formattedName = Enum.formatted(name: name) - return """ - typedef NS_ENUM(NSInteger, \(Config.classPrefix)\(formattedName)) { - \(cases.map { " \(Config.classPrefix)\(formatted(caseName: $0.0)) = \($0.1)" }.joined(separator: ",\n")) - } NS_SWIFT_NAME(\(formattedName)); - """ - } - static func == (lhs: Enum, rhs: Enum) -> Bool { - return lhs.name == rhs.name && lhs.cases.count == rhs.cases.count - } - func hash(into hasher: inout Hasher) { - hasher.combine(name) - } - static func < (lhs: Enum, rhs: Enum) -> Bool { - return lhs.name < rhs.name - } -} - -extension Enum { - /// Create an enum based on a given Cursor - init(cursor: Cursor) { - assert(cursor.kind == CXCursor_EnumDecl) - let cases = cursor.children - .filter { $0.kind == CXCursor_EnumConstantDecl } - .map { ($0.name, clang_getEnumConstantDeclValue($0.cursor)) } - self.init(name: cursor.name, cases: cases) - } -} diff --git a/vendor/brave-ios/objc-gen/objc-gen/Interface.swift b/vendor/brave-ios/objc-gen/objc-gen/Interface.swift deleted file mode 100644 index 0bd0e711060..00000000000 --- a/vendor/brave-ios/objc-gen/objc-gen/Interface.swift +++ /dev/null @@ -1,103 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import Foundation -import Clang - -/// A C++ struct which will generate an Obj-C @interface -struct Interface: Hashable, Comparable { - /// An interface @property - struct Property { - /// The name of the property (i.e. "isEnabled") (unformatted from C++) - let name: String - /// The property decleration (This will be the @property string placed inside a @interface) - let decleration: String - /// The assignment string (This will be the r-value string placed inside a @implementaion) - let assignmentString: String - - /// Convert a snake case property name into an Obj-C camcelCase'd one (i.e. "opening_balance_" - /// returns "openingBalance") - static func formatted(name: String) -> String { - let pieces = name.components(separatedBy: "_") - if pieces.isEmpty { return name } - if pieces.count == 1 { return pieces.first! } - return ([pieces.first!.lowercased()] + pieces.dropFirst().map { $0.capitalized }).joined() - } - } - /// The @interface's name - let name: String - /// The C++ structs name (including the namespace) - let cppTypeName: String - /// The name with the class prefix used from Config - var prefixedName: String { - return "\(Config.classPrefix)\(name)" - } - /// The properties that will mirror a C++ structs fields - let properties: [Property] - /// The generated output of a this @interface - var generatedPublicInterface: String { - return """ - OBJC_EXPORT - NS_SWIFT_NAME(\(name)) - @interface \(prefixedName) : NSObject - \(properties.map { $0.decleration }.joined(separator: "\n")) - @end - """ - } - /// The private generated output of a this @interface (containing C++ to Obj-C inits) - var generatedPrivateInterface: String { - return """ - @interface \(prefixedName) (Private) - - (instancetype)initWith\(name):(const \(cppTypeName)&)obj; - @end - """ - } - /// The generated implementation of this @interface (containing the Obj-C init methods found in - /// `generatedPrivateInterface`) - var generatedImplementation: String { - let assignments = properties.map({ return "self.\(Property.formatted(name: $0.name)) = \($0.assignmentString);"}) - return """ - @implementation \(Config.classPrefix)\(name) - - (instancetype)initWith\(name):(const \(cppTypeName)&)obj { - if ((self = [super init])) { - \(assignments.map { " \($0)" }.joined(separator: "\n")) - } - return self; - } - @end - """ - } - static func == (lhs: Interface, rhs: Interface) -> Bool { - return lhs.name == rhs.name - } - func hash(into hasher: inout Hasher) { - hasher.combine(name) - } - static func < (lhs: Interface, rhs: Interface) -> Bool { - return lhs.name < rhs.name - } -} - -extension Interface { - init(cursor: Cursor) throws { - // Currently only supporting creating an Obj-C class from a C++ struct - assert(cursor.kind == CXCursor_StructDecl) - self.init( - name: cursor.name, - cppTypeName: clang_getTypeSpelling(cursor.type).stringAndDisposeAfter, - properties: try cursor.children.filter({ $0.kind == CXCursor_FieldDecl }).map({ try Property(cursor: $0) }) - ) - } -} - -extension Interface.Property { - init(cursor: Cursor) throws { - assert(cursor.kind == CXCursor_FieldDecl) - self.init( - name: cursor.name, - decleration: "@property (nonatomic) \(try cursor.objCType()) \(Interface.Property.formatted(name: cursor.name));", - assignmentString: try cursor.objCAssignmentRValueString("obj") - ) - } -} diff --git a/vendor/brave-ios/objc-gen/objc-gen/Output.swift b/vendor/brave-ios/objc-gen/objc-gen/Output.swift deleted file mode 100644 index d1c5265d33c..00000000000 --- a/vendor/brave-ios/objc-gen/objc-gen/Output.swift +++ /dev/null @@ -1,123 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import Foundation -import Clang - -protocol TemplateOutput { - /// The file this template will be written too - var filename: String { get } - /// The generated string for this template - var generated: String { get } -} - -let thisFileIsGeneratedString = """ -/* WARNING: THIS FILE IS GENERATED. ANY CHANGES TO THIS FILE WILL BE OVERWRITTEN - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -""" - -/// Enums.h -final class EnumHeaderOutput: TemplateOutput { - let enums: [Enum] - init(enums: [Enum]) { - self.enums = enums - } - var filename: String { - return "Enums.h" - } - var generated: String { - return """ - \(thisFileIsGeneratedString) - - #import - - \(enums.map { $0.generated }.joined(separator: "\n\n")) - - """ - } -} - -/// Records.h -final class RecordsHeaderOutput: TemplateOutput { - let interfaces: [Interface] - init(interfaces: [Interface]) { - self.interfaces = interfaces - } - var filename: String { - return "Records.h" - } - var generated: String { - return """ - \(thisFileIsGeneratedString) - - #import - #import "Enums.h" - - @class \(interfaces.map { $0.prefixedName }.joined(separator: ", ")); - - NS_ASSUME_NONNULL_BEGIN - - \(interfaces.map { $0.generatedPublicInterface }.joined(separator: "\n\n")) - - NS_ASSUME_NONNULL_END - - """ - } -} - -/// Records+Private.h -final class PrivateRecordsHeaderOutput: TemplateOutput { - let interfaces: [Interface] - let cppIncludes: [String] - init(interfaces: [Interface], cppIncludes: [String]) { - self.interfaces = interfaces - self.cppIncludes = cppIncludes - } - var filename: String { - return "Records+Private.h" - } - var generated: String { - return """ - \(thisFileIsGeneratedString) - - #import - #import "Records.h" - - \(cppIncludes.map { "#include \"\($0)\"" }.joined(separator: "\n")) - - \(interfaces.map { $0.generatedPrivateInterface }.joined(separator: "\n\n")) - - """ - } -} - -/// Records.mm -final class ImplementationSourceOutput: TemplateOutput { - let interfaces: [Interface] - init(interfaces: [Interface]) { - self.interfaces = interfaces - } - var filename: String { - return "Records.mm" - } - var generated: String { - return """ - \(thisFileIsGeneratedString) - - #import "Records.h" - #import "Records+Private.h" - #import "CppTransformations.h" - - #import - #import - #import - - \(interfaces.map { $0.generatedImplementation }.joined(separator: "\n\n")) - - """ - } -} diff --git a/vendor/brave-ios/objc-gen/objc-gen/main.swift b/vendor/brave-ios/objc-gen/objc-gen/main.swift deleted file mode 100644 index 3d2e71513be..00000000000 --- a/vendor/brave-ios/objc-gen/objc-gen/main.swift +++ /dev/null @@ -1,157 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import Foundation -import Clang - -/* - **objc-gen** - Use libclang (https://clang.llvm.org/doxygen/group__CINDEX.html) to parse the AST of header - files and output Obj-C (which can then be imported by Swift) - - objc-gen requires the following dependencies: - - Xcode (Defaults to being required at /Applications/Xcode.app, but can be changed in the Config) - - LLVM (can be installed via `brew install llvm`) - - Input: - A directory or single header file to read supported `structs` & `enums` - Output: - - `Enums.h`: Contains all the enums used within inputted header files - - `Records.h`: Public Obj-C interface for all parsed C++ structs - - `Records+Private.h`: A private interface including init methods which take the mirrored C++ - struct as an argument. Used to create Obj-C structs from C++, and in the future, vice-versa - - `Records.mm`: The Obj-C++ implementations - - Currently only used for bat-native-ledger, but could be used for bat-native-ads as well - - Note: `CppTransformations.h` contains helper methods between supported C++ classes/structs - and an Obj-C type. I.e. `std::string` <-> `NSString`, `std::vector` <-> `NSArray`, and - `std::map` <-> `NSDictionary` and is required to be included by the project importing the - outputted files -*/ - -final class Config { - /// The Obj-C class prefixes - static let classPrefix = "BAT" - /// Includes which are to be included when parsing the AST (both are needed for some reason as of - /// llvm 8.0) - static let systemIncludes = [ - "/usr/local/opt/llvm/include/c++/v1", - "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include", - // Temporary hack: - "/Users/kyle/git/brave/brave-browser/src/", - "/Users/kyle/git/brave/brave-browser/src/out/sim-release/gen/brave/vendor/bat-native-ledger/include", - "/Users/kyle/git/brave/brave-browser/src/out/sim-release/gen/", - ] -} - -func generate(from files: [String], includePaths: [String], outputDirectory: String) { - var enums: Set = [] - var interfaces: Set = [] - - func _traverse(nodes: [Cursor]) { - for node in nodes where !node.children.isEmpty && node.isFromMainFile { - switch node.kind { - case CXCursor_Namespace: - _traverse(nodes: node.children) - case CXCursor_StructDecl: - do { - interfaces.insert(try Interface(cursor: node)) - } catch { - print("Skipping \(node.name) due to error: \(error)") - } - case CXCursor_EnumDecl: - enums.insert(Enum(cursor: node)) - default: - continue - } - } - } - - for file in files { - let idx = clang_createIndex(0, 1) - defer { clang_disposeIndex(idx) } - // Have to define "LEDGER_EXPORT" so we don't get parsing errors. - // I assume its because we are parsing headers and not source files - let args: [String] = ["-x", "c++", "-std=c++14", "-DLEDGER_EXPORT= ", "-iframework", "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks"] + - (Config.systemIncludes.flatMap { ["-isystem", $0] }) + - (includePaths.flatMap { ["-I", $0] }) - var unit: CXTranslationUnit! - let errorCode = clang_parseTranslationUnit2(idx, file, args.map { ($0 as NSString).utf8String }, Int32(args.count), nil, 0, 0, &unit) - if errorCode.rawValue != 0 { - print("Couldn't parse \(file)") - continue - } - - _traverse(nodes: Cursor(clang_getTranslationUnitCursor(unit)).children) - } - - let sortedInterfaces = interfaces.sorted() - - // We have to cheat a bit and force the export.h files to be at the top since a lot of files - // in the ledger includes use `LEDGER_EXPORT` but not `#include "bat/ledger/export.h" - let fudgedSortedFiles = files.sorted(by: { $0.contains("export.h") ? true : $0 < $1 }) - let cppIncludes: [String] = fudgedSortedFiles.map { filename in - var updatedPath = filename - includePaths.forEach { - updatedPath = updatedPath.replacingOccurrences(of: $0, with: "") - } - if updatedPath.hasPrefix("/") { - updatedPath = String(updatedPath.dropFirst()) - } - return updatedPath - } - - let outputedFiles: [TemplateOutput] = [ - EnumHeaderOutput(enums: enums.sorted()), - RecordsHeaderOutput(interfaces: sortedInterfaces), - PrivateRecordsHeaderOutput(interfaces: sortedInterfaces, cppIncludes: cppIncludes), - ImplementationSourceOutput(interfaces: sortedInterfaces) - ] - - do { - try FileManager.default.createDirectory(atPath: outputDirectory, withIntermediateDirectories: true, attributes: nil) - try outputedFiles.forEach { - try $0.generated.write(toFile: "\(outputDirectory)/\($0.filename)", atomically: true, encoding: .utf8) - } - } catch { - print("Failed to write generated files to output directory: \(String(describing: error))") - } -} - -guard let libraryPath = ProcessInfo.processInfo.environment["BATLibraryPath"], - let ledgerPath = ProcessInfo.processInfo.environment["BATLedgerPath"], - let adsPath = ProcessInfo.processInfo.environment["BATAdsPath"] else { - fatalError("Missing `BATLibraryPath` & `BATLedgerPath` from environment variables") -} - -guard FileManager.default.fileExists(atPath: "/usr/local/opt/llvm/include/c++/v1") else { - fatalError("This tool requires LLVM/Clang be downloaded at `/usr/local/opt/llvm`") -} - -// Generate ledger files -do { - let includePath = libraryPath.appending("/bat-native-ledger/include") - let headersPath = includePath.appending("/bat/ledger") - let filePaths = try! FileManager.default.contentsOfDirectory(atPath: headersPath) - .filter { $0.hasSuffix(".h") } - .map { return "\(headersPath)/\($0)" } - let outputPath = ledgerPath.appending("/Generated") - - generate(from: filePaths, includePaths: [includePath], outputDirectory: outputPath) - createBridge(from: "\(headersPath)/ledger_client.h", className: "LedgerClient", includePaths: [includePath], outputDirectory: outputPath) -} - -// Generate ads bridge -do { - let includePath = libraryPath.appending("/bat-native-ads/include") - let headersPath = includePath.appending("/bat/ads") -// let filePaths = try! FileManager.default.contentsOfDirectory(atPath: headersPath) -// .filter { $0.hasSuffix(".h") } -// .map { return "\(headersPath)/\($0)" } - let outputPath = adsPath.appending("/Generated") - -// generate(from: filePaths, includePaths: [includePath], outputDirectory: outputPath) - createBridge(from: "\(headersPath)/ads_client.h", className: "AdsClient", includePaths: [includePath], outputDirectory: outputPath) -} diff --git a/vendor/brave-ios/scripts/compile-model.py b/vendor/brave-ios/scripts/compile-model.py deleted file mode 100644 index 0d3ddc9c559..00000000000 --- a/vendor/brave-ios/scripts/compile-model.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2021 The Brave Authors. All rights reserved. -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this file, -# You can obtain one at http://mozilla.org/MPL/2.0/. - -import argparse -import subprocess -import sys - -def main(): - args = parse_args() - compile_model(args.model[0], args.output[0]) - -def compile_model(model, output): - xcode = subprocess.check_output(['xcode-select', '-print-path']).decode('utf-8') - subprocess.call(xcode.strip() + "/usr/bin/momc " + model + " " + output, shell=True) - -def parse_args(): - parser = argparse.ArgumentParser(description='Compile a CoreData model') - parser.add_argument('--model', nargs=1) - parser.add_argument('--output', nargs=1) - return parser.parse_args() - -if __name__ == '__main__': - sys.exit(main()) diff --git a/vendor/brave-ios/tests/BUILD.gn b/vendor/brave-ios/tests/BUILD.gn deleted file mode 100644 index fee661487de..00000000000 --- a/vendor/brave-ios/tests/BUILD.gn +++ /dev/null @@ -1,32 +0,0 @@ -import("//build/config/ios/rules.gni") - -ios_xctest_test("brave_rewards_ios_tests") { - testonly = true - # Remove when https://github.com/brave/brave-browser/issues/10703 is resolved - check_includes = false - deps = [ - "//brave/vendor/brave-ios:brave_rewards_ios_framework+link", - "//brave/vendor/bat-native-ledger", - "//ios/third_party/material_components_ios:material_components_ios+link", - ] - - bundle_deps = [ - "//brave/vendor/brave-ios:brave_rewards_ios_framework+bundle", - "//ios/third_party/material_components_ios:material_components_ios+bundle", - ] - - configs += [ "//brave/vendor/brave-ios:internal_config" ] - configs += [ "//build/config/compiler:enable_arc" ] - - frameworks = [ - "CoreData.framework", - ] - - sources = [ - "main.mm", - "ledger_database_test.mm", - "dictionary_transform_test.mm", - "vector_transform_test.mm", - "test_foo.mm", - ] -} diff --git a/vendor/brave-ios/tests/ledger_database_test.mm b/vendor/brave-ios/tests/ledger_database_test.mm deleted file mode 100644 index 43f8c5fbb20..00000000000 --- a/vendor/brave-ios/tests/ledger_database_test.mm +++ /dev/null @@ -1,890 +0,0 @@ -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. - -#import -#import - -#import "DataController.h" -#import "BATLedgerDatabase.h" -#import "CoreDataModels.h" -#import "BATBraveLedger.h" - -#include "bat/ledger/ledger_database.h" - -@interface TempTestDataController : DataController -@property (nonatomic, nullable) NSUUID *folderPrefix; -@end - -@implementation TempTestDataController - -- (NSURL *)storeDirectoryURL -{ - if (!self.folderPrefix) { - self.folderPrefix = [NSUUID UUID]; - } - const auto documentURL = [NSTemporaryDirectory() stringByAppendingPathComponent:self.folderPrefix.UUIDString]; - if (!documentURL) { - return nil; - } - return [NSURL fileURLWithPath:documentURL]; -} - -@end - -@interface LedgerDatabaseTest : XCTestCase { - ledger::LedgerDatabase *rewardsDatabase; -} -@property (nonatomic, copy) NSString *dbPath; -@end - -@implementation LedgerDatabaseTest - -- (void)setUp -{ - [super setUp]; - - DataController.shared = [[TempTestDataController alloc] init]; - - const auto name = [NSString stringWithFormat:@"%@.sqlite", NSUUID.UUID.UUIDString]; - self.dbPath = [NSTemporaryDirectory() stringByAppendingPathComponent:name]; - rewardsDatabase = ledger::LedgerDatabase::CreateInstance(base::FilePath(self.dbPath.UTF8String)); - - [self initializeSQLiteDatabase]; -} - -- (void)tearDown -{ - [super tearDown]; - delete rewardsDatabase; - [DataController.viewContext reset]; - [[NSFileManager defaultManager] removeItemAtURL:DataController.shared.storeDirectoryURL error:nil]; - [[NSFileManager defaultManager] removeItemAtPath:self.dbPath error:nil]; - [[NSFileManager defaultManager] removeItemAtPath:[self.dbPath stringByAppendingString:@"-journal"] error:nil]; -} - -// Test that migration script creates required tables -- (void)testCreatesTables -{ - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - - auto migrationResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrationResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name" - columnTypes:{ ledger::type::DBCommand::RecordBindingType::STRING_TYPE }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK, @"Failed to grab table names"); - - XCTAssert(response->result->is_records()); - const auto tableNames = [[NSMutableArray alloc] init]; - for (const auto& record : response->result->get_records()) { - for (const auto& field : record->fields) { - XCTAssert(field->is_string_value()); - const auto stringValue = field->get_string_value(); - [tableNames addObject:[NSString stringWithUTF8String:stringValue.c_str()]]; - } - } - XCTAssertNotEqual(tableNames.count, 0); - const auto expectedTables = @[ - @"activity_info", - @"contribution_info", - @"contribution_queue", - @"contribution_queue_publishers", - @"media_publisher_info", - @"meta", - @"pending_contribution", - @"promotion", - @"promotion_creds", - @"publisher_info", - @"recurring_donation", - @"server_publisher_amounts", - @"server_publisher_banner", - @"server_publisher_info", - @"server_publisher_links", - @"sqlite_sequence", - @"unblinded_tokens" - ]; - XCTAssertTrue([tableNames isEqualToArray:expectedTables]); -} - -// Test that migration script creates required indexes -- (void)testCreatesIndexes -{ - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - - auto migrationResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrationResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT name FROM sqlite_master WHERE (type='index' AND name NOT LIKE 'sqlite%') ORDER BY name;" - columnTypes:{ ledger::type::DBCommand::RecordBindingType::STRING_TYPE }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK, @"Failed to grab table names"); - - XCTAssert(response->result->is_records()); - const auto indexNames = [[NSMutableArray alloc] init]; - for (const auto& record : response->result->get_records()) { - for (const auto& field : record->fields) { - XCTAssert(field->is_string_value()); - const auto stringValue = field->get_string_value(); - [indexNames addObject:[NSString stringWithUTF8String:stringValue.c_str()]]; - } - } - XCTAssertNotEqual(indexNames.count, 0); - const auto expectedIndexes = @[ - @"activity_info_publisher_id_index", - @"contribution_info_publisher_id_index", - @"pending_contribution_publisher_id_index", - @"promotion_creds_promotion_id_index", - @"promotion_promotion_id_index", - @"recurring_donation_publisher_id_index", - @"server_publisher_amounts_publisher_key_index", - @"server_publisher_banner_publisher_key_index", - @"server_publisher_info_publisher_key_index", - @"server_publisher_links_publisher_key_index", - @"unblinded_tokens_token_id_index" - ]; - XCTAssertTrue([indexNames isEqualToArray:expectedIndexes]); -} - -// Tests when we insert an incomplete publisher info (which would end up with empty strings) -- (void)testMigratePublisherInfo -{ - PublisherInfo *publisher = [self coreDataModelOfClass:PublisherInfo.self]; - publisher.publisherID = @"brave.com"; - publisher.url = @"https://brave.com"; - publisher.faviconURL = @""; - publisher.name = @""; - publisher.provider = @""; - - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - const auto insertLine = [BATLedgerDatabase publisherInfoInsertFor:publisher]; - XCTAssert([migration containsString:insertLine]); - - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT publisher_id, excluded, name, favIcon, url, provider FROM publisher_info;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::INT_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssertEqual(response->result->get_records().size(), 1); - - const auto record = std::move(response->result->get_records()[0]); - XCTAssertEqual(record->fields[0]->get_string_value(), publisher.publisherID.UTF8String); - XCTAssertEqual(record->fields[1]->get_int_value(), publisher.excluded); - XCTAssertEqual(record->fields[2]->get_string_value(), publisher.name.UTF8String); - XCTAssertEqual(record->fields[3]->get_string_value(), publisher.faviconURL.UTF8String); - XCTAssertEqual(record->fields[4]->get_string_value(), publisher.url.UTF8String); - XCTAssertEqual(record->fields[5]->get_string_value(), publisher.provider.UTF8String); -} - -- (void)testMigratePublisherInfoChannel -{ - PublisherInfo *publisher = [self coreDataModelOfClass:PublisherInfo.self]; - publisher.publisherID = @"github#channel:12301619"; - publisher.url = @"https://github.com/brave"; - publisher.faviconURL = @""; - publisher.name = @"Brave Software"; - publisher.provider = @"github"; - - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - const auto insertLine = [BATLedgerDatabase publisherInfoInsertFor:publisher]; - XCTAssert([migration containsString:insertLine]); - - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT publisher_id, excluded, name, favIcon, url, provider FROM publisher_info;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::INT_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssertEqual(response->result->get_records().size(), 1); - - const auto record = std::move(response->result->get_records()[0]); - XCTAssertEqual(record->fields[0]->get_string_value(), publisher.publisherID.UTF8String); - XCTAssertEqual(record->fields[1]->get_int_value(), publisher.excluded); - XCTAssertEqual(record->fields[2]->get_string_value(), publisher.name.UTF8String); - XCTAssertEqual(record->fields[3]->get_string_value(), publisher.faviconURL.UTF8String); - XCTAssertEqual(record->fields[4]->get_string_value(), publisher.url.UTF8String); - XCTAssertEqual(record->fields[5]->get_string_value(), publisher.provider.UTF8String); -} - -- (void)testMigrateMediaPublisherInfo -{ - MediaPublisherInfo *media = [self coreDataModelOfClass:MediaPublisherInfo.self]; - media.mediaKey = @"github_brave"; - media.publisherID = @"github#channel:12301619"; - - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - const auto insertLine = [BATLedgerDatabase mediaPublisherInfoInsertFor:media]; - XCTAssert([migration containsString:insertLine]); - - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT media_key, publisher_id FROM media_publisher_info;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssertEqual(response->result->get_records().size(), 1); - - const auto record = std::move(response->result->get_records()[0]); - XCTAssertEqual(record->fields[0]->get_string_value(), media.mediaKey.UTF8String); - XCTAssertEqual(record->fields[1]->get_string_value(), media.publisherID.UTF8String); -} - -- (void)testMigrateActivityInfo -{ - ActivityInfo *activity = [self coreDataModelOfClass:ActivityInfo.self]; - activity.publisherID = @"brave.com"; - activity.duration = 74270; - activity.percent = 54; - activity.visits = 16; - activity.reconcileStamp = 1583427109; - activity.score = 50.914412; - activity.weight = 53.976898; - - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - const auto insertLine = [BATLedgerDatabase activityInfoInsertFor:activity]; - XCTAssert([migration containsString:insertLine]); - - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT publisher_id, duration, visits, score, percent, weight, reconcile_stamp FROM activity_info;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::INT64_TYPE, - ledger::type::DBCommand::RecordBindingType::INT_TYPE, - ledger::type::DBCommand::RecordBindingType::DOUBLE_TYPE, - ledger::type::DBCommand::RecordBindingType::INT_TYPE, - ledger::type::DBCommand::RecordBindingType::DOUBLE_TYPE, - ledger::type::DBCommand::RecordBindingType::INT64_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssertEqual(response->result->get_records().size(), 1); - - const auto record = std::move(response->result->get_records()[0]); - XCTAssertEqual(record->fields[0]->get_string_value(), activity.publisherID.UTF8String); - XCTAssertEqual(record->fields[1]->get_int64_value(), activity.duration); - XCTAssertEqual(record->fields[2]->get_int_value(), activity.visits); - XCTAssertEqual(record->fields[3]->get_double_value(), activity.score); - XCTAssertEqual(record->fields[4]->get_int_value(), activity.percent); - XCTAssertEqual(record->fields[5]->get_double_value(), activity.weight); - XCTAssertEqual(record->fields[6]->get_int64_value(), activity.reconcileStamp); -} - -- (void)testMigrateContributionInfo -{ - ContributionInfo *contribution = [self coreDataModelOfClass:ContributionInfo.self]; - contribution.publisherID = @"brave.com"; - contribution.probi = @"1000000000000000000"; - contribution.date = [[NSDate date] timeIntervalSince1970]; - contribution.type = static_cast(ledger::type::RewardsType::ONE_TIME_TIP); - contribution.month = 2; - contribution.year = 2020; - - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - const auto insertLine = [BATLedgerDatabase contributionInfoInsertFor:contribution]; - XCTAssert([migration containsString:insertLine]); - - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT publisher_id, probi, date, type, month, year FROM contribution_info;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::INT64_TYPE, - ledger::type::DBCommand::RecordBindingType::INT_TYPE, - ledger::type::DBCommand::RecordBindingType::INT_TYPE, - ledger::type::DBCommand::RecordBindingType::INT_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssertEqual(response->result->get_records().size(), 1); - - const auto record = std::move(response->result->get_records()[0]); - XCTAssertEqual(record->fields[0]->get_string_value(), contribution.publisherID.UTF8String); - XCTAssertEqual(record->fields[1]->get_string_value(), contribution.probi.UTF8String); - XCTAssertEqual(record->fields[2]->get_int64_value(), contribution.date); - XCTAssertEqual(record->fields[3]->get_int_value(), contribution.type); - XCTAssertEqual(record->fields[4]->get_int_value(), contribution.month); - XCTAssertEqual(record->fields[5]->get_int_value(), contribution.year); -} - -- (void)testMigrateContributionQueue -{ - ContributionQueue *queue = [self coreDataModelOfClass:ContributionQueue.self]; - queue.id = 10; - queue.type = static_cast(ledger::type::RewardsType::ONE_TIME_TIP); - queue.partial = false; - queue.amount = 1000.0; - - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - const auto insertLine = [BATLedgerDatabase contributionQueueInsertFor:queue]; - XCTAssert([migration containsString:insertLine]); - - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT contribution_queue_id, type, amount, partial, created_at FROM contribution_queue;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::INT_TYPE, - ledger::type::DBCommand::RecordBindingType::INT_TYPE, - ledger::type::DBCommand::RecordBindingType::DOUBLE_TYPE, - ledger::type::DBCommand::RecordBindingType::INT_TYPE, - ledger::type::DBCommand::RecordBindingType::INT64_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssertEqual(response->result->get_records().size(), 1); - - const auto record = std::move(response->result->get_records()[0]); - XCTAssertEqual(record->fields[0]->get_int_value(), queue.id); - XCTAssertEqual(record->fields[1]->get_int_value(), queue.type); - XCTAssertEqual(record->fields[2]->get_double_value(), queue.amount); - XCTAssertEqual(record->fields[3]->get_int_value(), queue.partial); - XCTAssertNotEqual(record->fields[4]->get_int64_value(), 0); - - // Check that the autoincrementing sequence is set correctly - const auto sequenceResponse = [self readSQL:@"SELECT seq FROM sqlite_sequence WHERE name = 'contribution_queue';" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::INT64_TYPE - }]; - const auto sequenceRecord = std::move(sequenceResponse->result->get_records()[0]); - XCTAssertEqual(sequenceRecord->fields[0]->get_int64_value(), queue.id); -} - -- (void)testMigrateContributionQueuePublishers -{ - ContributionQueue *queue = [self coreDataModelOfClass:ContributionQueue.self]; - queue.id = 1; - queue.type = static_cast(ledger::type::RewardsType::ONE_TIME_TIP); - queue.partial = false; - queue.amount = 1000.0; - - ContributionPublisher *queuePublisher = [self coreDataModelOfClass:ContributionPublisher.self]; - queuePublisher.queue = queue; - queuePublisher.publisherKey = @"brave.com"; - queuePublisher.amountPercent = 40; - - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - const auto insertLine = [BATLedgerDatabase contributionQueuePublisherInsertFor:queuePublisher]; - XCTAssert([migration containsString:insertLine]); - - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT contribution_queue_id, publisher_key, amount_percent FROM contribution_queue_publishers;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::INT_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::DOUBLE_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssertEqual(response->result->get_records().size(), 1); - - const auto record = std::move(response->result->get_records()[0]); - XCTAssertEqual(record->fields[0]->get_int_value(), queuePublisher.queue.id); - XCTAssertEqual(record->fields[1]->get_string_value(), queuePublisher.publisherKey.UTF8String); - XCTAssertEqual(record->fields[2]->get_double_value(), queuePublisher.amountPercent); -} - -- (void)testMetaTable -{ - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT key, value FROM meta;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssert(response->result->get_records().size() > 0); - - const auto metaTable = [[NSMutableDictionary alloc] init]; - for (const auto& record : response->result->get_records()) { - const auto key = [NSString stringWithUTF8String:record->fields[0]->get_string_value().c_str()]; - const auto value = [NSString stringWithUTF8String:record->fields[1]->get_string_value().c_str()]; - metaTable[key] = value; - } - - XCTAssert([metaTable[@"version"] isEqualToString:@"10"]); - XCTAssert([metaTable[@"last_compatible_version"] isEqualToString:@"1"]); -} - -- (void)testMigratePendingContributions -{ - PendingContribution *contribution = [self coreDataModelOfClass:PendingContribution.self]; - contribution.publisherID = @"github.com"; - contribution.amount = 10; - contribution.addedDate = [[NSDate date] timeIntervalSince1970]; - contribution.viewingID = [NSUUID UUID].UUIDString; - contribution.type = static_cast(ledger::type::RewardsType::ONE_TIME_TIP); - - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - const auto insertLine = [BATLedgerDatabase pendingContributionInsertFor:contribution]; - XCTAssert([migration containsString:insertLine]); - - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT publisher_id, amount, added_date, viewing_id, type FROM pending_contribution;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::DOUBLE_TYPE, - ledger::type::DBCommand::RecordBindingType::INT64_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::INT_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssertEqual(response->result->get_records().size(), 1); - - const auto record = std::move(response->result->get_records()[0]); - XCTAssertEqual(record->fields[0]->get_string_value(), contribution.publisherID.UTF8String); - XCTAssertEqual(record->fields[1]->get_double_value(), contribution.amount); - XCTAssertEqual(record->fields[2]->get_int64_value(), contribution.addedDate); - XCTAssertEqual(record->fields[3]->get_string_value(), contribution.viewingID.UTF8String); - XCTAssertEqual(record->fields[4]->get_int_value(), contribution.type); -} - -- (void)testMigratePromotions -{ - Promotion *promotion = [self coreDataModelOfClass:Promotion.self]; - promotion.promotionID = NSUUID.UUID.UUIDString; - promotion.version = 1; - promotion.type = BATPromotionTypeAds; - promotion.publicKeys = NSUUID.UUID.UUIDString; - promotion.suggestions = 0; - promotion.approximateValue = 20; - promotion.status = BATPromotionStatusActive; - promotion.expiryDate = [[NSDate date] dateByAddingTimeInterval:60]; - - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - const auto insertLine = [BATLedgerDatabase promotionInsertFor:promotion]; - XCTAssert([migration containsString:insertLine]); - - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT promotion_id, version, type, public_keys, suggestions, approximate_value, status, expires_at, created_at FROM promotion;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::INT_TYPE, - ledger::type::DBCommand::RecordBindingType::INT_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::INT_TYPE, - ledger::type::DBCommand::RecordBindingType::DOUBLE_TYPE, - ledger::type::DBCommand::RecordBindingType::INT_TYPE, - ledger::type::DBCommand::RecordBindingType::INT64_TYPE, - ledger::type::DBCommand::RecordBindingType::INT64_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssertEqual(response->result->get_records().size(), 1); - - const auto record = std::move(response->result->get_records()[0]); - XCTAssertEqual(record->fields[0]->get_string_value(), promotion.promotionID.UTF8String); - XCTAssertEqual(record->fields[1]->get_int_value(), promotion.version); - XCTAssertEqual(record->fields[2]->get_int_value(), promotion.type); - XCTAssertEqual(record->fields[3]->get_string_value(), promotion.publicKeys.UTF8String); - XCTAssertEqual(record->fields[4]->get_int_value(), promotion.suggestions); - XCTAssertEqual(record->fields[5]->get_double_value(), promotion.approximateValue); - XCTAssertEqual(record->fields[6]->get_int_value(), promotion.status); - XCTAssertEqual(record->fields[7]->get_int64_value(), static_cast(promotion.expiryDate.timeIntervalSince1970)); - XCTAssertNotEqual(record->fields[8]->get_int64_value(), 0); -} - -- (void)testMigratePromotionCreds -{ - PromotionCredentials *creds = [self coreDataModelOfClass:PromotionCredentials.self]; - creds.promotionID = NSUUID.UUID.UUIDString; - creds.batchProof = NSUUID.UUID.UUIDString; - creds.blindedCredentials = NSUUID.UUID.UUIDString; - creds.claimID = @"1"; - creds.publicKey = NSUUID.UUID.UUIDString; - creds.signedCredentials = NSUUID.UUID.UUIDString; - creds.tokens = NSUUID.UUID.UUIDString; - - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - const auto insertLine = [BATLedgerDatabase promotionCredsInsertFor:creds]; - XCTAssert([migration containsString:insertLine]); - - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT promotion_id, tokens, blinded_creds, signed_creds, public_key, batch_proof, claim_id FROM promotion_creds;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssertEqual(response->result->get_records().size(), 1); - - const auto record = std::move(response->result->get_records()[0]); - XCTAssertEqual(record->fields[0]->get_string_value(), creds.promotionID.UTF8String); - XCTAssertEqual(record->fields[1]->get_string_value(), creds.tokens.UTF8String); - XCTAssertEqual(record->fields[2]->get_string_value(), creds.blindedCredentials.UTF8String); - XCTAssertEqual(record->fields[3]->get_string_value(), creds.signedCredentials.UTF8String); - XCTAssertEqual(record->fields[4]->get_string_value(), creds.publicKey.UTF8String); - XCTAssertEqual(record->fields[5]->get_string_value(), creds.batchProof.UTF8String); - XCTAssertEqual(record->fields[6]->get_string_value(), creds.claimID.UTF8String); -} - -- (void)testMigrateIncompletePromotionCreds -{ - PromotionCredentials *creds = [self coreDataModelOfClass:PromotionCredentials.self]; - creds.promotionID = NSUUID.UUID.UUIDString; - creds.blindedCredentials = NSUUID.UUID.UUIDString; - creds.claimID = @"1"; - creds.tokens = NSUUID.UUID.UUIDString; - - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - const auto insertLine = [BATLedgerDatabase promotionCredsInsertFor:creds]; - XCTAssert([migration containsString:insertLine]); - - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT promotion_id, tokens, blinded_creds, signed_creds, public_key, batch_proof, claim_id FROM promotion_creds;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssertEqual(response->result->get_records().size(), 1); - - const auto record = std::move(response->result->get_records()[0]); - XCTAssertEqual(record->fields[0]->get_string_value(), creds.promotionID.UTF8String); - XCTAssertEqual(record->fields[1]->get_string_value(), creds.tokens.UTF8String); - XCTAssertEqual(record->fields[2]->get_string_value(), creds.blindedCredentials.UTF8String); - XCTAssertEqual(record->fields[3]->get_string_value(), ""); - XCTAssertEqual(record->fields[4]->get_string_value(), ""); - XCTAssertEqual(record->fields[5]->get_string_value(), ""); - XCTAssertEqual(record->fields[6]->get_string_value(), creds.claimID.UTF8String); -} - -- (void)testMigrateRecurringTips -{ - RecurringDonation *tip = [self coreDataModelOfClass:RecurringDonation.self]; - tip.publisherID = @"brave.com"; - tip.amount = 20; - tip.addedDate = [[NSDate date] timeIntervalSince1970]; - - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - const auto insertLine = [BATLedgerDatabase recurringDonationInsertFor:tip]; - XCTAssert([migration containsString:insertLine]); - - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT publisher_id, amount, added_date FROM recurring_donation;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::DOUBLE_TYPE, - ledger::type::DBCommand::RecordBindingType::INT64_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssertEqual(response->result->get_records().size(), 1); - - const auto record = std::move(response->result->get_records()[0]); - XCTAssertEqual(record->fields[0]->get_string_value(), tip.publisherID.UTF8String); - XCTAssertEqual(record->fields[1]->get_double_value(), tip.amount); - XCTAssertEqual(record->fields[2]->get_int64_value(), tip.addedDate); -} - -- (void)testMigrateUnblindedTokens -{ - UnblindedToken *token = [self coreDataModelOfClass:UnblindedToken.self]; - token.tokenID = 10; - token.tokenValue = @"1000000000"; - token.publicKey = NSUUID.UUID.UUIDString; - token.value = 10; - token.promotionID = NSUUID.UUID.UUIDString; - - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - const auto insertLine = [BATLedgerDatabase unblindedTokenInsertFor:token]; - XCTAssert([migration containsString:insertLine]); - - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT token_id, token_value, public_key, value, promotion_id, created_at FROM unblinded_tokens;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::INT_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::DOUBLE_TYPE, - ledger::type::DBCommand::RecordBindingType::STRING_TYPE, - ledger::type::DBCommand::RecordBindingType::INT64_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssertEqual(response->result->get_records().size(), 1); - - const auto record = std::move(response->result->get_records()[0]); - XCTAssertEqual(record->fields[0]->get_int_value(), token.tokenID); - XCTAssertEqual(record->fields[1]->get_string_value(), token.tokenValue.UTF8String); - XCTAssertEqual(record->fields[2]->get_string_value(), token.publicKey.UTF8String); - XCTAssertEqual(record->fields[3]->get_double_value(), token.value); - XCTAssertEqual(record->fields[4]->get_string_value(), token.promotionID.UTF8String); - XCTAssertNotEqual(record->fields[5]->get_int64_value(), 0); - - // Check that the autoincrementing sequence is set correctly - const auto sequenceResponse = [self readSQL:@"SELECT seq FROM sqlite_sequence WHERE name = 'unblinded_tokens';" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::INT64_TYPE - }]; - const auto sequenceRecord = std::move(sequenceResponse->result->get_records()[0]); - XCTAssertEqual(sequenceRecord->fields[0]->get_int64_value(), token.tokenID); -} - -- (void)testBATOnlyTransfer -{ - Promotion *promotion = [self coreDataModelOfClass:Promotion.self]; - promotion.promotionID = NSUUID.UUID.UUIDString; - promotion.version = 1; - promotion.type = BATPromotionTypeAds; - promotion.publicKeys = NSUUID.UUID.UUIDString; - promotion.suggestions = 0; - promotion.approximateValue = 20; - promotion.status = BATPromotionStatusActive; - promotion.expiryDate = [[NSDate date] dateByAddingTimeInterval:60]; - - UnblindedToken *token = [self coreDataModelOfClass:UnblindedToken.self]; - token.tokenID = 10; - token.tokenValue = @"1000000000"; - token.publicKey = NSUUID.UUID.UUIDString; - token.value = 10; - token.promotionID = promotion.promotionID; - - PublisherInfo *publisher = [self coreDataModelOfClass:PublisherInfo.self]; - publisher.publisherID = @"github#channel:12301619"; - publisher.url = @"https://github.com/brave"; - publisher.faviconURL = @""; - publisher.name = @"Brave Software"; - publisher.provider = @"github"; - - const auto migration = [BATLedgerDatabase migrateCoreDataBATOnlyToSQLTransaction]; - const auto tokenString = [BATLedgerDatabase unblindedTokenInsertFor:token]; - const auto promoString = [BATLedgerDatabase promotionInsertFor:promotion]; - XCTAssert([migration containsString:tokenString]); - XCTAssert([migration containsString:promoString]); - const auto pubInfoString = [BATLedgerDatabase publisherInfoInsertFor:publisher]; - XCTAssert(![migration containsString:pubInfoString]); - - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); -} - -#pragma mark - - -- (void)testInsertedQuotes -{ - PublisherInfo *publisher = [self coreDataModelOfClass:PublisherInfo.self]; - publisher.publisherID = @"github#channel:12301619"; - publisher.url = @"https://github.com/brave"; - publisher.faviconURL = @""; - publisher.name = @"'Brave Software'"; - publisher.provider = @"github"; - - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - const auto insert = [BATLedgerDatabase publisherInfoInsertFor:publisher]; - XCTAssert([insert containsString:@"'''Brave Software'''"]); - - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT name FROM publisher_info;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::STRING_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssertEqual(response->result->get_records().size(), 1); - - const auto record = std::move(response->result->get_records()[0]); - XCTAssertEqual(record->fields[0]->get_string_value(), publisher.name.UTF8String); -} - -- (void)testInsertedJSON -{ - NSDictionary *someJSON = @{ - @"key": @"value", - @"intKey": @(1), - @"boolKey": @YES, - @"arrayKey": @[ @"one", @"two", @"three" ], - @"dictKey": @{ @"one": @"two", @"three": @(4) } - }; - NSError *error = nil; - NSData *jsonData = [NSJSONSerialization dataWithJSONObject:someJSON options:0 error:&error]; - XCTAssertNil(error); - NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; - - PromotionCredentials *creds = [self coreDataModelOfClass:PromotionCredentials.self]; - creds.promotionID = NSUUID.UUID.UUIDString; - creds.blindedCredentials = NSUUID.UUID.UUIDString; - creds.claimID = @"1"; - creds.tokens = jsonString; - - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT tokens FROM promotion_creds;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::STRING_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssertEqual(response->result->get_records().size(), 1); - - const auto record = std::move(response->result->get_records()[0]); - const auto dbJSONString = [NSString stringWithUTF8String:record->fields[0]->get_string_value().c_str()]; - XCTAssert([dbJSONString isEqualToString:creds.tokens]); - - NSError *readError = nil; - NSDictionary *decodedJSON = [NSJSONSerialization JSONObjectWithData:[dbJSONString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&readError]; - XCTAssertNil(readError); - XCTAssert([someJSON isEqualToDictionary:decodedJSON]); -} - -- (void)testUnicodeInsert -{ - PublisherInfo *publisher = [self coreDataModelOfClass:PublisherInfo.self]; - publisher.publisherID = @"github#channel:12301619"; - publisher.url = @"https://github.com/brave"; - publisher.faviconURL = @""; - publisher.name = @"๐Ÿ˜ฒ๐Ÿ‘ป ๏ฝ‚ล•แตƒ๐•ง๐„ โ“ขโ“žโ„ฑลฃ๐–ฮฑ๐“ปฮญ โ™ฃโœŒ"; - publisher.provider = @"github"; - - const auto migration = [BATLedgerDatabase migrateCoreDataToSQLTransaction]; - - const auto migrateResponse = [self executeSQLCommand:migration]; - XCTAssertEqual(migrateResponse->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - - const auto response = [self readSQL:@"SELECT name FROM publisher_info;" columnTypes:{ - ledger::type::DBCommand::RecordBindingType::STRING_TYPE - }]; - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK); - XCTAssertEqual(response->result->get_records().size(), 1); - - const auto record = std::move(response->result->get_records()[0]); - XCTAssertEqual(record->fields[0]->get_string_value(), publisher.name.UTF8String); -} - -#pragma mark - - -- (void)testClearServerPubList -{ - ServerPublisherInfo *info = [self coreDataModelOfClass:ServerPublisherInfo.self]; - info.publisherID = @"brave.com"; - info.address = NSUUID.UUID.UUIDString; - info.banner = [self coreDataModelOfClass:ServerPublisherBanner.self]; - info.banner.publisherID = @"brave.com"; - ServerPublisherAmount *amount = [self coreDataModelOfClass:ServerPublisherAmount.self]; - amount.publisherID = @"brave.com"; - amount.serverPublisherInfo = info; - ServerPublisherLink *link = [self coreDataModelOfClass:ServerPublisherLink.self]; - link.publisherID = @"brave.com"; - link.serverPublisherInfo = info; - - // Save it to disk so the batch delete works - NSError *saveError = nil; - [DataController.viewContext save:&saveError]; - XCTAssertNil(saveError); - - { - const auto context = DataController.viewContext; - const auto fetchRequest = PublisherInfo.fetchRequest; - fetchRequest.entity = [NSEntityDescription entityForName:NSStringFromClass(ServerPublisherInfo.class) - inManagedObjectContext:context]; - - NSError *error; - const auto fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; - XCTAssertNil(error); - XCTAssertEqual(fetchedObjects.count, 1); - } - - [self waitForCompletion:^(XCTestExpectation *e) { - [BATLedgerDatabase deleteCoreDataServerPublisherList:^(NSError *error){ - XCTAssertNil(error); - [e fulfill]; - }]; - }]; - - const auto context = DataController.viewContext; - const auto fetchRequest = PublisherInfo.fetchRequest; - fetchRequest.entity = [NSEntityDescription entityForName:NSStringFromClass(ServerPublisherInfo.class) - inManagedObjectContext:context]; - - NSError *error; - const auto fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; - XCTAssertNil(error); - XCTAssertEqual(fetchedObjects.count, 0); -} - -#pragma mark - SQL Helpers - -- (__kindof NSManagedObject *)coreDataModelOfClass:(Class)clazz -{ - const auto entity = [NSEntityDescription entityForName:NSStringFromClass(clazz) inManagedObjectContext:DataController.viewContext]; - return [[clazz alloc] initWithEntity:entity insertIntoManagedObjectContext:DataController.viewContext]; -} - -- (void)initializeSQLiteDatabase -{ - auto transaction = ledger::type::DBTransaction::New(); - transaction->version = 10; - transaction->compatible_version = 1; - - const auto command = ledger::type::DBCommand::New(); - command->type = ledger::type::DBCommand::Type::INITIALIZE; - transaction->commands.push_back(command->Clone()); - - auto response = ledger::type::DBCommandResponse::New(); - rewardsDatabase->RunTransaction(std::move(transaction), response.get()); - XCTAssertEqual(response->status, ledger::type::DBCommandResponse::Status::RESPONSE_OK, @"Failed to initialize SQLite database"); -} - -- (ledger::type::DBCommandResponsePtr)executeSQLCommand:(NSString *)sqlCommand -{ - auto transaction = ledger::type::DBTransaction::New(); - - const auto command = ledger::type::DBCommand::New(); - command->type = ledger::type::DBCommand::Type::EXECUTE; - command->command = sqlCommand.UTF8String; - transaction->commands.push_back(command->Clone()); - - auto response = ledger::type::DBCommandResponse::New(); - rewardsDatabase->RunTransaction(std::move(transaction), response.get()); - return response->Clone(); -} - -- (ledger::type::DBCommandResponsePtr)readSQL:(NSString *)sqlCommand columnTypes:(std::vector)bindings -{ - auto transaction = ledger::type::DBTransaction::New(); - - const auto command = ledger::type::DBCommand::New(); - command->type = ledger::type::DBCommand::Type::READ; - command->command = sqlCommand.UTF8String; - command->record_bindings = bindings; - transaction->commands.push_back(command->Clone()); - - auto response = ledger::type::DBCommandResponse::New(); - rewardsDatabase->RunTransaction(std::move(transaction), response.get()); - return response->Clone(); -} - -#pragma mark - - -- (void)waitForCompletion:(void (^)(XCTestExpectation *))task -{ - auto __block expectation = [self expectationWithDescription:NSUUID.UUID.UUIDString]; - task(expectation); - [self waitForExpectations:@[expectation] timeout:5]; -} - -@end diff --git a/vendor/brave-ios/tests/test_foo.h b/vendor/brave-ios/tests/test_foo.h deleted file mode 100644 index 0fada957860..00000000000 --- a/vendor/brave-ios/tests/test_foo.h +++ /dev/null @@ -1,30 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -struct CppFoo { - CppFoo(const CppFoo &); - CppFoo(bool b, int i, std::string s, std::vector ds); - ~CppFoo(); - - bool boolean; - int integer; - std::string stringObject; - std::vector numbers; -}; - -@interface TestFoo : NSObject -@property (nonatomic, assign) BOOL boolean; -@property (nonatomic, assign) int integer; -@property (nonatomic, copy) NSString *stringObject; -@property (nonatomic, copy) NSArray *numbers; -- (instancetype)initWithCppFoo:(const CppFoo&)foo; -@end - -NS_ASSUME_NONNULL_END