Skip to content

Commit

Permalink
Fixes brave/brave-browser#2245, monthly donation functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanml committed Nov 27, 2018
1 parent 04ca065 commit 71ff51f
Show file tree
Hide file tree
Showing 17 changed files with 246 additions and 6 deletions.
39 changes: 39 additions & 0 deletions browser/extensions/api/brave_rewards_api.cc
Original file line number Diff line number Diff line change
Expand Up @@ -138,5 +138,44 @@ ExtensionFunction::ResponseAction BraveRewardsGetGrantFunction::Run() {
return RespondNow(NoArguments());
}

BraveRewardsSaveRecurringDonationFunction::~BraveRewardsSaveRecurringDonationFunction() {
}

ExtensionFunction::ResponseAction
BraveRewardsSaveRecurringDonationFunction::Run() {

std::unique_ptr<brave_rewards::SaveRecurringDonation::Params> params(
brave_rewards::SaveRecurringDonation::Params::Create(*args_));

Profile* profile = Profile::FromBrowserContext(browser_context());
RewardsService* rewards_service_ = RewardsServiceFactory::GetForProfile(profile);

if (rewards_service_) {
rewards_service_->AddRecurringPayment(params->publisher_key, params->new_amount);
}

return RespondNow(NoArguments());
}

BraveRewardsRemoveRecurringDonationFunction::~BraveRewardsRemoveRecurringDonationFunction() {
}

ExtensionFunction::ResponseAction
BraveRewardsRemoveRecurringDonationFunction::Run() {

std::unique_ptr<brave_rewards::RemoveRecurringDonation::Params> params(
brave_rewards::RemoveRecurringDonation::Params::Create(*args_));

Profile* profile = Profile::FromBrowserContext(browser_context());
RewardsService* rewards_service_ = RewardsServiceFactory::GetForProfile(profile);

if (rewards_service_) {
rewards_service_->RemoveRecurring(params->publisher_key);
}

return RespondNow(NoArguments());
}


} // namespace api
} // namespace extensions
20 changes: 20 additions & 0 deletions browser/extensions/api/brave_rewards_api.h
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,26 @@ class BraveRewardsGetGrantFunction : public UIThreadExtensionFunction {
ResponseAction Run() override;
};

class BraveRewardsSaveRecurringDonationFunction : public UIThreadExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION("braveRewards.saveRecurringDonation", UNKNOWN)

protected:
~BraveRewardsSaveRecurringDonationFunction() override;

ResponseAction Run() override;
};

class BraveRewardsRemoveRecurringDonationFunction : public UIThreadExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION("braveRewards.removeRecurringDonation", UNKNOWN)

protected:
~BraveRewardsRemoveRecurringDonationFunction() override;

ResponseAction Run() override;
};

} // namespace api
} // namespace extensions

Expand Down
37 changes: 37 additions & 0 deletions common/extensions/api/brave_rewards.json
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,17 @@
}
}
]
},
{
"name": "onRecurringDonations",
"type": "function",
"description": "",
"parameters": [
{
"name": "result",
"type": "any"
}
]
}
],
"functions": [
Expand Down Expand Up @@ -256,6 +267,32 @@
"type": "function",
"description": "Retrieves grant when panel is mounted",
"parameters": []
},
{
"name": "saveRecurringDonation",
"type": "function",
"description": "Updates recurring donation amount for rewards panel",
"parameters": [
{
"name": "publisher_key",
"type": "string"
},
{
"name": "new_amount",
"type": "integer"
}
]
},
{
"name": "removeRecurringDonation",
"type": "function",
"description": "Removes recurring donation for rewards panel",
"parameters": [
{
"name": "publisher_key",
"type": "string"
}
]
}
]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
* You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "brave/components/brave_rewards/browser/extension_rewards_service_observer.h"

#include "bat/ledger/publisher_info.h"
#include "brave/common/extensions/api/brave_rewards.h"
#include "brave/components/brave_rewards/browser/rewards_service.h"
Expand Down Expand Up @@ -137,4 +136,37 @@ void ExtensionRewardsServiceObserver::OnGetPublisherActivityFromUrl(
event_router->BroadcastEvent(std::move(event));
}

void ExtensionRewardsServiceObserver::OnRecurringDonations(
RewardsService* rewards_service,
const ledger::PublisherInfoList& list) {
extensions::EventRouter* event_router = extensions::EventRouter::Get(profile_);
if (!event_router) {
return;
}

base::DictionaryValue result;
auto recurringDonations = std::make_unique<base::ListValue>();

if (!list.empty()) {
for (auto const& item: list) {
auto recurringDonation = std::make_unique<base::DictionaryValue>();
recurringDonation->SetString("publisherKey", item.id);
recurringDonation->SetInteger("amount", item.weight);
recurringDonations->Append(std::move(recurringDonation));
}
}

result.SetList("recurringDonations", std::move(recurringDonations));

std::unique_ptr<base::ListValue> args(
extensions::api::brave_rewards::OnRecurringDonations::Create(result)
.release());

std::unique_ptr<extensions::Event> event(new extensions::Event(
extensions::events::BRAVE_START,
extensions::api::brave_rewards::OnRecurringDonations::kEventName,
std::move(args)));
event_router->BroadcastEvent(std::move(event));
}

} // namespace brave_rewards
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <memory>

