-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
96 lines (91 loc) Β· 3.38 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
import {JSDOM} from "jsdom";
import {fetch, CookieJar} from "node-fetch-cookies";
const cookieJar = new CookieJar();
export class txtsClient {
constructor(url) {
this.url = url;
}
async #fetchPage(username) {
try {
const response = await fetch(cookieJar,`${this.url}/@${username}`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const html = await response.text();
const jsdom = new JSDOM(html);
return jsdom.window.document;
} catch (error) {
console.log(`Could not fetch page:\n ${error}`);
return null;
}
}
async #fetchEditPage(username) {
try {
const response = await fetch(cookieJar,`${this.url}/@${username}/edit`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const html = await response.text();
const jsdom = new JSDOM(html);
return jsdom.window.document;
} catch (error) {
console.log(`Could not fetch edit page, are you sure that the user exists?\n ${error}`);
return null;
}
}
async getTxt(username) {
const document = await this.#fetchPage(username);
if (document) {
const primaryContainer = document.querySelector(".primary-container");
if (primaryContainer) {
primaryContainer.querySelectorAll('header, div').forEach(el => el.remove());
return primaryContainer.innerHTML;
} else {
console.warn("Warning: .primary-container not found.");
return null;
}
}
return null;
}
async isVerified(username) {
const document = await this.#fetchPage(username);
if (document) {
return !!document.querySelector(".verified-icon");
}
return false;
}
async editTxt(username, secret, content) {
const document = await this.#fetchEditPage(username);
if (document) {
const tokenElem = document.querySelector('input[name="__RequestVerificationToken"]');
if (!tokenElem) {
console.warn("Warning: __RequestVerificationToken not found.");
return false;
}
const tokenValue = tokenElem.value;
try {
const response = await fetch(cookieJar,`${this.url}/@${username}/edit`, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Origin": this.url,
"Referer": `${this.url}/@${username}/edit`
},
body: new URLSearchParams({
"__RequestVerificationToken": tokenValue,
"content": content,
"secret": secret
})
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return true; // Successfully edited the page
} catch (error) {
console.log(`Could not edit page:\n ${error}`);
return false;
}
}
return false;
}
}