This repository has been archived by the owner on Jan 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
server.js
195 lines (179 loc) · 5.46 KB
/
server.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
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const secure = require('express-force-https');
const { Op } = require('sequelize');
const request = require('request-promise');
const sortBy = require('lodash/sortBy');
const Promise = require('bluebird');
const morgan = require('morgan');
const { createMiddleware: createPrometheusMiddleware } = require('@promster/express');
const { createServer } = require('@promster/server');
require('dotenv').config();
const { App, MiningMonthlyReport } = require('./db/models');
const ENUMS = require('./db/models/constants/app-constants');
const { saveRanking } = require('./common/lib/twitter');
const { setup } = require('./common/lib/gcloud');
const appConstants = require('./db/models/constants/app-constants');
const AdminController = require('./controllers/admin-controller');
const UserController = require('./controllers/user-controller');
const MakerController = require('./controllers/maker-controller');
const WebhooksController = require('./controllers/webhooks-controller');
const dev = process.env.NODE_ENV !== 'production';
const port = parseInt(process.env.PORT, 10) || 4000;
const app = express();
app.use(createPrometheusMiddleware({ app }));
// Create `/metrics` endpoint on separate server
createServer({ port: 9154 }).then(() => console.log(`@promster/server started on port 9154.`));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ limit: '5mb' }));
app.use(
morgan(
':remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" :response-time ms',
),
);
app.enable('trust proxy');
app.set('trust proxy', () => true);
app.use(cors());
if (!dev) {
app.use(secure);
}
app.use('/api/admin', AdminController);
app.use('/api/maker', MakerController);
app.use('/api', UserController);
app.use('/api', WebhooksController);
app.use('/api/status', (req, res) => res.sendStatus(204));
app.post('/api/fetch_rankings', async (req, res) => {
if (process.env.API_KEY === req.query.key) {
const apps = await App.findAll();
const fetchRankings = apps.map((appModel) => saveRanking(appModel));
Promise.all(fetchRankings)
.then(() => {
res.send('OK');
})
.catch((error) => {
console.log('api error', error);
res.status(500).send('API Error.');
});
} else {
res.status(400).send('Bad Request');
}
});
app.get('/api/apps', async (req, res) => {
const apps = await App.findAllWithRankings();
const constants = { appConstants };
res.json({ apps, constants });
});
app.get('/api/app-mining-apps', async (req, res) => {
const apps = await App.findAll({
...App.includeOptions,
where: App.MiningReadyQuery,
attributes: { exclude: App.privateColumns },
});
let months = await MiningMonthlyReport.findAll({
where: {
status: 'published',
},
include: MiningMonthlyReport.includeOptions,
});
months = await Promise.map(months, async (report) => {
report.compositeRankings = await report.getCompositeRankings();
return report;
});
apps.forEach((_app, i) => {
const a = _app.get();
a.miningReady = true;
a.lifetimeEarnings = 0;
apps[i] = a;
});
months.forEach((month) => {
const { purchaseConversionRate } = month;
apps.forEach((_app, i) => {
month.MiningAppPayouts.forEach((payout) => {
if (_app.id === payout.appId) {
_app.lifetimeEarnings += payout.BTC * purchaseConversionRate;
apps[i] = _app;
}
});
});
// console.log()
});
const notReady = await App.findAll({
...App.includeOptions,
where: {
categoryID: {
[Op.ne]: ENUMS.categoryEnums['Sample Blockstack Apps'],
},
authenticationID: ENUMS.authenticationEnums.Blockstack,
[Op.or]: [
{
BTCAddress: {
[Op.or]: [{ [Op.eq]: null }, { [Op.eq]: '' }],
},
},
{
stacksAddress: {
[Op.or]: [{ [Op.eq]: null }, { [Op.eq]: '' }],
},
},
{
isKYCVerified: {
[Op.not]: true,
},
},
{
hasCollectedKYC: {
[Op.not]: true,
},
},
{
hasAcceptedSECTerms: {
[Op.not]: true,
},
},
],
status: 'accepted',
},
attributes: { exclude: App.privateColumns },
});
const allApps = apps.concat(
notReady.map((_app) => {
const a = _app.get();
a.miningReady = false;
a.lifetimeEarnings = 0;
return a;
}),
);
const sortedApps = sortBy(allApps, (_app) => -_app.lifetimeEarnings);
res.json({
apps: sortedApps,
});
});
app.get('/api/app-mining-months', async (req, res) => {
let months = await MiningMonthlyReport.findAll({
where: {
status: 'published',
},
include: [MiningMonthlyReport.includeOptions[0]],
order: [['year', 'ASC'], ['month', 'ASC']],
});
months = await Promise.map(months, async (report) => {
const month = report.get();
month.compositeRankings = await report.getCompositeRankings();
return month;
});
res.json({ months });
});
app.get('/api/mining-faq', async (req, res) => {
const faq = await request.get({
uri: 'https://docs.blockstack.org/develop/faq-data.json',
json: true,
});
res.json(faq);
});
setup().then(() => {
app.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});