#include "base/macros.h"
#include "bat/ledger/ledger.h"
#include "brave/components/brave_rewards/browser/rewards_service_observer.h"
#include "brave/components/brave_rewards/browser/rewards_service_private_observer.h"

Expand Down Expand Up @@ -38,7 +39,8 @@ class ExtensionRewardsServiceObserver : public RewardsServiceObserver,
// RewardsServicePrivateObserver implementation
void OnGetCurrentBalanceReport(RewardsService* rewards_service,
const BalanceReport& balance_report) override;

void OnRecurringDonations(RewardsService* rewards_service,
const ledger::PublisherInfoList& list) override;
private:
Profile* profile_;

Expand Down
1 change: 1 addition & 0 deletions components/brave_rewards/browser/rewards_service.h
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ class RewardsService : public KeyedService {
virtual void GetPublisherBanner(const std::string& publisher_id) = 0;
virtual void OnDonate(const std::string& publisher_key, int amount, bool recurring) = 0;
virtual void RemoveRecurring(const std::string& publisher_key) = 0;
virtual void AddRecurringPayment(const std::string& publisher_key, double new_amount) = 0;
virtual void UpdateRecurringDonationsList() = 0;
virtual void UpdateTipsList() = 0;
virtual void SetContributionAutoInclude(
Expand Down
10 changes: 10 additions & 0 deletions components/brave_rewards/browser/rewards_service_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1442,6 +1442,12 @@ ledger::PublisherInfoList GetRecurringDonationsOnFileTaskRunner(PublisherInfoDat
void RewardsServiceImpl::OnRecurringDonationsData(const ledger::PublisherInfoListCallback callback,
const ledger::PublisherInfoList list) {
callback(list, 0);
TriggerOnRecurringDonations(list);
}

void RewardsServiceImpl::TriggerOnRecurringDonations(const ledger::PublisherInfoList& list) {
for (auto& observer : observers_)
observer.OnRecurringDonations(this, list);
}

void RewardsServiceImpl::GetRecurringDonations(ledger::PublisherInfoListCallback callback) {
Expand Down Expand Up @@ -1502,6 +1508,10 @@ void RewardsServiceImpl::OnTipsUpdatedData(const ledger::PublisherInfoList list)
}
}

void RewardsServiceImpl::AddRecurringPayment(const std::string& publisher_key, double new_amount) {
SaveRecurringDonation(publisher_key, new_amount);
}

void RewardsServiceImpl::RemoveRecurring(const std::string& publisher_key) {
ledger_->RemoveRecurring(publisher_key);
}
Expand Down
2 changes: 2 additions & 0 deletions components/brave_rewards/browser/rewards_service_impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ class RewardsServiceImpl : public RewardsService,
void RemoveRecurring(const std::string& publisher_key) override;
void UpdateRecurringDonationsList() override;
void UpdateTipsList() override;
void AddRecurringPayment(const std::string& publisher_key, double new_amount) override;
void SetContributionAutoInclude(
std::string publisher_key, bool excluded, uint64_t windowId) override;
RewardsNotificationService* GetNotificationService() const override;
Expand Down Expand Up @@ -182,6 +183,7 @@ class RewardsServiceImpl : public RewardsService,
ledger::Result result,
std::unique_ptr<ledger::PublisherInfo> info,
uint64_t windowId);
void TriggerOnRecurringDonations(const ledger::PublisherInfoList& list);

// ledger::LedgerClient
std::string GenerateGUID() const override;
Expand Down
3 changes: 3 additions & 0 deletions components/brave_rewards/browser/rewards_service_observer.h
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ class RewardsServiceObserver : public base::CheckedObserver {
int error_code,
ledger::PublisherInfo* info,
uint64_t windowId) {};
virtual void OnRecurringDonations(
brave_rewards::RewardsService* rewards_service,
const std::vector<ledger::PublisherInfo>& list) {};
};

} // namespace brave_rewards
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,18 @@ export const includeInAutoContribution = (publisherKey: string, excluded: boolea
})

export const getGrant = () => action(types.GET_GRANT, {})

export const saveRecurringDonation = (publisherKey: string, newAmount: number) => action(types.SAVE_RECURRING_DONATION, {
publisherKey,
newAmount
})

export const removeRecurringContribution = (publisherKey: string) => action(types.REMOVE_RECURRING_DONATION, {
publisherKey
})

export const getRecurringDonations = () => action(types.GET_RECURRING_DONATIONS)

