-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
214 lines (178 loc) · 5.73 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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
const path = require('path')
const crypto = require("crypto");
const fastify = require('fastify')({logger: false});
const {auth} = require("twitter-api-sdk");
const {v4} = require("uuid")
const fs = require("fs");
const child_process = require("child_process");
fastify.register(require('@fastify/static'), {
root: path.join(__dirname, 'public'),
prefix: '/public/'
});
const config = {
twitter: {
client_id: process.env.TWITTER_CLIENT_ID,
client_secret: process.env.TWITTER_CLIENT_SECRET
}
}
const twtr = new auth.OAuth2User({
client_id: config.twitter.client_id,
client_secret: config.twitter.client_secret,
callback: "https://archive.alt-text.org/callback",
scopes: ["tweet.read", "users.read"],
});
fastify.get("/common.css", function (request, reply) {
reply.sendFile("common.css")
})
fastify.get("/src/jszip.min.js", function (request, reply) {
reply.sendFile("src/jszip.min.js")
})
fastify.get("/src/oboe-browser.min.js", function (request, reply) {
reply.sendFile("src/oboe-browser.min.js")
})
fastify.get("/img/loading.svg", function (request, reply) {
reply.sendFile("img/loading.svg")
})
fastify.get("/", function (request, reply) {
reply.sendFile("index.html")
});
fastify.get("/archive", function (request, reply) {
reply.sendFile("archive.html")
});
fastify.get("/download", function (request, reply) {
reply.sendFile("download.html")
});
fastify.get("/search", function (request, reply) {
reply.sendFile("search.html")
});
fastify.get("/health", function (request, reply) {
reply.status(200).send()
});
const twitterStates = {};
const MAX_STATE_LIFETIME_MILLIS = 5 * 60 * 1000;
function cleanTwitterStates() {
for (let state in twitterStates) {
let ts = twitterStates[state];
if (Date.now() - ts > MAX_STATE_LIFETIME_MILLIS * 3) {
console.log(`${ts}: Deleting expired state`);
delete twitterStates[state];
}
}
}
const signupOpts = {
handler: (request, reply) => {
const state = crypto.randomBytes(16).toString("base64");
twitterStates[state] = Date.now();
const authUrl = twtr.generateAuthURL({
state: state, code_challenge_method: "plain", code_challenge: crypto.randomBytes(64).toString("base64"),
});
reply.redirect(authUrl)
},
};
fastify.get("/auth", signupOpts);
const signupCallbackOpts = {
schema: {
querystring: {
type: "object",
properties: {
url: {
type: "string",
},
},
},
},
handler: async (request, reply) => {
const {code, state} = request.query;
const stateIssueTime = twitterStates[state];
if (!stateIssueTime) {
reply.status(400).send({error: "Unknown state"});
} else if (Date.now() - stateIssueTime > MAX_STATE_LIFETIME_MILLIS) {
reply.status(400).send({
error: `State expired, must hit callback within ${MAX_STATE_LIFETIME_MILLIS} milliseconds`,
});
}
delete twitterStates[state];
reply.redirect(307, `/archive?code=${code}`);
}
};
fastify.get("/callback", signupCallbackOpts);
const uploadOpts = {
schema: {
body: {
type: "object",
required: ["tweet_ids", "code"],
properties: {
tweet_ids: {
type: "array",
items: {
type: "string"
}
},
code: {
type: "string"
}
},
},
},
handler: async (request, reply) => {
const {tweet_ids, code} = request.body;
if (!code) {
reply.status(400).send({error: "Missing twitter code"})
return
}
if (!tweet_ids || tweet_ids.length === 0) {
reply.status(400).send({error: "No tweet ids specified"})
return
}
const uuid = v4();
const tokenWrapper = await twtr.requestAccessToken(code)
.catch(err => {
console.log(err)
return null;
});
let token = null;
if (tokenWrapper) {
if (tokenWrapper.token && tokenWrapper.token.access_token) {
token = tokenWrapper.token.access_token
} else {
reply.status(500).send({error: "Malformed token from Twitter"})
return
}
} else {
reply.status(400).send({error: "Twitter code too old"})
}
let file = `./in-progress/${uuid}.json`;
fs.writeFileSync(file, JSON.stringify({
token,
tweet_ids
}));
const child = child_process.spawn("/home/hannah/.nvm/versions/node/v16.18.1/bin/node", ["./task.js", uuid]);
child.stdout.on("data", data => {
console.log(`${uuid}: ${data}`);
});
child.stderr.on("data", data => {
console.log(`${uuid}: ${data}`);
});
child.on('error', (error) => {
console.log(`spawn error: ${error.message}`);
});
child.on("close", code => {
console.log(`child process ${uuid} exited with code ${code}`);
});
reply.status(200).send({uuid});
}
};
fastify.post("/api/upload", uploadOpts);
setInterval(cleanTwitterStates, 10000)
// Run the server and report out to the logs
fastify.listen(
{port: process.env.PORT, host: "0.0.0.0"},
function (err, address) {
if (err) {
fastify.log.error(err);
process.exit(1);
}
console.log(`Your app is listening on ${address}`);
fastify.log.info(`server listening on ${address}`);
}
);