/
insight-card.service.ts
199 lines (157 loc) · 6 KB
/
insight-card.service.ts
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
import { ForbiddenException, Injectable, Logger, NotFoundException } from "@nestjs/common";
import { HttpService } from "@nestjs/axios";
import { Resvg } from "@resvg/resvg-js";
import fs from "node:fs/promises";
import { GithubService } from "../../github/github.service";
import { S3FileStorageService } from "../../s3-file-storage/s3-file-storage.service";
import tailwindConfig from "../templates/tailwind.config";
import { firstValueFrom } from "rxjs";
import { RequiresUpdateMeta } from "../user-card/user-card.service";
import { DbInsight } from "../../github/entities/db-insight.entity";
import insightCardTemplate from "../templates/insight-card.template";
/*
* interface HighlightCardData {
* title: string;
* body: string;
* reactions: number;
* avatarUrl: string;
* repo: Repository;
* langTotal: number;
* langs: (Language & {
* size: number;
* })[];
* updated_at: Date;
* url: string;
* }
*/
interface InsightCardData {
pageName: string;
repos: { repoName: string; avatarUrl: string }[];
contributors: string[];
updated_at: Date;
}
@Injectable()
export class InsightCardService {
private readonly logger = new Logger(this.constructor.name);
constructor (
private readonly httpService: HttpService,
private readonly githubService: GithubService,
private readonly s3FileStorageService: S3FileStorageService,
) {}
private async getInsightData (insightId: number): Promise<InsightCardData> {
/*
* const highlightReq = await firstValueFrom(
* this.httpService.get<DbUserHighlight>(`https://api.opensauced.pizza/v1/user/highlights/${highlightId}`)
* );
* const { login, title, highlight: body, updated_at, url } = highlightReq.data;
*/
const insightPageReq = await firstValueFrom(
this.httpService.get<DbInsight>(`https://api.opensauced.pizza/v1/insights/${insightId}`),
);
const { repos, name, updated_at } = insightPageReq.data;
const repoIdsQuery = repos.map(repo => repo.repo_id).join(",");
const contributorsReq = await firstValueFrom(
this.httpService.get<{ author_login: string }[]>(
`https://api.opensauced.pizza/v1/contributors/search?repoIds=${repoIdsQuery}`,
),
);
const contributors = contributorsReq.data.map(contributor => contributor.author_login);
const repositories = repos.map(repo => {
const [owner, repoName] = repo.full_name.split("/");
return {
repoName,
avatarUrl: `https://github.com/${owner}.png&size=50`,
};
});
// const [owner, repoName] = url.replace("https://github.com/", "").split("/");
/*
* const user = await this.githubService.getUser(login);
* const repo = await this.githubService.getRepo(owner, repoName);
*/
/*
* const langList = repo.languages?.edges?.flatMap(edge => {
* if (edge) {
* return {
* ...edge.node,
* size: edge.size,
* };
* }
* }) as (Language & { size: number })[];
*/
return {
pageName: name,
repos: repositories,
contributors,
updated_at: new Date(updated_at),
};
}
// public only to be used in local scripts. Not for controller direct use.
async generateCardBuffer (insightId: number, insightData?: InsightCardData) {
const { html } = await import("satori-html");
const satori = (await import("satori")).default;
const { pageName, repos, contributors } = insightData ? insightData : await this.getInsightData(insightId);
const template = html(insightCardTemplate(pageName, contributors, repos));
const interArrayBuffer = await fs.readFile("node_modules/@fontsource/inter/files/inter-all-400-normal.woff");
const svg = await satori(template, {
width: 1200,
height: 627,
fonts: [
{
name: "Inter",
data: interArrayBuffer,
weight: 400,
style: "normal",
},
],
tailwindConfig,
});
const resvg = new Resvg(svg, { background: "rgba(238, 235, 230, .9)" });
const pngData = resvg.render();
return { png: pngData.asPng(), svg };
}
async checkRequiresUpdate (id: number): Promise<RequiresUpdateMeta> {
const hash = `insights/${String(id)}.png`;
const fileUrl = `${this.s3FileStorageService.getCdnEndpoint()}${hash}`;
const hasFile = await this.s3FileStorageService.fileExists(hash);
const returnVal: RequiresUpdateMeta = {
fileUrl,
hasFile,
needsUpdate: true,
lastModified: null,
};
if (hasFile) {
const lastModified = await this.s3FileStorageService.getFileLastModified(hash);
returnVal.lastModified = lastModified;
const { updated_at } = await this.getInsightData(id);
/*
* const metadata = await this.s3FileStorageService.getFileMeta(hash);
* const savedReactions = metadata?.["reactions-count"] ?? "0";
*/
if (lastModified && lastModified > updated_at) {
this.logger.debug(
`Highlight ${id} exists in S3 with lastModified: ${lastModified.toISOString()} newer than updated_at: ${updated_at.toISOString()}, and reaction count is the same, redirecting to ${fileUrl}`,
);
returnVal.needsUpdate = false;
}
}
return returnVal;
}
async getgetInsightCard (id: number): Promise<string> {
const { remaining } = await this.githubService.rateLimit();
if (remaining < 1000) {
throw new ForbiddenException("Rate limit exceeded");
}
const insightData = await this.getInsightData(id);
try {
const hash = `insights/${String(id)}.png`;
const fileUrl = `${this.s3FileStorageService.getCdnEndpoint()}${hash}`;
const { png } = await this.generateCardBuffer(id, insightData);
await this.s3FileStorageService.uploadFile(png, hash, "image/png");
this.logger.debug(`Insight ${id} did not exist in S3, generated image and uploaded to S3, redirecting`);
return fileUrl;
} catch (e) {
this.logger.error(`Error generating insight card for ${id}`, e);
throw (new NotFoundException);
}
}
}