export const onRecurringDonations = (result: RewardsExtension.RecurringDonation) => action(types.ON_RECURRING_DONATIONS, {
result
})
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,7 @@ chrome.rewardsNotifications.onNotificationAdded.addListener((id: string, type: n
chrome.rewardsNotifications.onNotificationDeleted.addListener((id: string, type: number, timestamp: number) => {
rewardsPanelActions.onNotificationDeleted(id, type, timestamp)
})

chrome.braveRewards.onRecurringDonations.addListener((result: RewardsExtension.RecurringDonation) => {
rewardsPanelActions.onRecurringDonations(result)
})
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,31 @@ export const rewardsPanelReducer = (state: RewardsExtension.State | undefined, a
chrome.braveRewards.getGrant()
break
}
case types.SAVE_RECURRING_DONATION:
{
let newAmount = payload.newAmount
let publisherKey = payload.publisherKey
if (publisherKey == null) {
break
}
chrome.braveRewards.saveRecurringDonation(publisherKey, newAmount)
break
}
case types.REMOVE_RECURRING_DONATION:
{
let publisherKey = payload.publisherKey
if (publisherKey == null) {
break
}
chrome.braveRewards.removeRecurringDonation(publisherKey)
break
}
case types.ON_RECURRING_DONATIONS:
{
state = { ...state }
state.recurringDonations = payload.result.recurringDonations
break
}
}

if (state !== startingState) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ const defaultState: RewardsExtension.State = {
total: '0'
},
notifications: {},
currentNotification: undefined
currentNotification: undefined,
recurringDonations: []
}

const cleanData = (state: RewardsExtension.State) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,28 @@ export class Panel extends React.Component<Props, State> {
console.log('doNothing click')
}

onContributionAmountChange = (publisherKey: string, newAmount: string) => {
const newValue = parseInt(newAmount)

if (newValue === 0) {
this.actions.removeRecurringContribution(publisherKey)
} else {
this.actions.saveRecurringDonation(publisherKey, newValue)
}
}

generateAmounts = () => {
const { rates } = this.props.rewardsPanelData.walletProperties

return [0, 1, 5, 10].map((value: number) => {
return {
tokens: value.toFixed(1),
converted: utils.convertBalance(value.toString(), rates),
selected: false
}
})
}

switchAutoContribute = () => {
const publisher: RewardsExtension.Publisher | undefined = this.getPublisher()
const publisherKey = publisher && publisher.publisher_key
Expand Down Expand Up @@ -256,6 +278,7 @@ export class Panel extends React.Component<Props, State> {
}

render () {
const { recurringDonations } = this.props.rewardsPanelData
const { balance, rates, grants } = this.props.rewardsPanelData.walletProperties
const publisher: RewardsExtension.Publisher | undefined = this.getPublisher()
const converted = utils.convertBalance(balance.toString(), rates)
Expand All @@ -268,6 +291,17 @@ export class Panel extends React.Component<Props, State> {
faviconUrl = `chrome://favicon/size/48@2x/${publisher.favicon_url}`
}
}

let defaultContribution = '0.0'
if (recurringDonations && (publisher && publisher.publisher_key)) {
recurringDonations.map((donation: any) => {
if (donation.publisherKey === publisher.publisher_key) {
defaultContribution = donation.amount.toFixed(1)
}
})
console.log(defaultContribution)
}

return (
<WalletWrapper
compact={true}
Expand Down Expand Up @@ -304,14 +338,15 @@ export class Panel extends React.Component<Props, State> {
platform={publisher.provider as Provider}
publisherName={publisher.name}
publisherImg={faviconUrl}
monthlyAmount={10}
monthlyAmount={0}
isVerified={publisher.verified}
tipsEnabled={true}
includeInAuto={!publisher.excluded}
attentionScore={(publisher.percentage || 0).toString()}
onToggleTips={this.doNothing}
donationAmounts={this.generateAmounts()}
donationAction={this.showDonateToSiteDetail}
onAmountChange={this.doNothing}
onAmountChange={this.onContributionAmountChange.bind(this, publisher.publisher_key)}
onIncludeInAuto={this.switchAutoContribute}
/>
: null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,9 @@ export const enum types {
ON_NOTIFICATION_DELETED = '@@rewards_panel/ON_NOTIFICATION_DELETED',
DELETE_NOTIFICATION = '@@rewards_panel/DELETE_NOTIFICATION',
INCLUDE_IN_AUTO_CONTRIBUTION = '@@rewards_panel/INCLUDE_IN_AUTO_CONTRIBUTION',
GET_GRANT = '@@rewards_panel/GET_GRANT'
GET_GRANT = '@@rewards_panel/GET_GRANT',
SAVE_RECURRING_DONATION = '@@rewards_panel/SAVE_RECURRING_DONATION',
REMOVE_RECURRING_DONATION = '@@rewards_panel/REMOVE_RECURRING_DONATION',
GET_RECURRING_DONATIONS = '@@rewards_panel/GET_RECURRING_DONATIONS',
ON_RECURRING_DONATIONS = '@@rewards_panel/ON_RECURRING_DONATIONS'
}
Loading

0 comments on commit 71ff51f

Please sign in to comment.