Skip to content

Commit

Permalink
Addresses review comments
Browse files Browse the repository at this point in the history
Part of brave#11037 PR
  • Loading branch information
NejcZdovc committed Oct 3, 2017
1 parent 0c40d97 commit 7042450
Show file tree
Hide file tree
Showing 7 changed files with 114 additions and 145 deletions.
187 changes: 87 additions & 100 deletions app/browser/api/ledger.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const qr = require('qr-image')
const underscore = require('underscore')
const tldjs = require('tldjs')
const urlFormat = require('url').format
const queryString = require('queryString')
const queryString = require('querystring')
const levelUp = require('level')
const random = require('random-lib')
const uuid = require('uuid')
Expand Down Expand Up @@ -51,8 +51,8 @@ let bootP
let quitP
let notificationPaymentDoneMessage
const _internal = {
verboseP: true,
debugP: true,
verboseP: process.env.LEDGER_VERBOSE || true,
debugP: process.env.LEDGER_DEBUG || true,
ruleset: {
raw: [],
cooked: []
Expand Down Expand Up @@ -102,6 +102,8 @@ const fileTypes = {
jpeg: new Buffer([0xff, 0xd8, 0xff]),
png: new Buffer([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
}
const minimumVisitTimeDefault = 8 * 1000
const nextAddFoundsTime = 3 * miliseconds.day

let signatureMax = 0
underscore.keys(fileTypes).forEach((fileType) => {
Expand Down Expand Up @@ -327,6 +329,7 @@ const getPublisherData = (result, scorekeeper) => {

let data = {
verified: result.options.verified || false,
exclude: result.options.exclude || false,
site: result.publisherKey,
views: result.visits,
duration: duration,
Expand Down Expand Up @@ -694,13 +697,13 @@ const addVisit = (state, location, timestamp, tabId) => {

const lastUrl = pageDataState.getLastUrl(state)
const aboutUrl = getSourceAboutUrl(lastUrl) || lastUrl
if (aboutUrl.match(/^about/)) {
if (aboutUrl && aboutUrl.match(/^about/)) {
state = pageDataState.resetInfo(state)
}

location = getSourceAboutUrl(location) || location

currentUrl = location.match(/^about/) ? locationDefault : location
currentUrl = (location && location.match(/^about/)) ? locationDefault : location
currentTimestamp = timestamp
return state
}
Expand Down Expand Up @@ -888,10 +891,9 @@ const pageDataChanged = (state) => {
excludeP(publisherKey, (unused, exclude) => {
if (!getSetting(settings.PAYMENTS_SITES_AUTO_SUGGEST)) {
exclude = false
} else {
exclude = !exclude
}
appActions.onPublisherOptionUpdate(publisherKey, 'exclude', exclude, true)
appActions.onPublisherOptionUpdate(publisherKey, 'exclude', exclude)
savePublisherOption(publisherKey, 'exclude', exclude)
})
}

Expand Down Expand Up @@ -1033,7 +1035,7 @@ const initSynopsis = (state) => {
state = ledgerState.saveSynopsis(state, null, synopsis.options)
let value = getSetting(settings.PAYMENTS_MINIMUM_VISIT_TIME)
if (!value) {
value = 8 * 1000
value = minimumVisitTimeDefault
appActions.changeSetting(settings.PAYMENTS_MINIMUM_VISIT_TIME, value)
}

Expand Down Expand Up @@ -1079,6 +1081,7 @@ const initSynopsis = (state) => {
const publisherKey = item[0]
excludeP(publisherKey, (unused, exclude) => {
appActions.onPublisherOptionUpdate(publisherKey, 'exclude', exclude)
savePublisherOption(publisherKey, 'exclude', exclude)
})

state = verifiedP(state, publisherKey, (error, result) => {
Expand Down Expand Up @@ -1132,9 +1135,6 @@ const enable = (state, paymentsEnabled) => {
}
})

// change undefined include publishers to include publishers
state = ledgerState.enableUndefinedPublishers(state, stateSynopsis.get('publishers'))

return state
}

Expand Down Expand Up @@ -1179,7 +1179,7 @@ const showNotificationReviewPublishers = (nextTime) => {
}

const showNotificationAddFunds = () => {
const nextTime = new Date().getTime() + (3 * miliseconds.day)
const nextTime = new Date().getTime() + nextAddFoundsTime
appActions.changeSetting(settings.PAYMENTS_NOTIFICATION_ADD_FUNDS_TIMESTAMP, nextTime)

appActions.showNotification({
Expand Down Expand Up @@ -1435,32 +1435,6 @@ const updateLedgerInfo = (state) => {
state = ledgerState.setInfoProp(state, 'buyMaximumUSD', false)
}

// TODO remove when BAT is implemented, we don't need this for BAT
/*
if ((client) && (now > ledgerInfo._internal.geoipExpiry)) {
ledgerInfo._internal.geoipExpiry = now + (5 * miliseconds.minute)
if (!ledgerGeoIP) ledgerGeoIP = require('ledger-geoip')
return ledgerGeoIP.getGeoIP(client.options, (err, provider, result) => {
if (err) console.warn('ledger geoip warning: ' + JSON.stringify(err, null, 2))
if (result) ledgerInfo.countryCode = result
ledgerInfo.exchangeInfo = ledgerInfo._internal.exchanges[ledgerInfo.countryCode]
if (now <= ledgerInfo._internal.exchangeExpiry) return updateLedgerInfo()
ledgerInfo._internal.exchangeExpiry = now + miliseconds.day
roundtrip({ path: '/v1/exchange/providers' }, client.options, (err, response, body) => {
if (err) console.error('ledger exchange error: ' + JSON.stringify(err, null, 2))
ledgerInfo._internal.exchanges = body || {}
ledgerInfo.exchangeInfo = ledgerInfo._internal.exchanges[ledgerInfo.countryCode]
updateLedgerInfo()
})
})
}
*/

return state
}

Expand Down Expand Up @@ -1793,6 +1767,7 @@ const onCallback = (state, result, delayTime) => {
const publisherKey = item[0]
excludeP(publisherKey, (unused, exclude) => {
appActions.onPublisherOptionUpdate(publisherKey, 'exclude', exclude)
savePublisherOption(publisherKey, 'exclude', exclude)
})
}
})
Expand Down Expand Up @@ -1860,80 +1835,91 @@ const initialize = (state, paymentsEnabled) => {

try {
const fs = require('fs')
// TODO change this back to async
fs.accessSync(pathName(statePath), fs.FF_OK)
const data = fs.readFileSync(pathName(statePath))
let parsedData

try {
parsedData = JSON.parse(data)
if (clientOptions.verboseP) {
console.log('\nstarting up ledger client integration')
fs.access(pathName(statePath), fs.FF_OK, (err) => {
if (err) {
return
}
} catch (ex) {
console.error('statePath parse error: ' + ex.toString())
return state
}

state = getStateInfo(state, parsedData)

try {
let timeUntilReconcile
clientprep()
client = ledgerClient(parsedData.personaId,
underscore.extend(parsedData.options, {roundtrip: roundtrip}, clientOptions),
parsedData)

// Scenario: User enables Payments, disables it, waits 30+ days, then
// enables it again -> reconcileStamp is in the past.
// In this case reset reconcileStamp to the future.
try {
timeUntilReconcile = client.timeUntilReconcile()
} catch (ex) {}

let ledgerWindow = (ledgerState.getSynopsisOption(state, 'numFrames') - 1) * ledgerState.getSynopsisOption(state, 'frameSize')
if (typeof timeUntilReconcile === 'number' && timeUntilReconcile < -ledgerWindow) {
client.setTimeUntilReconcile(null, (err, stateResult) => {
if (err) return console.error('ledger setTimeUntilReconcile error: ' + err.toString())
fs.readFile(pathName(statePath), (err, data) => {
if (err) {
return console.error('read error: ' + err.toString())
}

if (!stateResult) {
return
try {
appActions.onInitRead(JSON.parse(data))
if (clientOptions.verboseP) {
console.log('\nstarting up ledger client integration')
}
} catch (ex) {
console.error('statePath parse error: ' + ex.toString())
}
})
})

appActions.onTimeUntilReconcile(stateResult)
})
}
} catch (ex) {
console.error('ledger client creation error: ', ex)
return state
return state
} catch (err) {
if (err.code !== 'ENOENT') {
console.error('statePath read error: ' + err.toString())
}
state = ledgerState.resetInfo(state)
return state
}
}

// speed-up browser start-up by delaying the first synchronization action
setTimeout(() => {
if (!client) {
return
}
const onInitRead = (state, parsedData) => {
parsedData = parsedData.toJS()
state = getStateInfo(state, parsedData)

appActions.onLedgerFirstSync(parsedData)
}, 3 * miliseconds.second)
try {
let timeUntilReconcile
clientprep()
client = ledgerClient(parsedData.personaId,
underscore.extend(parsedData.options, {roundtrip: roundtrip}, clientOptions),
parsedData)

// Make sure bravery props are up-to-date with user settings
const address = ledgerState.getInfoProp(state, 'address')
if (address) {
state = ledgerState.setInfoProp(state, 'address', client.getWalletAddress())
}
// Scenario: User enables Payments, disables it, waits 30+ days, then
// enables it again -> reconcileStamp is in the past.
// In this case reset reconcileStamp to the future.
try {
timeUntilReconcile = client.timeUntilReconcile()
} catch (ex) {}

setPaymentInfo(getSetting(settings.PAYMENTS_CONTRIBUTION_AMOUNT))
getBalance(state)
let ledgerWindow = (ledgerState.getSynopsisOption(state, 'numFrames') - 1) * ledgerState.getSynopsisOption(state, 'frameSize')
if (typeof timeUntilReconcile === 'number' && timeUntilReconcile < -ledgerWindow) {
client.setTimeUntilReconcile(null, (err, stateResult) => {
if (err) return console.error('ledger setTimeUntilReconcile error: ' + err.toString())

return state
} catch (err) {
if (err.code !== 'ENOENT') {
console.error('statePath read error: ' + err.toString())
if (!stateResult) {
return
}

appActions.onTimeUntilReconcile(stateResult)
})
}
state = ledgerState.resetInfo(state)
} catch (ex) {
console.error('ledger client creation error: ', ex)
return state
}

// speed-up browser start-up by delaying the first synchronization action
setTimeout(() => {
if (!client) {
return
}

appActions.onLedgerFirstSync(parsedData)
}, 3 * miliseconds.second)

// Make sure bravery props are up-to-date with user settings
const address = ledgerState.getInfoProp(state, 'address')
if (address) {
state = ledgerState.setInfoProp(state, 'address', client.getWalletAddress())
}

setPaymentInfo(getSetting(settings.PAYMENTS_CONTRIBUTION_AMOUNT))
getBalance(state)

return state
}

const onTimeUntilReconcile = (state, stateResult) => {
Expand Down Expand Up @@ -2183,5 +2169,6 @@ module.exports = {
onTimeUntilReconcile,
run,
onNetworkConnected,
migration
migration,
onInitRead
}
16 changes: 5 additions & 11 deletions app/browser/reducers/ledgerReducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,9 @@ const settings = require('../../../js/constants/settings')

// State
const ledgerState = require('../../common/state/ledgerState')
const siteSettingsState = require('../../common/state/siteSettingsState')

// Utils
const ledgerApi = require('../../browser/api/ledger')
const urlUtil = require('../../../js/lib/urlutil')
const {makeImmutable} = require('../../common/state/immutableUtil')
const getSetting = require('../../../js/settings').getSetting

Expand Down Expand Up @@ -209,10 +207,8 @@ const ledgerReducer = (state, action, immutableAction) => {
case appConstants.APP_ON_EXCLUSION_STATUS:
{
const key = action.get('publisherKey')
const pattern = urlUtil.getHostPattern(key)
const value = action.get('excluded')
ledgerApi.savePublisherOption(key, 'exclude', value)
state = siteSettingsState.setSettingsProp(state, pattern, 'ledgerPayments', value)
state = ledgerState.setPublishersProp(state, key, ['options', 'exclude'], value)
state = ledgerApi.updatePublisherInfo(state)
break
Expand All @@ -229,13 +225,6 @@ const ledgerReducer = (state, action, immutableAction) => {
const key = action.get('publisherKey')
const prop = action.get('prop')
state = ledgerState.setPublisherOption(state, key, prop, value)

if (action.get('saveIntoSettings')) {
const pattern = urlUtil.getHostPattern(key)
if (prop === 'exclude') {
state = siteSettingsState.setSettingsProp(state, pattern, 'ledgerPayments', value)
}
}
break
}
case appConstants.APP_ON_LEDGER_WALLET_CREATE:
Expand Down Expand Up @@ -308,6 +297,11 @@ const ledgerReducer = (state, action, immutableAction) => {
state = ledgerState.setRecoveryStatus(state, null)
break
}
case appConstants.APP_ON_LEDGER_INIT_READ:
{
state = ledgerApi.onInitRead(state, action.get('parsedData'))
break
}
}
return state
}
Expand Down
14 changes: 8 additions & 6 deletions app/common/lib/ledgerUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,17 +161,11 @@ const visibleP = (state, publisherKey) => {

// Publisher Options
const deletedByUser = blockedP(state, publisherKey)
const includeExclude = stickyP(state, publisherKey)
const eligibleByStats = eligibleP(state, publisherKey) // num of visits and time spent
const isInExclusionList = publisherOptions.get('exclude')
const verifiedPublisher = publisherOptions.get('verified')

return (
eligibleByStats &&
(
isInExclusionList !== true ||
includeExclude
) &&
(
(onlyVerified && verifiedPublisher) ||
!onlyVerified
Expand Down Expand Up @@ -199,6 +193,14 @@ const stickyP = (state, publisherKey) => {
const pattern = urlUtil.getHostPattern(publisherKey)
let result = siteSettingsState.getSettingsProp(state, pattern, 'ledgerPayments')

if (result == null) {
const excluded = ledgerState.getPublisherOption(state, publisherKey, 'exclude')

if (excluded != null) {
result = !excluded
}
}

return (result === undefined || result)
}

Expand Down
Loading

0 comments on commit 7042450

Please sign in to comment.