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 974
/
ledger.js
3444 lines (2854 loc) · 98.9 KB
/
ledger.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* 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 acorn = require('acorn')
const format = require('date-fns/format')
const Immutable = require('immutable')
const electron = require('electron')
const ipc = electron.ipcMain
const session = electron.session
const path = require('path')
const os = require('os')
const qr = require('qr-image')
const underscore = require('underscore')
const tldjs = require('tldjs')
const urlFormat = require('url').format
const levelUp = require('level')
const random = require('random-lib')
const uuid = require('uuid')
const BigNumber = require('bignumber.js')
// Actions
const appActions = require('../../../js/actions/appActions')
// State
const aboutPreferencesState = require('../../common/state/aboutPreferencesState')
const ledgerState = require('../../common/state/ledgerState')
const pageDataState = require('../../common/state/pageDataState')
const updateState = require('../../common/state/updateState')
// Constants
const settings = require('../../../js/constants/settings')
const messages = require('../../../js/constants/messages')
const appConfig = require('../../../js/constants/appConfig')
const ledgerStatuses = require('../../common/constants/ledgerStatuses')
// Utils
const config = require('../../../js/constants/buildConfig')
const tabs = require('../../browser/tabs')
const locale = require('../../locale')
const getSetting = require('../../../js/settings').getSetting
const {getSourceAboutUrl, isSourceAboutUrl} = require('../../../js/lib/appUrlUtil')
const urlParse = require('../../common/urlParse')
const ruleSolver = require('../../extensions/brave/content/scripts/pageInformation')
const request = require('../../../js/lib/request')
const ledgerUtil = require('../../common/lib/ledgerUtil')
const tabState = require('../../common/state/tabState')
const pageDataUtil = require('../../common/lib/pageDataUtil')
const ledgerNotifications = require('./ledgerNotifications')
const ledgerVideoCache = require('../../common/cache/ledgerVideoCache')
const updater = require('../../updater')
const promoCodeFirstRunStorage = require('../../promoCodeFirstRunStorage')
const appUrlUtil = require('../../../js/lib/appUrlUtil')
const urlutil = require('../../../js/lib/urlutil')
const windowState = require('../../common/state/windowState')
const {makeImmutable, makeJS, isList, isImmutable} = require('../../common/state/immutableUtil')
const siteHacks = require('../../siteHacks')
const UrlUtil = require('../../../js/lib/urlutil')
const promotionStatuses = require('../../common/constants/promotionStatuses')
// Caching
let locationDefault = 'NOOP'
let currentUrl = locationDefault
let currentTimestamp = new Date().getTime()
let visitsByPublisher = {}
let bootP
let quitP
const _internal = {
verboseP: process.env.LEDGER_VERBOSE || false,
debugP: process.env.LEDGER_DEBUG || false,
ruleset: {
raw: [],
cooked: []
}
}
let userAgent = ''
// Libraries
let ledgerPublisher
let ledgerClient
let ledgerBalance
let client
let synopsis
// Timers
let balanceTimeoutId = false
let runTimeoutId
let promotionTimeoutId
let togglePromotionTimeoutId
let publisherInfoTimeoutId = false
let publisherInfoUpdateIntervalId
// Database
let v2RulesetDB
const v2RulesetPath = 'ledger-rulesV2.leveldb'
const statePath = 'ledger-state.json'
// Publisher info
const publisherInfoPath = 'publisher-data.json'
const publisherInfoUpdateInterval = ledgerUtil.milliseconds.day * 2
let publisherInfoData = []
// Definitions
const clientOptions = {
debugP: process.env.LEDGER_DEBUG,
loggingP: process.env.LEDGER_LOGGING,
rulesTestP: process.env.LEDGER_RULES_TESTING,
verboseP: process.env.LEDGER_VERBOSE,
server: process.env.LEDGER_SERVER_URL,
createWorker: electron.app.createWorker,
version: 'v2',
environment: process.env.LEDGER_ENVIRONMENT || 'production'
}
const platforms = {
'darwin': 'osx',
'win32x64': 'winx64',
'win32ia32': 'winia32',
'linux': 'linux'
}
let platform = platforms[process.platform]
if (process.platform === 'win32') {
platform = platforms[process.platform + process.arch]
}
let referralServer = 'https://laptop-updates-staging.herokuapp.com'
let referralAPI = 'key'
if (clientOptions.environment === 'production') {
referralServer = 'https://laptop-updates.brave.com'
referralAPI = config.referralAPI || process.env.LEDGER_REFERRAL_API_KEY || ''
}
const fileTypes = {
bmp: Buffer.from([0x42, 0x4d]),
gif: Buffer.from([0x47, 0x49, 0x46, 0x38, [0x37, 0x39], 0x61]),
ico: Buffer.from([0x00, 0x00, 0x01, 0x00]),
jpeg: Buffer.from([0xff, 0xd8, 0xff]),
png: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
}
const minimumVisitTimeDefault = 8 * 1000
let signatureMax = 0
underscore.keys(fileTypes).forEach((fileType) => {
if (signatureMax < fileTypes[fileType].length) signatureMax = fileTypes[fileType].length
})
signatureMax = Math.ceil(signatureMax * 1.5)
if (ipc) {
ipc.on(messages.LEDGER_PUBLISHER, (event, location) => {
if (!synopsis || event.sender.session === electron.session.fromPartition('default') || !tldjs.isValid(tldjs.getDomain(location))) {
event.returnValue = {}
return
}
let ctx = urlParse(location, true)
ctx.TLD = tldjs.getPublicSuffix(ctx.host)
if (!ctx.TLD) {
if (_internal.verboseP) console.log('\nno TLD for:' + ctx.host)
event.returnValue = {}
return
}
ctx = underscore.mapObject(ctx, function (value) {
if (!underscore.isFunction(value)) return value
})
ctx.URL = location
ctx.SLD = tldjs.getDomain(ctx.host)
ctx.RLD = tldjs.getSubdomain(ctx.host)
ctx.QLD = ctx.RLD ? underscore.last(ctx.RLD.split('.')) : ''
if (!event.sender.isDestroyed()) {
event.sender.send(messages.LEDGER_PUBLISHER_RESPONSE + '-' + location, {
context: ctx,
rules: _internal.ruleset.cooked
})
}
})
}
let ledgerPaymentsPresent = {}
const paymentPresent = (state, tabId, present) => {
if (present) {
ledgerPaymentsPresent[tabId] = present
} else {
delete ledgerPaymentsPresent[tabId]
}
if (present) {
appActions.onPromotionGet()
if (togglePromotionTimeoutId) {
clearTimeout(togglePromotionTimeoutId)
}
if (getSetting(settings.PAYMENTS_ENABLED)) {
if (!balanceTimeoutId) {
module.exports.getBalance(state)
}
state = checkSeed(state)
runPublishersUpdate(state)
}
} else if (balanceTimeoutId) {
clearTimeout(balanceTimeoutId)
balanceTimeoutId = false
}
if (!present) {
const status = ledgerState.getPromotionProp(state, 'promotionStatus')
if (
status === promotionStatuses.CAPTCHA_CHECK ||
status === promotionStatuses.CAPTCHA_ERROR ||
status === promotionStatuses.CAPTCHA_BLOCK
) {
state = ledgerState.setPromotionProp(state, 'promotionStatus', null)
}
}
return state
}
const checkSeed = (state) => {
const seed = ledgerState.getInfoProp(state, 'passphrase')
let localClient = client
if (!localClient) {
localClient = require('bat-client')
}
if (seed && localClient && !localClient.isValidPassPhrase(seed)) {
state = ledgerState.setAboutProp(state, 'status', ledgerStatuses.CORRUPTED_SEED)
}
return state
}
const getPublisherInfo = () => {
if (!client) {
return
}
client.fetchPublisherInfo((err, result) => {
if (err) {
console.error('Error while retrieving verified publishers', err.toString())
return
}
appActions.onPublishersInfoReceived(result)
})
}
const checkPublisherInfoUpdate = (state) => {
const verifiedPTimestamp = updateState.getUpdateProp(state, 'verifiedPublishersTimestamp') || null
if (
verifiedPTimestamp == null ||
(new Date().getTime() - verifiedPTimestamp) >= publisherInfoUpdateInterval
) {
if (publisherInfoTimeoutId) {
clearTimeout(publisherInfoTimeoutId)
}
// Startup and boot delay
const delay = (!bootP || !client) ? (ledgerUtil.milliseconds.second * 15) : 0
publisherInfoTimeoutId = setTimeout(() => {
module.exports.getPublisherInfo()
}, delay)
}
}
const updatePublishersInfo = (state, publisherKeys, publisherData) => {
if (publisherData == null || publisherKeys == null) {
return state
}
let updateData = []
if (!isList(publisherKeys)) {
publisherKeys = Immutable.List([publisherKeys])
}
publisherData = makeImmutable(publisherData)
const publishers = publisherData.filter(p => publisherKeys.indexOf(p.first()) > -1)
publishers.forEach((publisher) => {
const verified = !!publisher.get(1)
const publisherKey = publisher.get(0)
savePublisherOption(publisherKey, 'verified', verified)
updateData.push({
verified,
publisherKey
})
})
if (updateData.length > 0) {
appActions.onPublishersOptionUpdate(updateData)
}
if (process.env.NODE_ENV === 'test') {
['brianbondy.com', 'clifton.io'].forEach((key) => {
if (ledgerState.hasPublisher(state, key)) {
state = ledgerState.setPublisherOption(state, key, 'verified', true)
savePublisherOption(key, 'verified', true)
}
})
state = updatePublisherInfo(state)
}
return state
}
const addFoundClosed = (state) => {
if (balanceTimeoutId) {
clearTimeout(balanceTimeoutId)
}
const balanceFn = module.exports.getBalance.bind(null, state)
balanceTimeoutId = setTimeout(balanceFn, 5 * ledgerUtil.milliseconds.second)
}
const boot = () => {
if (bootP || client) {
return
}
bootP = true
const fs = require('fs')
fs.access(pathName(statePath), fs.FF_OK, (err) => {
if (!err) return
if (err.code !== 'ENOENT') console.error('statePath read error: ' + err.toString())
appActions.onBootStateFile()
})
}
const onBootStateFile = (state) => {
state = ledgerState.setInfoProp(state, 'creating', true)
try {
clientprep()
client = ledgerClient(null, underscore.extend({roundtrip: module.exports.roundtrip}, clientOptions), null)
} catch (ex) {
state = ledgerState.resetInfo(state)
bootP = false
console.error('ledger client boot error: ', ex)
return state
}
if (client.sync(callback) === true) {
run(state, random.randomInt({min: ledgerUtil.milliseconds.minute, max: 5 * ledgerUtil.milliseconds.minute}))
}
module.exports.getBalance(state)
bootP = false
return state
}
const promptForRecoveryKeyFile = () => {
const defaultRecoveryKeyFilePath = path.join(electron.app.getPath('downloads'), '/brave_wallet_recovery.txt')
if (process.env.SPECTRON) {
// skip the dialog for tests
console.log(`for test, trying to recover keys from path: ${defaultRecoveryKeyFilePath}`)
return defaultRecoveryKeyFilePath
} else {
const dialog = electron.dialog
const BrowserWindow = electron.BrowserWindow
dialog.showDialog(BrowserWindow.getFocusedWindow(), {
type: 'select-open-file',
defaultPath: defaultRecoveryKeyFilePath,
extensions: [['txt']],
includeAllFiles: false
}, (files) => {
appActions.onFileRecoveryKeys((files && files.length ? files[0] : null))
})
}
}
const logError = (state, err, caller) => {
if (err) {
console.error('Error in %j: %j', caller, err)
state = ledgerState.setLedgerError(state, err, caller)
} else {
state = ledgerState.setLedgerError(state)
}
return state
}
const loadKeysFromBackupFile = (state, filePath) => {
let recoveryKey = null
const fs = require('fs')
let data = fs.readFileSync(filePath)
if (!data || !data.length || !(data.toString())) {
state = logError(state, 'No data in backup file', 'recoveryWallet')
} else {
try {
const recoveryFileContents = data.toString()
let messageLines = recoveryFileContents.match(/^.+$/gm)
let passphraseLine = '' || messageLines[2]
const passphrasePattern = new RegExp([locale.translation('ledgerBackupText4'), '(.+)$'].join(' '))
recoveryKey = (passphraseLine.match(passphrasePattern) || [])[1]
} catch (exc) {
state = logError(state, exc, 'recoveryWallet')
}
}
return {
state,
recoveryKey
}
}
const getPublisherData = (result, scorekeeper) => {
let duration = result.duration
let data = {
verified: result.options.verified || false,
exclude: result.options.exclude || false,
publisherKey: result.publisherKey,
providerName: result.providerName,
siteName: result.publisherKey,
views: result.visits,
duration: duration,
daysSpent: 0,
hoursSpent: 0,
minutesSpent: 0,
secondsSpent: 0,
faviconURL: result.faviconURL,
score: result.scores ? result.scores[scorekeeper] : 0,
pinPercentage: result.pinPercentage,
weight: result.pinPercentage
}
data.publisherURL = result.publisherURL || ((result.protocol || 'https:') + '//' + result.publisherKey)
// media publisher
if (result.faviconName) {
data.siteName = locale.translation('publisherMediaName', {
publisherName: result.faviconName,
provider: result.providerName
})
}
if (duration >= ledgerUtil.milliseconds.day) {
data.daysSpent = Math.max(Math.round(duration / ledgerUtil.milliseconds.day), 1)
} else if (duration >= ledgerUtil.milliseconds.hour) {
data.hoursSpent = Math.max(Math.floor(duration / ledgerUtil.milliseconds.hour), 1)
data.minutesSpent = Math.round((duration % ledgerUtil.milliseconds.hour) / ledgerUtil.milliseconds.minute)
} else if (duration >= ledgerUtil.milliseconds.minute) {
data.minutesSpent = Math.max(Math.floor(duration / ledgerUtil.milliseconds.minute), 1)
data.secondsSpent = Math.round((duration % ledgerUtil.milliseconds.minute) / ledgerUtil.milliseconds.second)
} else {
data.secondsSpent = Math.max(Math.round(duration / ledgerUtil.milliseconds.second), 1)
}
if (_internal.verboseP) {
console.log('\ngetPublisherData result=' + JSON.stringify(result, null, 2) + '\ndata=' + JSON.stringify(data, null, 2))
}
return data
}
const normalizePinned = (dataPinned, total, target, setOne) => dataPinned.map((publisher) => {
let newPer
let floatNumber
if (setOne) {
newPer = 1
floatNumber = 1
} else {
floatNumber = (publisher.pinPercentage / total) * target
newPer = Math.floor(floatNumber)
if (newPer < 1) {
newPer = 1
}
}
publisher.weight = floatNumber
publisher.pinPercentage = newPer
return publisher
})
// courtesy of https://stackoverflow.com/questions/13483430/how-to-make-rounded-percentages-add-up-to-100#13485888
const roundToTarget = (l, target, property) => {
let off = target - underscore.reduce(l, (acc, x) => { return acc + Math.round(x[property]) }, 0)
return underscore.sortBy(l, (x) => Math.round(x[property]) - x[property])
.map((x, i) => {
x[property] = Math.round(x[property]) + (off > i) - (i >= (l.length + off))
return x
})
}
// Removes entries older entries and entries that have 0 visits across windows
const pruneSynopsis = (state) => {
if (!synopsis) {
return state
}
const json = synopsis.toJSON()
if (!json || !json.publishers) {
return state
}
appActions.onPruneSynopsis(json.publishers)
return ledgerState.saveSynopsis(state, json.publishers)
}
// TODO we should convert this function and all related ones into immutable
// TODO merge publishers and publisherData that is created in getPublisherData
// so that we don't need to create new Map every single time
const synopsisNormalizer = (state, changedPublisher, returnState = true, prune = false) => {
let dataPinned = [] // change to list
let dataUnPinned = [] // change to list
let dataExcluded = [] // change to list
const scorekeeper = ledgerState.getSynopsisOption(state, 'scorekeeper')
if (prune) {
state = module.exports.pruneSynopsis(state)
}
let publishers = ledgerState.getPublishers(state).toJS()
let pinnedTotal = 0
let unPinnedTotal = 0
Object.keys(publishers).forEach(publisherKey => {
let publisher = publishers[publisherKey]
if (!ledgerUtil.visibleP(state, publisherKey)) {
return
}
publisher.publisherKey = publisherKey
if (publisher.pinPercentage && publisher.pinPercentage > 0) {
// pinned
pinnedTotal += publisher.pinPercentage
dataPinned.push(getPublisherData(publisher, scorekeeper))
} else if (ledgerUtil.stickyP(state, publisher.publisherKey)) {
// unpinned
unPinnedTotal += publisher.scores ? publisher.scores[scorekeeper] : 0
dataUnPinned.push(publisher)
} else {
// excluded
let newPublisher = getPublisherData(publisher, scorekeeper)
newPublisher.percentage = 0
newPublisher.weight = 0
dataExcluded.push(newPublisher)
}
})
if (
dataPinned.length === 0 &&
dataUnPinned.length === 0 &&
dataExcluded.length === 0
) {
if (returnState) {
return ledgerState.saveAboutSynopsis(state, Immutable.List())
}
return []
}
// round if over 100% of pinned publishers
if (pinnedTotal > 100) {
if (changedPublisher) {
let changedObject = dataPinned.find(publisher => publisher.publisherKey === changedPublisher)
if (changedObject) {
const setOne = changedObject.pinPercentage > (100 - dataPinned.length - 1)
if (setOne) {
changedObject.pinPercentage = 100 - dataPinned.length + 1
changedObject.weight = changedObject.pinPercentage
}
const pinnedRestTotal = pinnedTotal - changedObject.pinPercentage
dataPinned = dataPinned.filter(publisher => publisher.publisherKey !== changedPublisher)
dataPinned = module.exports.normalizePinned(dataPinned, pinnedRestTotal, (100 - changedObject.pinPercentage), setOne)
dataPinned = module.exports.roundToTarget(dataPinned, (100 - changedObject.pinPercentage), 'pinPercentage')
dataPinned.push(changedObject)
}
} else {
dataPinned = module.exports.normalizePinned(dataPinned, pinnedTotal, 100)
dataPinned = module.exports.roundToTarget(dataPinned, 100, 'pinPercentage')
}
dataUnPinned = dataUnPinned.map((result) => {
let publisher = getPublisherData(result, scorekeeper)
publisher.percentage = 0
publisher.weight = 0
return publisher
})
} else if (dataUnPinned.length === 0 && pinnedTotal < 100) {
// when you don't have any unpinned sites and pinned total is less then 100 %
let changedObject = dataPinned.find(publisher => publisher.publisherKey === changedPublisher)
if (changedObject) {
const pinnedRestTotal = pinnedTotal - changedObject.pinPercentage
const restPercentage = 100 - changedObject.pinPercentage
dataPinned = dataPinned.filter(publisher => publisher.publisherKey !== changedPublisher)
dataPinned = module.exports.normalizePinned(dataPinned, pinnedRestTotal, restPercentage)
dataPinned = module.exports.roundToTarget(dataPinned, restPercentage, 'pinPercentage')
dataPinned.push(changedObject)
} else {
dataPinned = module.exports.normalizePinned(dataPinned, pinnedTotal, 100, false)
dataPinned = module.exports.roundToTarget(dataPinned, 100, 'pinPercentage')
}
} else {
// unpinned publishers
dataUnPinned = dataUnPinned.map((result) => {
let publisher = getPublisherData(result, scorekeeper)
const floatNumber = (publisher.score / unPinnedTotal) * (100 - pinnedTotal)
publisher.percentage = Math.round(floatNumber)
publisher.weight = floatNumber
return publisher
})
// normalize unpinned values
dataUnPinned = module.exports.roundToTarget(dataUnPinned, (100 - pinnedTotal), 'percentage')
}
const newData = dataPinned.concat(dataUnPinned, dataExcluded)
// sync synopsis
newData.forEach((item) => {
const publisherKey = item.publisherKey
const weight = item.weight
const pinPercentage = item.pinPercentage
savePublisherData(publisherKey, 'weight', weight)
savePublisherData(publisherKey, 'pinPercentage', pinPercentage)
state = ledgerState.setPublishersProp(state, publisherKey, 'weight', weight)
state = ledgerState.setPublishersProp(state, publisherKey, 'pinPercentage', pinPercentage)
})
if (returnState) {
return ledgerState.saveAboutSynopsis(state, newData)
}
return newData
}
const updatePublisherInfo = (state, changedPublisher, refresh = false) => {
if (!refresh && !getSetting(settings.PAYMENTS_ENABLED)) {
return state
}
state = synopsisNormalizer(state, changedPublisher)
return state
}
const inspectP = (db, path, publisher, property, key, callback) => {
const done = (err, result) => {
if (callback) {
if (err) {
callback(err, null)
return
}
callback(err, result[property])
}
}
if (!key) key = publisher
db.get(key, (err, value) => {
let result
if (err) {
if (!err.notFound) console.error(path + ' get ' + key + ' error: ' + JSON.stringify(err, null, 2))
return done(err)
}
try {
result = JSON.parse(value)
} catch (ex) {
console.error(v2RulesetPath + ' stream invalid JSON ' + key + ': ' + value)
result = {}
}
done(null, result)
})
}
const runPublishersUpdate = (state) => {
const publishers = ledgerState.getPublishers(state)
if (publishers.isEmpty()) {
return
}
module.exports.updatePublishers(state, Array.from(publishers.keys()))
}
const updatePublishers = (state, publisherKeys) => {
const fs = require('fs')
if (publisherInfoData && publisherInfoData.size > 0) {
appActions.onPublishersInfoRead(publisherKeys, publisherInfoData)
return state
}
fs.readFile(pathName(publisherInfoPath), (err, data) => {
if (err) {
console.error('Error: Could not read from publishers file')
return
}
try {
const result = JSON.parse(data)
publisherInfoData = makeImmutable(result)
appActions.onPublishersInfoRead(publisherKeys, publisherInfoData)
} catch (err) {
console.error(`Error: Could not parse data from publishers file`)
}
})
return state
}
// TODO rename function
const excludeP = (publisherKey, callback) => {
let doneP
const done = (err, result) => {
doneP = true
callback(err, result)
}
if (!v2RulesetDB) {
return setTimeout(() => excludeP(publisherKey, callback), 5 * ledgerUtil.milliseconds.second)
}
inspectP(v2RulesetDB, v2RulesetPath, publisherKey, 'exclude', 'domain:' + publisherKey, (err, result) => {
if (!err) {
return done(err, result)
}
let props = ledgerPublisher.getPublisherProps(publisherKey)
if (!props) return done()
v2RulesetDB.createReadStream({lt: 'domain:'}).on('data', (data) => {
if (doneP) return
const sldP = data.key.indexOf('SLD:') === 0
const tldP = data.key.indexOf('TLD:') === 0
if (!tldP && !sldP) return
if (underscore.intersection(data.key.split(''),
['^', '$', '*', '+', '?', '[', '(', '{', '|']).length === 0) {
if (data.key !== ('TLD:' + props.TLD) && (props.SLD && data.key !== ('SLD:' + props.SLD.split('.')[0]))) {
return
}
} else {
try {
const regexp = new RegExp(data.key.substr(4))
if (!regexp.test(props[tldP ? 'TLD' : 'SLD'])) return
} catch (ex) {
console.error(v2RulesetPath + ' stream invalid regexp ' + data.key + ': ' + ex.toString())
}
}
let result
try {
result = JSON.parse(data.value)
} catch (ex) {
console.error(v2RulesetPath + ' stream invalid JSON ' + data.entry + ': ' + data.value)
}
done(null, result.exclude)
}).on('error', (err) => {
console.error(v2RulesetPath + ' stream error: ' + JSON.stringify(err, null, 2))
}).on('close', () => {
}).on('end', () => {
if (!doneP) done(null, false)
})
})
}
const addSiteVisit = (state, timestamp, location, tabId, manualAdd = false) => {
if (!synopsis || location == null) {
return state
}
const protocol = urlParse(location).protocol
location = pageDataUtil.getInfoKey(location)
const minimumVisitTime = getSetting(settings.PAYMENTS_MINIMUM_VISIT_TIME)
const duration = manualAdd ? parseInt(minimumVisitTime) : new Date().getTime() - timestamp
const locationData = manualAdd ? Immutable.fromJS({ publisher: tldjs.getDomain(location) }) : ledgerState.getLocation(state, location)
if (_internal.verboseP) {
console.log(
`locations[${location}]=${JSON.stringify(locationData, null, 2)} ` +
`duration=${(duration)} msec tabId= ${tabId}`
)
}
if (locationData.isEmpty()) {
return state
}
let publisherKey = locationData.get('publisher')
let revisitP = false
if (duration >= minimumVisitTime) {
if (!visitsByPublisher[publisherKey]) {
visitsByPublisher[publisherKey] = {}
}
if (!visitsByPublisher[publisherKey][location]) {
visitsByPublisher[publisherKey][location] = {
tabIds: []
}
}
revisitP = manualAdd ? false : visitsByPublisher[publisherKey][location].tabIds.indexOf(tabId) !== -1
if (!revisitP) {
visitsByPublisher[publisherKey][location].tabIds.push(tabId)
}
}
return module.exports.saveVisit(state, publisherKey, {
duration,
protocol: protocol,
revisited: revisitP
})
}
const saveVisit = (state, publisherKey, options) => {
if (!synopsis || !publisherKey || !options) {
return state
}
if (_internal.verboseP) {
console.log('\nadd publisher ' + publisherKey + ': ' + (options.duration / 1000) + ' sec' + ' revisitP=' + options.revisited)
}
synopsis.addPublisher(publisherKey, {
duration: options.duration,
revisitP: options.revisited,
ignoreMinTime: options.ignoreMinTime || false
})
state = ledgerState.setPublisher(state, publisherKey, synopsis.publishers[publisherKey])
if (options.protocol) {
state = ledgerState.setPublishersProp(state, publisherKey, 'protocol', options.protocol)
}
state = updatePublisherInfo(state)
state = module.exports.checkVerifiedStatus(state, publisherKey)
return state
}
const checkVerifiedStatus = (state, publisherKeys) => {
if (publisherKeys == null) {
return state
}
if (!Array.isArray(publisherKeys)) {
publisherKeys = [publisherKeys]
}
state = module.exports.updatePublishers(state, publisherKeys)
return state
}
const shouldTrackTab = (state, tabId) => {
let tabFromState = tabState.getByTabId(state, tabId)
if (tabFromState == null) {
tabFromState = pageDataState.getLastClosedTab(state, tabId)
}
const partition = tabFromState.get('partition', '')
const ses = session.fromPartition(partition)
const isPrivate = (ses && ses.isOffTheRecord()) || tabFromState.get('incognito') || partition === appConfig.tor.partition
return !isPrivate && !tabFromState.isEmpty() && ledgerUtil.shouldTrackView(tabFromState)
}
const addNewLocation = (state, location, tabId = tabState.TAB_ID_NONE, keepInfo = false, manualAdd = false) => {
// We always want to have the latest active tabId
const currentTabId = manualAdd ? tabId : pageDataState.getLastActiveTabId(state)
state = pageDataState.setLastActiveTabId(state, tabId)
if (location === currentUrl && !manualAdd) {
return state
}
// Save previous recorder page
if (currentUrl !== locationDefault && currentTabId != null && currentTabId !== tabState.TAB_ID_NONE && !manualAdd) {
if (module.exports.shouldTrackTab(state, currentTabId)) {
state = module.exports.addSiteVisit(state, currentTimestamp, currentUrl, currentTabId)
}
}
if (manualAdd) {
const minimumVisits = getSetting(settings.PAYMENTS_MINIMUM_VISITS)
for (let v = 0; v < minimumVisits; v++) {
state = module.exports.addSiteVisit(state, currentTimestamp, location, currentTabId, manualAdd)
}
return state
}
if (location === locationDefault && !keepInfo) {
state = pageDataState.resetInfo(state)
}
// Update to the latest view
currentUrl = location
currentTimestamp = new Date().getTime()
return state
}
const onFavIconReceived = (state, publisherKey, blob) => {
if (publisherKey == null) {
return state
}
state = ledgerState.setPublishersProp(state, publisherKey, 'faviconURL', blob)
module.exports.savePublisherData(publisherKey, 'faviconURL', blob)
return state
}
const getFavIcon = (state, publisherKey, page) => {
let publisher = ledgerState.getPublisher(state, publisherKey)
const protocol = page.get('protocol')
if (protocol && !publisher.get('protocol')) {
publisher = publisher.set('protocol', protocol)
state = ledgerState.setPublishersProp(state, publisherKey, 'protocol', protocol)
}
if (publisher.get('faviconURL') == null && (page.get('faviconURL') || publisher.get('protocol'))) {
let faviconURL = page.get('faviconURL') || publisher.get('protocol') + '//' + urlParse(page.get('key')).host + '/favicon.ico'
if (_internal.debugP) {
console.log('\nrequest: ' + faviconURL)
}
state = ledgerState.setPublishersProp(state, publisherKey, 'faviconURL', null)
fetchFavIcon(publisherKey, faviconURL)
}
return state
}
const fetchFavIcon = (publisherKey, url, redirects) => {
if (typeof redirects === 'undefined') {
redirects = 0
}
request.request({url: url, responseType: 'blob'}, (err, response, blob) => {
let matchP, prefix, tail
if (response && _internal.verboseP) {
console.log('[ response for ' + url + ' ]')
console.log('>>> HTTP/' + response.httpVersionMajor + '.' + response.httpVersionMinor + ' ' + response.statusCode +
' ' + (response.statusMessage || ''))
underscore.keys(response.headers).forEach((header) => {
console.log('>>> ' + header + ': ' + response.headers[header])
})
console.log('>>>')
console.log('>>> ' + (blob || '').substr(0, 80))
}
if (_internal.debugP) {
console.log('\nresponse: ' + url +
' errP=' + (!!err) + ' blob=' + (blob || '').substr(0, 80) + '\nresponse=' +
JSON.stringify(response, null, 2))
}
if (err) {
console.error('response error: ' + err.toString() + '\n' + err.stack)
return null
}
if (response.statusCode === 301 && response.headers.location) {
if (redirects < 3) fetchFavIcon(publisherKey, response.headers.location, redirects++)
return null
}
if (response.statusCode !== 200 || response.headers['content-length'] === '0') {
return null
}
tail = blob.indexOf(';base64,')
if (blob.indexOf('data:image/') !== 0) {
// NB: for some reason, some sites return an image, but with the wrong content-type...
if (tail <= 0) {
return null
}
prefix = Buffer.from(blob.substr(tail + 8, signatureMax), 'base64')
underscore.keys(fileTypes).forEach((fileType) => {
if (matchP) return