-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
364 lines (301 loc) · 10.7 KB
/
app.js
File metadata and controls
364 lines (301 loc) · 10.7 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
const express = require("express");
const bodyParser = require("body-parser");
const Mastodon = require("mastodon-api");
const MongoHandler = require("./lib/MongoHandler");
const APIHandler = require("./lib/APIHandler");
const R = require("./lib/Resources");
//I'm for only developing!
try {
require("dotenv").config();
} catch (error) {
null;
}
const SITEURL = "https://mastodon-rater.herokuapp.com";
const Mongo = new MongoHandler(process.env.DB_URI, process.env.DB_NAME);
if (!process.env.DB_URI) throw R.ERROR.ENV.DB_URI;
if (!process.env.DB_NAME) throw R.ERROR.ENV.DB_NAME;
let app = express();
app.set("PORT:HTTP", process.env.PORT || 8001);
app.use(bodyParser.json());
app.use("/", express.static(`${__dirname}/view`));
app.use("/locale", express.static(`${__dirname}/locale`));
/**
* <GET>
* Gets whether MastodonRater exists in the instance
*/
app.get("/api/exists", (req, res) => {
const { instance, redirectTo } = req.query;
if (!instance || !redirectTo) {
res.status(400).end(R.API_END_WITH_ERROR(new TypeError("2 queries, 'instance' and 'redirectTo' are required.")));
return;
}
Mongo.existsApp(instance, redirectTo).then(exists => res.end(R.API_END({ exists })));
});
/**
* <GET>
* Gets a list of connected instances
*/
app.get("/api/apps", (req, res) => {
Mongo.getInstances().then(instances => res.end(R.API_END({ instances })));
});
/**
* <GET>
* Gets information of MastodonRater in the instance
*
* <POST>
* Generates MastodonRater in the instance
*
* <DELETE>
* Removes information of MastodonRater from the instance
*/
app.route("/api/app").get((req, res) => {
const { instance, redirectTo } = req.query;
if (!instance || !redirectTo) {
res.status(400).end(R.API_END_WITH_ERROR(new TypeError("2 queries, 'instance' and 'redirectTo' are required.")));
return;
}
Mongo.getApp(instance, redirectTo).then(info => res.end(R.API_END(info)));
}).post((req, res) => {
const { instance, redirectTo } = req.body;
if (!instance || !redirectTo) {
res.status(400).end(R.API_END_WITH_ERROR(new TypeError("2 payloads, 'instance' and 'redirectTo' are required.")));
return;
}
Mongo.existsApp(instance, redirectTo).then(exists => {
if (exists) {
res.end(R.API_END());
} else {
let appInfo = {};
Mastodon.createOAuthApp(`${instance}/api/v1/apps`, "MastodonRater", "read write", redirectTo).then(info => {
const { id } = info;
const clientId = info.client_id;
const secretId = info.client_secret;
appInfo = Object.assign({}, { id, redirectTo, clientId, secretId });
Mongo.storeApp(instance, appInfo);
return Mastodon.getAuthorizationUrl(clientId, secretId, instance, "read write", redirectTo);
}).then(authUrl => {
res.end(R.API_END(Object.assign(appInfo, { authUrl })));
}).catch(() => {
res.status(400).end(R.API_END_WITH_ERROR(new URIError(`${instance} is not an instance.`)));
});
}
});
}).delete((req, res) => {
const { instance } = req.body;
Mongo.removeApp(instance).then(() => res.end(R.API_END()));
});
/**
* <GET>
* Gets user's token from received code
*/
app.get("/api/token", (req, res) => {
const { instance, clientId, secretId, code, redirectTo } = req.query;
if (!instance || !clientId || !secretId || !code || !redirectTo) {
res.status(400).end(R.API_END_WITH_ERROR(new TypeError("5 queries, 'instance', 'clientId', 'secretId', 'code', and 'redirectTo' are required.")));
return;
}
Mastodon.getAccessToken(clientId, secretId, code, instance, redirectTo).then(accessToken => {
res.end(R.API_END({ accessToken }));
}).catch(() => {
res.status(400).end(R.API_END_WITH_ERROR(new TypeError("Any queries are invalid.")));
return;
});
});
/**
* <GET>
* Gets whether a provided token is valid
*/
app.get("/api/tokenValidate", (req, res) => {
const { instance, token } = req.query;
let Mstdn = new Mastodon({ api_url: `${instance}/api/v1/`, access_token: token });
Mstdn.get("accounts/verify_credentials").then(info => res.end(R.API_END({ valid: !info.data.error })));
});
/**
* <POST>
* Toots with provided contents
*/
app.post("/api/toot", (req, res) => {
const { instance, token, privacy, status, spoiler_text } = req.body;
if (!instance || !token) {
res.status(400).end(R.API_END_WITH_ERROR(new TypeError("2 payloads, 'instance' and 'token' are required.")));
}
let Mstdn = new Mastodon({ api_url: `${instance}/api/v1/`, access_token: token });
Mstdn.post("statuses", {
status,
spoiler_text,
visibility: privacy || "public"
}).then(info => {
if (info.resp.statusCode !== 200) return Promise.reject(info);
res.end(R.API_END({ status: info.data }));
}).catch(info => {
res.status(info.resp.statusCode).end(R.API_END_WITH_ERROR(new Error(info.data.error)));
throw new Error(info.data.error);
});
});
/**
* <POST>
* Executes Toot Rater
*/
app.post("/api/feature/TootRater", (req, res) => {
const { instance, token, privacy } = req.body;
if (!instance || !token) {
res.status(400).end(R.API_END_WITH_ERROR(new TypeError("2 payloads, 'instance' and 'token' are required.")));
}
let serverStatuses = 0,
userStatuses = 0,
rate = 0;
let Mstdn = new Mastodon({ api_url: `${instance}/api/v1/`, access_token: token });
Mstdn.get("instance").then(info => {
if (info.resp.statusCode !== 200) return Promise.reject(info);
serverStatuses = info.data.stats.status_count;
return Mstdn.get("accounts/verify_credentials");
}).then(info => {
if (info.resp.statusCode !== 200) return Promise.reject(info);
userStatuses = info.data.statuses_count;
rate = (userStatuses / serverStatuses * 100).toFixed(3);
return Mstdn.post("statuses", {
status: [
`@${info.data.acct} さんの`,
`#トゥート率 は${rate}%です!`,
"",
"(Tooted from #MastodonRater)",
SITEURL
].join("\r\n"),
visibility: privacy || "public"
});
}).then(info => {
if (info.resp.statusCode !== 200) return Promise.reject(info);
res.end(R.API_END({ rate }));
}).catch(info => {
res.status(info.resp.statusCode).end(R.API_END_WITH_ERROR(new Error(info.data.error)));
throw new Error(info.data.error);
});
});
/**
* <POST>
* Executes TPD
*/
app.post("/api/feature/TPD", (req, res) => {
const { instance, token, privacy } = req.body;
if (!instance || !token) {
res.status(400).end(R.API_END_WITH_ERROR(new TypeError("2 payloads, 'instance' and 'token' are required.")));
}
let days = 0,
tpd = 0;
let Mstdn = new Mastodon({ api_url: `${instance}/api/v1/`, access_token: token });
Mstdn.get("accounts/verify_credentials").then(info => {
if (info.resp.statusCode !== 200) return Promise.reject(info);
let nowTime = new Date().getTime(),
createdAt = new Date(info.data.created_at).getTime();
days = Math.floor((nowTime - createdAt) / (1000 * 60 * 60 * 24));
tpd = Math.floor(info.data.statuses_count / days);
return Mstdn.post("statuses", {
status: [
`@${info.data.acct} さんの`,
`経過日数は${days}日`,
`#TPD は${tpd}です!`,
"",
"(Tooted from #MastodonRater)",
SITEURL
].join("\r\n"),
visibility: privacy || "public"
});
}).then(info => {
if (info.resp.statusCode !== 200) return Promise.reject(info);
res.end(R.API_END({ days, tpd }));
}).catch(info => {
res.status(info.resp.statusCode).end(R.API_END_WITH_ERROR(new Error(info.data.error)));
throw new Error(info.data.error);
});
});
/**
* <POST>
* Executes Relevance Analyzer
*/
app.post("/api/feature/RelevanceAnalyzer", (req, res) => {
const { instance, token, privacy, isImmediately } = req.body;
let { dateRange } = req.body;
if (!instance || !token) {
res.status(400).end(R.API_END_WITH_ERROR(new TypeError("2 payloads, 'instance' and 'token' are required.")));
}
if (!dateRange) {
let today = new Date();
dateRange = new Date(today.getFullYear(), today.getMonth(), today.getDate());
} else if (Number.isInteger(dateRange)) {
dateRange = new Date(dateRange);
}
let me = {};
let friends = [];
let ranking = [];
let Mstdn = new Mastodon({ api_url: `${instance}/api/v1/`, access_token: token });
let mstdnHandler = new APIHandler(Mstdn);
Mstdn.get("accounts/verify_credentials").then(info => {
if (info.resp.statusCode !== 200) return Promise.reject(info);
me = info.data;
if (me.following_count > me.followers_count) {
return mstdnHandler.getFollowers(me.id);
} else {
return mstdnHandler.getFollowing(me.id);
}
}).then(users => {
return mstdnHandler.getFriends(users);
}).then(_friends => {
friends = _friends;
return mstdnHandler.getStatuses(me.id, new Date(), dateRange);
}).then(statuses => {
for (let status of statuses) {
if (status.reblog && friends[status.reblog.account.id]) friends[status.reblog.account.id].reblogScore += R.API_FEATURE_RA_REBLOG;
if (status.mentions) {
for (let mention of status.mentions) {
if (friends[mention.id]) friends[mention.id].mentionScore += R.API_FEATURE_RA_MENTION;
}
}
}
}).then(() => {
ranking = friends.filter(friend => (friend.sumScore = friend.reblogScore + friend.mentionScore) !== 0);
ranking = ranking.sort((a, b) => {
if (a.sumScore < b.sumScore) return 1;
if (a.sumScore > b.sumScore) return -1;
return 0;
});
let tootContent = [
"#RelevanceAnalyzer",
`${dateRange.toLocaleString()}までの #統計さん`,
"",
`@${me.acct} さんと`,
`仲良しのユーザーは`,
"",
(amount => {
const rankIn = [];
for (let i = 0; i < amount; i++) {
if (!ranking[i]) return rankIn.join("\r\n");
rankIn.push([
`《${i + 1}位》`,
`${ranking[i].acct}(Score ${ranking[i].sumScore})`,
""
].join("\r\n"));
}
return rankIn.join("\r\n");
})(R.API_FEATURE_RA_AMOUNT),
"の方々です!!",
"",
"(Tooted from #MastodonRater)",
SITEURL
].join("\r\n");
if (isImmediately) {
return Mstdn.post("statuses", {
status: tootContent,
spoiler_text: "#RelevanceAnalyzer | #統計さん",
visibility: privacy || "public"
});
}
res.end(R.API_END({ ranking: tootContent, isImmediately: false }));
}).then(info => {
if (info.resp.statusCode !== 200) return Promise.reject(info);
res.end(R.API_END({ ranking, isImmediately: true }));
}).catch(info => {
res.status(info.resp.statusCode).end(R.API_END_WITH_ERROR(new Error(info.data.error)));
throw new Error(info.data.error);
});
});
app.listen(app.get("PORT:HTTP"), () => console.log(`[MastodonRater] I'm running on port:${app.get("PORT:HTTP")}✨`));