This repository has been archived by the owner on Dec 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 973
/
ledgerUtil.js
336 lines (271 loc) · 8.56 KB
/
ledgerUtil.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/* 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/. */
'use strict'
const Immutable = require('immutable')
const moment = require('moment')
const BigNumber = require('bignumber.js')
const queryString = require('querystring')
// State
const siteSettingsState = require('../state/siteSettingsState')
const ledgerState = require('../state/ledgerState')
// Constants
const settings = require('../../../js/constants/settings')
const ledgerMediaProviders = require('../constants/ledgerMediaProviders')
// Utils
const {responseHasContent} = require('./httpUtil')
const urlUtil = require('../../../js/lib/urlutil')
const getSetting = require('../../../js/settings').getSetting
const urlParse = require('../urlParse')
/**
* Is page an actual page being viewed by the user? (not an error page, etc)
* If the page is invalid, we don't want to collect usage info.
* @param {Map} tabValue - data about provided tab
* @return {boolean} true if page should have usage collected, false if not
*/
const shouldTrackView = (tabValue) => {
if (tabValue == null) {
return false
}
const aboutError = tabValue.has('aboutDetails')
const activeEntry = tabValue.getIn(['navigationState', 'activeEntry']) || {}
const response = activeEntry.httpStatusCode === 0 || responseHasContent(activeEntry.httpStatusCode)
return !aboutError && response
}
const batToCurrencyString = (bat, ledgerData) => {
const balance = Number(bat || 0)
const currency = 'USD'
if (balance === 0) {
return `0.00 ${currency}`
}
const hasBeenUpgraded = ledgerData && ledgerData.hasIn(['rates', 'BTC'])
if (ledgerData == null || !hasBeenUpgraded) {
return ''
}
const rate = ledgerData.get('currentRate') || 0
const converted = new BigNumber(new BigNumber(rate.toString())).times(balance).toFixed(2)
return `${converted} ${currency}`
}
const formatCurrentBalance = (ledgerData) => {
let currency = 'USD'
let balance = 0
let converted = 0
let hasRate = false
if (ledgerData != null) {
balance = Number(ledgerData.get('balance') || 0)
converted = Number.parseFloat(ledgerData.get('converted')) || 0
hasRate = ledgerData.has('currentRate') && ledgerData.hasIn(['rates', 'BTC'])
}
balance = balance.toFixed(2)
converted = converted.toFixed(2)
return `${balance} BAT${hasRate ? ` (${converted} ${currency})` : ''}`
}
const formattedTimeFromNow = (timestamp) => {
moment.locale(navigator.language)
return moment(new Date(timestamp)).fromNow()
}
const formattedDateFromTimestamp = (timestamp, format) => {
moment.locale(navigator.language)
return moment(new Date(timestamp)).format(format)
}
const walletStatus = (ledgerData) => {
let status = {}
if (ledgerData.get('error')) {
status.id = 'statusOnError'
} else if (ledgerData.get('created')) {
const transactions = ledgerData.get('transactions')
const pendingFunds = Number(ledgerData.get('unconfirmed') || 0).toFixed(2)
if (pendingFunds + Number(ledgerData.get('balance') || 0) <
0.9 * Number(ledgerData.get('bat') || 0)) {
status.id = 'insufficientFundsStatus'
} else if (pendingFunds > 0) {
status.id = 'pendingFundsStatus'
status.args = {funds: `${pendingFunds} BAT (${batToCurrencyString(pendingFunds, ledgerData)})`}
} else if (transactions && transactions.size > 0) {
status.id = 'defaultWalletStatus'
} else {
status.id = 'createdWalletStatus'
}
} else if (ledgerData.get('creating')) {
status.id = 'creatingWalletStatus'
} else {
status.id = 'createWalletStatus'
}
return status
}
// TODO rename function
const blockedP = (state, publisherKey) => {
const pattern = urlUtil.getHostPattern(publisherKey)
const ledgerPaymentsShown = siteSettingsState.getSettingsProp(state, pattern, 'ledgerPaymentsShown')
return ledgerPaymentsShown === false
}
// TODO rename
const contributeP = (state, publisherKey) => {
const publisher = ledgerState.getPublisher(state, publisherKey)
return (
(stickyP(state, publisherKey) || publisher.getIn(['options', 'exclude']) !== true) &&
eligibleP(state, publisherKey) &&
!blockedP(state, publisherKey)
)
}
// TODO rename function
const visibleP = (state, publisherKey) => {
const publisher = ledgerState.getPublisher(state, publisherKey)
let showOnlyVerified = ledgerState.getSynopsisOption(state, 'showOnlyVerified')
if (showOnlyVerified == null) {
showOnlyVerified = getSetting(settings.PAYMENTS_ALLOW_NON_VERIFIED)
state = ledgerState.setSynopsisOption(state, 'showOnlyVerified', showOnlyVerified)
}
const publisherOptions = publisher.get('options', Immutable.Map())
const onlyVerified = !showOnlyVerified
// Publisher Options
const deletedByUser = blockedP(state, publisherKey)
const eligibleByStats = eligibleP(state, publisherKey) // num of visits and time spent
const verifiedPublisher = publisherOptions.get('verified')
return (
eligibleByStats &&
(
(onlyVerified && verifiedPublisher) ||
!onlyVerified
)
) &&
!deletedByUser
}
// TODO rename function
const eligibleP = (state, publisherKey) => {
const scorekeeper = ledgerState.getSynopsisOption(state, 'scorekeeper')
const minPublisherDuration = ledgerState.getSynopsisOption(state, 'minPublisherDuration')
const minPublisherVisits = ledgerState.getSynopsisOption(state, 'minPublisherVisits')
const publisher = ledgerState.getPublisher(state, publisherKey)
return (
publisher.getIn(['scores', scorekeeper]) > 0 &&
publisher.get('duration') >= minPublisherDuration &&
publisher.get('visits') >= minPublisherVisits
)
}
// TODO rename function
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)
}
const getMediaId = (data, type) => {
let id = null
if (type == null || data == null) {
return id
}
switch (type) {
case ledgerMediaProviders.YOUTUBE:
{
id = data.docid
break
}
}
return id
}
const getMediaKey = (id, type) => {
if (id == null || type == null) {
return null
}
return `${type.toLowerCase()}_${id}`
}
const getMediaData = (xhr, type) => {
let result = null
if (xhr == null || type == null) {
return result
}
switch (type) {
case ledgerMediaProviders.YOUTUBE:
{
const parsedUrl = urlParse(xhr)
let query = null
if (parsedUrl && parsedUrl.query) {
query = queryString.parse(parsedUrl.query)
}
result = query
break
}
}
return result
}
const getMediaDuration = (data, type) => {
let duration = 0
switch (type) {
case ledgerMediaProviders.YOUTUBE: {
duration = getYouTubeDuration(data)
break
}
}
return duration
}
const getYouTubeDuration = (data) => {
let time = 0
if (data == null || data.st == null || data.et == null) {
return time
}
const startTime = data.st.split(',')
const endTime = data.et.split(',')
if (startTime.length !== endTime.length) {
return time
}
for (let i = 0; i < startTime.length; i++) {
time += parseFloat(endTime[i]) - parseFloat(startTime[i])
}
// we get seconds back, so we need to convert it into ms
time = time * 1000
return parseInt(time)
}
const getMediaProvider = (url) => {
let provider = null
if (url == null) {
return provider
}
// Youtube
if (url.startsWith('https://www.youtube.com/api/stats/watchtime?')) {
provider = ledgerMediaProviders.YOUTUBE
}
return provider
}
const milliseconds = {
year: 365 * 24 * 60 * 60 * 1000,
week: 7 * 24 * 60 * 60 * 1000,
day: 24 * 60 * 60 * 1000,
hour: 60 * 60 * 1000,
minute: 60 * 1000,
second: 1000
}
const getMethods = () => {
const publicMethods = {
shouldTrackView,
batToCurrencyString,
formattedTimeFromNow,
formattedDateFromTimestamp,
walletStatus,
blockedP,
contributeP,
visibleP,
eligibleP,
stickyP,
formatCurrentBalance,
getMediaId,
getMediaDuration,
getMediaProvider,
getMediaData,
getMediaKey,
milliseconds
}
let privateMethods = {}
if (process.env.NODE_ENV === 'test') {
privateMethods = {
getYouTubeDuration
}
}
return Object.assign({}, publicMethods, privateMethods)
}
module.exports = getMethods()