Move iOS code from brave/vendor to brave/ios

This commit is contained in:
Kyle Hickinson
2021-06-30 16:52:00 -04:00
parent 0b9ef3d581
commit 52ec010182
153 changed files with 5878 additions and 7624 deletions
+5 -1
View File
@@ -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
-2
View File
@@ -1,8 +1,6 @@
/vendor/*
!/vendor/bat-native-ledger
!/vendor/bat-native-ads
!/vendor/brave-ios
!/vendor/CPPLINT.cfg
.DS_Store
.tags*
/.idea/
+1 -1
View File
@@ -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
}
+1 -1
View File
@@ -1,5 +1,5 @@
import("//brave/build/config.gni")
group("brave") {
deps = [ "//brave/vendor/brave-ios" ]
deps = [ "//brave/ios:brave_ios" ]
}
+41
View File
@@ -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" ]
}
}
+2
View File
@@ -0,0 +1,2 @@
# cpp_transformations.h Use int16/int64/etc, rather than the C type long
filter=-runtime/int
+321
View File
@@ -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 <Foundation/Foundation.h>
#import <objc/runtime.h>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "base/containers/flat_map.h"
static std::map<const char*, SEL> 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<const char*, SEL> 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 <typename T>
NS_INLINE NSArray<NSNumber*>* NSArrayFromVector(std::vector<T> 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<NSNumber*>(call(NSNumber.class, selector, t));
[a addObject:number];
}
return a;
}
/// Convert an NSArray storing NSNumber's to a std::vector storing primatives
template <typename T>
NS_INLINE std::vector<T> VectorFromNSArray(NSArray<NSNumber*>* a) {
std::vector<T> 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<NSString*>* NSArrayFromVector(std::vector<std::string> 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<std::string> VectorFromNSArray(NSArray<NSString*>* a) {
std::vector<std::string> 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 <typename T, typename U>
NS_INLINE NSArray<T>* NSArrayFromVector(std::vector<U> 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 <typename T, typename U>
NS_INLINE NSArray<T>* NSArrayFromVector(const std::vector<U>* 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 <typename T, typename U>
NS_INLINE std::vector<U> VectorFromNSArray(NSArray<T>* a,
U (^transformValue)(T)) {
std::vector<U> 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 <typename T>
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<NSNumberCall>(method_getImplementation(method));
return call(NSNumber.class, selector, t);
}
/// Convert a String's to primitives mapping to an NSDictionary<NSString*,
/// NSNumber *>
template <typename T>
NS_INLINE NSDictionary<NSString*, NSNumber*>* NSDictionaryFromMap(
std::map<std::string, T> 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<NSString*,
/// NSNumber *>
template <typename T>
NS_INLINE NSDictionary<NSString*, NSNumber*>* NSDictionaryFromMap(
base::flat_map<std::string, T> 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<NSString*, NSString*>* NSDictionaryFromMap(
std::map<std::string, std::string> 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<NSString*, NSString*>* NSDictionaryFromMap(
base::flat_map<std::string, std::string> 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 <typename V, typename ObjCObj>
NS_INLINE NSDictionary<NSString*, ObjCObj>* NSDictionaryFromMap(
std::map<std::string, V> 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 <typename V, typename ObjCObj>
NS_INLINE NSDictionary<NSString*, ObjCObj>* NSDictionaryFromMap(
base::flat_map<std::string, V> 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 <typename K, typename KObjC, typename V, typename VObjC>
NS_INLINE NSDictionary<KObjC, VObjC>* NSDictionaryFromMap(
std::map<K, V> 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 <typename K, typename KObjC, typename V, typename VObjC>
NS_INLINE NSDictionary<KObjC, VObjC>* NSDictionaryFromMap(
base::flat_map<K, V> 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<std::string, std::string> MapFromNSDictionary(
NSDictionary<NSString*, NSString*>* d) {
base::flat_map<std::string, std::string> 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_
@@ -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:
@@ -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():
+93
View File
@@ -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",
]
}
}
@@ -5,7 +5,7 @@
#import <Foundation/Foundation.h>
#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)
-2
View File
@@ -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",
+80
View File
@@ -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
}
+1 -1
View File
@@ -1,2 +1,2 @@
# ios/app/brave_core_main.h:20: Using C-style cast. Use reinterpret_cast<NSString*>(...) instead [readability/casting] [4] ??
filter=-readability/casting,-whitespace/parens
filter=-readability/casting,-whitespace/parens,-whitespace/operators
@@ -5,13 +5,13 @@
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>BraveRewards</string>
<string>BraveCore</string>
<key>CFBundleIdentifier</key>
<string>com.brave.ios.rewards</string>
<string>com.brave.ios.core</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>BraveRewards</string>
<string>BraveCore</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
+2
View File
@@ -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",
+8 -1
View File
@@ -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;
+29
View File
@@ -5,9 +5,11 @@
#import "brave/ios/app/brave_core_main.h"
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#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<BraveWebClient> _webClient;
std::unique_ptr<BraveMainDelegate> _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_ =
+5 -3
View File
@@ -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();
}
-19
View File
@@ -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",
]
+58
View File
@@ -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}}" ]
}
+37
View File
@@ -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 <Foundation/Foundation.h>
#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_
@@ -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
@@ -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 <Foundation/Foundation.h>
#import "bat/ads/ads_client.h"
@protocol NativeAdsClientBridge
#include <string>
#include <vector>
@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<uint64_t>)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_
+77
View File
@@ -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 <Foundation/Foundation.h>
#include <string>
#include <vector>
#import "bat/ads/ads_client.h"
@protocol AdsClientBridge;
class AdsClientIOS : public ads::AdsClient {
public:
explicit AdsClientIOS(id<AdsClientBridge> bridge);
~AdsClientIOS() override;
private:
__unsafe_unretained id<AdsClientBridge> 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<uint64_t> 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_
+172
View File
@@ -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<AdsClientBridge> 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<uint64_t> 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];
}
@@ -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 <Foundation/Foundation.h>
#import <UserNotifications/UserNotifications.h>
@@ -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<BATBraveAdsNotificationHandler> notificationsHandler;
/// @see BraveAdsNotificationHandler
@property(nonatomic, weak, nullable) id<BraveAdsNotificationHandler>
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<NSDate *> *)getAdsHistoryDates;
- (NSArray<NSDate*>*)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_
@@ -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 <limits>
#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 <Network/Network.h>
#import <UIKit/UIKit.h>
#import "base/base64.h"
#include <limits>
#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 () <NativeAdsClientBridge> {
NativeAdsClient* adsClient;
@interface BraveAds () <AdsClientBridge> {
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<uint8_t> seed;
for (NSNumber* number in wallet.recoverySeed) {
seed.push_back(static_cast<uint8_t>(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<ads::AdNotificationEventType>(eventType));
base::SysNSStringToUTF8(uuid),
static_cast<ads::AdNotificationEventType>(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<ads::NewTabPageAdEventType>(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<ads::mojom::BraveAdsInlineContentAdEventType>(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<ads::PromotedContentAdEventType>(eventType));
}
@@ -655,7 +650,8 @@ BATClassAdsBridge(BOOL, isDebug, setDebug, g_is_debug)
if (![self isAdsServiceRunning]) {
return;
}
ads->purgeOrphanedAdEventsForType(adType.UTF8String);
ads->PurgeOrphanedAdEventsForType(
static_cast<ads::mojom::BraveAdsAdType>(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];
}
@@ -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 <Foundation/Foundation.h>
#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_
@@ -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
+24
View File
@@ -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" ]
}
@@ -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 <Foundation/Foundation.h>
#import <string>
#import <map>
#include <map>
#include <string>
#include <vector>
#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<std::string, std::string>& 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<std::string, std::string>& 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_
+208
View File
@@ -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 <vector>
#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<NSNumber*, NSTimer*>* timers; // {ID: Timer}
@property(nonatomic, copy) NSMutableArray<NSURLSessionDataTask*>* 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<std::string>&)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<const char*>(data.bytes), data.length);
}
std::string errorDescription;
if (error) {
errorDescription = error.localizedDescription.UTF8String;
}
// For some reason I couldn't just do `base::flat_map<std::string,
// std::string> responseHeaders;` due to base::flat_map's non-const
// key insertion
auto* responseHeaders =
new base::flat_map<std::string, std::string>();
[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<std::string, std::string>(*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
+58
View File
@@ -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"
}
+367
View File
@@ -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 <Foundation/Foundation.h>
#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<NSString*, NSString*>*)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<BATPublisherInfo*>*))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<BATSKUOrderItem*>*)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<BATPublisherInfo*>*))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<BATPublisherInfo*>*))completion;
- (void)tipPublisherDirectly:(BATPublisherInfo*)publisher
amount:(double)amount
currency:(NSString*)currency
completion:(void (^)(BATResult result))completion;
#pragma mark - Promotions
@property(nonatomic, readonly) NSArray<BATPromotion*>* pendingPromotions;
@property(nonatomic, readonly) NSArray<BATPromotion*>* finishedPromotions;
/// Updates `pendingPromotions` and `finishedPromotions` based on the database
- (void)updatePendingAndFinishedPromotions:
(nullable void (^)(bool shouldReconcileAds))completion;
- (void)fetchPromotions:(nullable void (^)(NSArray<BATPromotion*>* 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<BATPendingContributionInfo*>* 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<BATContributionInfo*>* 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<RewardsNotification*>* 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_
File diff suppressed because it is too large Load Diff
@@ -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 <Foundation/Foundation.h>
#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<BATPromotion*>* promotions);
/// Eligable grants were added to the wallet
@property(nonatomic, copy, nullable) void (^promotionsAdded)
(NSArray<BATPromotion*>* 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<BATPublisherInfo*>* normalizedList);
@property(nonatomic, copy, nullable) void (^pendingContributionAdded)();
@property(nonatomic, copy, nullable) void (^pendingContributionsRemoved)
(NSArray<NSString*>* 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<RewardsNotification*>* 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_
@@ -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
@@ -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 <Foundation/Foundation.h>
#import "bat/ledger/ledger_client.h"
#include <string>
#include <vector>
#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<std::string>&)args callback:(ledger::client::ResultCallback)callback;
- (void)showNotification:(const std::string&)type
args:(const std::vector<std::string>&)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_
@@ -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 <Foundation/Foundation.h>
#include <string>
#include <vector>
#import "bat/ledger/ledger_client.h"
@protocol LedgerClientBridge;
class LedgerClientIOS : public ledger::LedgerClient {
public:
explicit LedgerClientIOS(id<LedgerClientBridge> bridge);
~LedgerClientIOS() override;
private:
__unsafe_unretained id<LedgerClientBridge> 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<std::string>& 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_
+174
View File
@@ -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<LedgerClientBridge> 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<std::string>& 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];
}
@@ -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}}" ]
}
@@ -0,0 +1 @@
exclude_files=core_data_models
@@ -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 <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
@class PublisherInfo;
@@ -12,16 +12,16 @@ NS_ASSUME_NONNULL_BEGIN
OBJC_EXPORT
@interface ActivityInfo : NSManagedObject
+ (NSFetchRequest<ActivityInfo *> *)fetchRequest;
+ (NSFetchRequest<ActivityInfo*>*)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
@@ -6,7 +6,7 @@
@implementation ActivityInfo
+ (NSFetchRequest<ActivityInfo *> *)fetchRequest {
+ (NSFetchRequest<ActivityInfo*>*)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"ActivityInfo"];
}
@@ -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",
]
}
@@ -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 <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
@class PublisherInfo;
@@ -12,15 +12,15 @@ NS_ASSUME_NONNULL_BEGIN
OBJC_EXPORT
@interface ContributionInfo : NSManagedObject
+ (NSFetchRequest<ContributionInfo *> *)fetchRequest;
+ (NSFetchRequest<ContributionInfo*>*)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
@@ -6,7 +6,7 @@
@implementation ContributionInfo
+ (NSFetchRequest<ContributionInfo *> *)fetchRequest {
+ (NSFetchRequest<ContributionInfo*>*)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"ContributionInfo"];
}
@@ -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 <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
@class ContributionQueue;
@@ -12,11 +12,11 @@ NS_ASSUME_NONNULL_BEGIN
OBJC_EXPORT
@interface ContributionPublisher : NSManagedObject
+ (NSFetchRequest<ContributionPublisher *> *)fetchRequest;
+ (NSFetchRequest<ContributionPublisher*>*)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
@@ -6,7 +6,7 @@
@implementation ContributionPublisher
+ (NSFetchRequest<ContributionPublisher *> *)fetchRequest {
+ (NSFetchRequest<ContributionPublisher*>*)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"ContributionPublisher"];
}
@@ -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 <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
@class ContributionPublisher;
NS_ASSUME_NONNULL_BEGIN
OBJC_EXPORT
@interface ContributionQueue : NSManagedObject
+ (NSFetchRequest<ContributionQueue*>*)fetchRequest;
@property(nonatomic) int64_t id;
@property(nonatomic) int32_t type;
@property(nonatomic) double amount;
@property(nonatomic) bool partial;
@property(nullable, nonatomic, retain)
NSSet<ContributionPublisher*>* publishers;
@end
@interface ContributionQueue (CoreDataGeneratedAccessors)
- (void)addPublishersObject:(ContributionPublisher*)value;
- (void)removePublishersObject:(ContributionPublisher*)value;
- (void)addPublishers:(NSSet<ContributionPublisher*>*)values;
- (void)removePublishers:(NSSet<ContributionPublisher*>*)values;
@end
NS_ASSUME_NONNULL_END
@@ -6,7 +6,7 @@
@implementation ContributionQueue
+ (NSFetchRequest<ContributionQueue *> *)fetchRequest {
+ (NSFetchRequest<ContributionQueue*>*)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"ContributionQueue"];
}
@@ -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 <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
#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"
@@ -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 <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
OBJC_EXPORT
@interface MediaPublisherInfo : NSManagedObject
+ (NSFetchRequest<MediaPublisherInfo *> *)fetchRequest;
+ (NSFetchRequest<MediaPublisherInfo*>*)fetchRequest;
@property (nonatomic, copy) NSString *mediaKey;
@property (nonatomic, copy) NSString *publisherID;
@property(nonatomic, copy) NSString* mediaKey;
@property(nonatomic, copy) NSString* publisherID;
@end
@@ -6,7 +6,7 @@
@implementation MediaPublisherInfo
+ (NSFetchRequest<MediaPublisherInfo *> *)fetchRequest {
+ (NSFetchRequest<MediaPublisherInfo*>*)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"MediaPublisherInfo"];
}
@@ -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 <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
@class PublisherInfo;
@@ -12,14 +12,14 @@ NS_ASSUME_NONNULL_BEGIN
OBJC_EXPORT
@interface PendingContribution : NSManagedObject
+ (NSFetchRequest<PendingContribution *> *)fetchRequest;
+ (NSFetchRequest<PendingContribution*>*)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
@@ -6,7 +6,7 @@
@implementation PendingContribution
+ (NSFetchRequest<PendingContribution *> *)fetchRequest {
+ (NSFetchRequest<PendingContribution*>*)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"PendingContribution"];
}
@@ -0,0 +1,32 @@
//
// Promotion+CoreDataClass.h
//
//
// Created by Kyle Hickinson on 2019-10-21.
//
//
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
@class PromotionCredentials;
NS_ASSUME_NONNULL_BEGIN
OBJC_EXPORT
@interface Promotion : NSManagedObject
+ (NSFetchRequest<Promotion*>*)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
@@ -1,6 +1,6 @@
//
// Promotion+CoreDataClass.m
//
//
//
// Created by Kyle Hickinson on 2019-10-21.
//
@@ -10,7 +10,7 @@
@implementation Promotion
+ (NSFetchRequest<Promotion *> *)fetchRequest {
+ (NSFetchRequest<Promotion*>*)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"Promotion"];
}
@@ -0,0 +1,29 @@
//
// PromotionCredentials+CoreDataClass.h
//
//
// Created by Kyle Hickinson on 2019-10-21.
//
//
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
OBJC_EXPORT
@interface PromotionCredentials : NSManagedObject
+ (NSFetchRequest<PromotionCredentials*>*)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
@@ -1,6 +1,6 @@
//
// PromotionCredentials+CoreDataClass.m
//
//
//
// Created by Kyle Hickinson on 2019-10-21.
//
@@ -10,7 +10,7 @@
@implementation PromotionCredentials
+ (NSFetchRequest<PromotionCredentials *> *)fetchRequest {
+ (NSFetchRequest<PromotionCredentials*>*)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"PromotionCredentials"];
}
@@ -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 <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
@class ActivityInfo, ContributionInfo, RecurringDonation, PendingContribution;
NS_ASSUME_NONNULL_BEGIN
OBJC_EXPORT
@interface PublisherInfo : NSManagedObject
+ (NSFetchRequest<PublisherInfo*>*)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<ActivityInfo*>* activities;
@property(nullable, nonatomic, retain) NSSet<ContributionInfo*>* contributions;
@property(nullable, nonatomic, retain)
NSSet<RecurringDonation*>* recurringDonations;
@property(nullable, nonatomic, retain)
NSSet<PendingContribution*>* pendingContributions;
@end
@interface PublisherInfo (CoreDataGeneratedAccessors)
- (void)addActivitiesObject:(ActivityInfo*)value;
- (void)removeActivitiesObject:(ActivityInfo*)value;
- (void)addActivities:(NSSet<ActivityInfo*>*)values;
- (void)removeActivities:(NSSet<ActivityInfo*>*)values;
- (void)addContributionsObject:(ContributionInfo*)value;
- (void)removeContributionsObject:(ContributionInfo*)value;
- (void)addContributions:(NSSet<ContributionInfo*>*)values;
- (void)removeContributions:(NSSet<ContributionInfo*>*)values;
- (void)addRecurringDonationsObject:(RecurringDonation*)value;
- (void)removeRecurringDonationsObject:(RecurringDonation*)value;
- (void)addRecurringDonations:(NSSet<RecurringDonation*>*)values;
- (void)removeRecurringDonations:(NSSet<RecurringDonation*>*)values;
- (void)addPendingContributionsObject:(PendingContribution*)value;
- (void)removePendingContributionsObject:(PendingContribution*)value;
- (void)addPendingContributions:(NSSet<PendingContribution*>*)values;
- (void)removePendingContributions:(NSSet<PendingContribution*>*)values;
@end
NS_ASSUME_NONNULL_END
@@ -6,7 +6,7 @@
@implementation PublisherInfo
+ (NSFetchRequest<PublisherInfo *> *)fetchRequest {
+ (NSFetchRequest<PublisherInfo*>*)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"PublisherInfo"];
}
@@ -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 <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
@class PublisherInfo;
@@ -12,12 +12,12 @@ NS_ASSUME_NONNULL_BEGIN
OBJC_EXPORT
@interface RecurringDonation : NSManagedObject
+ (NSFetchRequest<RecurringDonation *> *)fetchRequest;
+ (NSFetchRequest<RecurringDonation*>*)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
@@ -6,7 +6,7 @@
@implementation RecurringDonation
+ (NSFetchRequest<RecurringDonation *> *)fetchRequest {
+ (NSFetchRequest<RecurringDonation*>*)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"RecurringDonation"];
}
@@ -11,11 +11,11 @@ NS_ASSUME_NONNULL_BEGIN
OBJC_EXPORT
@interface ServerPublisherAmount : NSManagedObject
+ (NSFetchRequest<ServerPublisherAmount *> *)fetchRequest;
+ (NSFetchRequest<ServerPublisherAmount*>*)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
@@ -6,7 +6,7 @@
@implementation ServerPublisherAmount
+ (NSFetchRequest<ServerPublisherAmount *> *)fetchRequest {
+ (NSFetchRequest<ServerPublisherAmount*>*)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"ServerPublisherAmount"];
}
@@ -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 <CoreData/CoreData.h>
@class ServerPublisherInfo;
NS_ASSUME_NONNULL_BEGIN
OBJC_EXPORT
@interface ServerPublisherBanner : NSManagedObject
+ (NSFetchRequest<ServerPublisherBanner*>*)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
@@ -6,7 +6,7 @@
@implementation ServerPublisherBanner
+ (NSFetchRequest<ServerPublisherBanner *> *)fetchRequest {
+ (NSFetchRequest<ServerPublisherBanner*>*)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"ServerPublisherBanner"];
}
@@ -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 <CoreData/CoreData.h>
@class ServerPublisherBanner, ServerPublisherAmount, ServerPublisherLink;
NS_ASSUME_NONNULL_BEGIN
OBJC_EXPORT
@interface ServerPublisherInfo : NSManagedObject
+ (NSFetchRequest<ServerPublisherInfo*>*)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<ServerPublisherAmount*>* amounts;
@property(nullable, nonatomic, retain) NSSet<ServerPublisherLink*>* links;
@end
@interface ServerPublisherInfo (CoreDataGeneratedAccessors)
- (void)addAmountsObject:(ServerPublisherAmount*)value;
- (void)removeAmountsObject:(ServerPublisherAmount*)value;
- (void)addAmounts:(NSSet<ServerPublisherAmount*>*)values;
- (void)removeAmounts:(NSSet<ServerPublisherAmount*>*)values;
- (void)addLinksObject:(ServerPublisherLink*)value;
- (void)removeLinksObject:(ServerPublisherLink*)value;
- (void)addLinks:(NSSet<ServerPublisherLink*>*)values;
- (void)removeLinks:(NSSet<ServerPublisherLink*>*)values;
@end
NS_ASSUME_NONNULL_END
@@ -6,7 +6,7 @@
@implementation ServerPublisherInfo
+ (NSFetchRequest<ServerPublisherInfo *> *)fetchRequest {
+ (NSFetchRequest<ServerPublisherInfo*>*)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"ServerPublisherInfo"];
}
@@ -11,12 +11,12 @@ NS_ASSUME_NONNULL_BEGIN
OBJC_EXPORT
@interface ServerPublisherLink : NSManagedObject
+ (NSFetchRequest<ServerPublisherLink *> *)fetchRequest;
+ (NSFetchRequest<ServerPublisherLink*>*)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
@@ -6,7 +6,7 @@
@implementation ServerPublisherLink
+ (NSFetchRequest<ServerPublisherLink *> *)fetchRequest {
+ (NSFetchRequest<ServerPublisherLink*>*)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"ServerPublisherLink"];
}
@@ -0,0 +1,29 @@
//
// UnblindedToken+CoreDataClass.h
//
//
// Created by Kyle Hickinson on 2019-10-21.
//
//
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
@class Promotion;
NS_ASSUME_NONNULL_BEGIN
OBJC_EXPORT
@interface UnblindedToken : NSManagedObject
+ (NSFetchRequest<UnblindedToken*>*)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
@@ -1,6 +1,6 @@
//
// UnblindedToken+CoreDataClass.m
//
//
//
// Created by Kyle Hickinson on 2019-10-21.
//
@@ -10,7 +10,7 @@
@implementation UnblindedToken
+ (NSFetchRequest<UnblindedToken *> *)fetchRequest {
+ (NSFetchRequest<UnblindedToken*>*)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"UnblindedToken"];
}
@@ -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 <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
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_
@@ -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
@@ -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 <Foundation/Foundation.h>
#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_
@@ -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 <Foundation/Foundation.h>
#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<int64_t>(
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<NSString*>* 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<NSString*> alloc] init];
[fetchedObjects
enumerateObjectsUsingBlock:^(NSManagedObject* _Nonnull obj,
NSUInteger idx, BOOL* _Nonnull stop) {
if (![obj isKindOfClass:clazz]) {
return;
}
[statements addObject:block(obj)];
}];
return statements;
}
@end
@@ -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 <Foundation/Foundation.h>
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_
@@ -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
@@ -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 <Foundation/Foundation.h>
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 <NSSecureCoding>
@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_
@@ -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
+19
View File
@@ -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" ]
}
@@ -5,7 +5,7 @@
#import <XCTest/XCTest.h>
#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<std::string, int> m { {"0", 0}, {"1", 1}, {"2", 2} };
- (void)testStringPrimitiveMapToDictionary {
std::map<std::string, int> m{{"0", 0}, {"1", 1}, {"2", 2}};
const auto dict = NSDictionaryFromMap(m);
XCTAssertEqual(dict.count, 3);
XCTAssertEqual(dict.count, static_cast<NSUInteger>(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<std::string, std::string> m { {"0", "test0"}, {"1", "test1"}, {"2", "test2"} };
- (void)testStringStringMapToDictionary {
std::map<std::string, std::string> m{
{"0", "test0"}, {"1", "test1"}, {"2", "test2"}};
const auto dict = NSDictionaryFromMap(m);
XCTAssertEqual(dict.count, 3);
XCTAssertEqual(dict.count, static_cast<NSUInteger>(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<std::string, CppFoo> 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<std::string, CppFoo> 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<NSUInteger>(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<std::string, std::string> map = MapFromNSDictionary(d);
XCTAssert(map["1"] == "2");
XCTAssert(map["3"] == "4");
@@ -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 <XCTest/XCTest.h>
#import <UIKit/UIKit.h>
#if !defined(__has_feature) || !__has_feature(objc_arc)
+36
View File
@@ -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 <Foundation/Foundation.h>
#include <string>
#include <vector>
NS_ASSUME_NONNULL_BEGIN
struct CppFoo {
CppFoo(const CppFoo&);
CppFoo(bool b, int i, std::string s, std::vector<double> ds);
~CppFoo();
bool boolean;
int integer;
std::string stringObject;
std::vector<double> numbers;
};
@interface TestFoo : NSObject
@property(nonatomic, assign) BOOL boolean;
@property(nonatomic, assign) int integer;
@property(nonatomic, copy) NSString* stringObject;
@property(nonatomic, copy) NSArray<NSNumber*>* numbers;
- (instancetype)initWithCppFoo:(const CppFoo&)foo;
@end
NS_ASSUME_NONNULL_END
#endif // BRAVE_IOS_TESTING_TEST_FOO_H_
@@ -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<double> 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<double> 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;
}
@@ -3,7 +3,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#import <XCTest/XCTest.h>
#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<int> v { 1, 2, 3 };
- (void)testPrimitiveVectorToNSNumberArray {
std::vector<int> 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<NSNumber *> *a = @[ @(1), @(2), @(3) ];
- (void)testNSNumberArrayToPrimitiveVector {
NSArray<NSNumber*>* a = @[ @(1), @(2), @(3) ];
std::vector<int> v = VectorFromNSArray<int>(a);
XCTAssertTrue(v.size() == 3);
XCTAssertTrue(v[0] == 1 && v[1] == 2 && v[2] == 3);
}
- (void)testStringVectorToStringArray
{
std::vector<std::string> v { "1", "2", "3" };
- (void)testStringVectorToStringArray {
std::vector<std::string> 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<NSString *> *a = @[ @"1", @"2", @"3" ];
- (void)testStringArrayToStringVector {
NSArray<NSString*>* a = @[ @"1", @"2", @"3" ];
std::vector<std::string> v = VectorFromNSArray(a);
XCTAssertTrue(v.size() == 3);
XCTAssertTrue(v[0] == "1" && v[1] == "2" && v[2] == "3");
}
- (void)testVectorObjectsToArrayObjects
{
std::vector<CppFoo> 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<CppFoo> 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);
}
-1
View File
@@ -1 +0,0 @@
exclude_files=brave-ios

Some files were not shown because too many files have changed in this diff Show More