-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
215 lines (195 loc) · 6.35 KB
/
index.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
require('dotenv').config();
const { Octokit } = require("@octokit/rest");
const axios = require("axios");
const eaw = require('eastasianwidth');
const {
GH_TOKEN: githubToken,
GIST_ID: gistId,
TRAKT_ID: traktId,
TRAKT_USERNAME: traktUser,
MOVIE_BOX_MODE: movieBoxMode
} = process.env
const octokit = new Octokit({
auth: `token ${githubToken}`
});
const API_URL = 'https://api.trakt.tv';
function truncateString(str, num, suf) {
let suffix = '';
if (suf) {
suffix = '...';
}
if (str.length <= num) {
return str
}
return str.slice(0, num) + suffix;
}
function generateBarChart(percent, size) {
const syms = "░▏▎▍▌▋▊▉█";
const frac = Math.floor((size * 8 * percent) / 100);
const barsFull = Math.floor(frac / 8);
if (barsFull >= size) {
return syms.substring(8, 9).repeat(size);
}
const semi = frac % 8;
return [
syms.substring(8, 9).repeat(barsFull),
syms.substring(semi, semi + 1),
].join("").padEnd(size, syms.substring(0, 1));
}
async function main() {
if (!traktId || !traktUser || !gistId || !githubToken || !movieBoxMode){
throw new Error('Please check your environment variables, as you are missing one.')
}
let gist, endpoint, gistTitle, API_END, mainData, mainJson, lines = [],
showsGnreData, moviesGnreData, showsGnreJson, moviesGnreJson;
switch(movieBoxMode) {
case 'movies':
endpoint = 'history/movies';
gistTitle = `🎞 My last watched movies`;
break;
case 'shows':
endpoint = 'history/shows';
gistTitle = `📺 My last watched shows`;
break;
case 'stats':
endpoint = 'stats';
gistTitle = `📊 My movie + shows statistics`;
break;
}
API_END = `${API_URL}/users/${traktUser}/${endpoint}`;
MOVIES_GNRE_API_END = `${API_URL}/users/${traktUser}/watched/movies?extended=full&limit=10000`;
SHOWS_GNRE_API_END = `${API_URL}/users/${traktUser}/watched/shows?extended=full&limit=10000`;
try {
mainData = await axios.request(API_END, {
method: "GET",
url: API_END,
headers: {
'Content-Type': 'application/json',
'trakt-api-key': traktId,
'trakt-api-version': '2',
}
});
mainJson = mainData.data
if (movieBoxMode == 'stats') {
showsGnreData = await axios.request(SHOWS_GNRE_API_END, {
method: "GET",
url: SHOWS_GNRE_API_END,
headers: {
'Content-Type': 'application/json',
'trakt-api-key': traktId,
'trakt-api-version': '2',
}
});
showsGnreJson = showsGnreData.data
moviesGnreData = await axios.request(MOVIES_GNRE_API_END, {
method: "GET",
url: MOVIES_GNRE_API_END,
headers: {
'Content-Type': 'application/json',
'trakt-api-key': traktId,
'trakt-api-version': '2',
}
});
moviesGnreJson = moviesGnreData.data
}
} catch (error) {
console.error(`movie-box ran into an issue getting your Trakt.tv data:\n${error}`);
}
try {
gist = await octokit.gists.get({
gist_id: gistId
});
} catch (error) {
console.error(`movie-box ran into an issue getting your Gist:\n${error}`);
}
try {
switch(movieBoxMode) {
case 'shows':
for(let i = 0; i < 5; i++) {
const title = truncateString(mainJson[i].show.title, 35, true);
const season = mainJson[i].episode.season.toString().padStart(2, '0');
const episode = mainJson[i].episode.number.toString().padStart(2, '0');
const w = new Date(mainJson[i].watched_at);
const d = w.getDate().toString().padStart(2, '0');
const m = (w.getMonth() + 1).toString().padStart(2, '0');
const y = truncateString(w.getFullYear().toString(), 2, false);
lines.push([
`S${season}E${episode}`,
title.padEnd(40 + title.length - eaw.length(title)),
`${d}-${m}-${y}`
].join(' '));
}
break;
case 'movies':
for(let i = 0; i < 5; i++) {
const title = truncateString(mainJson[i].movie.title, 41, true);
const w = new Date(mainJson[i].watched_at);
const d = w.getDate().toString().padStart(2, '0');
const m = (w.getMonth() + 1).toString().padStart(2, '0');
const y = truncateString(w.getFullYear().toString(), 2, false);
lines.push([
title.padEnd(46 + title.length - eaw.length(title)),
`${d}-${m}-${y}`
].join(' '));
}
break;
case 'stats':
let genres = [];
const nMovies = mainJson.movies.watched;
const nEpisodes = mainJson.episodes.watched;
const nShows = mainJson.shows.watched;
for(let i = 0; i < moviesGnreJson.length; i++) {
genres = genres.concat(moviesGnreJson[i].movie.genres);
}
for(let i = 0; i < showsGnreJson.length; i++) {
genres = genres.concat(showsGnreJson[i].show.genres);
}
let genreScore = genres.reduce(function (acc, curr) {
if (typeof acc[curr] == 'undefined') {
acc[curr] = 1;
} else {
acc[curr] += 1;
}
return acc;
}, {});
let genreScoreList = Object.keys(genreScore).map(function(key) {
return [key, genreScore[key] * 100 / genres.length];
});
genreScoreList.sort(function(first, second) {
return second[1] - first[1];
});
lines.push([
`I've watched ${nMovies} movies and ${nEpisodes} episodes of ${nShows} shows.\n`,
'My favorite 3 genres are:',
].join(''));
for(let i = 0; i < 3; i++) {
lines.push([
genreScoreList[i][0].padEnd(25),
generateBarChart(genreScoreList[i][1], 21),
String(genreScoreList[i][1].toFixed(1)).padStart(5) + "%"
].join(' '));
}
break;
}
} catch (error) {
console.error(`movie-box ran into an issue processing your data:\n${error}`);
}
try {
// Get original filename to update that same file
const filename = Object.keys(gist.data.files)[0];
await octokit.gists.update({
gist_id: gistId,
files: {
[filename]: {
filename: gistTitle,
content: lines.join("\n")
}
}
});
} catch (error) {
console.error(`Unable to update gist\n${error}`);
}
}
(async () => {
await main();
})();