forked from Deskuma/chatgpt-chatlog-export
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLogGPT-conv-export.js
224 lines (198 loc) · 6.4 KB
/
LogGPT-conv-export.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
216
217
218
219
220
221
222
223
224
// Language: JavaScript
// LogGPT: Chat Log Export
//
// Author: <https://github.com/unixwzrd>
// Version: 1.0.3 Renamed the application and changed the oicons.
// License: MIT
//
// Version 1.0.5
// - Removed Chrome an Firefox code
// - Changed the API handling for new Safari and deprecated API
// Const variable
const DOMAIN_LOGGPT = "chatgpt.com";
const DEBUG = false;
const gptSession = { data: null };
if (DEBUG) document.body.style.border = "5px solid red";
// logging
function clog(msg) {
if (DEBUG) if (msg.startsWith("[debug]")) console.log(msg);
}
// Detect Browser
const BRW_SAFARI = "Safari";
function detectBrowser() {
return BRW_SAFARI;
}
const DETECT_BROWSER = detectBrowser();
// Encryption and decryption
// Shuffle String
function shuffleString(str) {
const chars = str.split(""); // Split a string into an array character by character
for (let i = chars.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1)); // random integer from 0 to i
[chars[i], chars[j]] = [chars[j], chars[i]]; // replace split string
}
return chars.join(""); // return array to string
}
// Create a temporary encryption key
function generateRandomString(length) {
const array = new Uint8Array(length);
window.crypto.getRandomValues(array);
const charset = shuffleString(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
);
clog(`[debug] charset: ${charset}`);
return Array.from(array, (x) => charset[x % charset.length]).join("");
}
const KEY_TOKEN = generateRandomString(32);
clog(`[debug] KEY_TOKEN: ${KEY_TOKEN}`);
// Encryption
function encryptToken(token, key) {
let encrypted = "";
for (let i = 0; i < token.length; i++) {
let charCode = token.charCodeAt(i) ^ key.charCodeAt(i % key.length);
encrypted += String.fromCharCode(charCode);
}
return encrypted;
}
// Decryption
function decryptToken(token, key) {
let decrypted = "";
for (let i = 0; i < token.length; i++) {
let charCode = token.charCodeAt(i) ^ key.charCodeAt(i % key.length);
decrypted += String.fromCharCode(charCode);
}
return decrypted;
}
// Get ThreadId (ChatId)
function getThreadId() {
const url = window.location.href;
const match = url.match(/c\/([\w-]+)/);
return match ? match[1] : null;
}
// Get AccessToken
async function getAccessToken() {
return await getAccessTokenSafari();
}
async function getAccessTokenSafari() {
clog(`[debug] gptSession.data: ${gptSession.data == null}`);
if (gptSession.data == null) {
const threadId = getThreadId();
const response = await fetch(`https://${DOMAIN_LOGGPT}/api/auth/session`, {
credentials: "include",
headers: {
"User-Agent": window.navigator.userAgent,
Accept: "*/*",
"Accept-Language": navigator.language,
"Alt-Used": `${DOMAIN_LOGGPT}`,
Pragma: "no-cache",
"Cache-Control": "no-cache",
},
referrer: `https://${DOMAIN_LOGGPT}/c/${threadId}`,
method: "GET",
mode: "cors",
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
clog(`[debug] getAccessToken() response: ${data != null}`);
// Encrypt the accessToken
data.accessToken = encryptToken(data.accessToken, KEY_TOKEN);
// cache
gptSession.data = data;
clog(`[debug] accessToken: ${gptSession.data != null}`);
if (gptSession.data != null) {
// cache OK
if (DEBUG) document.body.style.border = "5px solid green";
}
} else {
// Do not refetch if cached
}
// decrypt and return
return decryptToken(gptSession.data.accessToken, KEY_TOKEN);
}
// Export conversation (download)
function downloadThreadId(threadId, jsonText) {
const prefix = "LogGPT-clog";
const blob = new Blob([jsonText], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${prefix}-${threadId}.json`;
a.click();
}
// Download Icon Resource
function getIconURL() {
if (typeof browser !== "undefined") {
return browser.runtime.getURL("icons/download-icon.min.svg");
} else {
console.error("Unsupported browser: Cannot determine icon URL");
return "";
}
}
// Display to confirm that the extended function is working
if (DEBUG) document.body.style.border = "5px solid yellow";
// Create a save button (export button)
const saveButton = document.createElement("button");
const iconURL = getIconURL();
clog(`[debug] iconURL: ${iconURL}`);
const iconImage = document.createElement("img");
iconImage.src = iconURL;
iconImage.alt = "Download";
saveButton.appendChild(iconImage);
// Image icon position
saveButton.style.position = "fixed";
saveButton.style.top = "0.8em";
saveButton.style.right = "15em";
saveButton.style.zIndex = "9999";
// Insert a save button into your page
let currentThreadId = -1;
setInterval(() => {
// Monitor the thread ID and delete it if it cannot be obtained
const threadId = getThreadId();
if (currentThreadId != threadId) {
currentThreadId = threadId;
if (threadId != null) document.body.appendChild(saveButton);
else if (saveButton.parentNode) {
saveButton.parentNode.removeChild(saveButton);
}
}
}, 1000);
async function getConversation(threadId) {
return await getConversationSafari(threadId);
}
async function getConversationSafari(threadId) {
const token = await getAccessToken();
clog(`[debug] threadId: ${threadId}`);
clog(`[debug] token: ${token != null}`);
const response = await fetch(
`https://${DOMAIN_LOGGPT}/backend-api/conversation/${threadId}`,
{
credentials: "include",
headers: {
"User-Agent": window.navigator.userAgent,
Accept: "*/*",
"Accept-Language": navigator.language,
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
"Alt-Used": `${DOMAIN_LOGGPT}`,
Pragma: "no-cache",
"Cache-Control": "no-cache",
},
referrer: `https://${DOMAIN_LOGGPT}/chat/${threadId}`,
method: "GET",
mode: "cors",
}
);
const data = await response.json();
return data;
}
// Handle when the download button is clicked
saveButton.addEventListener("click", async () => {
clog("[debug] click -> export download");
// Get conversation data
const threadId = getThreadId();
const data = await getConversation(threadId);
// Format and download acquired conversation data
downloadThreadId(threadId, JSON.stringify(data, null, 2));
});