-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathfetch-screenshots.ts
More file actions
86 lines (70 loc) · 2.46 KB
/
Copy pathfetch-screenshots.ts
File metadata and controls
86 lines (70 loc) · 2.46 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
import config from "../../config.js";
import { assertOkResponse, maybeCompressBase64 } from "../../lib/utils.js";
import { SessionType } from "../../lib/constants.js";
import { DOMAINS } from "../../lib/domains.js";
//Extracts screenshot URLs from BrowserStack session logs
async function extractScreenshotUrls(
sessionId: string,
sessionType: SessionType,
): Promise<string[]> {
const credentials = `${config.browserstackUsername}:${config.browserstackAccessKey}`;
const auth = Buffer.from(credentials).toString("base64");
const baseUrl = `${DOMAINS.API}/${sessionType === SessionType.Automate ? "automate" : "app-automate"}`;
const url = `${baseUrl}/sessions/${sessionId}/logs`;
const response = await fetch(url, {
headers: {
"Content-Type": "application/json",
Authorization: `Basic ${auth}`,
},
});
await assertOkResponse(response, "Session");
const text = await response.text();
const urls: string[] = [];
const SCREENSHOT_PATTERN = /REQUEST.*GET.*\/screenshot/;
const RESPONSE_VALUE_PATTERN = /"value"\s*:\s*"([^"]+)"/;
// Split logs into lines and process them
const lines = text.split("\n");
for (let i = 0; i < lines.length - 1; i++) {
const currentLine = lines[i];
const nextLine = lines[i + 1];
if (SCREENSHOT_PATTERN.test(currentLine)) {
const match = nextLine.match(RESPONSE_VALUE_PATTERN);
if (match && match[1]) {
urls.push(match[1]);
}
}
}
return urls;
}
//Converts screenshot URLs to base64 encoded images
async function convertUrlsToBase64(
urls: string[],
): Promise<Array<{ url: string; base64: string }>> {
const screenshots = await Promise.all(
urls.map(async (url) => {
const response = await fetch(url);
const arrayBuffer = await response.arrayBuffer();
const base64 = Buffer.from(arrayBuffer).toString("base64");
// Compress the base64 image if needed
const compressedBase64 = await maybeCompressBase64(base64);
return {
url,
base64: compressedBase64,
};
}),
);
return screenshots;
}
//Fetches and converts screenshot URLs to base64 encoded images
export async function fetchAutomationScreenshots(
sessionId: string,
sessionType: SessionType = SessionType.Automate,
) {
const urls = await extractScreenshotUrls(sessionId, sessionType);
if (urls.length === 0) {
return [];
}
// Take only the last 5 URLs
const lastFiveUrls = urls.slice(-5);
return await convertUrlsToBase64(lastFiveUrls);
}