-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.jsx
More file actions
906 lines (805 loc) · 24.2 KB
/
server.jsx
File metadata and controls
906 lines (805 loc) · 24.2 KB
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
var aws = require('aws-sdk')
import passport from 'passport'
import session from 'cookie-session'
import {
getRelatedContent,
deleteRelatedContentByUri
} from './shared/backend/admin/admin_related_services'
import { get_episodes } from './shared/backend/get_episodes'
import { get_episodes_by_guid } from './shared/backend/get_episodes_by_guid'
import { get_rfc_metadata } from './shared/backend/get_rfc_metadata'
import { join_slack } from './shared/backend/join_slack'
import { send_email } from './shared/backend/send_email'
import { search_site } from './shared/backend/search_site'
import { get_blogs_rss } from './shared/backend/get_blogs_rss'
import { get_blogs } from './shared/backend/get_blogs'
import { order_create } from './shared/backend/order_create'
import { add_order } from './shared/backend/add_order'
import { order_fulfill } from './shared/backend/order_fulfill'
import { order_list } from './shared/backend/order_list'
import { ready, getTempFile, getFile } from './shared/backend/v1/recording'
import {
write as writeProposal,
upload as uploadProposalFiles,
getRecording
} from './shared/backend/v1/proposals'
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'
import compression from 'compression'
import { getJobs, extractLocation } from './backend/api/v1/jobs_util'
import { feed_uri } from './shared/daos/episodes'
import {
apiMemberFeed,
loadEpisodes,
loadProducts,
load,
get_contributors,
loadYearRange,
loadCurrentRFC
} from './shared/daos/serverInit'
import place_order from './shared/printful/wrapper'
import { getProducts } from './shared/daos/products'
import express from 'express'
import FileStreamRotator from 'file-stream-rotator'
import fs from 'fs'
import createLocation from 'history/lib/createLocation'
import Immutable from 'immutable'
import promiseMiddleware from './shared/lib/promiseMiddleware'
import thunk from 'redux-thunk'
import fetchComponentData from './shared/lib/fetchComponentData'
import morgan from 'morgan'
import path from 'path'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { ServerStyleSheet } from 'styled-components'
import { Provider } from 'react-redux'
import { RouterContext, match } from 'react-router'
import { isEmpty, clone, some, includes } from 'lodash'
import routes from './shared/routes'
import * as reducers from './shared/reducers'
import { createStore, combineReducers, applyMiddleware } from 'redux'
import Helmet from 'react-helmet'
import { get_podcasts_from_cache } from './shared/utils/redux_loader'
import redirects_map from './redirects'
import { logger } from './logger.js'
import { reducer as formReducer } from 'redux-form'
import axios from 'axios'
import minifyHTML from 'express-minify-html'
import Rollbar from 'rollbar'
import http from 'http'
var Influx = require('influx')
console.log('server.jsx : starting')
const env = process.env.NODE_ENV === 'dev' || process.env.NODE_ENV === 'development' ? 'dev' : 'prod'
const base_url = 'https://4sevcujref.execute-api.us-east-1.amazonaws.com/' + "prod"
const app = express()
/*
* CONFIGURATION
*/
if (process.env.NODE_ENV === 'dev') {
console.log('wepback.dev')
require('./webpack.dev').default(app)
}
var aws_accessKeyId = ''
var aws_secretAccessKey = ''
var aws_region = ''
var stripe_key = 'sk_test_81PZIV6UfHDlapSAkn18bmQi'
var sp_key = 'test_Z_gOWbE8iwjhXf4y4vqizQ'
var slack_key = ''
var aws_proposals_bucket = ''
var rfc_table_name = 'rfc'
var latest_rfc_id = 'test-request'
var itunesId = 'xxxx'
console.dir('env = ' + env)
var ipinfo_token = process.env.IPINFO_TOKEN
itunesId = process.env.ITUNES
stripe_key = process.env.STRIPE
sp_key = process.env.SP
slack_key = process.env.SLACK
var elastic_search_endpoint = process.env.ELASTIC_SEARCH_ENDPOINT
aws_accessKeyId = process.env.AWS_ACCESS_KEY_ID
aws_secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY
aws_region = process.env.AWS_REGION
aws_proposals_bucket = process.env.RECORDING_AWS_PROPOSALS_BUCKET
aws.config.update({
accessKeyId: aws_accessKeyId,
secretAccessKey: aws_secretAccessKey,
region: aws_region
})
var influxdb = undefined
const influx_config = process.env.INFLUXDB_ON === 'true'
if (false) {
console.log('initializing influxdb')
influxdb = new Influx.InfluxDB({
protocol: 'https',
host: process.env.INFLUXDB_HOST,
database: process.env.INFLUXDB_DATABASE,
port: process.env.INFLUXDB_PORT,
username: process.env.INFLUXDB_USER,
password: process.env.INFLUXDB_PASSWORD
})
// options: { ca: ca },
} else {
console.log('NOT initializing influxdb')
}
/*
* INITIALIZE CACHE
*/
let Cache = {}
const resetCache = () => {
return {
title_map: {}, // `uri` -> <title>
content_map: {}, // `uri` -? {s3 blog content}
folders: [],
episodes_map: {}, // `guid` | 'latest' -> {episode}
episodes_blog_map: {}, // `blog_id` -> {episode}
episodes_list: [], // guids
episodes_content: [], // pn
products: {},
contributors: {},
rfc: {}
}
}
const reducer = combineReducers({
...reducers,
form: formReducer
})
global.my_cache = Cache = resetCache()
global.env = 'prod'
/*
* REFRESH
*/
const doRefresh = () => {
console.log('-[Refreshing Cache]-')
// Let node make requests asynchronous
return Promise.all([
//loadEpisodes(),
loadProducts(),
get_contributors(),
loadCurrentRFC(),
loadYearRange()
])
.then(results => {
// but wait until all of them will be done
console.log('-[All cache data fetched]-')
const [products, contributors, rfc, yearRanges] = results
// episodes
/*
const {
episodes_map,
episodes_blog_map,
episodes_list,
episodes_content,
member_feed
} = episodes
*/
Cache.episodes_map = {}
Cache.episodes_list = []
Cache.episodes_content = {}
Cache.episodes_blog_map = {}
Cache.member_feed = {}
// products
Cache.products = null
Cache.products = {}
Cache.products.items = clone(products)
//contributors
Cache.contributors = clone(contributors)
// RFC
Cache.rfc = rfc
// Years
Cache.yearRanges = clone(yearRanges)
})
.then(() => console.log('-[Refreshing Complete]-'))
.catch(err => {
console.error(`Failed to fetch cache`)
console.dir(err)
})
}
setInterval(doRefresh, 60 * 60 * 1000)
/*
* ENVIRONMENT SPECIFIC CONFIGURATION
*/
if (env == 'prod') {
function shouldCompress(req, res) {
if (req.headers['x-no-compression']) {
// don't compress responses with this request header
return false
}
// fallback to standard filter function
return compression.filter(req, res)
}
app.use(compression({ filter: shouldCompress }))
var logDirectory = path.join(__dirname, 'log')
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)
var accessLogStream = FileStreamRotator.getStream({
date_format: 'YYYYMMDD',
filename: path.join(logDirectory, 'access-%DATE%.log'),
frequency: 'daily',
verbose: false
})
app.use(morgan('combined', { stream: accessLogStream }))
} else {
require('./webpack.dev').default(app)
const proxy = require('http-proxy-middleware')
/*
const wsProxy = proxy('/recording', {
target: 'ws://127.0.0.1:9001',
// pathRewrite: {
// '^/websocket' : '/socket', // rewrite path.
// '^/removepath' : '' // remove path.
// },
changeOrigin: true, // for vhosted sites, changes host header to match to target's host
ws: true, // enable websocket proxy
logLevel: 'debug'
})
app.use(wsProxy)
*/
}
/*
* WIRING UP APP
*/
// MIDDLEWARES
app.set('trust proxy', 1)
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, 'views'))
app.use(express.static(path.join(__dirname, 'public')))
app.use(cookieParser())
app.use(bodyParser.json())
app.use(
bodyParser.urlencoded({
extended: true
})
)
// CORS
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, authorization'
)
res.header('Access-Control-Allow-Methods', 'GET,POST,DELETE,PUT,OPTIONS')
next()
})
app.use(
session({
secret: 'secret',
resave: true,
name: 'session',
keys: ['datas', 'member'],
// Cookie Options
maxAge: 24 * 60 * 60 * 1000 // 24 hours
})
)
// PASSPORT
app.use(passport.initialize())
app.use(passport.session())
var challenge_response = 'not_set'
app.all('/.well-known/acme-challenge/:id', function(req, res) {
res.status(200).send(`${req.params.id}.${challenge_response}`)
})
/*
* SETUP API
*/
const docClient = new aws.DynamoDB.DocumentClient()
function api_router(req, res) {
if (req.url.indexOf('/api/slack/join') == 0) {
var req = req.body
join_slack(req, res, slack_key)
return true
} else if (req.url.indexOf('/api/members/feed') == 0) {
apiMemberFeed(req, res, Cache.member_feed)
return true
} else if (req.url.indexOf('/api/v1/proposals/files') == 0) {
uploadProposalFiles(req, res, aws_proposals_bucket)
return true
} else if (req.url.indexOf('/api/v1/proposals/recording') == 0) {
getRecording(req, res)
return true
} else if (req.url.indexOf('/api/v1/proposals') == 0) {
writeProposal(req, res)
return true
} else if (req.url.indexOf('/api/v1/recording/ready') == 0) {
ready(req, res, aws_proposals_bucket)
return true
} else if (req.url.indexOf('/api/v1/recording/get') == 0) {
getTempFile(req, res, aws_proposals_bucket)
return true
} else if (req.url.indexOf('/api/refresh') == 0) {
doRefresh()
return res.status(200).end(JSON.stringify({ status: 'ok' }))
} else if (req.url.indexOf('/api/search') == 0) {
search_site(req, res, elastic_search_endpoint)
return true
} else if (req.url.indexOf('/api/email/send') == 0) {
send_email(req, res, elastic_search)
return true
} else if (req.url.indexOf('/api/order/create') == 0) {
order_create(req, res, stripe_key)
return true
} else if (req.url.indexOf('/api/order/add') == 0) {
add_order(req, res, base_url, stripe_key)
return true
} else if (req.url.indexOf('/api/order/fulfill') == 0) {
order_fulfill(req, res, stripe_key)
return true
} else if (req.url.indexOf('/api/order/list') == 0) {
order_list(req, res, stripe_key)
return true
} else if (req.url.indexOf('/api/contributors/list') == 0) {
var url = `${base_url}/blog/contributors/list`
return axios.get(url).then(function(contributors) {
return res.status(200).end(JSON.stringify(contributors))
}).catch(function(err) {
console.log(err)
return res.status(500).end("{}")
})
} else if (req.url.indexOf('/api/blog/contributors/list') == 0) {
var url = `${base_url}/blog/contributors/list`
return axios.get(url).then(function(contributors) {
return res.status(200).end(JSON.stringify(contributors))
}).catch(function(err) {
console.log(err)
return res.status(500).end("{}")
})
} else if (req.url.indexOf('/api/Related') == 0) {
related_content(req, res)
return true
} else if (req.url.indexOf('/api/blog/list') == 0) {
console.log(req);
get_blogs(req, res)
return true
} else if (req.url == '/api/blog/categories') {
var folders = Cache.folders
return res.status(200).end(JSON.stringify(folders))
} else if (req.url.indexOf('/api/blog/rss') === 0) {
get_blogs_rss(req, res)
return true
} else if (req.url.indexOf('/api/store/order/add') === 0) {
var printful_key = process.env.PRINTFUL_API
var payload = req.body
var customer = payload['customer']
var designId = payload['designId']
var size = payload['size']
var ok_callback = function(r, info) {
var resp = r['data']
var result = { msg: 'ok' }
return res.status(200).end(JSON.stringify(result))
}
var error_callback = function(err) {
console.log('api error')
var jstr = JSON.stringify(err)
console.log(jstr)
var result = { msg: 'fail' }
return res.status(500).end(JSON.stringify(result))
}
var promise = place_order(
printful_key,
customer,
designId,
size,
ok_callback,
error_callback
)
return promise
} else if (req.url.indexOf('/api/store/list') == 0) {
var products = Cache.products
return res.status(200).end(JSON.stringify(products))
} else if (req.url.indexOf('/api/episodes/list') == 0) {
get_episodes(req, res, Cache.episodes_map, Cache.episodes_list)
return true
} else if (req.url.indexOf('/api/v1/store/order/add') == 0) {
add_order(req)
} else if (req.url.indexOf('/api/episodes/get') == 0) {
get_episodes_by_guid(req, res, Cache.episodes_map, Cache.episodes_list)
return true
} else if (req.url == '/api/rfc/list') {
get_rfc_metadata(req, res, Cache, docClient, rfc_table_name, latest_rfc_id)
return true
} else if (req.url === '/api/admin/related') {
getRelatedContent(req.body.uri, docClient).then(related => {
res.send(related)
})
return true
} else if (req.url === '/api/admin/related/delete') {
deleteRelatedContentByUri(
req.body.uri,
req.body.related_uri,
docClient
).then(related => {
res.send(related)
})
return true
} else if (req.url === '/api/admin/related/create') {
createRelatedContent(req.body.uri, req.body.data, docClient).then(
related => {
res.send(related)
}
)
return true
} else if (req.url === '/api/cert/set') {
var b = req.body
var chal = b['c']
challenge_response = chal
return res.status(200).end(JSON.stringify({ status: chal }))
} else if (req.url.indexOf('/api/s3/blogs') === 0) {
var AWS_S3 = new aws.S3();
AWS_S3.listObjects({
Bucket: 'dataskeptic.com',
Prefix: 'blog/'
}, (err, data) => {
console.log({err, data});
if (err) return res.status(500).end(JSON.stringify(err));
res.status(200).end(JSON.stringify(data));
});
return true;
}
return false
}
/*
* INITIALIZE STORE
*/
function inject_folders(store, my_cache) {
var folders = my_cache.folders
store.dispatch({ type: 'ADD_FOLDERS', payload: folders })
}
function inject_years(store, my_cache) {
var yearsData = [2019, 2018, 2017, 2016, 2015, 2014]
var ymap = {}
for (var i = 0; i < yearsData.length; i++) {
var rangeData = yearsData[i]
ymap[rangeData.year] = 1
}
var years = Object.keys(ymap)
years = years.sort().reverse()
store.dispatch({ type: 'SET_YEARS', payload: [2019, 2018, 2017, 2016, 2015, 2014] })
}
const getFeaturesAPI = pageType =>
axios.get(`${base_url}/cms${pageType ? '/' + pageType : ''}`)
function getContributorPosts(contributor) {
console.log("Server getting contributors!")
return axios
.get(`${base_url}/blog/list?contributor=${contributor}&limit=21`)
.then(res => res.data)
.catch(err => console.log)
}
function getEpisode(guid) {
var uri = `${base_url}/podcast/episodes/get?guid=${guid}`
return axios.get(uri)
}
async function inject_homepage(store, my_cache, location) {
const res = await getFeaturesAPI('homepage')
store.dispatch({
type: 'CMS_INJECT_HOMEPAGE_CONTENT',
payload: { data: res.data }
})
const guid = res.data.latest_episode.guid
const episode = undefined
if (episode == undefined) {
var promise = getEpisode(guid)
promise.then(function(res) {
var episode = res.data
store.dispatch({
type: 'ADD_EPISODES',
payload: [episode]
})
})
.catch(err => {
console.log('Caught in server.jsx :(')
console.log(err)
})
} else {
store.dispatch({ type: 'ADD_EPISODES', payload: [episode] })
}
const q = 'data'
const jobs = await getJobs(q, location)
store.dispatch({
type: 'CMS_INJECT_HOMEPAGE_JOB_LISTING',
payload: { data: jobs }
})
}
function inject_products(store, my_cache, pathname) {
var products = my_cache.products['items']
store.dispatch({ type: 'ADD_PRODUCTS', payload: products })
}
function inject_podcast(store, my_cache, pathname) {
var episodes = get_podcasts_from_cache(my_cache, pathname)
store.dispatch({ type: 'ADD_EPISODES', payload: episodes })
}
async function inject_contributor(store, cache, pathanme) {
const contributor = pathanme.split('/').pop()
const blogs = await getContributorPosts(contributor)
store.dispatch({
type: 'SET_CONTRIBUTOR_BLOGS',
payload: { contributor, blogs }
})
}
async function updateState(store, pathname, req) {
inject_years(store, Cache)
store.dispatch({
type: 'PROPOSAL_SET_BUCKET',
payload: { aws_proposals_bucket }
})
if (!isEmpty(Cache.contributors)) {
store.dispatch({
type: 'SET_CONTRIBUTORS',
payload: Cache.contributors
})
}
if (pathname === '' || pathname === '/') {
const location = extractLocation(req)
await inject_homepage(store, Cache, location)
}
if (pathname.indexOf('/blog') === 0) {
} else if (pathname === '/members' || pathname === '/store') {
inject_products(store, Cache, pathname)
} else if (pathname.indexOf('/podcast') === 0) {
inject_podcast(store, Cache, pathname)
} else if (pathname.indexOf('/contributor') === 0) {
await inject_contributor(store, Cache, pathname)
}
store.dispatch({ type: 'ADD_FOLDERS', payload: Cache.folders })
store.dispatch({
type: 'FETCH_CURRENT_PROPOSAL_SUCCESS',
payload: {
data: Cache.rfc
}
})
const isAuthenticated = req.isAuthenticated()
logger.info(`isAuthenticated = ${isAuthenticated}, req.user = ${JSON.stringify(req.user)}`)
if (isAuthenticated) {
store.dispatch({
type: 'AUTH_USER_SUCCESS',
payload: {
data: req.user
}
})
}
}
/*
* RENDERING
*/
function renderView(store, renderProps, location) {
const InitialView = (
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
)
const sheet = new ServerStyleSheet()
const componentHTML = renderToString(sheet.collectStyles(InitialView))
const helmet = Helmet.renderStatic()
const styles = sheet.getStyleTags()
const state = store.getState()
const route = renderProps.matchContext.router.routes.slice(-1)[0]
const notFound = route.notFound
return {
state: state,
html: componentHTML,
helmet: helmet,
styles: styles,
notFound: notFound
}
}
/**
* You might want to change the response schema.
* Please update this key to
* have latest request response data in the user session
*/
const CURRENT_IP_REQ_VERSION = 7
const localIPs = ['127.0.0.1', '::1']
function getIpData(ip) {
const localIP = localIPs.indexOf(ip) > -1
if (localIP) {
ip = ''
}
const url = `http://ipinfo.io${ip && `/${ip}`}/json`
const safe = function(str) {
if (str == undefined) {
return ''
} else {
return str.replace(/'/g, '"')
}
}
return axios
.get(url)
.then(res => res.data)
.then(data => {
if (data['postal'] == undefined) {
data['postal'] = ''
}
const { ip, city, region, country, loc, org, postal } = data
var lat = -1
var lng = -1
if (loc != undefined) {
;[lat, lng] = loc.split(',')
}
return {
ip,
city: safe(city),
region: safe(region),
country: safe(country),
lat,
lng,
org: safe(org),
postal: safe(postal),
version: CURRENT_IP_REQ_VERSION
}
})
}
async function tracking(req, res) {
if (!ipinfo_token) return
let ip = 'not-set'
if (req.connection) {
ip = req.connection.remoteAddress
}
let ipInfo = req.session.ipInfo
if (isEmpty(ipInfo)) ipInfo = null
if (ipInfo && ipInfo.version !== CURRENT_IP_REQ_VERSION) {
ipInfo = null
}
req.session.ver = CURRENT_IP_REQ_VERSION
if (!ipInfo) {
console.log('ipInfo not defined')
let ipData
try {
// wait for ip info request data
ipInfo = ipData = await getIpData(ip)
console.log('success getIpData')
} catch (error) {
console.log('problem with tracking')
console.log(ip)
console.log(ipinfo_token)
console.log(error)
ipInfo = ipData = {
error: true,
version: CURRENT_IP_REQ_VERSION
}
}
// save to current session if not empty
if (ipData) {
console.log('save to current session if not empty')
req.session.ipInfo = { ...ipData }
}
}
if (ipInfo) {
if (influxdb) {
const { country, region, postal, lat, lng } = ipInfo
const pnt = {
measurement: 'impression',
tags: { country, region, postal },
fields: { lat, lng },
version: CURRENT_IP_REQ_VERSION
}
var lst = [pnt]
return influxdb
.writePoints(lst)
.then(function() {})
.catch(function(err) {
console.error('Error saving data to InfluxDB!')
console.log(err)
})
}
} else {
console.log('ipInfo is undefined')
}
}
const api = require('./backend/api/v1')
app.use('/api/v1', async (req, res, next) => {
await tracking(req, res)
next()
})
app.use('/api/v1/', api(() => Cache))
if (env === 'prod') {
const rollbar = Rollbar.init({
accessToken: '4555957947d347a69caf6e017ea72f51',
handleUncaughtExceptions: true,
verbose: false,
payload: {
environment: env
}
})
app.use(rollbar.errorHandler())
app.use(
minifyHTML({
override: true,
exception_url: false,
htmlMinifier: {
removeComments: false,
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
removeEmptyAttributes: false,
minifyJS: false
}
})
)
}
const renderPage = async (req, res) => {
if (req.url == '/favicon.ico') {
return res.redirect(301, 'https://s3.amazonaws.com/dataskeptic.com/favicon.ico')
}
if (req.url == '/data-skeptic-bonus.xml') {
return res.redirect(307, 'https://s3.amazonaws.com/data-skeptic-bonus-feed/data-skeptic-bonus.xml')
}
if (req.url.indexOf('/src-') > 0) {
var u = req.url
console.log({u})
var i = u.indexOf('/blog/') + '/blog'.length
if (i > 0) {
var hostname = 's3.amazonaws.com/dataskeptic.com'
if (env != 'prod') {
hostname = 's3.amazonaws.com/prod.dataskeptic.com'
}
var redir = u.substring(i, u.length)
return res.redirect(301, 'https://' + hostname + redir)
}
} else if (req.url.indexOf('/api') == 0) {
var routed = api_router(req, res)
if (routed) {
return
}
}
var redir = redirects_map['redirects_map'][req.url]
var hostname = req.headers.host
if (redir != undefined) {
console.log('Redirecting to ' + hostname + redir)
return res.redirect(301, 'http://' + hostname + redir)
}
if (req.url == '/feed.rss') {
return res.redirect(307, 'http://dataskeptic.libsyn.com/rss')
}
if (req.url.indexOf('.svg') > -1) {
return res.status(404).end('File Not Found')
}
const location = createLocation(req.url)
logger.info(`URL req.url = ${req.url}`)
match({ routes, location }, async (err, redirectLocation, renderProps) => {
logger.info(`MATCH function`)
if (err) {
console.error(err)
return res.status(500).end('Internal server error')
}
if (!renderProps) {
res.render('error')
}
let store = applyMiddleware(thunk, promiseMiddleware)(createStore)(reducer)
logger.info(`updateState location.pathname = ${location.pathname}`)
await updateState(store, location.pathname, req)
await tracking(req, res)
fetchComponentData(
store.dispatch,
renderProps.components,
renderProps.params
)
.then(() => renderView(store, renderProps, location))
.then(({ html, state, helmet, notFound, styles }) => {
if (notFound) {
return res.status(404).render('index', {
staticHTML: html,
initialState: state,
helmet,
env,
itunesId,
styles
})
}
return res.render('index', {
staticHTML: html,
initialState: state,
helmet,
env,
itunesId,
styles
})
})
.catch(err => {
console.error('HTML generation error')
console.dir(err)
return res.end(err)
})
})
}
doRefresh().then(() => {
console.log('CACHE IS now READY')
app.use(renderPage)
console.log('yay!')
})
export default app